feat: upload project files

This commit is contained in:
Kuingsmile
2025-06-26 15:09:20 +08:00
parent 4908980153
commit 7724a21484
172 changed files with 33261 additions and 2 deletions

110
.github/ISSUE_TEMPLATE/bug_report.yml vendored Normal file
View File

@@ -0,0 +1,110 @@
name: Bug Report
description: Create a report to help us improve OpenList Desktop
title: '[BUG] '
labels: ['bug', 'needs-triage']
body:
- type: markdown
attributes:
value: |
Thank you for taking the time to report a bug! Please fill out the form below to help us understand and fix the issue.
- type: textarea
id: bug-description
attributes:
label: Bug Description
description: A clear and concise description of what the bug is.
validations:
required: true
- type: textarea
id: steps-to-reproduce
attributes:
label: Steps to Reproduce
description: Steps to reproduce the behavior
placeholder: |
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
validations:
required: true
- type: textarea
id: expected-behavior
attributes:
label: Expected Behavior
description: A clear and concise description of what you expected to happen.
validations:
required: true
- type: textarea
id: actual-behavior
attributes:
label: Actual Behavior
description: A clear and concise description of what actually happened.
validations:
required: true
- type: dropdown
id: operating-system
attributes:
label: Operating System
description: What operating system are you using?
options:
- Windows 11
- Windows 10
- macOS (Intel)
- macOS (Apple Silicon)
- Ubuntu
- Other Linux Distribution
- Other
validations:
required: true
- type: dropdown
id: architecture
attributes:
label: System Architecture
description: What system architecture are you using?
options:
- x64 (64-bit)
- arm64
- x86 (32-bit)
- Other
validations:
required: true
- type: input
id: app-version
attributes:
label: OpenList Desktop Version
description: What version of OpenList Desktop are you using?
placeholder: e.g. v0.1.0
validations:
required: true
- type: textarea
id: logs
attributes:
label: Application Logs
description: Please provide relevant logs from the Logs tab in the application
render: shell
- type: textarea
id: additional-context
attributes:
label: Additional Context
description: Add any other context about the problem here, including screenshots if applicable.
- type: checkboxes
id: checklist
attributes:
label: Checklist
description: Please confirm the following
options:
- label: I have searched existing issues to ensure this is not a duplicate
required: true
- label: I have provided all required environment information
required: true
- label: I can reproduce this issue consistently
required: true

14
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1,14 @@
blank_issues_enabled: false
contact_links:
- name: 💬 Discussions
url: https://github.com/OpenListTeam/openlist-desktop/discussions
about: Ask questions, share ideas, and discuss with the community
- name: 📖 Documentation
url: https://github.com/OpenListTeam/openlist-desktop/blob/main/README.md
about: Read the project documentation and setup guides
- name: 🔧 OpenList Documentation
url: https://docs.oplist.org/
about: Official OpenList documentation for the underlying service
- name: 🌐 Rclone Documentation
url: https://rclone.org/docs/
about: Official Rclone documentation for remote storage configuration

View File

@@ -0,0 +1,130 @@
name: Documentation Issue
description: Report issues with documentation or suggest improvements
title: '[DOCS] '
labels: ['documentation', 'needs-triage']
body:
- type: markdown
attributes:
value: |
Help us improve the documentation! Please describe what's missing, unclear, or incorrect.
- type: dropdown
id: doc-type
attributes:
label: Documentation Type
description: Which type of documentation needs attention?
options:
- README.md
- Setup/Installation instructions
- Configuration guide
- API documentation
- Troubleshooting guide
- Code comments
- GitHub issue templates
- Contributing guidelines
- License/Legal documentation
- Other
validations:
required: true
- type: dropdown
id: issue-type
attributes:
label: Issue Type
description: What type of documentation issue is this?
options:
- Missing information
- Incorrect/outdated information
- Unclear instructions
- Typo/grammar error
- Missing examples
- Broken links
- Formatting issues
- Translation needed
- New documentation needed
- Other
validations:
required: true
- type: textarea
id: issue-description
attributes:
label: Issue Description
description: Describe the documentation issue in detail.
validations:
required: true
- type: textarea
id: location
attributes:
label: Location
description: Where is the documentation issue located?
placeholder: |
- File: e.g. README.md, docs/setup.md
- Section: e.g. "Installation", "Configuration"
- Line numbers: e.g. lines 25-30
- URL: if it's online documentation
- type: textarea
id: current-content
attributes:
label: Current Content
description: If applicable, paste the current content that needs to be changed.
- type: textarea
id: suggested-content
attributes:
label: Suggested Improvement
description: What should the documentation say instead? Provide your suggested content.
- type: dropdown
id: priority
attributes:
label: Priority
description: How important is this documentation fix?
options:
- Low - Minor improvement
- Medium - Notable issue
- High - Blocks users/contributors
- Critical - Prevents successful use
validations:
required: true
- type: checkboxes
id: platforms
attributes:
label: Platform Specific
description: Is this documentation issue specific to certain platforms?
options:
- label: Windows-specific
- label: macOS-specific
- label: Linux-specific
- label: Cross-platform issue
- type: checkboxes
id: contribution
attributes:
label: Contribution
description: Are you willing to help improve the documentation?
options:
- label: I can help write/improve the content
- label: I can review proposed changes
- label: I can test the instructions
- label: I can provide examples or screenshots
- type: textarea
id: additional-context
attributes:
label: Additional Context
description: Any other context about this documentation issue.
- type: checkboxes
id: checklist
attributes:
label: Checklist
description: Please confirm the following
options:
- label: I have searched existing issues for similar documentation problems
required: true
- label: I have checked that this documentation issue still exists in the current version
required: true

View File

@@ -0,0 +1,86 @@
name: Feature Request
description: Suggest an idea for OpenList Desktop
title: '[FEATURE] '
labels: ['enhancement', 'needs-triage']
body:
- type: markdown
attributes:
value: |
Thank you for suggesting a new feature! Please fill out the form below to help us understand your request.
- type: textarea
id: feature-description
attributes:
label: Feature Description
description: A clear and concise description of the feature you'd like to see added.
validations:
required: true
- type: textarea
id: problem-statement
attributes:
label: Problem Statement
description: Is your feature request related to a problem? Please describe what problem this feature would solve.
placeholder: I'm always frustrated when...
- type: textarea
id: proposed-solution
attributes:
label: Proposed Solution
description: Describe the solution you'd like to see implemented.
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives Considered
description: Describe any alternative solutions or features you've considered.
- type: dropdown
id: feature-category
attributes:
label: Feature Category
description: Which area of the application does this feature relate to?
options:
- User Interface / UX
- OpenList Service Management
- Rclone / Remote Storage
- Settings / Configuration
- Logging / Monitoring
- Performance / Optimization
- Security / Authentication
- Cross-platform Support
- Auto-updater
- Other
validations:
required: true
- type: checkboxes
id: implementation
attributes:
label: Implementation
description: Check all that apply
options:
- label: I am willing to help implement this feature
- label: This feature requires changes to the frontend (Vue.js)
- label: This feature requires changes to the backend (Rust/Tauri)
- label: This feature requires changes to external binaries (OpenList/Rclone)
- label: This feature affects multiple platforms
- type: textarea
id: additional-context
attributes:
label: Additional Context
description: Add any other context, mockups, or examples about the feature request here.
- type: checkboxes
id: checklist
attributes:
label: Checklist
description: Please confirm the following
options:
- label: I have searched existing issues to ensure this feature hasn't been requested before
required: true
- label: This feature request is specific to OpenList Desktop (not the underlying OpenList or Rclone projects)
required: true

109
.github/ISSUE_TEMPLATE/question.yml vendored Normal file
View File

@@ -0,0 +1,109 @@
name: Question or General Issue
description: Ask a question or report an issue that doesn't fit other categories
title: '[QUESTION] '
labels: ['question', 'needs-triage']
body:
- type: markdown
attributes:
value: |
Have a question or issue that doesn't fit the other categories? Please provide details below.
- type: dropdown
id: question-type
attributes:
label: Question Type
description: What type of question or issue is this?
options:
- General usage question
- Configuration question
- Compatibility question
- Best practices question
- Troubleshooting help
- Unclear behavior
- Integration question
- Development question
- Other
validations:
required: true
- type: textarea
id: question-description
attributes:
label: Question or Issue Description
description: Describe your question or issue in detail.
validations:
required: true
- type: textarea
id: context
attributes:
label: Context
description: Provide any relevant context that might help us understand your question.
placeholder: |
- What are you trying to accomplish?
- What have you already tried?
- What resources have you consulted?
- type: dropdown
id: operating-system
attributes:
label: Operating System
description: What operating system are you using?
options:
- Windows 11
- Windows 10
- macOS (Intel)
- macOS (Apple Silicon)
- Ubuntu
- Other Linux Distribution
- Other
- Not applicable
- type: input
id: app-version
attributes:
label: OpenList Desktop Version
description: What version of OpenList Desktop are you using? (if applicable)
placeholder: e.g. v0.1.0
- type: textarea
id: configuration-details
attributes:
label: Configuration Details
description: If relevant, describe your current configuration.
placeholder: |
- Service settings
- Mount configurations
- Custom binary paths
- Special flags or options
- type: textarea
id: expected-behavior
attributes:
label: Expected Behavior
description: What did you expect to happen? (if applicable)
- type: textarea
id: actual-behavior
attributes:
label: Actual Behavior
description: What actually happened? (if applicable)
- type: textarea
id: additional-info
attributes:
label: Additional Information
description: Any other information that might be helpful.
- type: checkboxes
id: checklist
attributes:
label: Checklist
description: Please confirm the following
options:
- label: I have searched existing issues and discussions for similar questions
required: true
- label: I have checked the documentation and README
required: true
- label: This question is specifically about OpenList Desktop (not general OpenList or Rclone questions)
required: true

134
.github/workflows/auto-version.yml vendored Normal file
View File

@@ -0,0 +1,134 @@
name: 'Auto Version and Release'
on:
workflow_dispatch:
permissions:
contents: write
packages: write
jobs:
check-commits:
runs-on: ubuntu-latest
outputs:
should-release: ${{ steps.check.outputs.should-release }}
version-type: ${{ steps.check.outputs.version-type }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check for conventional commits
id: check
run: |
# Get commits since last tag
LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
if [ -z "$LAST_TAG" ]; then
echo "No previous tag found, will create initial release"
echo "should-release=true" >> $GITHUB_OUTPUT
echo "version-type=minor" >> $GITHUB_OUTPUT
exit 0
fi
COMMITS=$(git log $LAST_TAG..HEAD --oneline)
if echo "$COMMITS" | grep -qE "^[a-f0-9]+ (feat|fix|BREAKING CHANGE)"; then
echo "Found commits that warrant a release"
echo "should-release=true" >> $GITHUB_OUTPUT
# Determine version bump type
if echo "$COMMITS" | grep -q "BREAKING CHANGE"; then
echo "version-type=major" >> $GITHUB_OUTPUT
elif echo "$COMMITS" | grep -q "feat"; then
echo "version-type=minor" >> $GITHUB_OUTPUT
else
echo "version-type=patch" >> $GITHUB_OUTPUT
fi
else
echo "No commits found that warrant a release"
echo "should-release=false" >> $GITHUB_OUTPUT
fi
auto-release:
needs: check-commits
if: needs.check-commits.outputs.should-release == 'true'
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.GITHUB_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 'lts/*'
- name: Calculate new version
id: version
run: |
# Get current version from package.json
CURRENT_VERSION=$(node -p "require('./package.json').version")
echo "Current version: $CURRENT_VERSION"
# Parse version
IFS='.' read -ra VERSION_PARTS <<< "$CURRENT_VERSION"
MAJOR=${VERSION_PARTS[0]}
MINOR=${VERSION_PARTS[1]}
PATCH=${VERSION_PARTS[2]}
# Bump version based on commit type
case "${{ needs.check-commits.outputs.version-type }}" in
major)
MAJOR=$((MAJOR + 1))
MINOR=0
PATCH=0
;;
minor)
MINOR=$((MINOR + 1))
PATCH=0
;;
patch)
PATCH=$((PATCH + 1))
;;
esac
NEW_VERSION="$MAJOR.$MINOR.$PATCH"
echo "New version: $NEW_VERSION"
echo "version=$NEW_VERSION" >> $GITHUB_OUTPUT
echo "tag=v$NEW_VERSION" >> $GITHUB_OUTPUT
- name: Update version in files
run: |
# Update package.json
npm version ${{ steps.version.outputs.version }} --no-git-tag-version
# Update Cargo.toml
sed -i 's/^version = "[^"]*"/version = "${{ steps.version.outputs.version }}"/' src-tauri/Cargo.toml
# Update tauri.conf.json
sed -i 's/"version": "[^"]*"/"version": "${{ steps.version.outputs.version }}"/' src-tauri/tauri.conf.json
- name: Commit version bump
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git add package.json src-tauri/Cargo.toml src-tauri/tauri.conf.json
git commit -m "chore: bump version to ${{ steps.version.outputs.version }} [skip ci]"
git push
- name: Create and push tag
run: |
git tag ${{ steps.version.outputs.tag }}
git push origin ${{ steps.version.outputs.tag }}
- name: Trigger release workflow
run: |
curl -X POST \
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/repos/${{ github.repository }}/actions/workflows/release.yml/dispatches \
-d '{"ref":"main","inputs":{"version":"${{ steps.version.outputs.tag }}"}}'

228
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,228 @@
name: 'Build and Release'
on:
workflow_dispatch:
inputs:
version:
description: 'Version to release (e.g. v1.0.0)'
required: true
type: string
env:
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
# macOS signing and notarization
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
jobs:
changelog:
name: Generate Changelog
runs-on: ubuntu-latest
outputs:
changelog: ${{ steps.changelog.outputs.changelog }}
tag: ${{ steps.tag.outputs.tag }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get tag
id: tag
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
echo "tag=${{ github.event.inputs.version }}" >> $GITHUB_OUTPUT
else
echo "tag=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
fi
- name: Generate changelog
id: changelog
run: |
# Get the previous tag
PREVIOUS_TAG=$(git tag --sort=-version:refname | grep -v "^${{ steps.tag.outputs.tag }}$" | head -n 1)
if [ -z "$PREVIOUS_TAG" ]; then
echo "No previous tag found, generating changelog from first commit"
COMMITS=$(git log --pretty=format:"- %s (%h)" --reverse)
else
echo "Generating changelog from $PREVIOUS_TAG to ${{ steps.tag.outputs.tag }}"
COMMITS=$(git log --pretty=format:"- %s (%h)" $PREVIOUS_TAG..${{ steps.tag.outputs.tag }})
fi
# Create changelog
CHANGELOG="## What's Changed"$'\n\n'"$COMMITS"
# Save to file and output
echo "$CHANGELOG" > changelog.md
echo "changelog<<EOF" >> $GITHUB_OUTPUT
echo "$CHANGELOG" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
- name: Upload changelog
uses: actions/upload-artifact@v4
with:
name: changelog
path: changelog.md
build:
needs: changelog
strategy:
fail-fast: false
matrix:
include:
- platform: 'macos-latest'
args: '--target aarch64-apple-darwin'
target: 'aarch64-apple-darwin'
- platform: 'macos-latest'
args: '--target x86_64-apple-darwin'
target: 'x86_64-apple-darwin'
- platform: 'ubuntu-20.04'
args: '--target x86_64-unknown-linux-gnu'
target: 'x86_64-unknown-linux-gnu'
- platform: 'windows-latest'
args: '--target x86_64-pc-windows-msvc'
target: 'x86_64-pc-windows-msvc'
runs-on: ${{ matrix.platform }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install dependencies (ubuntu only)
if: matrix.platform == 'ubuntu-20.04'
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.0-dev libappindicator3-dev librsvg2-dev patchelf
- name: Rust setup
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- name: Rust cache
uses: swatinem/rust-cache@v2
with:
workspaces: './src-tauri -> target'
- name: Sync node version and setup cache
uses: actions/setup-node@v4
with:
node-version: 'lts/*'
cache: 'npm'
- name: Install frontend dependencies
run: npm ci
- name: Import Apple Developer Certificate (macOS only)
if: matrix.platform == 'macos-latest'
uses: apple-actions/import-codesign-certs@v2
with:
p12-file-base64: ${{ secrets.APPLE_CERTIFICATE }}
p12-password: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
- name: Build the app
uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# macOS signing and notarization environment variables
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
# Enable signing and notarization for macOS
APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
ENABLE_CODE_SIGNING: ${{ matrix.platform == 'macos-latest' && 'true' || 'false' }}
with:
tagName: ${{ needs.changelog.outputs.tag }}
releaseName: 'OpenList Desktop ${{ needs.changelog.outputs.tag }}'
releaseBody: ${{ needs.changelog.outputs.changelog }}
releaseDraft: false
prerelease: false
args: ${{ matrix.args }}
publish:
needs: [changelog, build]
runs-on: ubuntu-latest
if: always() && needs.build.result == 'success'
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Download changelog
uses: actions/download-artifact@v4
with:
name: changelog
- name: Update release
uses: softprops/action-gh-release@v1
with:
tag_name: ${{ needs.changelog.outputs.tag }}
name: 'OpenList Desktop ${{ needs.changelog.outputs.tag }}'
body_path: changelog.md
draft: false
prerelease: false
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Update latest.json for auto-updater
run: |
# Get the latest release info
RELEASE_INFO=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
"https://api.github.com/repos/${{ github.repository }}/releases/latest")
# Extract version and download URLs
VERSION=$(echo "$RELEASE_INFO" | jq -r '.tag_name')
RELEASE_NOTES=$(echo "$RELEASE_INFO" | jq -r '.body')
RELEASE_DATE=$(echo "$RELEASE_INFO" | jq -r '.published_at')
# Create latest.json for Tauri updater
cat > latest.json << EOF
{
"version": "$VERSION",
"notes": $(echo "$RELEASE_NOTES" | jq -R -s .),
"pub_date": "$RELEASE_DATE",
"platforms": {
"darwin-x86_64": {
"signature": "",
"url": "https://github.com/${{ github.repository }}/releases/download/$VERSION/OpenList-Desktop_${VERSION}_x64_mac.dmg.tar.gz"
},
"darwin-aarch64": {
"signature": "",
"url": "https://github.com/${{ github.repository }}/releases/download/$VERSION/OpenList-Desktop_${VERSION}_aarch64_mac.dmg.tar.gz"
},
"linux-x86_64": {
"signature": "",
"url": "https://github.com/${{ github.repository }}/releases/download/$VERSION/openlist-desktop_${VERSION}_amd64.AppImage.tar.gz"
},
"windows-x86_64": {
"signature": "",
"url": "https://github.com/${{ github.repository }}/releases/download/$VERSION/OpenList-Desktop_${VERSION}_x64_en-US.msi.zip"
}
}
}
EOF
echo "Generated latest.json for auto-updater"
cat latest.json
- name: Commit and push latest.json
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
# Check if there are changes to commit
if [[ -n $(git status --porcelain) ]]; then
git add latest.json
git commit -m "Update latest.json for auto-updater [skip ci]"
git push origin HEAD:main
else
echo "No changes to commit"
fi
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

49
.gitignore vendored Normal file
View File

@@ -0,0 +1,49 @@
# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# Tauri
src-tauri/target/
src-tauri/binary/
src-tauri/resources/
# OS
Thumbs.db
# IDE
*.swp
*.swo
# Build outputs
build/
# Config files
.env.local
.env.development.local
.env.test.local
.env.production.local
# Runtime data
data/
mount/
*.pid

18
.prettierrc Normal file
View File

@@ -0,0 +1,18 @@
{
"arrowParens": "avoid",
"bracketSpacing": true,
"htmlWhitespaceSensitivity": "css",
"insertPragma": false,
"jsxBracketSameLine": false,
"jsxSingleQuote": true,
"printWidth": 120,
"proseWrap": "always",
"quoteProps": "as-needed",
"requirePragma": false,
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "none",
"useTabs": false,
"endOfLine": "lf"
}

7
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,7 @@
{
"recommendations": [
"Vue.volar",
"tauri-apps.tauri-vscode",
"rust-lang.rust-analyzer"
]
}

15
.vscode/mcp.json vendored Normal file
View File

@@ -0,0 +1,15 @@
{
"inputs": [
// The "inputs" section defines the inputs required for the MCP server configuration.
{
"type": "promptString"
}
],
"servers": {
// The "servers" section defines the MCP servers you want to use.
"fetch": {
"command": "uvx",
"args": ["mcp-server-fetch"]
}
}
}

37
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,37 @@
{
"[rust]": {
"editor.defaultFormatter": "rust-lang.rust-analyzer",
"editor.formatOnSave": true
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[vue]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[css]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"typescript.tsdk": "node_modules\\typescript\\lib",
// "rust-analyzer.cargo.target": "x86_64-unknown-linux-gnu"
//"rust-analyzer.cargo.target": "x86_64-pc-windows-msvc"
// "rust-analyzer.cargo.target": "x86_64-apple-darwin",
}

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

360
README.md
View File

@@ -1,2 +1,358 @@
# openlist-desktop
A desktop application for OpenList
# OpenList Desktop
<div align="center">
<img src="./app-icon.png" alt="OpenList Desktop" width="128" height="128" />
**跨平台的 OpenList 桌面应用程序,集成云存储功能**
[![License](https://img.shields.io/badge/license-GPL--3.0-blue.svg)](./LICENSE)
[![Vue](https://img.shields.io/badge/Vue-3.5.17-green.svg)](https://vuejs.org/)
[![Tauri](https://img.shields.io/badge/Tauri-2.6.0-orange.svg)](https://tauri.app/)
[![Rust](https://img.shields.io/badge/Rust-2024-red.svg)](https://www.rust-lang.org/)
[English](./README_en.md) | [中文](./README.md)
</div>
## WIP
该项目仍在开发中预计很快发布1.0版本。
## 🔍 概述
OpenList Desktop 是一个功能强大的跨平台桌面应用程序,为管理 OpenList 服务和通过 Rclone 集成云存储提供用户友好的界面。使用现代 Web 技术和 Rust 构建,提供无缝的文件管理、云存储挂载和服务监控功能。
该应用程序是一个全面的解决方案,用于:
- 管理 OpenList 文件管理服务
- 挂载和管理云存储WebDAV
- 监控服务健康和性能
- 提供系统托盘集成以进行后台操作
## ✨ 功能特性
### 🚀 核心功能
- **OpenList 服务管理**:启动、停止和监控 OpenList 核心服务
- **云存储集成**:通过 Rclone 挂载
- **实时监控**:跟踪服务状态、运行时间和性能指标
- **进程管理**:具有自动重启功能的高级进程控制
- **系统托盘**:带系统托盘通知的后台操作
### ⚙️ 管理功能
- **服务控制**:启动/停止/重启 OpenList 和 Rclone 服务
- **配置管理**:所有服务的基于 GUI 的配置
- **日志监控**:实时日志查看和管理
- **更新管理**:自动更新检查和安装
- **自动启动**:配置应用程序与系统一起启动
### 🎨 用户体验
- **现代 UI**:使用 Vue.js 构建的简洁、直观界面
- **多语言**:支持英语和中文
- **响应式设计**:针对各种屏幕尺寸优化
- **键盘快捷键**:使用键盘快捷键高效导航
- **教程系统**:为新用户提供内置教程
## 📸 应用截图
### 主页仪表板
![主页仪表板](./screenshot/homepage.png)
主仪表板提供您的 OpenList Desktop 环境的全面概览:
- 服务状态监控
- 常见任务的快速操作按钮
- 版本管理和更新通知
- 服务管理控制
### 挂载管理
![挂载管理](./screenshot/mountpage.png)
轻松管理您的云存储连接:
- 添加和配置存储远程
- 挂载/卸载云存储
- 监控挂载状态和统计信息
- 配置自动挂载选项
### 设置配置
![设置](./screenshot/settingpage.png)
全面的设置管理:
- OpenList 服务配置
- 启动和自动化偏好设置
- 主题和语言选择
### 日志监控
![日志监控](./screenshot/logpage.png)
跟踪系统操作:
- 实时日志流
- 按来源和级别过滤日志
- 导出和清除日志功能
### 更新管理
![更新管理](./screenshot/update.png)
保持最新版本:
- 检查 OpenList 和 Rclone 更新
- 下载和安装更新
- 版本历史和更新日志
- 自动更新计划
## 📦 安装
### 系统要求
- **操作系统**Windows 10+、macOS 10.15+ 或 LinuxUbuntu 18.04+
### 下载选项
#### 1. GitHub 发布版(推荐)
从 [GitHub Releases](https://github.com/OpenListTeam/openlist-desktop/releases) 下载最新版本:
- **Windows**`OpenList-Desktop_x.x.x_x64_en-US.msi`
- **macOS**`OpenList-Desktop_x.x.x_x64.dmg`
- **Linux**`OpenList-Desktop_x.x.x_amd64.AppImage`
#### 2. 从源码构建
```bash
# 克隆仓库
git clone https://github.com/OpenListTeam/openlist-desktop.git
cd openlist-desktop
# 安装依赖
npm install
# 准备开发环境
npm run prepare-dev
# 构建应用程序
npm run build
npm run tauri build
```
### 安装步骤
#### Windows
1. 下载 `.msi` 安装程序
2. 以管理员身份运行安装程序
3. 按照安装向导进行操作
4. 从开始菜单或桌面快捷方式启动
#### macOS
1. 下载 `.dmg` 文件
2. 打开 DMG 并将 OpenList Desktop 拖到应用程序文件夹
3. 右键单击并选择"打开"(仅首次)
4. 在提示时授予必要权限
#### Linux
1. 下载 `.AppImage` 文件
2. 使其可执行:`chmod +x OpenList-Desktop*.AppImage`
3. 运行 AppImage`./OpenList-Desktop*.AppImage`
4. 可选:使用 AppImageLauncher 安装以进行系统集成
## 🚀 使用说明
### 首次启动
1. **初始设置**:首次启动时,应用程序将指导您完成初始配置
2. **服务安装**:在提示时安装 OpenList 服务
3. **存储配置**:配置您的第一个云存储连接
4. **教程**:完成交互式教程以学习关键功能
### 基本操作
#### 启动服务
```
仪表板 → 服务管理 → 启动 OpenList 服务
仪表板 → 快速操作 → 启动 Rclone 后端
```
#### 添加云存储
1. 导航到 **挂载** 选项卡
2. 点击 **添加远程** 按钮
3. 配置存储设置:
- **名称**:存储的唯一标识符
- **类型**存储提供商WebDAV
- **URL**:存储端点 URL
- **凭据**:用户名和密码
- **挂载点**:本地目录路径
4. 点击 **保存****挂载**
#### 监控操作
- **服务状态**:检查仪表板上的服务健康指示器
- **日志**:使用日志选项卡监控系统操作
- **性能**:在仪表板上查看运行时间和响应指标
### 高级功能
#### 自动挂载配置
```javascript
// 配置存储在启动时自动挂载
{
"autoMount": true,
"extraFlags": ["--vfs-cache-mode", "full"],
"mountPoint": "/mnt/cloudstorage"
}
```
#### 自定义 Rclone 标志
添加自定义 Rclone 标志以获得最佳性能:
- `--vfs-cache-mode full`:启用完整 VFS 缓存
- `--buffer-size 256M`:增加缓冲区大小
- `--transfers 10`:并发传输限制
#### 系统托盘操作
- **右键单击托盘图标** 进行快速操作
- **双击** 显示/隐藏主窗口
- **服务状态** 通过图标颜色指示
## ⚙️ 配置
### 应用程序设置
#### OpenList 服务配置
```json
{
"openlist": {
"port": 5244,
"api_token": "your-secure-token",
"auto_launch": true,
"ssl_enabled": false
}
}
```
#### Rclone 配置
```json
{
"rclone": {
"config": {
"mycloud": {
"type": "webdav",
"url": "https://cloud.example.com/dav",
"user": "username",
"pass": "encrypted-password",
"mountPoint": "C:/CloudDrive",
"autoMount": true,
"extraFlags": ["--vfs-cache-mode", "full"]
}
},
"auto_mount": true
}
}
```
#### 应用程序偏好设置
```json
{
"app": {
"theme": "auto",
"language": "zh",
"auto_update_enabled": true,
"monitor_interval": 30000
}
}
```
### 环境变量
- `OPENLIST_API_TOKEN`:覆盖默认 API 令牌
- `OPENLIST_PORT`覆盖默认端口5244
- `RCLONE_CONFIG_DIR`:自定义 Rclone 配置目录
- `LOG_LEVEL`设置日志级别debug、info、warn、error
## 🔧 开发
### 开发环境设置
#### 先决条件
- **Node.js**v18+ 和 npm
- **Rust**:最新稳定版本
- **Git**:版本控制
#### 设置步骤
```bash
# 克隆仓库
git clone https://github.com/OpenListTeam/openlist-desktop.git
cd openlist-desktop
# 安装 Node.js 依赖
npm install
# 安装 Rust 依赖
cd src-tauri
cargo fetch
# 准备开发环境
cd ..
npm run prepare-dev
# 启动开发服务器
npm run dev
```
#### 开发命令
```bash
# 启动带热重载的开发服务器
npm run dev
# 启动不带文件监视的开发
npm run nowatch
# 运行代码检查
npm run lint
# 修复代码检查问题
npm run lint:fix
# 类型检查
npm run build --dry-run
```
## 🤝 贡献
我们欢迎社区贡献!
## 📄 许可证
本项目在 **GNU 通用公共许可证 v3.0** 下许可 - 详情请参见 [LICENSE](./LICENSE) 文件。
---
<div align="center">
<p>由 OpenList 团队用 ❤️ 制作</p>
<p>
<a href="https://github.com/OpenListTeam/openlist-desktop">GitHub</a> •
<a href="https://openlist.team">网站</a> •
<a href="https://t.me/OpenListTeam">Telegram</a>
</p>
</div>

357
README_en.md Normal file
View File

@@ -0,0 +1,357 @@
# OpenList Desktop
<div align="center">
<img src="./app-icon.png" alt="OpenList Desktop" width="128" height="128" />
**A cross-platform desktop application for OpenList with cloud storage integration**
[![License](https://img.shields.io/badge/license-GPL--3.0-blue.svg)](./LICENSE)
[![Vue](https://img.shields.io/badge/Vue-3.5.17-green.svg)](https://vuejs.org/)
[![Tauri](https://img.shields.io/badge/Tauri-2.6.0-orange.svg)](https://tauri.app/)
[![Rust](https://img.shields.io/badge/Rust-2024-red.svg)](https://www.rust-lang.org/)
[English](./README.md) | [中文](./README_zh.md)
</div>
## WIP
This project is still under development and will soon release version 1.0.
## 🔍 Overview
OpenList Desktop is a powerful cross-platform desktop application that provides a user-friendly interface for managing OpenList services and integrating cloud storage through Rclone. Built with modern web technologies and Rust, it offers seamless file management, cloud storage mounting, and service monitoring capabilities.
The application serves as a comprehensive solution for:
- Managing OpenList file management services
- Mounting and managing cloud storage (WebDAV)
- Monitoring service health and performance
- Providing system tray integration for background operations
## ✨ Features
### 🚀 Core Features
- **OpenList Service Management**: Start, stop, and monitor OpenList core services
- **Cloud Storage Integration**: Mount via Rclone
- **Real-time Monitoring**: Track service status, uptime, and performance metrics
- **Process Management**: Advanced process control with auto-restart capabilities
- **System Tray**: Background operation with system tray notifications
### ⚙️ Management Features
- **Service Control**: Start/stop/restart OpenList and Rclone services
- **Configuration Management**: GUI-based configuration for all services
- **Log Monitoring**: Real-time log viewing and management
- **Update Management**: Automatic update checking and installation
- **Auto-startup**: Configure applications to start with system boot
### 🎨 User Experience
- **Modern UI**: Clean, intuitive interface built with Vue.js
- **Multi-language**: Support for English and Chinese
- **Responsive Design**: Optimized for various screen sizes
- **Keyboard Shortcuts**: Efficient navigation with keyboard shortcuts
- **Tutorial System**: Built-in tutorial for new users
## 📸 Screenshots
### Home Dashboard
![Home Dashboard](./screenshot/homepage.png)
The main dashboard provides a comprehensive overview of your OpenList Desktop environment with:
- Service status monitoring
- Quick action buttons for common tasks
- Version management and update notifications
- Service management controls
### Mount Management
![Mount Management](./screenshot/mountpage.png)
Manage your cloud storage connections with ease:
- Add and configure storage remotes
- Mount/unmount cloud storage
- Monitor mount status and statistics
- Configure auto-mounting options
### Settings Configuration
![Settings](./screenshot/settingpage.png)
Comprehensive settings management:
- OpenList service configuration
- Startup and automation preferences
- Theme and language selection
### Log Monitoring
![Log Monitoring](./screenshot/logpage.png)
Keep track of system operations:
- Real-time log streaming
- Filter logs by source and level
- Export and clear log functionality
### Update Management
![Update Management](./screenshot/update.png)
Stay up-to-date with the latest versions:
- Check for OpenList and Rclone updates
- Download and install updates
- Version history and changelog
- Automatic update scheduling
## 📦 Installation
### Prerequisites
- **Operating System**: Windows 10+, macOS 10.15+, or Linux (Ubuntu 18.04+)
### Download Options
#### 1. GitHub Releases (Recommended)
Download the latest release from [GitHub Releases](https://github.com/OpenListTeam/openlist-desktop/releases):
- **Windows**: `OpenList-Desktop_x.x.x_x64_en-US.msi`
- **macOS**: `OpenList-Desktop_x.x.x_x64.dmg`
- **Linux**: `OpenList-Desktop_x.x.x_amd64.AppImage`
#### 2. Build from Source
```bash
# Clone the repository
git clone https://github.com/OpenListTeam/openlist-desktop.git
cd openlist-desktop
# Install dependencies
npm install
# Prepare development environment
npm run prepare-dev
# Build the application
npm run build
npm run tauri build
```
### Installation Steps
#### Windows
1. Download the `.msi` installer
2. Run the installer as Administrator
3. Follow the installation wizard
4. Launch from Start Menu or Desktop shortcut
#### macOS
1. Download the `.dmg` file
2. Open the DMG and drag OpenList Desktop to Applications
3. Right-click and select "Open" (first time only)
4. Grant necessary permissions when prompted
#### Linux
1. Download the `.AppImage` file
2. Make it executable: `chmod +x OpenList-Desktop*.AppImage`
3. Run the AppImage: `./OpenList-Desktop*.AppImage`
4. Optional: Install using AppImageLauncher for system integration
## 🚀 Usage
### First Launch
1. **Initial Setup**: On first launch, the application will guide you through initial configuration
2. **Service Installation**: Install the OpenList service when prompted
3. **Storage Configuration**: Configure your first cloud storage connection
4. **Tutorial**: Complete the interactive tutorial to learn key features
### Basic Operations
#### Starting Services
```
Dashboard → Service Management → Start OpenList Service
Dashboard → Quick Actions → Start Rclone Backend
```
#### Adding Cloud Storage
1. Navigate to **Mount** tab
2. Click **Add Remote** button
3. Configure storage settings:
- **Name**: Unique identifier for your storage
- **Type**: Storage provider (WebDAV)
- **URL**: Storage endpoint URL
- **Credentials**: Username and password
- **Mount Point**: Local directory path
4. Click **Save** and **Mount**
#### Monitoring Operations
- **Service Status**: Check the dashboard for service health indicators
- **Logs**: Use the Logs tab to monitor system operations
- **Performance**: View uptime and response metrics on the dashboard
### Advanced Features
#### Auto-mounting Configuration
```javascript
// Configure storage to mount automatically on startup
{
"autoMount": true,
"extraFlags": ["--vfs-cache-mode", "full"],
"mountPoint": "/mnt/cloudstorage"
}
```
#### Custom Rclone Flags
Add custom Rclone flags for optimal performance:
- `--vfs-cache-mode full`: Enable full VFS caching
- `--buffer-size 256M`: Increase buffer size
- `--transfers 10`: Concurrent transfer limit
#### System Tray Operations
- **Right-click tray icon** for quick actions
- **Double-click** to show/hide main window
- **Service status** indicated by icon color
## ⚙️ Configuration
### Application Settings
#### OpenList Service Configuration
```json
{
"openlist": {
"port": 5244,
"api_token": "your-secure-token",
"auto_launch": true,
"ssl_enabled": false
}
}
```
#### Rclone Configuration
```json
{
"rclone": {
"config": {
"mycloud": {
"type": "webdav",
"url": "https://cloud.example.com/dav",
"user": "username",
"pass": "encrypted-password",
"mountPoint": "C:/CloudDrive",
"autoMount": true,
"extraFlags": ["--vfs-cache-mode", "full"]
}
},
"auto_mount": true
}
}
```
#### Application Preferences
```json
{
"app": {
"theme": "auto",
"language": "en",
"auto_update_enabled": true,
"monitor_interval": 30000
}
}
```
### Environment Variables
- `OPENLIST_API_TOKEN`: Override default API token
- `OPENLIST_PORT`: Override default port (5244)
- `RCLONE_CONFIG_DIR`: Custom Rclone configuration directory
- `LOG_LEVEL`: Set logging level (debug, info, warn, error)
## 🔧 Development
### Development Environment Setup
#### Prerequisites
- **Node.js**: v18+ with npm
- **Rust**: Latest stable version
- **Git**: Version control
#### Setup Steps
```bash
# Clone repository
git clone https://github.com/OpenListTeam/openlist-desktop.git
cd openlist-desktop
# Install Node.js dependencies
npm install
# Install Rust dependencies
cd src-tauri
cargo fetch
# Prepare development environment
cd ..
npm run prepare-dev
# Start development server
npm run dev
```
#### Development Commands
```bash
# Start development server with hot reload
npm run dev
# Start development without file watching
npm run nowatch
# Run linting
npm run lint
# Fix linting issues
npm run lint:fix
# Type checking
npm run build --dry-run
```
## 🤝 Contributing
We welcome contributions from the community!
## 📄 License
This project is licensed under the **GNU General Public License v3.0** - see the [LICENSE](./LICENSE) file for details.
---
<div align="center">
<p>Made with ❤️ by the OpenList Team</p>
<p>
<a href="https://github.com/OpenListTeam/openlist-desktop">GitHub</a> •
<a href="https://openlist.team">Website</a> •
<a href="https://t.me/OpenListTeam">Telegram</a>
</p>
</div>

BIN
app-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 418 KiB

106
eslint.config.mjs Normal file
View File

@@ -0,0 +1,106 @@
// @ts-check
import eslint from '@eslint/js'
import simpleImportSort from 'eslint-plugin-simple-import-sort'
import eslintPluginUnicorn from 'eslint-plugin-unicorn'
import globals from 'globals'
import tseslint from 'typescript-eslint'
export default tseslint.config(
{
files: ['./src/*.{ts,tsx,cts,mts,js,cjs,mjs}', './scripts/*.{ts,js,mjs}', './test/*.{ts,js,mjs}']
},
{
ignores: [
'**/node_modules/**',
'**/dist/**',
'vitest.workspace.mjs',
'cases/**',
'test/**',
'benchmark/**',
'webpack.config.js',
'bin/*'
]
},
eslint.configs.recommended,
...tseslint.configs.recommended,
...tseslint.configs.stylistic,
{
plugins: {
'simple-import-sort': simpleImportSort,
unicorn: eslintPluginUnicorn
},
rules: {
'simple-import-sort/imports': 'error',
'simple-import-sort/exports': 'error'
}
},
{
languageOptions: {
parserOptions: {
warnOnUnsupportedTypeScriptVersion: false
},
globals: globals.node
}
},
{
rules: {
eqeqeq: 'error',
'no-caller': 'error',
'no-constant-condition': ['error', { checkLoops: false }],
'no-eval': 'error',
'no-extra-bind': 'error',
'no-new-func': 'error',
'no-new-wrappers': 'error',
'no-throw-literal': 'error',
'no-undef-init': 'error',
'no-var': 'error',
'object-shorthand': 'error',
'prefer-const': 'error',
'prefer-object-spread': 'error',
'unicode-bom': ['error', 'never'],
// Enabled in eslint:recommended, but not applicable here
'no-extra-boolean-cast': 'off',
'no-case-declarations': 'off',
'no-cond-assign': 'off',
'no-control-regex': 'off',
'no-inner-declarations': 'off',
'no-empty': 'off',
// @typescript-eslint/eslint-plugin
'no-unused-expressions': 'off',
'@typescript-eslint/no-unused-expressions': 'off',
'@typescript-eslint/ban-ts-comment': 'off',
'@typescript-eslint/class-literal-property-style': 'off',
'@typescript-eslint/consistent-indexed-object-style': 'off',
'@typescript-eslint/consistent-generic-constructors': 'off',
'@typescript-eslint/no-duplicate-enum-values': 'off',
'@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/no-namespace': 'off',
'@typescript-eslint/no-non-null-asserted-optional-chain': 'off',
'@typescript-eslint/no-var-requires': 'off',
'@typescript-eslint/no-empty-interface': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-empty-object-type': 'off', // {} is a totally useful and valid type.
'@typescript-eslint/no-require-imports': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/no-inferrable-types': 'off',
// Pending https://github.com/typescript-eslint/typescript-eslint/issues/4820
'@typescript-eslint/prefer-optional-chain': 'off',
'unicorn/prefer-node-protocol': 'error'
}
},
{
files: ['**/*.mjs', '**/*.mts'],
rules: {
// These globals don't exist outside of CJS files.
'no-restricted-globals': [
'error',
{ name: '__filename' },
{ name: '__dirname' },
{ name: 'require' },
{ name: 'module' },
{ name: 'exports' }
]
}
}
)

14
index.html Normal file
View File

@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>OpenList Desktop</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

84
package.json Normal file
View File

@@ -0,0 +1,84 @@
{
"name": "openlist-desktop",
"description": "A desktop application for OpenList",
"keywords": [
"openlist",
"desktop",
"application",
"vue",
"tauri"
],
"private": true,
"version": "0.1.0",
"author": {
"name": "OpenList Team",
"email": "96409857+Kuingsmile@users.noreply.github.com"
},
"type": "module",
"license": "GPL-3.0",
"homepage": "https://github.com/OpenListTeam/openlist-desktop",
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview",
"tauri": "tauri",
"nowatch": "tauri dev --no-watch",
"lint": "eslint src/**/*.ts",
"lint:fix": "eslint src/**/*.ts --fix",
"cz": "git-cz",
"release": "bump-version",
"prepare-dev": "node scripts/prepare.js"
},
"config": {
"commitizen": {
"path": "./node_modules/cz-customizable"
},
"cz-customizable": {
"config": "./node_modules/node-bump-version/.cz-config.cjs"
}
},
"commitlint": {
"extends": [
"./node_modules/node-bump-version/dist/commitlint-node/index.js"
]
},
"dependencies": {
"@headlessui/vue": "^1.7.23",
"@tauri-apps/api": "^2.6.0",
"@tauri-apps/plugin-autostart": "^2.5.0",
"@tauri-apps/plugin-dialog": "^2.3.0",
"@tauri-apps/plugin-fs": "^2.4.0",
"@tauri-apps/plugin-opener": "^2.4.0",
"@tauri-apps/plugin-process": "^2.3.0",
"@tauri-apps/plugin-shell": "^2.3.0",
"@tauri-apps/plugin-store": "^2.3.0",
"@vueuse/core": "^13.4.0",
"chrono-node": "^2.8.3",
"dexie": "^4.0.11",
"lucide-vue-next": "^0.523.0",
"pinia": "^3.0.3",
"vue": "^3.5.17",
"vue-i18n": "11.1.7",
"vue-router": "^4.5.1"
},
"devDependencies": {
"@tauri-apps/cli": "^2.6.0",
"@types/node": "^22.9.3",
"@typescript-eslint/eslint-plugin": "^8.35.0",
"@typescript-eslint/parser": "^8.35.0",
"@vitejs/plugin-vue": "^6.0.0",
"adm-zip": "^0.5.16",
"eslint": "^9.29.0",
"eslint-plugin-simple-import-sort": "^12.1.1",
"eslint-plugin-unicorn": "^59.0.1",
"fs-extra": "^11.3.0",
"https-proxy-agent": "^7.0.6",
"node-bump-version": "^2.0.0",
"node-fetch": "^3.3.2",
"tar": "^7.4.3",
"typescript": "^5.8.3",
"typescript-eslint": "^8.35.0",
"vite": "^7.0.0",
"vue-tsc": "^2.2.10"
}
}

10
public/tauri.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 6.1 KiB

10
public/vite.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 6.1 KiB

BIN
screenshot/homepage.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

BIN
screenshot/logpage.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

BIN
screenshot/mountpage.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

BIN
screenshot/settingpage.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

BIN
screenshot/update.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

181
scripts/prepare.js Normal file
View File

@@ -0,0 +1,181 @@
import { execSync } from 'node:child_process'
import path from 'node:path'
import AdmZip from 'adm-zip'
import fs from 'fs-extra'
import fetch from 'node-fetch'
import { extract } from 'tar'
import { downloadFile, getFetchOptions, getOpenlistArchMap, getRcloneArchMap, platformIdentifierMap } from './utils.js'
const cwd = process.cwd()
const target = process.argv.find(arg => arg.startsWith('--target='))?.slice(9)
const platformArch = target ? platformIdentifierMap[target] : `${process.platform}-${process.arch}`
const [platform, arch] = platformArch.split('-')
const isWin = platform === 'win32'
console.log(`platform: ${platform}, arch: ${arch}`)
const sidecarHost =
target ||
execSync('rustc -vV')
.toString()
.match(/(?<=host: ).+(?=\s*)/g)[0]
if (!getOpenlistArchMap[platformArch]) {
throw new Error(`Unsupported target: ${platformArch}. Supported: ${Object.keys(getOpenlistArchMap).join(', ')}`)
}
// Rclone version management
let rcloneVersion = 'v1.70.0'
const rcloneVersionUrl = 'https://github.com/rclone/rclone/releases/latest/download/version.txt'
async function getLatestRcloneVersion() {
try {
const response = await fetch(rcloneVersionUrl, getFetchOptions())
rcloneVersion = (await response.text()).trim().replace('rclone ', '')
console.log(`Latest rclone version: ${rcloneVersion}`)
} catch (error) {
console.log('Error fetching latest rclone version:', error.message)
}
}
// openlist version management
let openlistVersion = 'v4.0.0'
async function getLatestOpenlistVersion() {
try {
const response = await fetch(
'https://api.github.com/repos/OpenListTeam/OpenList/releases/latest',
getFetchOptions()
)
const data = await response.json()
openlistVersion = data.tag_name
console.log(`Latest OpenList version: ${openlistVersion}`)
} catch (error) {
console.log('Error fetching latest OpenList version:', error.message)
}
}
const createBinaryInfo = (name, archMap, baseUrl, version = '') => {
const zipName = archMap[platformArch]
return {
name,
targetFile: `${name}-${sidecarHost}${isWin ? '.exe' : ''}`,
exeFile: `${name}${isWin ? '.exe' : ''}`,
zipFile: zipName,
downloadURL: `${baseUrl}${version ? `/${version}` : ''}/${zipName}`
}
}
// OpenList service URL
const serviceUrl = `https://github.com/Kuingsmile/openlist-desktop-service/releases/download/${sidecarHost}`
const getServiceInfo = exeName => {
const ext = isWin ? '.exe' : ''
const suffix = '-' + sidecarHost
return {
file: exeName + suffix + ext,
downloadURL: `${serviceUrl}/${exeName}${ext}`
}
}
async function resolveSidecar(binInfo) {
const { name, targetFile, zipFile, exeFile, downloadURL } = binInfo
const binaryDir = path.join(cwd, 'src-tauri', 'binary')
const binaryPath = path.join(binaryDir, targetFile)
await fs.mkdir(binaryDir, { recursive: true })
const zipPath = path.join(binaryDir, zipFile)
try {
await downloadFile(downloadURL, zipPath)
if (zipFile.endsWith('.zip')) {
const zip = new AdmZip(zipPath)
zip.extractAllTo(binaryDir, true)
if (name === 'rclone') {
const extractedDir = path.join(binaryDir, zipFile.replace('.zip', ''))
await fs.rename(path.join(extractedDir, exeFile), binaryPath)
await fs.remove(extractedDir)
} else {
await fs.rename(path.join(binaryDir, exeFile), binaryPath)
}
} else {
await extract({ cwd: binaryDir, file: zipPath })
await fs.rename(path.join(binaryDir, exeFile), binaryPath)
}
await fs.remove(zipPath)
await fs.chmod(binaryPath, 0o755)
} catch (err) {
console.error(`Error preparing "${name}":`, err.message)
await fs.rm(binaryPath, { recursive: true, force: true })
throw err
}
}
async function resolveService(resourceInfo, isChmod = true, defaultMode = 0o755) {
const { file, downloadURL } = resourceInfo
const resourceDir = path.join(cwd, 'src-tauri', 'binary')
const resourcePath = path.join(resourceDir, file)
await fs.mkdir(resourceDir, { recursive: true })
try {
await downloadFile(downloadURL, resourcePath)
if (isChmod) {
await fs.chmod(resourcePath, defaultMode)
}
console.log(`"${file}" downloaded to ${resourcePath}`)
} catch (err) {
console.error(`Error preparing "${file}":`, err.message)
await fs.rm(resourcePath, { recursive: true, force: true })
throw err
}
}
async function retryTask(name, fn, maxRetries = 5) {
for (let i = 0; i < maxRetries; i++) {
try {
console.log(`task::${name} try ${i}`)
await fn()
return
} catch (err) {
console.log(`task::${name} try ${i} ==`, err.message)
if (i === maxRetries - 1) throw err
}
}
}
async function main() {
await getLatestOpenlistVersion()
await retryTask('openlist', () =>
resolveSidecar(
createBinaryInfo(
'openlist',
getOpenlistArchMap,
'https://github.com/OpenListTeam/OpenList/releases/download',
openlistVersion
)
)
)
await retryTask('rclone', async () => {
await getLatestRcloneVersion()
await resolveSidecar(
createBinaryInfo(
'rclone',
getRcloneArchMap(rcloneVersion),
'https://github.com/rclone/rclone/releases/download',
rcloneVersion
)
)
})
await resolveService(getServiceInfo('install-openlist-service'))
await resolveService(getServiceInfo('openlist-desktop-service'))
await resolveService(getServiceInfo('uninstall-openlist-service'))
}
main().catch(console.log)

51
scripts/utils.js Normal file
View File

@@ -0,0 +1,51 @@
import fs from 'fs-extra'
import { HttpsProxyAgent } from 'https-proxy-agent'
import fetch from 'node-fetch'
export const platformIdentifierMap = {
'x86_64-pc-windows-msvc': 'win32-x64',
'i686-pc-windows-msvc': 'win32-ia32',
'aarch64-pc-windows-msvc': 'win32-arm64',
'x86_64-apple-darwin': 'darwin-x64',
'aarch64-apple-darwin': 'darwin-arm64',
'x86_64-unknown-linux-gnu': 'linux-x64',
'i686-unknown-linux-gnu': 'linux-ia32',
'aarch64-unknown-linux-gnu': 'linux-arm64',
'armv7-unknown-linux-gnueabihf': 'linux-arm'
}
const archMaps = {
'win32-x64': { openlist: 'windows-amd64', rclone: 'windows-amd64' },
'win32-ia32': { openlist: 'windows-386', rclone: 'windows-386' },
'win32-arm64': { openlist: 'windows-arm64', rclone: 'windows-arm64' },
'darwin-x64': { openlist: 'darwin-amd64', rclone: 'osx-amd64' },
'darwin-arm64': { openlist: 'darwin-arm64', rclone: 'osx-arm64' },
'linux-x64': { openlist: 'linux-amd64', rclone: 'linux-amd64' },
'linux-ia32': { openlist: 'linux-386', rclone: 'linux-386' },
'linux-arm64': { openlist: 'linux-arm64', rclone: 'linux-arm64' },
'linux-arm': { openlist: 'linux-arm-7', rclone: 'linux-arm-v7' }
}
export const getOpenlistArchMap = Object.fromEntries(
Object.entries(archMaps).map(([key, { openlist }]) => [
key,
`openlist-${openlist}.${key.startsWith('darwin') || key.startsWith('linux') ? 'tar.gz' : 'zip'}`
])
)
export const getRcloneArchMap = version =>
Object.fromEntries(Object.entries(archMaps).map(([key, { rclone }]) => [key, `rclone-${version}-${rclone}.zip`]))
export async function downloadFile(url, path) {
const response = await fetch(url, {
...getFetchOptions(),
headers: { 'Content-Type': 'application/octet-stream' }
})
await fs.writeFile(path, new Uint8Array(await response.arrayBuffer()))
console.log(`download finished: ${url}`)
}
export const getFetchOptions = () => {
const proxy = process.env.HTTP_PROXY || process.env.http_proxy || process.env.HTTPS_PROXY || process.env.https_proxy
return proxy ? { agent: new HttpsProxyAgent(proxy) } : {}
}

7
src-tauri/.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas

7030
src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

69
src-tauri/Cargo.toml Normal file
View File

@@ -0,0 +1,69 @@
[package]
name = "openlist-desktop"
version = "0.1.0"
description = "A Tauri App"
authors = ["Kuingsmile"]
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
# The `_lib` suffix may seem redundant but it is necessary
# to make the lib name unique and wouldn't conflict with the bin name.
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
name = "openlist_desktop_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = ["tray-icon"] }
tauri-plugin-opener = "2"
tauri-plugin-process = "2"
tauri-plugin-fs = "2"
tauri-plugin-dialog = "2"
tauri-plugin-shell = "2"
tauri-plugin-store = "2"
tauri-plugin-autostart = "2.4.0"
tauri-plugin-single-instance = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
anyhow = "1.0"
thiserror = "1.0"
chrono = { version = "0.4", features = ["serde"] }
log = "0.4"
log4rs = "1.3.0"
env_logger = "0.11"
dirs = "5.0"
open = "5.3.2"
reqwest = { version = "0.12.20", features = ["json", "rustls-tls", "cookies"] }
once_cell = "1.21.3"
parking_lot = "0.12.4"
url = "2.5.4"
sysinfo = "0.32"
lazy_static = "1.5.0"
base64 = "0.22"
zip = "2.2"
tar = "0.4"
flate2 = "1.0"
regex = "1.10"
[target.'cfg(windows)'.dependencies]
runas = "=1.2.0"
deelevate = "0.2.0"
windows-service = "0.8.0"
[target.'cfg(target_os = "linux")'.dependencies]
users = "0.11.0"
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-single-instance = "2"
[profile.release]
panic = "abort"
codegen-units = 1
lto = true
opt-level = "s"
strip = true

3
src-tauri/build.rs Normal file
View File

@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

View File

@@ -0,0 +1,22 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:default",
"opener:default",
"core:window:default",
"core:window:allow-minimize",
"core:window:allow-maximize",
"core:window:allow-unmaximize",
"core:window:allow-close",
"core:window:allow-is-maximized",
"core:window:allow-start-dragging",
"core:window:allow-toggle-maximize",
"core:window:allow-internal-toggle-maximize",
"autostart:allow-enable",
"autostart:allow-disable",
"autostart:allow-is-enabled"
]
}

BIN
src-tauri/icons/128x128.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

BIN
src-tauri/icons/32x32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

BIN
src-tauri/icons/64x64.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

BIN
src-tauri/icons/icon.icns Normal file

Binary file not shown.

BIN
src-tauri/icons/icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

BIN
src-tauri/icons/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 958 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View File

@@ -0,0 +1,9 @@
[Desktop Entry]
Categories={{{categories}}}
Comment={{{comment}}}
Exec={{{exec}}} %u
StartupWMClass={{{exec}}}
Icon={{{icon}}}
Name={{{name}}}
Terminal=false
Type=Application

View File

@@ -0,0 +1,4 @@
#!/bin/bash
chmod +x /usr/bin/install-openlist-service
chmod +x /usr/bin/uninstall-openlist-service
chmod +x /usr/bin/openlist-desktop-service

View File

@@ -0,0 +1,2 @@
#!/bin/bash
/usr/bin/uninstall-openlist-service

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<false/>
<key>com.apple.security.application-groups</key>
<array>
<string>io.github.openlistteam.openlist.desktop</string>
</array>
<key>com.apple.security.inherit</key>
<true/>
</dict>
</plist>

File diff suppressed because it is too large Load Diff

49
src-tauri/rustfmt.toml Normal file
View File

@@ -0,0 +1,49 @@
max_width = 100
hard_tabs = false
tab_spaces = 4
newline_style = "Auto"
edition = "2024"
reorder_imports = true
reorder_modules = true
imports_granularity = "Crate"
group_imports = "StdExternalCrate"
use_small_heuristics = "Default"
remove_nested_parens = true
merge_derives = true
use_try_shorthand = true
use_field_init_shorthand = true
force_explicit_abi = true
fn_single_line = false
where_single_line = false
force_multiline_blocks = false
brace_style = "SameLineWhere"
format_strings = false
format_macro_matchers = true
normalize_comments = true
normalize_doc_attributes = false
wrap_comments = true
comment_width = 80
trailing_comma = "Vertical"
trailing_semicolon = true
spaces_around_ranges = false
binop_separator = "Front"
chain_width = 60
match_block_trailing_comma = false
match_arm_blocks = true
control_brace_style = "AlwaysSameLine"
single_line_if_else_max_width = 50
blank_lines_upper_bound = 1
blank_lines_lower_bound = 0
empty_item_single_line = true
struct_lit_single_line = true
fn_params_layout = "Tall"

View File

@@ -0,0 +1,33 @@
use std::env;
use std::process::Command;
#[tauri::command]
pub async fn get_binary_version(binary_name: Option<String>) -> Result<String, String> {
let app_dir = env::current_exe().unwrap().parent().unwrap().to_path_buf();
let binary_path = if cfg!(windows) {
app_dir.join(format!(
"{}.exe",
binary_name.unwrap_or("openlist".to_string())
))
} else {
app_dir.join(binary_name.unwrap_or("openlist".to_string()))
};
let output = Command::new(binary_path)
.arg("version")
.output()
.map_err(|e| e.to_string())?;
if output.status.success() {
let version_output = String::from_utf8_lossy(&output.stdout);
let version_line = version_output
.lines()
.find(|line| line.starts_with("Version:") || line.starts_with("rclone"))
.ok_or("Version not found in output")?;
let version = version_line
.split_whitespace()
.nth(1)
.ok_or("Failed to parse version")?;
return Ok(version.to_string());
} else {
return Err("Failed to get OpenList binary version".to_string());
}
}

View File

@@ -0,0 +1,40 @@
use std::fs;
use tauri::State;
use crate::conf::config::MergedSettings;
use crate::object::structs::AppState;
use crate::utils::path::app_config_file_path;
#[tauri::command]
pub async fn save_settings(
settings: MergedSettings,
state: State<'_, AppState>,
) -> Result<bool, String> {
state.update_settings(settings.clone());
let settings_path = app_config_file_path().map_err(|e| e.to_string())?;
let settings_json = serde_json::to_string_pretty(&settings).map_err(|e| e.to_string())?;
fs::write(settings_path, settings_json).map_err(|e| e.to_string())?;
log::info!("Settings saved successfully");
Ok(true)
}
#[tauri::command]
pub async fn load_settings(state: State<'_, AppState>) -> Result<Option<MergedSettings>, String> {
state.load_settings()?;
Ok(state.get_settings())
}
#[tauri::command]
pub async fn reset_settings(state: State<'_, AppState>) -> Result<Option<MergedSettings>, String> {
let default_settings = MergedSettings::default();
state.update_settings(default_settings.clone());
let settings_path = app_config_file_path().map_err(|e| e.to_string())?;
let settings_json =
serde_json::to_string_pretty(&default_settings).map_err(|e| e.to_string())?;
fs::write(settings_path, settings_json).map_err(|e| e.to_string())?;
log::info!("Settings reset to default");
Ok(Some(default_settings))
}

View File

@@ -0,0 +1,537 @@
use crate::{cmd::config::save_settings, object::structs::AppState};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::env;
use std::path::PathBuf;
use std::process::Command;
use std::time::Duration;
use tauri::{AppHandle, Emitter, State};
use tokio::io::AsyncWriteExt;
#[derive(Debug, Serialize, Deserialize)]
pub struct GitHubRelease {
tag_name: String,
name: String,
body: String,
published_at: String,
assets: Vec<GitHubAsset>,
prerelease: bool,
draft: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct GitHubAsset {
id: u64,
name: String,
size: u64,
download_count: u64,
browser_download_url: String,
content_type: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateAsset {
name: String,
url: String,
size: u64,
platform: String,
#[serde(rename = "type")]
asset_type: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateCheck {
#[serde(rename = "hasUpdate")]
has_update: bool,
#[serde(rename = "currentVersion")]
current_version: String,
#[serde(rename = "latestVersion")]
latest_version: String,
#[serde(rename = "releaseDate")]
release_date: String,
#[serde(rename = "releaseNotes")]
release_notes: String,
assets: Vec<UpdateAsset>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct DownloadProgress {
downloaded: u64,
total: u64,
percentage: f64,
speed: f64,
}
fn get_current_platform() -> String {
let os = env::consts::OS;
let arch = env::consts::ARCH;
match os {
"windows" => format!("{}-pc-windows-msvc", arch),
"macos" => format!("{}-apple-darwin", arch),
"linux" => format!("{}-unknown-linux-gnu", arch),
_ => format!("{}-{}", arch, os),
}
}
fn filter_assets_for_platform(assets: &[GitHubAsset]) -> Vec<UpdateAsset> {
let platform = get_current_platform();
let os = env::consts::OS;
assets
.iter()
.filter_map(|asset| {
let name = asset.name.to_lowercase();
let is_for_platform = match os {
"windows" => {
name.contains("windows")
|| name.contains("win")
|| name.contains("msvc")
|| name.contains("exe")
}
"macos" => {
name.contains("darwin")
|| name.contains("macos")
|| name.contains("mac")
|| name.contains("dmg")
}
"linux" => {
name.contains("linux")
|| name.contains("gnu")
|| name.contains("deb")
|| name.contains("rpm")
}
_ => false,
};
if !is_for_platform {
return None;
}
let asset_type = if name.ends_with(".exe") {
"exe"
} else if name.ends_with(".deb") {
"deb"
} else if name.ends_with(".rpm") {
"rpm"
} else if name.ends_with(".dmg") {
"dmg"
} else {
return None;
};
Some(UpdateAsset {
name: asset.name.clone(),
url: asset.browser_download_url.clone(),
size: asset.size,
platform: platform.clone(),
asset_type: asset_type.to_string(),
})
})
.collect()
}
fn compare_versions(current: &str, latest: &str) -> bool {
let current = current.trim_start_matches('v');
let latest = latest.trim_start_matches('v');
let parse_version = |version: &str| -> Vec<u32> {
version
.split('.')
.filter_map(|part| {
let numeric_part = part.split('-').next().unwrap_or(part);
numeric_part.parse::<u32>().ok()
})
.collect()
};
let current_parts = parse_version(current);
let latest_parts = parse_version(latest);
let max_len = current_parts.len().max(latest_parts.len());
for i in 0..max_len {
let current_part = current_parts.get(i).unwrap_or(&0);
let latest_part = latest_parts.get(i).unwrap_or(&0);
match latest_part.cmp(current_part) {
std::cmp::Ordering::Greater => return true,
std::cmp::Ordering::Less => return false,
std::cmp::Ordering::Equal => continue,
}
}
false
}
#[tauri::command]
pub async fn check_for_updates() -> Result<UpdateCheck, String> {
log::info!("Checking for updates...");
let client = Client::new();
let url = "https://api.github.com/repos/OpenListTeam/openlist-desktop/releases/latest";
let response = client
.get(url)
.header("User-Agent", "OpenList-Desktop")
.timeout(Duration::from_secs(30))
.send()
.await
.map_err(|e| {
let error_msg = format!("Network error while checking for updates: {}", e);
log::error!("{}", error_msg);
error_msg
})?;
if !response.status().is_success() {
let status = response.status();
let error_msg = if status.as_u16() == 404 {
"Repository not found. Please check the repository URL.".to_string()
} else if status.as_u16() == 403 {
"API rate limit exceeded. Please try again later.".to_string()
} else {
format!(
"GitHub API returned status: {} ({})",
status.as_u16(),
status.canonical_reason().unwrap_or("Unknown")
)
};
log::error!("{}", error_msg);
return Err(error_msg);
}
let release: GitHubRelease = response.json().await.map_err(|e| {
log::error!("Failed to parse GitHub response: {}", e);
format!("Failed to parse update information: {}", e)
})?;
let current_version = env!("CARGO_PKG_VERSION");
let latest_version = release.tag_name.as_str();
let has_update = compare_versions(current_version, latest_version);
let assets = filter_assets_for_platform(&release.assets);
log::info!(
"Update check result: current={}, latest={}, has_update={}, assets_count={}",
current_version,
latest_version,
has_update,
assets.len()
);
Ok(UpdateCheck {
has_update,
current_version: current_version.to_string(),
latest_version: latest_version.to_string(),
release_date: release.published_at,
release_notes: release.body,
assets,
})
}
#[tauri::command]
pub async fn download_update(
app: AppHandle,
asset_url: String,
asset_name: String,
) -> Result<String, String> {
log::info!("Starting download of update: {}", asset_name);
let client = Client::new();
let temp_dir = std::env::temp_dir();
let file_path = temp_dir.join(&asset_name);
log::info!("Downloading to: {:?}", file_path);
let mut response = client
.get(&asset_url)
.header("User-Agent", "OpenList-Desktop")
.timeout(Duration::from_secs(9000))
.send()
.await
.map_err(|e| {
let error_msg = format!("Failed to start download: {}", e);
log::error!("{}", error_msg);
error_msg
})?;
if !response.status().is_success() {
let status = response.status();
let error_msg = if status.as_u16() == 404 {
"Download file not found. The release asset may have been removed.".to_string()
} else {
format!(
"Download failed with status: {} ({})",
status.as_u16(),
status.canonical_reason().unwrap_or("Unknown")
)
};
log::error!("{}", error_msg);
return Err(error_msg);
}
let total_size = response.content_length().unwrap_or(0);
log::info!("Download size: {} bytes", total_size);
let mut file = tokio::fs::File::create(&file_path).await.map_err(|e| {
log::error!("Failed to create download file: {}", e);
format!("Failed to create file: {}", e)
})?;
let mut downloaded = 0u64;
let mut last_progress_time = std::time::Instant::now();
let mut last_downloaded = 0u64;
while let Some(chunk) = response.chunk().await.map_err(|e| {
log::error!("Download chunk error: {}", e);
format!("Download error: {}", e)
})? {
file.write_all(&chunk).await.map_err(|e| {
log::error!("File write error: {}", e);
format!("File write error: {}", e)
})?;
downloaded += chunk.len() as u64;
let now = std::time::Instant::now();
if now.duration_since(last_progress_time).as_secs() >= 1 || downloaded >= total_size {
let elapsed = now.duration_since(last_progress_time).as_secs_f64();
let speed = if elapsed > 0.0 {
(downloaded - last_downloaded) as f64 / elapsed
} else {
0.0
};
let percentage = if total_size > 0 {
(downloaded as f64 / total_size as f64) * 100.0
} else {
0.0
};
let progress = DownloadProgress {
downloaded,
total: total_size,
percentage,
speed,
};
if let Err(e) = app.emit("download-progress", &progress) {
log::error!("Failed to emit download progress: {}", e);
}
last_progress_time = now;
last_downloaded = downloaded;
}
}
file.flush().await.map_err(|e| {
log::error!("Failed to flush file: {}", e);
format!("File flush error: {}", e)
})?;
log::info!("Download completed: {} bytes", downloaded);
if let Err(e) = app.emit("update-download-completed", ()) {
log::error!("Failed to emit download completed event: {}", e);
}
Ok(file_path.to_string_lossy().to_string())
}
#[tauri::command]
pub async fn install_update_and_restart(
app: AppHandle,
installer_path: String,
) -> Result<(), String> {
log::info!("Installing update from: {}", installer_path);
let path = PathBuf::from(&installer_path);
if !path.exists() {
let error_msg = "Installer file not found".to_string();
log::error!("{}", error_msg);
return Err(error_msg);
}
if let Err(e) = app.emit("update-install-started", ()) {
log::error!("Failed to emit install started event: {}", e);
}
let result = match env::consts::OS {
"windows" => install_windows_update(&path).await,
"macos" => install_macos_update(&path).await,
"linux" => install_linux_update(&path).await,
_ => Err("Unsupported platform for auto-update".to_string()),
};
match result {
Ok(_) => {
log::info!("Update installation started successfully");
if let Err(e) = app.emit("update-install-completed", ()) {
log::error!("Failed to emit install completed event: {}", e);
}
if let Err(e) = app.emit("app-restarting", ()) {
log::error!("Failed to emit app restarting event: {}", e);
}
tokio::time::sleep(Duration::from_millis(1000)).await;
std::process::exit(0);
}
Err(e) => {
log::error!("Update installation failed: {}", e);
if let Err(emit_err) = app.emit("update-install-error", &e) {
log::error!("Failed to emit install error event: {}", emit_err);
}
Err(e)
}
}
}
async fn install_windows_update(installer_path: &PathBuf) -> Result<(), String> {
log::info!("Installing Windows update...");
let mut cmd = Command::new(installer_path);
cmd.arg("/SILENT");
tokio::task::spawn_blocking(move || {
cmd.spawn()
.map_err(|e| format!("Failed to start Windows installer: {}", e))
})
.await
.map_err(|e| format!("Task error: {}", e))?
.map_err(|e| e)?;
Ok(())
}
async fn install_macos_update(installer_path: &PathBuf) -> Result<(), String> {
log::info!("Installing macOS update...");
let mut cmd = Command::new("open");
cmd.arg(installer_path);
tokio::task::spawn_blocking(move || {
cmd.spawn()
.map_err(|e| format!("Failed to start macOS installer: {}", e))
})
.await
.map_err(|e| format!("Task error: {}", e))?
.map_err(|e| e)?;
Ok(())
}
async fn install_linux_update(installer_path: &PathBuf) -> Result<(), String> {
log::info!("Installing Linux update...");
let extension = installer_path
.extension()
.and_then(|s| s.to_str())
.unwrap_or("");
let mut cmd = match extension {
"deb" => {
let mut cmd = Command::new("pkexec");
cmd.args(["dpkg", "-i"]);
cmd.arg(installer_path);
cmd
}
"rpm" => {
let mut cmd = Command::new("pkexec");
cmd.args(["rpm", "-i"]);
cmd.arg(installer_path);
cmd
}
_ => {
return Err("Unsupported Linux package format".to_string());
}
};
tokio::task::spawn_blocking(move || {
cmd.spawn()
.map_err(|e| format!("Failed to start Linux installer: {}", e))
})
.await
.map_err(|e| format!("Task error: {}", e))?
.map_err(|e| e)?;
Ok(())
}
#[tauri::command]
pub async fn get_current_version() -> Result<String, String> {
Ok(env!("CARGO_PKG_VERSION").to_string())
}
#[tauri::command]
pub async fn set_auto_check_enabled(
enabled: bool,
state: State<'_, AppState>,
) -> Result<(), String> {
log::info!("Setting auto-check updates preference to: {}", enabled);
let mut settings = state.get_settings().unwrap_or_else(|| {
use crate::conf::config::MergedSettings;
MergedSettings::default()
});
settings.app.auto_update_enabled = Some(enabled);
state.update_settings(settings.clone());
save_settings(settings, state)
.await
.map_err(|e| format!("Failed to save settings: {}", e))?;
Ok(())
}
#[tauri::command]
pub async fn is_auto_check_enabled(state: State<'_, AppState>) -> Result<bool, String> {
let settings = state.get_settings().unwrap_or_else(|| {
use crate::conf::config::MergedSettings;
MergedSettings::default()
});
Ok(settings.app.auto_update_enabled.unwrap_or(true))
}
pub async fn perform_background_update_check(app: AppHandle) -> Result<(), String> {
log::debug!("Performing background update check...");
match check_for_updates().await {
Ok(update_check) => {
if update_check.has_update {
log::info!(
"Background check: Update available {} -> {}",
update_check.current_version,
update_check.latest_version
);
if let Err(e) = app.emit("background-update-available", &update_check) {
log::error!("Failed to emit background-update-available event: {}", e);
}
} else {
log::debug!("Background check: App is up to date");
}
Ok(())
}
Err(e) => {
log::debug!("Background update check failed: {}", e);
Ok(())
}
}
}
#[tauri::command]
pub async fn restart_app(app: AppHandle) {
log::info!("Restarting application...");
if let Err(e) = app.emit("app-restarting", ()) {
log::error!("Failed to emit app-restarting event: {}", e);
}
tokio::time::sleep(Duration::from_millis(500)).await;
app.restart();
}

View File

@@ -0,0 +1,146 @@
use crate::object::structs::AppState;
use crate::utils::api::{ListProcessResponse, ProcessStatus, get_api_key, get_server_port};
use reqwest;
use std::collections::HashMap;
use std::str::FromStr;
use tauri::State;
#[tauri::command]
pub async fn get_process_list(state: State<'_, AppState>) -> Result<Vec<ProcessStatus>, String> {
let api_key = get_api_key(state);
let port = get_server_port();
let client = reqwest::Client::new();
let response = client
.get(format!("http://127.0.0.1:{}/api/v1/processes", port))
.header("Authorization", format!("Bearer {}", api_key))
.send()
.await
.map_err(|e| format!("Failed to send request: {}", e))?;
if response.status().is_success() {
let response_text = response
.text()
.await
.map_err(|e| format!("Failed to read response text: {}", e))?;
let process_list = match serde_json::from_str::<ListProcessResponse>(&response_text) {
Ok(process_list) => process_list,
Err(e) => {
return Err(format!(
"Failed to parse response: {}, response: {}",
e, response_text
));
}
};
Ok(process_list.data)
} else {
Err(format!("Failed to get process list: {}", response.status()))
}
}
#[tauri::command]
pub async fn start_process(id: String, state: State<'_, AppState>) -> Result<bool, String> {
let api_key = get_api_key(state);
let port = get_server_port();
let client = reqwest::Client::new();
let response = client
.post(format!(
"http://127.0.0.1:{}/api/v1/processes/{}/start",
port, id
))
.header("Authorization", format!("Bearer {}", api_key))
.send()
.await
.map_err(|e| format!("Failed to send request: {}", e))?;
if response.status().is_success() {
Ok(true)
} else {
Err(format!("Failed to start process: {}", response.status()))
}
}
#[tauri::command]
pub async fn stop_process(id: String, state: State<'_, AppState>) -> Result<bool, String> {
let api_key = get_api_key(state);
let port = get_server_port();
let client = reqwest::Client::new();
let response = client
.post(format!(
"http://127.0.0.1:{}/api/v1/processes/{}/stop",
port, id
))
.header("Authorization", format!("Bearer {}", api_key))
.send()
.await
.map_err(|e| format!("Failed to send request: {}", e))?;
if response.status().is_success() {
Ok(true)
} else {
Err(format!("Failed to stop process: {}", response.status()))
}
}
#[tauri::command]
pub async fn restart_process(id: String, state: State<'_, AppState>) -> Result<bool, String> {
let api_key = get_api_key(state);
let port = get_server_port();
let client = reqwest::Client::new();
let stop_response = client
.post(format!(
"http://127.0.0.1:{}/api/v1/processes/{}/stop",
port, id
))
.header("Authorization", format!("Bearer {}", api_key))
.send()
.await
.map_err(|e| format!("Failed to send request: {}", e))?;
if stop_response.status().is_success() {
let start_response = client
.post(
url::Url::from_str(&format!(
"http://127.0.0.1:{}/api/v1/processes/{}/start",
port, id
))
.unwrap(),
)
.header("Authorization", format!("Bearer {}", api_key))
.send()
.await
.map_err(|e| format!("Failed to send request: {}", e))?;
if start_response.status().is_success() {
Ok(true)
} else {
Err(format!(
"Failed to start OpenList Core process: {}",
start_response.status()
))
}
} else {
Err(format!(
"Failed to stop OpenList Core process: {}",
stop_response.status()
))
}
}
#[tauri::command]
pub async fn update_process(
id: String,
update_config: HashMap<String, String>,
state: State<'_, AppState>,
) -> Result<bool, String> {
let api_key = get_api_key(state);
let port = get_server_port();
let client = reqwest::Client::new();
let response = client
.put(format!("http://127.0.0.1:{}/api/v1/processes/{}", port, id))
.header("Authorization", format!("Bearer {}", api_key))
.json(&update_config)
.send()
.await
.map_err(|e| format!("Failed to send request: {}", e))?;
if response.status().is_success() {
Ok(true)
} else {
Err(format!("Failed to update process: {}", response.status()))
}
}

77
src-tauri/src/cmd/logs.rs Normal file
View File

@@ -0,0 +1,77 @@
use regex::Regex;
use std::env;
#[tauri::command]
pub async fn get_admin_password() -> Result<String, String> {
let app_dir = env::current_exe().unwrap().parent().unwrap().to_path_buf();
let logs_dir = app_dir.join("logs/process_openlist_core.log");
let logs_content =
std::fs::read_to_string(logs_dir).map_err(|e| format!("Failed to read log file: {}", e))?;
let re = Regex::new(r"Successfully created the admin user and the initial password is: (\w+)")
.map_err(|e| format!("Failed to create regex: {}", e))?;
let mut last_password = None;
for line in logs_content.lines() {
if let Some(captures) = re.captures(line) {
if let Some(password) = captures.get(1) {
last_password = Some(password.as_str().to_string());
}
}
}
last_password.ok_or("No admin password found in logs".to_string())
}
#[tauri::command]
pub async fn get_logs(source: Option<String>) -> Result<Vec<String>, String> {
match source.as_deref() {
Some("openlist") => {
let app_dir = env::current_exe().unwrap().parent().unwrap().to_path_buf();
let logs_dir = app_dir.join("data/log/log.log");
let logs = std::fs::read_to_string(logs_dir)
.map_err(|e| e.to_string())?
.lines()
.map(|line| line.to_string())
.collect();
Ok(logs)
}
Some("app") => {
let app_dir = env::current_exe().unwrap().parent().unwrap().to_path_buf();
let logs_dir = app_dir.join("logs/app.log");
let logs = std::fs::read_to_string(logs_dir)
.map_err(|e| e.to_string())?
.lines()
.map(|line| line.to_string())
.collect();
Ok(logs)
}
Some("rclone") => {
let app_dir = env::current_exe().unwrap().parent().unwrap().to_path_buf();
let logs_dir = app_dir.join("logs/process_rclone.log");
let logs = std::fs::read_to_string(logs_dir)
.map_err(|e| e.to_string())?
.lines()
.map(|line| line.to_string())
.collect();
Ok(logs)
}
Some("openlist_core") => {
let app_dir = env::current_exe().unwrap().parent().unwrap().to_path_buf();
let logs_dir = app_dir.join("logs/process_openlist_core.log");
let logs = std::fs::read_to_string(logs_dir)
.map_err(|e| e.to_string())?
.lines()
.map(|line| line.to_string())
.collect();
Ok(logs)
}
_ => Err("Invalid log source".to_string()),
}
}
#[tauri::command]
pub async fn clear_logs() -> Result<bool, String> {
Ok(true)
}

10
src-tauri/src/cmd/mod.rs Normal file
View File

@@ -0,0 +1,10 @@
pub mod binary;
pub mod config;
pub mod custom_updater;
pub mod http_api;
pub mod logs;
pub mod openlist_core;
pub mod os_operate;
pub mod rclone_core;
pub mod rclone_mount;
pub mod service;

View File

@@ -0,0 +1,109 @@
use crate::object::structs::{AppState, ServiceStatus};
use crate::utils::api::{CreateProcessResponse, ProcessConfig, get_api_key, get_server_port};
use crate::utils::path::{get_app_logs_dir, get_openlist_binary_path};
use reqwest;
use tauri::State;
use url::Url;
#[tauri::command]
pub async fn create_openlist_core_process(
auto_start: bool,
state: State<'_, AppState>,
) -> Result<ProcessConfig, String> {
let binary_path = get_openlist_binary_path()
.map_err(|e| format!("Failed to get OpenList binary path: {}", e))?;
let log_file_path =
get_app_logs_dir().map_err(|e| format!("Failed to get app logs directory: {}", e))?;
let log_file_path = log_file_path.join("process_openlist_core.log");
let api_key = get_api_key(state);
let port = get_server_port();
let config = ProcessConfig {
id: "openlist_core".into(),
name: "single_openlist_core_process".into(),
bin_path: binary_path.to_string_lossy().into_owned(),
args: vec!["server".into()],
log_file: log_file_path.to_string_lossy().into_owned(),
working_dir: binary_path
.parent()
.map(|p| p.to_string_lossy().into_owned()),
env_vars: None,
auto_restart: true,
auto_start,
run_as_admin: false,
created_at: 0,
updated_at: 0,
};
let client = reqwest::Client::new();
let response = client
.post(format!("http://127.0.0.1:{}/api/v1/processes", port))
.json(&config)
.header("Authorization", format!("Bearer {}", api_key))
.send()
.await
.map_err(|e| format!("Failed to send request: {}", e))?;
if response.status().is_success() {
let response_text = response
.text()
.await
.map_err(|e| format!("Failed to read response text: {}", e))?;
let process_config = match serde_json::from_str::<CreateProcessResponse>(&response_text) {
Ok(process_config) => process_config,
Err(e) => {
return Err(format!(
"Failed to parse response: {}, response: {}",
e, response_text
));
}
};
Ok(process_config.data)
} else {
Err(format!(
"Failed to create OpenList Core process: {}",
response.status()
))
}
}
#[tauri::command]
pub async fn get_openlist_core_status(state: State<'_, AppState>) -> Result<ServiceStatus, String> {
let app_settings = state
.app_settings
.read()
.clone()
.ok_or("Failed to read app settings")?;
let openlist_config = app_settings.openlist;
let protocol = if openlist_config.ssl_enabled {
"https"
} else {
"http"
};
let health_check_url = format!("{}://localhost:{}", protocol, openlist_config.port);
let url =
Url::parse(&health_check_url).map_err(|e| format!("Invalid health check URL: {}", e))?;
let port = url.port_or_known_default();
let health_url = format!("{}/ping", health_check_url);
let local_pid = None;
match reqwest::get(&health_url).await {
Ok(response) => {
let is_running = response.status().is_success();
Ok(ServiceStatus {
running: is_running,
pid: local_pid,
port,
})
}
Err(_) => Ok(ServiceStatus {
running: false,
pid: local_pid,
port,
}),
}
}

View File

@@ -0,0 +1,533 @@
use std::fs;
use std::path::PathBuf;
use tauri::{AppHandle, State};
use crate::cmd::http_api::{get_process_list, start_process, stop_process};
use crate::object::structs::{AppState, FileItem};
use crate::utils::path::{get_openlist_binary_path, get_rclone_binary_path};
#[tauri::command]
pub async fn open_folder(path: String) -> Result<bool, String> {
let path_buf = PathBuf::from(path);
open::that(path_buf.as_os_str()).map_err(|e| e.to_string())?;
Ok(true)
}
#[tauri::command]
pub async fn open_file(path: String) -> Result<bool, String> {
let path_buf = PathBuf::from(path);
open::that_detached(path_buf.as_os_str()).map_err(|e| e.to_string())?;
Ok(true)
}
#[tauri::command]
pub async fn open_url(url: String) -> Result<bool, String> {
open::that(url).map_err(|e| e.to_string())?;
Ok(true)
}
#[tauri::command]
pub fn select_directory(title: String, app_handle: AppHandle) -> Result<Option<String>, String> {
use tauri_plugin_dialog::DialogExt;
let dir_path = app_handle
.dialog()
.file()
.set_title(&title)
.blocking_pick_folder();
Ok(dir_path.map(|path| path.to_string()))
}
#[tauri::command]
pub async fn list_files(
path: String,
_state: State<'_, AppState>,
) -> Result<Vec<FileItem>, String> {
let path_buf = PathBuf::from(&path);
if !path_buf.exists() {
return Err("Path does not exist".to_string());
}
let mut files = Vec::new();
if path_buf.is_dir() {
let entries = fs::read_dir(&path_buf).map_err(|e| e.to_string())?;
for entry in entries {
let entry = entry.map_err(|e| e.to_string())?;
let metadata = entry.metadata().map_err(|e| e.to_string())?;
let file_name = entry.file_name().to_string_lossy().to_string();
let file_path = entry.path().to_string_lossy().to_string();
files.push(FileItem {
name: file_name,
path: file_path,
is_dir: metadata.is_dir(),
size: if metadata.is_file() {
Some(metadata.len())
} else {
None
},
modified: metadata
.modified()
.ok()
.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
.map(|duration| {
chrono::DateTime::from_timestamp(duration.as_secs() as i64, 0)
.unwrap_or_default()
.to_rfc3339()
}),
});
}
}
files.sort_by(|a, b| match (a.is_dir, b.is_dir) {
(true, false) => std::cmp::Ordering::Less,
(false, true) => std::cmp::Ordering::Greater,
_ => a.name.cmp(&b.name),
});
Ok(files)
}
#[tauri::command]
pub async fn get_available_versions(tool: String) -> Result<Vec<String>, String> {
let url = match tool.as_str() {
"openlist" => "https://api.github.com/repos/OpenListTeam/OpenList/releases",
"rclone" => "https://api.github.com/repos/rclone/rclone/releases",
_ => return Err("Unsupported tool".to_string()),
};
let client = reqwest::Client::builder()
.user_agent("OpenList Desktop/1.0")
.build()
.map_err(|e| e.to_string())?;
let response = client.get(url).send().await.map_err(|e| e.to_string())?;
let releases: serde_json::Value = response.json().await.map_err(|e| e.to_string())?;
let versions = releases
.as_array()
.unwrap_or(&vec![])
.iter()
.take(10)
.filter_map(|release| release["tag_name"].as_str())
.map(|tag| tag.to_string())
.collect();
Ok(versions)
}
#[tauri::command]
pub async fn update_tool_version(
tool: String,
version: String,
state: State<'_, AppState>,
) -> Result<String, String> {
log::info!("Updating {} to version {}", tool, version);
let process_list = get_process_list(state.clone())
.await
.map_err(|e| format!("Failed to get process list: {}", e))?;
let process_name = match tool.as_str() {
"openlist" => "single_openlist_core_process",
"rclone" => "single_rclone_backend_process",
_ => return Err("Unsupported tool".to_string()),
};
let running_process = process_list.iter().find(|p| p.config.name == process_name);
let was_running = running_process.map(|p| p.is_running).unwrap_or(false);
let process_id = running_process.map(|p| p.config.id.clone());
if was_running {
if let Some(pid) = &process_id {
log::info!("Stopping {} process with ID: {}", tool, pid);
match tool.as_str() {
"openlist" | "rclone" => {
stop_process(pid.clone(), state.clone())
.await
.map_err(|e| format!("Failed to stop process: {}", e))?;
}
_ => return Err("Unsupported tool".to_string()),
}
log::info!("Successfully stopped {} process", tool);
}
}
let result = download_and_replace_binary(&tool, &version).await;
match result {
Ok(_) => {
log::info!("Successfully downloaded and replaced {} binary", tool);
if was_running {
if let Some(pid) = &process_id {
log::info!("Starting {} process with ID: {}", tool, pid);
match tool.as_str() {
"openlist" | "rclone" => {
start_process(pid.clone(), state.clone())
.await
.map_err(|e| format!("Failed to start {} process: {}", tool, e))?;
}
_ => return Err("Unsupported tool".to_string()),
}
log::info!("Successfully restarted {} process", tool);
}
}
Ok(format!("Successfully updated {} to {}", tool, version))
}
Err(e) => {
log::error!("Failed to update {} binary: {}", tool, e);
if was_running {
if let Some(pid) = &process_id {
log::info!(
"Attempting to restart {} with previous binary after update failure",
tool
);
match tool.as_str() {
"openlist" | "rclone" => {
let _ = start_process(pid.clone(), state.clone()).await;
}
_ => {}
}
}
}
Err(format!("Failed to update {} to {}: {}", tool, version, e))
}
}
}
async fn download_and_replace_binary(tool: &str, version: &str) -> Result<(), String> {
let platform = std::env::consts::OS;
let arch = std::env::consts::ARCH;
let platform_arch = format!(
"{}-{}",
match platform {
"windows" => "win32",
"macos" => "darwin",
"linux" => "linux",
_ => return Err(format!("Unsupported platform: {}", platform)),
},
match arch {
"x86_64" => "x64",
"x86" => "ia32",
"aarch64" => "arm64",
"arm" => "arm",
_ => return Err(format!("Unsupported architecture: {}", arch)),
}
);
log::info!("Detected platform: {}", platform_arch);
let (binary_path, download_info) = match tool {
"openlist" => {
let path = get_openlist_binary_path()
.map_err(|e| format!("Failed to get OpenList binary path: {}", e))?;
let info = get_openlist_download_info(&platform_arch, version)?;
(path, info)
}
"rclone" => {
let path = get_rclone_binary_path()
.map_err(|e| format!("Failed to get Rclone binary path: {}", e))?;
let info = get_rclone_download_info(&platform_arch, version)?;
(path, info)
}
_ => return Err("Unsupported tool".to_string()),
};
log::info!("Downloading {} from: {}", tool, download_info.download_url);
let temp_dir = std::env::temp_dir().join(format!("{}-update-{}", tool, version));
fs::create_dir_all(&temp_dir).map_err(|e| format!("Failed to create temp directory: {}", e))?;
let archive_path = temp_dir.join(&download_info.archive_name);
download_file(&download_info.download_url, &archive_path).await?;
let extracted_binary_path = extract_binary(
&archive_path,
&temp_dir,
&download_info.executable_name,
tool,
)
.await?;
let backup_path = binary_path.with_extension(format!(
"{}.backup",
binary_path
.extension()
.and_then(|s| s.to_str())
.unwrap_or("")
));
if binary_path.exists() {
fs::copy(&binary_path, &backup_path)
.map_err(|e| format!("Failed to backup current binary: {}", e))?;
}
fs::copy(&extracted_binary_path, &binary_path).map_err(|e| {
if backup_path.exists() {
let _ = fs::copy(&backup_path, &binary_path);
let _ = fs::remove_file(&backup_path);
}
format!("Failed to replace binary: {}", e)
})?;
if backup_path.exists() {
let _ = fs::remove_file(&backup_path);
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = fs::metadata(&binary_path)
.map_err(|e| format!("Failed to get binary metadata: {}", e))?
.permissions();
perms.set_mode(0o755);
fs::set_permissions(&binary_path, perms)
.map_err(|e| format!("Failed to set executable permissions: {}", e))?;
}
let _ = fs::remove_file(&extracted_binary_path);
let _ = fs::remove_dir_all(&temp_dir);
log::info!("Successfully replaced {} binary", tool);
Ok(())
}
struct DownloadInfo {
download_url: String,
archive_name: String,
executable_name: String,
}
fn get_openlist_download_info(platform_arch: &str, version: &str) -> Result<DownloadInfo, String> {
let arch_map = get_openlist_arch_mapping(platform_arch)?;
let is_windows = platform_arch.starts_with("win32");
let is_unix = platform_arch.starts_with("darwin") || platform_arch.starts_with("linux");
let archive_ext = if is_unix { "tar.gz" } else { "zip" };
let exe_ext = if is_windows { ".exe" } else { "" };
let archive_name = format!("openlist-{}.{}", arch_map, archive_ext);
let executable_name = format!("openlist{}", exe_ext);
let download_url = format!(
"https://github.com/OpenListTeam/OpenList/releases/download/{}/{}",
version, archive_name
);
Ok(DownloadInfo {
download_url,
archive_name,
executable_name,
})
}
fn get_rclone_download_info(platform_arch: &str, version: &str) -> Result<DownloadInfo, String> {
let arch_map = get_rclone_arch_mapping(platform_arch)?;
let is_windows = platform_arch.starts_with("win32");
let exe_ext = if is_windows { ".exe" } else { "" };
let archive_name = format!("rclone-{}-{}.zip", version, arch_map);
let executable_name = format!("rclone{}", exe_ext);
let download_url = format!(
"https://github.com/rclone/rclone/releases/download/{}/{}",
version, archive_name
);
Ok(DownloadInfo {
download_url,
archive_name,
executable_name,
})
}
fn get_openlist_arch_mapping(platform_arch: &str) -> Result<&'static str, String> {
match platform_arch {
"win32-x64" => Ok("windows-amd64"),
"win32-ia32" => Ok("windows-386"),
"win32-arm64" => Ok("windows-arm64"),
"darwin-x64" => Ok("darwin-amd64"),
"darwin-arm64" => Ok("darwin-arm64"),
"linux-x64" => Ok("linux-amd64"),
"linux-ia32" => Ok("linux-386"),
"linux-arm64" => Ok("linux-arm64"),
"linux-arm" => Ok("linux-arm-7"),
_ => Err(format!(
"Unsupported platform architecture: {}",
platform_arch
)),
}
}
fn get_rclone_arch_mapping(platform_arch: &str) -> Result<&'static str, String> {
match platform_arch {
"win32-x64" => Ok("windows-amd64"),
"win32-ia32" => Ok("windows-386"),
"win32-arm64" => Ok("windows-arm64"),
"darwin-x64" => Ok("osx-amd64"),
"darwin-arm64" => Ok("osx-arm64"),
"linux-x64" => Ok("linux-amd64"),
"linux-ia32" => Ok("linux-386"),
"linux-arm64" => Ok("linux-arm64"),
"linux-arm" => Ok("linux-arm-v7"),
_ => Err(format!(
"Unsupported platform architecture: {}",
platform_arch
)),
}
}
async fn download_file(url: &str, path: &PathBuf) -> Result<(), String> {
log::info!("Downloading file from: {}", url);
let client = reqwest::Client::builder()
.user_agent("OpenList Desktop/1.0")
.build()
.map_err(|e| format!("Failed to create HTTP client: {}", e))?;
let response = client
.get(url)
.send()
.await
.map_err(|e| format!("Failed to download file: {}", e))?;
if !response.status().is_success() {
return Err(format!(
"Download failed with status: {}",
response.status()
));
}
let bytes = response
.bytes()
.await
.map_err(|e| format!("Failed to read response bytes: {}", e))?;
fs::write(path, &bytes).map_err(|e| format!("Failed to write file: {}", e))?;
log::info!("Downloaded file to: {:?}", path);
Ok(())
}
async fn extract_binary(
archive_path: &PathBuf,
extract_dir: &PathBuf,
executable_name: &str,
tool: &str,
) -> Result<PathBuf, String> {
log::info!("Extracting archive: {:?}", archive_path);
let archive_name = archive_path
.file_name()
.and_then(|s| s.to_str())
.ok_or("Invalid archive path")?;
if archive_name.ends_with(".zip") {
extract_zip(archive_path, extract_dir, executable_name, tool)
} else if archive_name.ends_with(".tar.gz") {
extract_tar_gz(archive_path, extract_dir, executable_name, tool)
} else {
Err(format!("Unsupported archive format: {}", archive_name))
}
}
fn extract_zip(
archive_path: &PathBuf,
extract_dir: &PathBuf,
executable_name: &str,
tool: &str,
) -> Result<PathBuf, String> {
let file =
fs::File::open(archive_path).map_err(|e| format!("Failed to open zip file: {}", e))?;
let mut archive =
zip::ZipArchive::new(file).map_err(|e| format!("Failed to read zip archive: {}", e))?;
let mut executable_path = None;
for i in 0..archive.len() {
let mut file = archive
.by_index(i)
.map_err(|e| format!("Failed to read zip entry: {}", e))?;
let file_name = file.name();
let is_target_executable = if tool == "rclone" {
file_name.ends_with(executable_name) && file_name.contains("rclone")
} else {
file_name == executable_name || file_name.ends_with(&format!("/{}", executable_name))
};
if is_target_executable {
let output_path = extract_dir.join(executable_name);
let mut output_file = fs::File::create(&output_path)
.map_err(|e| format!("Failed to create output file: {}", e))?;
std::io::copy(&mut file, &mut output_file)
.map_err(|e| format!("Failed to extract file: {}", e))?;
executable_path = Some(output_path);
break;
}
}
executable_path
.ok_or_else(|| format!("Executable '{}' not found in zip archive", executable_name))
}
fn extract_tar_gz(
archive_path: &PathBuf,
extract_dir: &PathBuf,
executable_name: &str,
_tool: &str,
) -> Result<PathBuf, String> {
use flate2::read::GzDecoder;
use tar::Archive;
let file =
fs::File::open(archive_path).map_err(|e| format!("Failed to open tar.gz file: {}", e))?;
let gz_decoder = GzDecoder::new(file);
let mut archive = Archive::new(gz_decoder);
let mut executable_path = None;
for entry in archive
.entries()
.map_err(|e| format!("Failed to read tar entries: {}", e))?
{
let mut entry = entry.map_err(|e| format!("Failed to read tar entry: {}", e))?;
let path = entry
.path()
.map_err(|e| format!("Failed to get entry path: {}", e))?;
if let Some(file_name) = path.file_name() {
if file_name == executable_name {
let output_path = extract_dir.join(executable_name);
let mut output_file = fs::File::create(&output_path)
.map_err(|e| format!("Failed to create output file: {}", e))?;
std::io::copy(&mut entry, &mut output_file)
.map_err(|e| format!("Failed to extract file: {}", e))?;
executable_path = Some(output_path);
break;
}
}
}
executable_path.ok_or_else(|| {
format!(
"Executable '{}' not found in tar.gz archive",
executable_name
)
})
}

View File

@@ -0,0 +1,123 @@
use crate::cmd::http_api::{get_process_list, start_process};
use crate::object::structs::AppState;
use crate::utils::api::ProcessConfig;
use crate::utils::path::{get_app_logs_dir, get_rclone_binary_path};
use crate::utils::api::{CreateProcessResponse, get_api_key, get_server_port};
use reqwest::{self, Client};
use std::time::Duration;
use tauri::State;
// use 45572 due to the reserved port on Windows
pub const RCLONE_API_BASE: &str = "http://127.0.0.1:45572";
// admin:admin base64 encoded
pub const RCLONE_AUTH: &str = "Basic YWRtaW46YWRtaW4=";
#[tauri::command]
pub async fn create_and_start_rclone_backend(
state: State<'_, AppState>,
) -> Result<ProcessConfig, String> {
let process_list = get_process_list(state.clone()).await?;
if let Some(existing_process) = process_list
.iter()
.find(|p| p.config.name == "single_rclone_backend_process")
{
if !existing_process.is_running {
start_process(existing_process.config.id.clone(), state).await?;
}
return Ok(existing_process.config.clone());
}
let new_process_config = create_rclone_backend_process(state.clone()).await?;
start_process(new_process_config.id.clone(), state).await?;
Ok(new_process_config)
}
#[tauri::command]
pub async fn create_rclone_backend_process(
state: State<'_, AppState>,
) -> Result<ProcessConfig, String> {
let binary_path =
get_rclone_binary_path().map_err(|e| format!("Failed to get rclone binary path: {}", e))?;
let log_file_path =
get_app_logs_dir().map_err(|e| format!("Failed to get app logs directory: {}", e))?;
let rclone_conf_path = binary_path
.parent()
.map(|p| p.join("rclone.conf"))
.ok_or_else(|| "Failed to determine rclone.conf path".to_string())?;
let log_file_path = log_file_path.join("process_rclone.log");
let api_key = get_api_key(state);
let port = get_server_port();
let config = ProcessConfig {
id: "rclone_backend".into(),
name: "single_rclone_backend_process".into(),
bin_path: binary_path.to_string_lossy().into_owned(),
args: vec![
"--config".into(),
rclone_conf_path.to_string_lossy().into_owned(),
"rcd".into(),
"--rc-user".into(),
"admin".into(),
"--rc-pass".into(),
"admin".into(),
"--rc-addr".into(),
format!("127.0.0.1:45572"),
"--rc-web-gui-no-open-browser".into(),
],
log_file: log_file_path.to_string_lossy().into_owned(),
working_dir: binary_path
.parent()
.map(|p| p.to_string_lossy().into_owned()),
env_vars: None,
auto_restart: true,
auto_start: true,
run_as_admin: false,
created_at: 0,
updated_at: 0,
};
let client = reqwest::Client::new();
let response = client
.post(format!("http://127.0.0.1:{}/api/v1/processes", port))
.json(&config)
.header("Authorization", format!("Bearer {}", api_key))
.send()
.await
.map_err(|e| format!("Failed to send request: {}", e))?;
if response.status().is_success() {
let response_text = response
.text()
.await
.map_err(|e| format!("Failed to read response text: {}", e))?;
let process_config = match serde_json::from_str::<CreateProcessResponse>(&response_text) {
Ok(process_config) => process_config,
Err(e) => {
return Err(format!(
"Failed to parse response: {}, response: {}",
e, response_text
));
}
};
Ok(process_config.data)
} else {
Err(format!(
"Failed to create Rclone Core process: {}",
response.status()
))
}
}
#[tauri::command]
pub async fn get_rclone_backend_status(_state: State<'_, AppState>) -> Result<bool, String> {
Ok(is_rclone_running().await)
}
async fn is_rclone_running() -> bool {
let client = Client::new();
let response = client
.get(&format!("{}/", RCLONE_API_BASE))
.timeout(Duration::from_secs(1))
.send()
.await;
response.is_ok()
}

View File

@@ -0,0 +1,412 @@
use super::http_api::get_process_list;
use super::rclone_core::{RCLONE_API_BASE, RCLONE_AUTH};
use crate::conf::rclone::{RcloneCreateRemoteRequest, RcloneMountRequest, RcloneWebdavConfig};
use crate::object::structs::{
AppState, RcloneMountInfo, RcloneMountListResponse, RcloneRemoteListResponse,
};
use crate::utils::api::{CreateProcessResponse, ProcessConfig, get_api_key, get_server_port};
use crate::utils::path::{get_app_logs_dir, get_rclone_binary_path};
use reqwest::Client;
use serde_json::json;
use std::fs;
use std::path::Path;
use tauri::State;
#[tauri::command]
pub async fn rclone_list_config(
remote_type: String,
_state: State<'_, AppState>,
) -> Result<serde_json::Value, String> {
let client = Client::new();
let response = client
.post(format!("{}/config/dump", RCLONE_API_BASE))
.header("Authorization", RCLONE_AUTH)
.send()
.await
.map_err(|e| format!("Failed to send request: {}", e))?;
if response.status().is_success() {
let response_text = response
.text()
.await
.map_err(|e| format!("Failed to read response text: {}", e))?;
let json: serde_json::Value = serde_json::from_str(&response_text)
.map_err(|e| format!("Failed to parse JSON: {}", e))?;
let remotes = if remote_type.is_empty() {
json.clone()
} else {
if let Some(obj) = json.as_object() {
let mut filtered_map = serde_json::Map::new();
for (remote_name, remote_config) in obj {
if let Some(config_obj) = remote_config.as_object() {
if let Some(remote_type_value) = config_obj.get("type") {
if let Some(type_str) = remote_type_value.as_str() {
if type_str == remote_type {
filtered_map.insert(remote_name.clone(), remote_config.clone());
}
}
}
}
}
serde_json::Value::Object(filtered_map)
} else {
serde_json::Value::Object(serde_json::Map::new())
}
};
Ok(remotes)
} else {
Err(format!(
"Failed to list Rclone config: {}",
response.status()
))
}
}
#[tauri::command]
pub async fn rclone_list_remotes() -> Result<Vec<String>, String> {
let client = Client::new();
let response = client
.post(&format!("{}/config/listremotes", RCLONE_API_BASE))
.header("Authorization", RCLONE_AUTH)
.send()
.await
.map_err(|e| format!("Failed to list remotes: {}", e))?;
if response.status().is_success() {
let remote_list: RcloneRemoteListResponse = response
.json()
.await
.map_err(|e| format!("Failed to parse remote list response: {}", e))?;
Ok(remote_list.remotes)
} else {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
Err(format!("Failed to list remotes: {}", error_text))
}
}
#[tauri::command]
pub async fn rclone_list_mounts() -> Result<RcloneMountListResponse, String> {
let client = Client::new();
let response = client
.post(&format!("{}/mount/listmounts", RCLONE_API_BASE))
.header("Authorization", RCLONE_AUTH)
.send()
.await
.map_err(|e| format!("Failed to list mounts: {}", e))?;
if response.status().is_success() {
let mount_list: RcloneMountListResponse = response
.json()
.await
.map_err(|e| format!("Failed to parse mount list response: {}", e))?;
Ok(mount_list)
} else {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
Err(format!("Failed to list mounts: {}", error_text))
}
}
#[tauri::command]
pub async fn rclone_create_remote(
name: String,
r#type: String,
config: RcloneWebdavConfig,
_state: State<'_, AppState>,
) -> Result<bool, String> {
let client = Client::new();
let create_request = RcloneCreateRemoteRequest {
name: name.clone(),
r#type: r#type.clone(),
parameters: crate::conf::rclone::RcloneWebdavConfig {
url: config.url.clone(),
vendor: config.vendor.clone(),
user: config.user.clone(),
pass: config.pass.clone(),
},
};
let response = client
.post(&format!("{}/config/create", RCLONE_API_BASE))
.header("Authorization", RCLONE_AUTH)
.header("Content-Type", "application/json")
.json(&create_request)
.send()
.await
.map_err(|e| format!("Failed to create remote config: {}", e))?;
if response.status().is_success() {
Ok(true)
} else {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
Err(format!("Failed to create remote config: {}", error_text))
}
}
#[tauri::command]
pub async fn rclone_update_remote(
name: String,
r#type: String,
config: RcloneWebdavConfig,
_state: State<'_, AppState>,
) -> Result<bool, String> {
let client = Client::new();
let response = client
.post(&format!("{}/config/update", RCLONE_API_BASE))
.header("Authorization", RCLONE_AUTH)
.header("Content-Type", "application/json")
.json(&json!({ "name": name, "type": r#type, "parameters": config }))
.send()
.await
.map_err(|e| format!("Failed to update remote config: {}", e))?;
if response.status().is_success() {
Ok(true)
} else {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
Err(format!("Failed to update remote config: {}", error_text))
}
}
#[tauri::command]
pub async fn rclone_delete_remote(
name: String,
_state: State<'_, AppState>,
) -> Result<bool, String> {
let client = Client::new();
let response = client
.post(&format!("{}/config/delete", RCLONE_API_BASE))
.header("Authorization", RCLONE_AUTH)
.header("Content-Type", "application/json")
.json(&json!({ "name": name }))
.send()
.await
.map_err(|e| format!("Failed to delete remote config: {}", e))?;
if response.status().is_success() {
Ok(true)
} else {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
Err(format!("Failed to delete remote config: {}", error_text))
}
}
#[tauri::command]
pub async fn rclone_mount_remote(
mount_request: RcloneMountRequest,
_state: State<'_, AppState>,
) -> Result<bool, String> {
let client = Client::new();
let response = client
.post(&format!("{}/mount/mount", RCLONE_API_BASE))
.header("Authorization", RCLONE_AUTH)
.header("Content-Type", "application/json")
.json(&mount_request)
.send()
.await
.map_err(|e| format!("Failed to mount remote: {}", e))?;
if response.status().is_success() {
Ok(true)
} else {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
Err(format!("Failed to mount remote: {}", error_text))
}
}
#[tauri::command]
pub async fn rclone_unmount_remote(
mount_point: String,
_state: State<'_, AppState>,
) -> Result<bool, String> {
let client = Client::new();
let response = client
.post(&format!("{}/mount/unmount", RCLONE_API_BASE))
.header("Authorization", RCLONE_AUTH)
.header("Content-Type", "application/json")
.json(&json!({ "mountPoint": mount_point }))
.send()
.await
.map_err(|e| format!("Failed to unmount remote: {}", e))?;
if response.status().is_success() {
Ok(true)
} else {
let error_text = response
.text()
.await
.unwrap_or_else(|_| "Unknown error".to_string());
Err(format!("Failed to unmount remote: {}", error_text))
}
}
#[tauri::command]
pub async fn create_rclone_mount_remote_process(
config: ProcessConfig,
state: State<'_, AppState>,
) -> Result<ProcessConfig, String> {
let binary_path =
get_rclone_binary_path().map_err(|e| format!("Failed to get rclone binary path: {}", e))?;
let log_file_path =
get_app_logs_dir().map_err(|e| format!("Failed to get app logs directory: {}", e))?;
let log_file_path = log_file_path.join("process_rclone.log");
let rclone_conf_path = binary_path
.parent()
.map(|p| p.join("rclone.conf"))
.ok_or_else(|| "Failed to determine rclone.conf path".to_string())?;
let api_key = get_api_key(state);
let port = get_server_port();
let mut args: Vec<String> = vec![
"mount".into(),
"--config".into(),
rclone_conf_path.to_string_lossy().into_owned(),
];
args.extend(config.args.clone());
let config = ProcessConfig {
id: config.id.clone(),
name: config.name.clone(),
bin_path: binary_path.to_string_lossy().into_owned(),
args,
log_file: log_file_path.to_string_lossy().into_owned(),
working_dir: binary_path
.parent()
.map(|p| p.to_string_lossy().into_owned()),
env_vars: config.env_vars.clone(),
auto_restart: true,
auto_start: config.auto_start,
run_as_admin: false,
created_at: 0,
updated_at: 0,
};
let client = reqwest::Client::new();
let response = client
.post(format!("http://127.0.0.1:{}/api/v1/processes", port))
.json(&config)
.header("Authorization", format!("Bearer {}", api_key))
.send()
.await
.map_err(|e| format!("Failed to send request: {}", e))?;
if response.status().is_success() {
let response_text = response
.text()
.await
.map_err(|e| format!("Failed to read response text: {}", e))?;
let process_config = match serde_json::from_str::<CreateProcessResponse>(&response_text) {
Ok(process_config) => process_config,
Err(e) => {
return Err(format!(
"Failed to parse response: {}, response: {}",
e, response_text
));
}
};
Ok(process_config.data)
} else {
Err(format!(
"Failed to create Rclone Mount Remote process: {}",
response.status()
))
}
}
#[tauri::command]
pub async fn check_mount_status(
mount_point: String,
_state: State<'_, AppState>,
) -> Result<bool, String> {
let path = Path::new(&mount_point);
if !path.exists() {
return Ok(false);
}
#[cfg(target_os = "windows")]
{
if mount_point.len() == 2 && mount_point.ends_with(':') {
let drive_path = format!("{}\\", mount_point);
match fs::read_dir(&drive_path) {
Ok(_) => return Ok(true),
Err(_) => return Ok(false),
}
}
match fs::read_dir(&mount_point) {
Ok(_) => Ok(true),
Err(_) => Ok(false),
}
}
#[cfg(any(target_os = "linux", target_os = "macos"))]
{
match fs::read_dir(&mount_point) {
Ok(_) => Ok(true),
Err(_) => Ok(false),
}
}
}
#[tauri::command]
pub async fn get_mount_info_list(
state: State<'_, AppState>,
) -> Result<Vec<RcloneMountInfo>, String> {
let process_list = get_process_list(state.clone()).await?;
let mut mount_infos = Vec::new();
for process in process_list {
if process.name.starts_with("rclone_mount_") {
let args = &process.config.args;
if args.len() >= 3 && args[0] == "mount" {
let remote_path = args[3].clone();
let mount_point = args[4].clone();
let mount_status =
match check_mount_status(mount_point.clone(), state.clone()).await {
Ok(is_mounted) => {
if process.is_running {
if is_mounted { "mounted" } else { "mounting" }
} else {
if is_mounted {
"unmounting"
} else {
"unmounted"
}
}
}
Err(_) => "error",
};
mount_infos.push(RcloneMountInfo {
name: remote_path.split(':').next().unwrap_or("").to_string(),
process_id: process.id,
remote_path,
mount_point,
status: mount_status.to_string(),
});
}
}
}
Ok(mount_infos)
}

View File

@@ -0,0 +1,35 @@
use crate::core::service::check_service_status as check_service_status_impl;
use crate::core::service::install_service as install_service_impl;
use crate::core::service::restart_service as restart_service_impl;
use crate::core::service::stop_service as stop_service_impl;
use crate::core::service::uninstall_service as uninstall_service_impl;
#[tauri::command]
pub async fn check_service_status() -> Result<bool, String> {
check_service_status_impl().await.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn install_service() -> Result<bool, String> {
install_service_impl().await.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn uninstall_service() -> Result<bool, String> {
uninstall_service_impl().await.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn stop_service() -> Result<bool, String> {
stop_service_impl().await.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn restart_service() -> Result<bool, String> {
restart_service_impl().await.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn start_service() -> Result<bool, String> {
check_service_status_impl().await.map_err(|e| e.to_string())
}

Some files were not shown because too many files have changed in this diff Show More