Compare commits

...
34 Commits
Author SHA1 Message Date
liwei 195dfac74b test 2024-01-19 14:31:03 +08:00
liwei 1c1fab2002 test 2024-01-19 11:54:36 +08:00
madoka773 abccbabc78 fix: wrong debian installed size (#335) 2024-01-19 11:17:50 +08:00
Levi c26eb26b8f fix: default download path on mobile (#337) 2024-01-19 11:12:27 +08:00
Levi 74beea6044 feat: auto create torrent task for http download (#334) 2024-01-18 18:38:44 +08:00
Levi e548d7e0c9 feat: save window size and resize on startup (#332) 2024-01-18 15:00:05 +08:00
madoka773 a996d57914 ci: fix debian 12 depends (#329) 2024-01-18 11:16:50 +08:00
Levi f7dc60ad50 fix: proxy setting only numeric input (#328) 2024-01-18 09:17:06 +08:00
Levi 8425a96ac9 feat: add mirror.ghproxy.com trackers subscribe cdn (#330) 2024-01-17 22:09:37 +08:00
Tracey Lesley 99f4e8c895 feat: add download stats info (#323) 2024-01-17 21:59:01 +08:00
Elliot cc0f61b527 feat: improve zh-TW translation (#327) 2024-01-17 18:16:40 +08:00
Levi 922ef969a6 feat: add thanks item for contributors (#325) 2024-01-16 19:02:20 +08:00
Tracey Lesley 3a542054fc fix: compatible with not follow the http range response standard 2024-01-14 09:58:14 +08:00
Levi 895a8d2ee4 fix: foreground task scope (#314) 2024-01-05 21:49:21 +08:00
madoka773 29d0f5ebcf ci: use flutter distributor (#313) 2024-01-04 12:46:16 +08:00
Levi 31228e3edf release: v1.5.3 2023-12-15 19:23:16 +08:00
Levi 31a32d7e14 fix: handle api panic (#302) 2023-12-15 19:20:56 +08:00
Levi 65fd6fb489 fix: http pause handle (#303) 2023-12-15 19:15:38 +08:00
Levi 953b878a89 fix: adapt mobile proxy settings ui (#301) 2023-12-15 19:09:48 +08:00
Elliot ae4ca3da58 feat: improve zh-TW translation (#300) 2023-12-14 18:06:49 +08:00
Levi d09bd180af release: v1.5.2 2023-12-13 09:38:34 +08:00
liwei 3d24e353c5 docs: docker data path mounted 2023-12-13 08:57:57 +08:00
Levi ce7489b0c0 feat: support volume storage dir on docker (#291) 2023-12-13 08:51:22 +08:00
Levi 2b5091ba21 feat: improve extension engine (#298)
1. support onError event
2. add built-in MessageError
2023-12-12 19:00:42 +08:00
Levi ff32971aca fix: repair invalid filename (#296) 2023-12-12 18:40:36 +08:00
Levi f2af61f9aa fix: sort of completed tasks (#297) 2023-12-12 18:36:40 +08:00
Elliot d935b9d631 feat: improve zh_TW translate (#287) 2023-12-04 23:01:49 +08:00
liwei ae66d1d83d docs: fix contributing 2023-12-04 13:41:27 +08:00
madoka773 aa91ca1d50 ci: linux build use libappindicator (#286) 2023-12-04 13:36:27 +08:00
liwei 2d4bdea5cb fix: android file open 2023-12-02 22:51:44 +08:00
liwei 2f2393ac20 fix: i18n word 2023-12-02 19:22:37 +08:00
Levi 5a761e244a release: v1.5.1 2023-12-02 18:47:07 +08:00
Levi 6538766780 fix: incorrect file name in task files view (#285) 2023-12-02 18:45:16 +08:00
Levi 16b7a3d5b3 feat: support proxy (#284) 2023-12-02 18:36:52 +08:00
93 changed files with 1937 additions and 1569 deletions

No files matched your search

+2
View File
@@ -19,6 +19,8 @@ categories:
label: 'doc' label: 'doc'
- title: '🚀 CI/CD' - title: '🚀 CI/CD'
label: 'ci' label: 'ci'
- title: '🌎 Internationalization'
label: 'translation'
change-template: '- $TITLE @$AUTHOR (#$NUMBER)' change-template: '- $TITLE @$AUTHOR (#$NUMBER)'
version-resolver: version-resolver:
major: major:
+17 -111
View File
@@ -223,126 +223,32 @@ jobs:
with: with:
flutter-version: ${{ env.FLUTTER_VERSION }} flutter-version: ${{ env.FLUTTER_VERSION }}
- run: | - run: |
sudo apt-get update -y sudo apt update -y
sudo apt-get install -y ninja-build libgtk-3-dev libayatana-appindicator3-dev # flutter build dependencies
sudo apt install -y ninja-build libgtk-3-dev libappindicator3-dev
# rpm build dependencies
sudo apt install -y rpm patchelf
# appimage build dependencies
sudo apt install -y libfuse2 locate
wget -O appimagetool "https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage"
chmod +x appimagetool
sudo mv appimagetool /usr/local/bin/
- name: Build - name: Build
env: env:
VERSION: ${{ needs.get-release.outputs.tag_name }} VERSION: ${{ needs.get-release.outputs.tag_name }}
run: | run: |
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/linux/bundle/lib/libgopeed.so github.com/GopeedLab/gopeed/bind/desktop go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/linux/bundle/lib/libgopeed.so github.com/GopeedLab/gopeed/bind/desktop
cd ui/flutter cd ui/flutter
flutter build linux dart pub global activate -sgit https://github.com/GopeedLab/flutter_distributor.git --git-path packages/flutter_distributor
mkdir -p build/dist flutter_distributor package --platform linux --targets appimage,deb
cd dist/*
# Build portable mv gopeed-*-linux.AppImage Gopeed-${VERSION}-linux-x86_64.AppImage
tar -C build/linux/x64/release/bundle -czaf build/dist/Gopeed-$VERSION-linux-amd64-portable.tar.gz ./ mv gopeed-*-linux.deb Gopeed-${VERSION}-linux-amd64.deb
# Build deb package
mkdir -p debian/gopeed/opt/gopeed
mkdir -p debian/gopeed/usr/share/applications
mkdir -p debian/gopeed/usr/share/icons/hicolor/scalable/apps
mkdir -p debian/gopeed/DEBIAN
cp -r build/linux/x64/release/bundle/* debian/gopeed/opt/gopeed/
cp assets/icon/icon.svg debian/gopeed/usr/share/icons/hicolor/scalable/apps/com.gopeed.Gopeed.svg
cat>debian/gopeed/DEBIAN/postinst<<EOF
#!/bin/bash
ln -sf /opt/gopeed/gopeed /usr/bin/gopeed
EOF
cat>debian/gopeed/DEBIAN/postrm<<EOF
#!/bin/bash
rm -rf /usr/bin/gopeed
EOF
chmod 0755 debian/gopeed/DEBIAN/postinst
chmod 0755 debian/gopeed/DEBIAN/postrm
cat>debian/gopeed/DEBIAN/control<<EOF
Package: gopeed
Version: ${VERSION:1}
Architecture: amd64
Essential: no
Priority: optional
Depends:
Maintainer: monkeyWie
Description: High speed downloader that supports all platforms.
EOF
cp linux/assets/com.gopeed.Gopeed.desktop debian/gopeed/usr/share/applications/gopeed.desktop
dpkg-deb --build debian/gopeed
mv debian/gopeed.deb build/dist/Gopeed-$VERSION-linux-amd64.deb
# Build AppImage
sudo apt-get -y install libfuse2
wget -O appimage-builder https://github.com/AppImageCrafters/appimage-builder/releases/download/v1.1.0/appimage-builder-1.1.0-x86_64.AppImage
chmod +x appimage-builder
mkdir AppDir
cp -r build/linux/x64/release/bundle/* AppDir
mkdir -p AppDir/usr/share/icons/hicolor/scalable/apps/
cp assets/icon/icon.svg AppDir/usr/share/icons/hicolor/scalable/apps/gopeed.svg
cat>AppImageBuilder.yml<<EOF
version: 1
AppDir:
path: ${PWD}/AppDir
app_info:
id: com.gopeed.gopeed
name: Gopeed
icon: gopeed
version: ${VERSION:1}
exec: gopeed
exec_args: \$@
apt:
arch: amd64
allow_unauthenticated: true
sources:
- sourceline: deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ jammy main restricted
universe multiverse
- sourceline: deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ jammy-updates main
restricted universe multiverse
- sourceline: deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ jammy-backports
main restricted universe multiverse
- sourceline: deb http://security.ubuntu.com/ubuntu/ jammy-security main restricted
universe multiverse
include: []
files:
include: []
exclude:
- usr/share/man
- usr/share/doc/*/README.*
- usr/share/doc/*/changelog.*
- usr/share/doc/*/NEWS.*
- usr/share/doc/*/TODO.*
test:
fedora-30:
image: appimagecrafters/tests-env:fedora-30
command: ./AppRun
debian-stable:
image: appimagecrafters/tests-env:debian-stable
command: ./AppRun
archlinux-latest:
image: appimagecrafters/tests-env:archlinux-latest
command: ./AppRun
centos-7:
image: appimagecrafters/tests-env:centos-7
command: ./AppRun
ubuntu-xenial:
image: appimagecrafters/tests-env:ubuntu-xenial
command: ./AppRun
AppImage:
arch: x86_64
update-information: guess
EOF
./appimage-builder --skip-tests --recipe AppImageBuilder.yml
mv Gopeed-*-x86_64.AppImage build/dist/Gopeed-$VERSION-linux-amd64.AppImage
- name: Upload - name: Upload
uses: shogo82148/actions-upload-release-asset@v1 uses: shogo82148/actions-upload-release-asset@v1
with: with:
upload_url: ${{ needs.get-release.outputs.upload_url }} upload_url: ${{ needs.get-release.outputs.upload_url }}
asset_path: ui/flutter/build/dist/* asset_path: ui/flutter/dist/*/*
overwrite: true overwrite: true
build-snap: build-snap:
if: ${{ github.event.inputs.platform == 'all' || github.event.inputs.platform == 'snap' }} if: ${{ github.event.inputs.platform == 'all' || github.event.inputs.platform == 'snap' }}
@@ -405,7 +311,7 @@ jobs:
plugin: flutter plugin: flutter
stage-packages: stage-packages:
- libgtk-3-dev - libgtk-3-dev
- libayatana-appindicator3-dev - libappindicator3-dev
flutter-target: lib/main.dart flutter-target: lib/main.dart
EOF EOF
+1 -1
View File
@@ -4,7 +4,7 @@
*.dll *.dll
*.so *.so
*.dylib *.dylib
ui/flutter/dist/
# Test binary, built with `go test -c` # Test binary, built with `go test -c`
*.test *.test
+2 -23
View File
@@ -17,17 +17,9 @@ start the front-end flutter project in `debug` mode to run.
## Translation ## Translation
The internationalization files of Gopeed are located in the `ui/flutter/assets/locales` directory. The internationalization files of Gopeed are located in the `ui/flutter/lib/i18n/langs` directory.
You only need to add the corresponding language file in this directory. You only need to add the corresponding language file in this directory.
Generate locales after you edit locales:
```
get generate locales
```
Please refer to `en_us.dart` for translation. Please refer to `en_us.dart` for translation.
## flutter development ## flutter development
@@ -38,17 +30,4 @@ Turn on build_runner watcher if you want to edit api/models:
``` ```
flutter pub run build_runner watch flutter pub run build_runner watch
``` ```
get-cli commands usages:
```
create:
controller: Generate controller
page: Use to generate pages
view: Generate view
generate:
locales: Generate translation file from json files
model: generate Class model from json
```
+1 -22
View File
@@ -17,17 +17,9 @@
## 翻訳 ## 翻訳
Gopeed の国際化ファイルは `ui/flutter/assets/locales` ディレクトリにあります。 Gopeed の国際化ファイルは `ui/flutter/lib/i18n/langs` ディレクトリにあります。
このディレクトリに対応する言語ファイルを追加するだけでよいです。 このディレクトリに対応する言語ファイルを追加するだけでよいです。
ロケール編集後にロケールを生成:
```
get generate locales
```
翻訳については `en_us.dart` を参照してください。 翻訳については `en_us.dart` を参照してください。
## flutter での開発 ## flutter での開発
@@ -39,16 +31,3 @@ api/models を編集したい場合は build_runner watcher をオンにしま
``` ```
flutter pub run build_runner watch flutter pub run build_runner watch
``` ```
get-cli コマンドの使用法:
```
create:
controller: Generate controller
page: Use to generate pages
view: Generate view
generate:
locales: Generate translation file from json files
model: generate Class model from json
```
+2 -20
View File
@@ -14,15 +14,9 @@ flutter 项目即可运行。
## 翻译 ## 翻译
Gopeed 的国际化文件位于 `ui/flutter/assets/locales` 目录下,只需要在该目录下添加对应的语言文件即可。 Gopeed 的国际化文件位于 `ui/flutter/lib/i18n/langs` 目录下,只需要在该目录下添加对应的语言文件即可。
编辑locales后请运行以下命令: 请注意以 `en_us.dart` 为参照进行翻译。
```
get generate locales
```
请注意以 `en_US.json` 为参照进行翻译。
## flutter开发 ## flutter开发
@@ -34,15 +28,3 @@ get generate locales
flutter pub run build_runner watch flutter pub run build_runner watch
``` ```
适用get-cli 命令:
```
create:
controller: Generate controller
page: Use to generate pages
view: Generate view
generate:
locales: Generate translation file from json files
model: generate Class model from json
```
+2 -20
View File
@@ -12,15 +12,10 @@
## 翻譯 ## 翻譯
Gopeed 的翻譯文件位於 `ui/flutter/assets/locales` 目錄中,只需要修改或新建翻譯文件即可。 Gopeed 的翻譯文件位於 `ui/flutter/lib/i18n/langs` 目錄中,只需要修改或新建翻譯文件即可。
修改locales後請執行一下指令:
``` 請以 `en_us.dart` 作為參照。
get generate locales
```
請以 `en_US.json` 作為參照。
## flutter開發 ## flutter開發
@@ -31,16 +26,3 @@ get generate locales
``` ```
flutter pub run build_runner watch flutter pub run build_runner watch
``` ```
適用於 get-cli 的指令:
```
create:
controller: Generate controller
page: Use to generate pages
view: Generate view
generate:
locales: Generate translation file from json files
model: generate Class model from json
```
+1
View File
@@ -17,5 +17,6 @@ FROM alpine:3.14.2
LABEL maintainer="monkeyWie" LABEL maintainer="monkeyWie"
WORKDIR /app WORKDIR /app
COPY --from=go /app/dist/gopeed ./ COPY --from=go /app/dist/gopeed ./
VOLUME ["/app/storage"]
EXPOSE 9999 EXPOSE 9999
ENTRYPOINT ["./gopeed"] ENTRYPOINT ["./gopeed"]
+4 -3
View File
@@ -16,7 +16,7 @@
Gopeed (full name Go Speed), a high-speed downloader developed by `Golang` + `Flutter`, supports (HTTP, BitTorrent, Magnet) protocol, and supports all platforms. In addition to basic download functions, Gopeed is also a highly customizable downloader that supports implementing more features through integration with [APIs](https://docs.gopeed.com/dev-api.html) or installation and development of [extensions](https://docs.gopeed.com/dev-extension.html). Gopeed (full name Go Speed), a high-speed downloader developed by `Golang` + `Flutter`, supports (HTTP, BitTorrent, Magnet) protocol, and supports all platforms. In addition to basic download functions, Gopeed is also a highly customizable downloader that supports implementing more features through integration with [APIs](https://docs.gopeed.com/dev-api.html) or installation and development of [extensions](https://docs.gopeed.com/dev-extension.html).
Visit ✈ [Official Website](https://gopeed.com) | 📖 [Develop Docs](https://docs.gopeed.com) Visit ✈ [Official Website](https://gopeed.com) | 📖 [Official Docs](https://docs.gopeed.com)
## Install ## Install
@@ -47,9 +47,11 @@ go install github.com/GopeedLab/gopeed/cmd/gopeed@latest
#### Start directly #### Start directly
```bash ```bash
docker run -d -p 9999:9999 -v /path/to/download:/root/Downloads liwei2633/gopeed docker run -d -p 9999:9999 -v /path/to/download:/root/Downloads -v /path/to/storage:/app/storage liwei2633/gopeed
``` ```
[More details for docker](https://docs.gopeed.com/install.html#docker-installation)
#### Using Docker Compose #### Using Docker Compose
```bash ```bash
@@ -160,7 +162,6 @@ cd ../../
rm -rf cmd/web/dist rm -rf cmd/web/dist
cp -r ui/flutter/build/web cmd/web/dist cp -r ui/flutter/build/web cmd/web/dist
go build -tags nosqlite,web -ldflags="-s -w" -o bin/ github.com/GopeedLab/gopeed/cmd/web go build -tags nosqlite,web -ldflags="-s -w" -o bin/ github.com/GopeedLab/gopeed/cmd/web
go run cmd/web/main.go
``` ```
## Credits ## Credits
+3 -2
View File
@@ -46,9 +46,11 @@ go install github.com/GopeedLab/gopeed/cmd/gopeed@latest
#### 直接始める #### 直接始める
```bash ```bash
docker run -d -p 9999:9999 -v /path/to/download:/root/Downloads liwei2633/gopeed docker run -d -p 9999:9999 -v /path/to/download:/root/Downloads -v /path/to/storage:/app/storage liwei2633/gopeed
``` ```
[Dockerの使用については](https://docs.gopeed.com/install.html#docker-installation)
#### Docker Compose の使用 #### Docker Compose の使用
```bash ```bash
@@ -159,7 +161,6 @@ cd ../../
rm -rf cmd/web/dist rm -rf cmd/web/dist
cp -r ui/flutter/build/web cmd/web/dist cp -r ui/flutter/build/web cmd/web/dist
go build -tags nosqlite,web -ldflags="-s -w" -o bin/ github.com/GopeedLab/gopeed/cmd/web go build -tags nosqlite,web -ldflags="-s -w" -o bin/ github.com/GopeedLab/gopeed/cmd/web
go run cmd/web/main.go
``` ```
## 感謝 ## 感謝
+5 -4
View File
@@ -13,9 +13,9 @@
## 介绍 ## 介绍
Gopeed(全称 Go Speed),是一款由`Golang`+`Flutter`开发的高速下载器,支持(HTTP、BitTorrent、Magnet)协议下载,并且支持全平台使用。除了基本的下载功能外,Gopeed 还是一款高度可定制化的下载器,支持通过对接[APIs](https://docs.gopeed.com/zh/dev-api.html)或者安装和开发[扩展](https://docs.gopeed.com/zh/dev-extension.html)来实现更多的功能。 Gopeed(全称 Go Speed),直译过来中文名叫做`够快下载器`(不是狗屁下载器!),是一款由`Golang`+`Flutter`开发的高速下载器,支持(HTTP、BitTorrent、Magnet)协议下载,并且支持全平台使用。除了基本的下载功能外,Gopeed 还是一款高度可定制化的下载器,支持通过对接[APIs](https://docs.gopeed.com/zh/dev-api.html)或者安装和开发[扩展](https://docs.gopeed.com/zh/dev-extension.html)来实现更多的功能。
访问 ✈ [官方网站](https://gopeed.com/zh-CN) | 📖 [开发文档](https://docs.gopeed.com/zh/) 访问 ✈ [官方网站](https://gopeed.com/zh-CN) | 📖 [官方文档](https://docs.gopeed.com/zh/)
## 安装 ## 安装
@@ -46,9 +46,11 @@ go install github.com/GopeedLab/gopeed/cmd/gopeed@latest
#### 直接运行 #### 直接运行
```bash ```bash
docker run -d -p 9999:9999 -v /path/to/download:/root/Downloads liwei2633/gopeed docker run -d -p 9999:9999 -v /path/to/download:/root/Downloads -v /path/to/storage:/app/storage liwei2633/gopeed
``` ```
[更多关于 Docker 的使用](https://docs.gopeed.com/zh/install.html#docker-%E5%AE%89%E8%A3%85)
#### 使用 Docker Compose #### 使用 Docker Compose
```bash ```bash
@@ -159,7 +161,6 @@ cd ../../
rm -rf cmd/web/dist rm -rf cmd/web/dist
cp -r ui/flutter/build/web cmd/web/dist cp -r ui/flutter/build/web cmd/web/dist
go build -tags nosqlite,web -ldflags="-s -w" -o bin/ github.com/GopeedLab/gopeed/cmd/web go build -tags nosqlite,web -ldflags="-s -w" -o bin/ github.com/GopeedLab/gopeed/cmd/web
go run cmd/web/main.go
``` ```
## 感谢 ## 感谢
+3 -2
View File
@@ -46,9 +46,11 @@ go install github.com/GopeedLab/gopeed/cmd/gopeed@latest
#### 直接執行 #### 直接執行
```bash ```bash
docker run -d -p 9999:9999 -v /path/to/download:/root/Downloads liwei2633/gopeed docker run -d -p 9999:9999 -v /path/to/download:/root/Downloads -v /path/to/storage:/app/storage liwei2633/gopeed
``` ```
[更多關於 Docker 的使用](https://docs.gopeed.com/zh/install.html#docker-%E5%AE%89%E8%A3%85)
#### 使用 Docker Compose #### 使用 Docker Compose
```bash ```bash
@@ -159,7 +161,6 @@ cd ../../
rm -rf cmd/web/dist rm -rf cmd/web/dist
cp -r ui/flutter/build/web cmd/web/dist cp -r ui/flutter/build/web cmd/web/dist
go build -tags nosqlite,web -ldflags="-s -w" -o bin/ github.com/GopeedLab/gopeed/cmd/web go build -tags nosqlite,web -ldflags="-s -w" -o bin/ github.com/GopeedLab/gopeed/cmd/web
go run cmd/web/main.go
``` ```
## 感謝 ## 感謝
+1 -1
View File
@@ -23,7 +23,7 @@ func parse() *args {
cliArgs.Address = flag.String("A", "0.0.0.0", "Bind Address") cliArgs.Address = flag.String("A", "0.0.0.0", "Bind Address")
cliArgs.Port = flag.Int("P", 9999, "Bind Port") cliArgs.Port = flag.Int("P", 9999, "Bind Port")
cliArgs.Username = flag.String("u", "gopeed", "HTTP Basic Auth Username") cliArgs.Username = flag.String("u", "gopeed", "HTTP Basic Auth Username")
cliArgs.Password = flag.String("p", "", "HTTP Basic Auth Password") cliArgs.Password = flag.String("p", "", "HTTP Basic Auth Pwd")
cliArgs.ApiToken = flag.String("T", "", "API token, that can only be used when basic authentication is enabled.") cliArgs.ApiToken = flag.String("T", "", "API token, that can only be used when basic authentication is enabled.")
cliArgs.configPath = flag.String("c", "./config.json", "Config file path") cliArgs.configPath = flag.String("c", "./config.json", "Config file path")
flag.Parse() flag.Parse()
+9
View File
@@ -9,6 +9,8 @@ import (
"github.com/GopeedLab/gopeed/cmd" "github.com/GopeedLab/gopeed/cmd"
"github.com/GopeedLab/gopeed/pkg/rest/model" "github.com/GopeedLab/gopeed/pkg/rest/model"
"io/fs" "io/fs"
"os"
"path/filepath"
) )
//go:embed dist/* //go:embed dist/*
@@ -29,10 +31,17 @@ func main() {
} }
} }
exe, err := os.Executable()
if err != nil {
panic(err)
}
dir := filepath.Dir(exe)
cfg := &model.StartConfig{ cfg := &model.StartConfig{
Network: "tcp", Network: "tcp",
Address: fmt.Sprintf("%s:%d", *args.Address, *args.Port), Address: fmt.Sprintf("%s:%d", *args.Address, *args.Port),
Storage: model.StorageBolt, Storage: model.StorageBolt,
StorageDir: filepath.Join(dir, "storage"),
ApiToken: *args.ApiToken, ApiToken: *args.ApiToken,
ProductionMode: true, ProductionMode: true,
WebEnable: true, WebEnable: true,
+3 -2
View File
@@ -4,8 +4,9 @@ services:
gopeed: gopeed:
container_name: gopeed container_name: gopeed
ports: ports:
- 9999:9999 # HTTP port (host:container) - "9999:9999" # HTTP port (host:container)
image: liwei2633/gopeed image: liwei2633/gopeed
volumes: volumes:
- ~/Downloads:/root/Downloads # replace with your prefer path - ~/gopeed/Downloads:/root/Downloads # mount download path
#- ~/gopeed/storage:/app/storage # if you need to mount storage path, uncomment this line
restart: unless-stopped restart: unless-stopped
+1
View File
@@ -5,6 +5,7 @@ go 1.19
require ( require (
github.com/anacrolix/missinggo/v2 v2.7.2-0.20230527121029-a582b4f397b9 github.com/anacrolix/missinggo/v2 v2.7.2-0.20230527121029-a582b4f397b9
github.com/anacrolix/torrent v1.52.5 github.com/anacrolix/torrent v1.52.5
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5
github.com/dop251/goja v0.0.0-20231027120936-b396bb4c349d github.com/dop251/goja v0.0.0-20231027120936-b396bb4c349d
github.com/dop251/goja_nodejs v0.0.0-20231122114759-e84d9a924c5c github.com/dop251/goja_nodejs v0.0.0-20231122114759-e84d9a924c5c
github.com/go-git/go-git/v5 v5.8.1 github.com/go-git/go-git/v5 v5.8.1
+2 -13
View File
@@ -8,7 +8,6 @@ crawshaw.io/sqlite v0.3.3-0.20220618202545-d1964889ea3c/go.mod h1:igAO5JulrQ1Dbd
dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk= dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk=
dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
filippo.io/edwards25519 v1.0.0-rc.1 h1:m0VOOB23frXZvAOK44usCgLWvtsxIoMCTBGJZlpmGfU= filippo.io/edwards25519 v1.0.0-rc.1 h1:m0VOOB23frXZvAOK44usCgLWvtsxIoMCTBGJZlpmGfU=
filippo.io/edwards25519 v1.0.0-rc.1/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY= github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=
github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow=
@@ -34,7 +33,6 @@ github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuy
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alexflint/go-scalar v1.1.0/go.mod h1:LoFvNMqS1CPrMVltza4LvnGKhaSpc3oyLEBUZVhhS2o=
github.com/anacrolix/chansync v0.3.0 h1:lRu9tbeuw3wl+PhMu/r+JJCRu5ArFXIluOgdF0ao6/U= github.com/anacrolix/chansync v0.3.0 h1:lRu9tbeuw3wl+PhMu/r+JJCRu5ArFXIluOgdF0ao6/U=
github.com/anacrolix/chansync v0.3.0/go.mod h1:DZsatdsdXxD0WiwcGl0nJVwyjCKMDv+knl1q2iBjA2k= github.com/anacrolix/chansync v0.3.0/go.mod h1:DZsatdsdXxD0WiwcGl0nJVwyjCKMDv+knl1q2iBjA2k=
github.com/anacrolix/dht/v2 v2.19.2-0.20221121215055-066ad8494444 h1:8V0K09lrGoeT2KRJNOtspA7q+OMxGwQqK/Ug0IiaaRE= github.com/anacrolix/dht/v2 v2.19.2-0.20221121215055-066ad8494444 h1:8V0K09lrGoeT2KRJNOtspA7q+OMxGwQqK/Ug0IiaaRE=
@@ -74,7 +72,6 @@ github.com/anacrolix/mmsg v1.0.0 h1:btC7YLjOn29aTUAExJiVUhQOuf/8rhm+/nWCMAnL3Hg=
github.com/anacrolix/mmsg v1.0.0/go.mod h1:x8kRaJY/dCrY9Al0PEcj1mb/uFHwP6GCJ9fLl4thEPc= github.com/anacrolix/mmsg v1.0.0/go.mod h1:x8kRaJY/dCrY9Al0PEcj1mb/uFHwP6GCJ9fLl4thEPc=
github.com/anacrolix/multiless v0.3.0 h1:5Bu0DZncjE4e06b9r1Ap2tUY4Au0NToBP5RpuEngSis= github.com/anacrolix/multiless v0.3.0 h1:5Bu0DZncjE4e06b9r1Ap2tUY4Au0NToBP5RpuEngSis=
github.com/anacrolix/multiless v0.3.0/go.mod h1:TrCLEZfIDbMVfLoQt5tOoiBS/uq4y8+ojuEVVvTNPX4= github.com/anacrolix/multiless v0.3.0/go.mod h1:TrCLEZfIDbMVfLoQt5tOoiBS/uq4y8+ojuEVVvTNPX4=
github.com/anacrolix/publicip v0.2.0/go.mod h1:67G1lVkLo8UjdEcJkwScWVTvlJ35OCDsRJoWXl/wi4g=
github.com/anacrolix/stm v0.2.0/go.mod h1:zoVQRvSiGjGoTmbM0vSLIiaKjWtNPeTvXUSdJQA4hsg= github.com/anacrolix/stm v0.2.0/go.mod h1:zoVQRvSiGjGoTmbM0vSLIiaKjWtNPeTvXUSdJQA4hsg=
github.com/anacrolix/stm v0.4.0 h1:tOGvuFwaBjeu1u9X1eIh9TX8OEedEiEQ1se1FjhFnXY= github.com/anacrolix/stm v0.4.0 h1:tOGvuFwaBjeu1u9X1eIh9TX8OEedEiEQ1se1FjhFnXY=
github.com/anacrolix/stm v0.4.0/go.mod h1:GCkwqWoAsP7RfLW+jw+Z0ovrt2OO7wRzcTtFYMYY5t8= github.com/anacrolix/stm v0.4.0/go.mod h1:GCkwqWoAsP7RfLW+jw+Z0ovrt2OO7wRzcTtFYMYY5t8=
@@ -85,7 +82,6 @@ github.com/anacrolix/sync v0.4.0/go.mod h1:BbecHL6jDSExojhNtgTFSBcdGerzNc64tz3DC
github.com/anacrolix/tagflag v0.0.0-20180109131632-2146c8d41bf0/go.mod h1:1m2U/K6ZT+JZG0+bdMK6qauP49QT4wE5pmhJXOKKCHw= github.com/anacrolix/tagflag v0.0.0-20180109131632-2146c8d41bf0/go.mod h1:1m2U/K6ZT+JZG0+bdMK6qauP49QT4wE5pmhJXOKKCHw=
github.com/anacrolix/tagflag v1.0.0/go.mod h1:1m2U/K6ZT+JZG0+bdMK6qauP49QT4wE5pmhJXOKKCHw= github.com/anacrolix/tagflag v1.0.0/go.mod h1:1m2U/K6ZT+JZG0+bdMK6qauP49QT4wE5pmhJXOKKCHw=
github.com/anacrolix/tagflag v1.1.0/go.mod h1:Scxs9CV10NQatSmbyjqmqmeQNwGzlNe0CMUMIxqHIG8= github.com/anacrolix/tagflag v1.1.0/go.mod h1:Scxs9CV10NQatSmbyjqmqmeQNwGzlNe0CMUMIxqHIG8=
github.com/anacrolix/tagflag v1.3.0/go.mod h1:Scxs9CV10NQatSmbyjqmqmeQNwGzlNe0CMUMIxqHIG8=
github.com/anacrolix/torrent v1.52.5 h1:jWowdx+EU6zFVfBwmnL0d3H4J6vTFEGOrHI35YdfIT8= github.com/anacrolix/torrent v1.52.5 h1:jWowdx+EU6zFVfBwmnL0d3H4J6vTFEGOrHI35YdfIT8=
github.com/anacrolix/torrent v1.52.5/go.mod h1:CcM8oPMYye5J42cSqJrmUpqwRFgSsJQ1jCEHwygqnqQ= github.com/anacrolix/torrent v1.52.5/go.mod h1:CcM8oPMYye5J42cSqJrmUpqwRFgSsJQ1jCEHwygqnqQ=
github.com/anacrolix/upnp v0.1.3-0.20220123035249-922794e51c96 h1:QAVZ3pN/J4/UziniAhJR2OZ9Ox5kOY2053tBbbqUPYA= github.com/anacrolix/upnp v0.1.3-0.20220123035249-922794e51c96 h1:QAVZ3pN/J4/UziniAhJR2OZ9Ox5kOY2053tBbbqUPYA=
@@ -95,6 +91,7 @@ github.com/anacrolix/utp v0.1.0/go.mod h1:MDwc+vsGEq7RMw6lr2GKOEqjWny5hO5OZXRVNa
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8= github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk= github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg= github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/benbjohnson/immutable v0.2.0/go.mod h1:uc6OHo6PN2++n98KHLxW8ef4W42ylHiQSENghE1ezxI= github.com/benbjohnson/immutable v0.2.0/go.mod h1:uc6OHo6PN2++n98KHLxW8ef4W42ylHiQSENghE1ezxI=
@@ -144,7 +141,6 @@ github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFP
github.com/edsrzf/mmap-go v1.1.0 h1:6EUwBLQ/Mcr1EYLE4Tn1VdW1A4ckqCQWZBw8Hr0kjpQ= github.com/edsrzf/mmap-go v1.1.0 h1:6EUwBLQ/Mcr1EYLE4Tn1VdW1A4ckqCQWZBw8Hr0kjpQ=
github.com/edsrzf/mmap-go v1.1.0/go.mod h1:19H/e8pUPLicwkyNgOykDXkJ9F0MHE+Z52B8EIth78Q= github.com/edsrzf/mmap-go v1.1.0/go.mod h1:19H/e8pUPLicwkyNgOykDXkJ9F0MHE+Z52B8EIth78Q=
github.com/elazarl/goproxy v0.0.0-20221015165544-a0805db90819 h1:RIB4cRk+lBqKK3Oy0r2gRX4ui7tuhiZq2SuTtTCi0/0= github.com/elazarl/goproxy v0.0.0-20221015165544-a0805db90819 h1:RIB4cRk+lBqKK3Oy0r2gRX4ui7tuhiZq2SuTtTCi0/0=
github.com/elliotchance/orderedmap v1.4.0/go.mod h1:wsDwEaX5jEoyhbs7x93zk2H/qv0zwuhg4inXhDkYqys=
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
github.com/felixge/httpsnoop v1.0.1 h1:lvB5Jl89CsZtGIWuTcDM1E/vkVs49/Ml7JJe07l8SPQ= github.com/felixge/httpsnoop v1.0.1 h1:lvB5Jl89CsZtGIWuTcDM1E/vkVs49/Ml7JJe07l8SPQ=
@@ -242,7 +238,6 @@ github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq
github.com/ianlancetaylor/demangle v0.0.0-20220319035150-800ac71e25c2/go.mod h1:aYm2/VgdVmcIU8iMfdMvDMsRAQjcfZSKFby6HOFvi/w= github.com/ianlancetaylor/demangle v0.0.0-20220319035150-800ac71e25c2/go.mod h1:aYm2/VgdVmcIU8iMfdMvDMsRAQjcfZSKFby6HOFvi/w=
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A= github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo= github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=
github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/jtolds/gls v4.2.1+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/jtolds/gls v4.2.1+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
@@ -282,7 +277,6 @@ github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3Rllmb
github.com/mschoch/smat v0.0.0-20160514031455-90eadee771ae/go.mod h1:qAyveg+e4CE+eKJXWVjKXM4ck2QobLqTDytGJbLLhJg= github.com/mschoch/smat v0.0.0-20160514031455-90eadee771ae/go.mod h1:qAyveg+e4CE+eKJXWVjKXM4ck2QobLqTDytGJbLLhJg=
github.com/mschoch/smat v0.2.0 h1:8imxQsjDm8yFEAVBe7azKmKSgzSkZXDuKkSq9374khM= github.com/mschoch/smat v0.2.0 h1:8imxQsjDm8yFEAVBe7azKmKSgzSkZXDuKkSq9374khM=
github.com/mschoch/smat v0.2.0/go.mod h1:kc9mz7DoBKqDyiRL7VZN8KvXQMWeTaVnttLRXOlotKw= github.com/mschoch/smat v0.2.0/go.mod h1:kc9mz7DoBKqDyiRL7VZN8KvXQMWeTaVnttLRXOlotKw=
github.com/multiformats/go-base36 v0.1.0/go.mod h1:kFGE83c6s80PklsHO9sRn2NCoffoRdUUOENyW/Vv6sM=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
@@ -368,7 +362,6 @@ github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsT
github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A=
github.com/prometheus/procfs v0.0.11/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/procfs v0.0.11/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
@@ -404,8 +397,8 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/tidwall/btree v1.6.0 h1:LDZfKfQIBHGHWSwckhXI0RPSXzlo+KYdjK7FWSqOzzg= github.com/tidwall/btree v1.6.0 h1:LDZfKfQIBHGHWSwckhXI0RPSXzlo+KYdjK7FWSqOzzg=
github.com/tidwall/btree v1.6.0/go.mod h1:twD9XRA5jj9VUQGELzDO4HPQTNJsoWWfYEL+EUQ2cKY= github.com/tidwall/btree v1.6.0/go.mod h1:twD9XRA5jj9VUQGELzDO4HPQTNJsoWWfYEL+EUQ2cKY=
github.com/tinylib/msgp v1.0.2/go.mod h1:+d+yLhGm8mzTaHzB+wgMYrodPfmZrzkirds8fDWklFE= github.com/tinylib/msgp v1.0.2/go.mod h1:+d+yLhGm8mzTaHzB+wgMYrodPfmZrzkirds8fDWklFE=
@@ -419,8 +412,6 @@ github.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM
github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw= github.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.etcd.io/bbolt v1.3.7-0.20231005155708-db45d0d6b1f6 h1:NkHVT1GBVV9hUj1iWglFxAuNlvLHELFn71U2H7aOIog=
go.etcd.io/bbolt v1.3.7-0.20231005155708-db45d0d6b1f6/go.mod h1:tDI2vlr15+D9cyN3odhFrZJi3oJj8HlHaOEFPrUiGSY=
go.etcd.io/bbolt v1.3.8 h1:xs88BrvEv273UsB79e0hcVrlUWmS0a8upikMFhSyAtA= go.etcd.io/bbolt v1.3.8 h1:xs88BrvEv273UsB79e0hcVrlUWmS0a8upikMFhSyAtA=
go.etcd.io/bbolt v1.3.8/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw= go.etcd.io/bbolt v1.3.8/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw=
go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk=
@@ -537,8 +528,6 @@ golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q= golang.org/x/sys v0.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=
golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+2
View File
@@ -1,12 +1,14 @@
package controller package controller
import ( import (
"net/url"
"os" "os"
"path/filepath" "path/filepath"
) )
type Controller struct { type Controller struct {
GetConfig func(v any) bool GetConfig func(v any) bool
ProxyUrl *url.URL
FileController FileController
//ContextDialer() (proxy.Dialer, error) //ContextDialer() (proxy.Dialer, error)
} }
+2
View File
@@ -21,6 +21,8 @@ type Fetcher interface {
Pause() error Pause() error
Close() error Close() error
// Stats refreshes health statistics and returns the latest information
Stats() any
// Meta returns the meta information of the download. // Meta returns the meta information of the download.
Meta() *FetcherMeta Meta() *FetcherMeta
// Progress returns the progress of the download. // Progress returns the progress of the download.
+15
View File
@@ -9,6 +9,7 @@ import (
"github.com/GopeedLab/gopeed/pkg/util" "github.com/GopeedLab/gopeed/pkg/util"
"github.com/anacrolix/torrent" "github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/metainfo" "github.com/anacrolix/torrent/metainfo"
"net/http"
"path/filepath" "path/filepath"
"sync" "sync"
"sync/atomic" "sync/atomic"
@@ -63,6 +64,9 @@ func (f *Fetcher) initClient() (err error) {
cfg := torrent.NewDefaultClientConfig() cfg := torrent.NewDefaultClientConfig()
cfg.ListenPort = f.config.ListenPort cfg.ListenPort = f.config.ListenPort
if f.ctl.ProxyUrl != nil {
cfg.HTTPProxy = http.ProxyURL(f.ctl.ProxyUrl)
}
cfg.DefaultStorage = newFileOpts(newFileClientOpts{ cfg.DefaultStorage = newFileOpts(newFileClientOpts{
ClientBaseDir: cfg.DataDir, ClientBaseDir: cfg.DataDir,
HandleFileTorrent: func(infoHash metainfo.Hash, ft *fileTorrentImpl) { HandleFileTorrent: func(infoHash metainfo.Hash, ft *fileTorrentImpl) {
@@ -124,6 +128,7 @@ func (f *Fetcher) Start() (err error) {
file.Download() file.Download()
} }
} }
return return
} }
@@ -184,6 +189,16 @@ func (f *Fetcher) Meta() *fetcher.FetcherMeta {
return f.meta return f.meta
} }
func (f *Fetcher) Stats() any {
stats := f.torrent.Stats()
baseStats := &bt.Stats{
TotalPeers: stats.TotalPeers,
ActivePeers: stats.ActivePeers,
ConnectedSeeders: stats.ConnectedSeeders,
}
return baseStats
}
func (f *Fetcher) Progress() fetcher.Progress { func (f *Fetcher) Progress() fetcher.Progress {
if !f.torrentReady.Load() { if !f.torrentReady.Load() {
return f.progress return f.progress
+13 -2
View File
@@ -8,6 +8,8 @@ import (
"github.com/GopeedLab/gopeed/internal/test" "github.com/GopeedLab/gopeed/internal/test"
"github.com/GopeedLab/gopeed/pkg/base" "github.com/GopeedLab/gopeed/pkg/base"
"github.com/GopeedLab/gopeed/pkg/protocol/bt" "github.com/GopeedLab/gopeed/pkg/protocol/bt"
"github.com/GopeedLab/gopeed/pkg/util"
"net/url"
"os" "os"
"reflect" "reflect"
"testing" "testing"
@@ -50,7 +52,15 @@ func TestFetcher_Resolve_DataUri_Torrent(t *testing.T) {
} }
func TestFetcher_Config(t *testing.T) { func TestFetcher_Config(t *testing.T) {
doResolve(t, buildConfigFetcher()) doResolve(t, buildConfigFetcher(nil))
}
func TestFetcher_ResolveWithProxy(t *testing.T) {
usr, pwd := "admin", "123"
proxyListener := test.StartSocks5Server(usr, pwd)
defer proxyListener.Close()
doResolve(t, buildConfigFetcher(util.BuildProxyUrl("socks5", proxyListener.Addr().String(), usr, pwd)))
} }
func doResolve(t *testing.T, fetcher fetcher.Fetcher) { func doResolve(t *testing.T, fetcher fetcher.Fetcher) {
@@ -90,7 +100,7 @@ func buildFetcher() fetcher.Fetcher {
return fetcher return fetcher
} }
func buildConfigFetcher() fetcher.Fetcher { func buildConfigFetcher(proxyUrl *url.URL) fetcher.Fetcher {
fetcher := new(FetcherBuilder).Build() fetcher := new(FetcherBuilder).Build()
newController := controller.NewController() newController := controller.NewController()
mockCfg := config{ mockCfg := config{
@@ -104,6 +114,7 @@ func buildConfigFetcher() fetcher.Fetcher {
} }
return true return true
} }
newController.ProxyUrl = proxyUrl
fetcher.Setup(newController) fetcher.Setup(newController)
return fetcher return fetcher
} }
+31 -22
View File
@@ -18,6 +18,7 @@ import (
"os" "os"
"path" "path"
"strconv" "strconv"
"strings"
"time" "time"
) )
@@ -90,7 +91,7 @@ func (f *Fetcher) Resolve(req *base.Request) error {
if err != nil { if err != nil {
return err return err
} }
client := buildClient() client := f.buildClient()
// send Range request to check whether the server supports breakpoint continuation // send Range request to check whether the server supports breakpoint continuation
// just test one byte, Range: bytes=0-0 // just test one byte, Range: bytes=0-0
httpReq.Header.Set(base.HttpHeaderRange, fmt.Sprintf(base.HttpHeaderRangeFormat, 0, 0)) httpReq.Header.Set(base.HttpHeaderRange, fmt.Sprintf(base.HttpHeaderRangeFormat, 0, 0))
@@ -104,8 +105,8 @@ func (f *Fetcher) Resolve(req *base.Request) error {
Range: false, Range: false,
Files: []*base.FileInfo{}, Files: []*base.FileInfo{},
} }
if base.HttpCodePartialContent == httpResp.StatusCode { if base.HttpCodePartialContent == httpResp.StatusCode || (base.HttpCodeOK == httpResp.StatusCode && httpResp.Header.Get(base.HttpHeaderAcceptRanges) == base.HttpHeaderBytes && strings.HasPrefix(httpResp.Header.Get(base.HttpHeaderContentRange), base.HttpHeaderBytes)) {
// 返回206响应码表示支持断点下载 // 1.返回206响应码表示支持断点下载 2.不返回206但是Accept-Ranges首部并且等于bytes也表示支持断点下载
res.Range = true res.Range = true
// 解析资源大小: bytes 0-1000/1001 => 1001 // 解析资源大小: bytes 0-1000/1001 => 1001
contentTotal := path.Base(httpResp.Header.Get(base.HttpHeaderContentRange)) contentTotal := path.Base(httpResp.Header.Get(base.HttpHeaderContentRange))
@@ -217,6 +218,11 @@ func (f *Fetcher) Meta() *fetcher.FetcherMeta {
return f.meta return f.meta
} }
func (f *Fetcher) Stats() any {
// todo http download health
return &fhttp.Stats{}
}
func (f *Fetcher) Progress() fetcher.Progress { func (f *Fetcher) Progress() fetcher.Progress {
p := make(fetcher.Progress, 0) p := make(fetcher.Progress, 0)
if len(f.chunks) > 0 { if len(f.chunks) > 0 {
@@ -264,7 +270,7 @@ func (f *Fetcher) fetchChunk(index int, ctx context.Context) (err error) {
return err return err
} }
var ( var (
client = buildClient() client = f.buildClient()
buf = make([]byte, 8192) buf = make([]byte, 8192)
maxRetries = 3 maxRetries = 3
) )
@@ -306,26 +312,13 @@ func (f *Fetcher) fetchChunk(index int, ctx context.Context) (err error) {
if err != nil { if err != nil {
return err return err
} }
defer resp.Body.Close()
if resp.StatusCode != base.HttpCodeOK && resp.StatusCode != base.HttpCodePartialContent { if resp.StatusCode != base.HttpCodeOK && resp.StatusCode != base.HttpCodePartialContent {
err = NewRequestError(resp.StatusCode, resp.Status) err = NewRequestError(resp.StatusCode, resp.Status)
return err return err
} }
return nil // Http request success, reset retry times
}() chunk.retryTimes = 0
if err != nil {
// If canceled, do not retry
if errors.Is(err, context.Canceled) {
return
}
// retry request after 1 second
chunk.retryTimes = chunk.retryTimes + 1
time.Sleep(time.Second)
continue
}
// Http request success, reset retry times
chunk.retryTimes = 0
err = func() error {
defer resp.Body.Close()
for { for {
n, err := resp.Body.Read(buf) n, err := resp.Body.Read(buf)
if n > 0 { if n > 0 {
@@ -342,7 +335,18 @@ func (f *Fetcher) fetchChunk(index int, ctx context.Context) (err error) {
return err return err
} }
} }
return nil
}() }()
if err != nil {
// If canceled, do not retry
if errors.Is(err, context.Canceled) {
return
}
// retry request after 1 second
chunk.retryTimes = chunk.retryTimes + 1
time.Sleep(time.Second)
continue
}
// if chunk is completed, reset other not complete chunks retry times // if chunk is completed, reset other not complete chunks retry times
if err == nil { if err == nil {
for _, c := range f.chunks { for _, c := range f.chunks {
@@ -430,11 +434,16 @@ func (f *Fetcher) splitChunk() (chunks []*chunk) {
return return
} }
func buildClient() *http.Client { func (f *Fetcher) buildClient() *http.Client {
transport := &http.Transport{}
// Cookie handle // Cookie handle
jar, _ := cookiejar.New(nil) jar, _ := cookiejar.New(nil)
if f.ctl.ProxyUrl != nil {
transport.Proxy = http.ProxyURL(f.ctl.ProxyUrl)
}
return &http.Client{ return &http.Client{
Jar: jar, Transport: transport,
Jar: jar,
} }
} }
+30
View File
@@ -8,6 +8,7 @@ import (
"github.com/GopeedLab/gopeed/internal/test" "github.com/GopeedLab/gopeed/internal/test"
"github.com/GopeedLab/gopeed/pkg/base" "github.com/GopeedLab/gopeed/pkg/base"
"github.com/GopeedLab/gopeed/pkg/protocol/http" "github.com/GopeedLab/gopeed/pkg/protocol/http"
"github.com/GopeedLab/gopeed/pkg/util"
"net" "net"
"reflect" "reflect"
"testing" "testing"
@@ -141,6 +142,15 @@ func TestFetcher_DownloadResume(t *testing.T) {
downloadResume(listener, 16, t) downloadResume(listener, 16, t)
} }
func TestFetcher_DownloadWithProxy(t *testing.T) {
httpListener := test.StartTestFileServer()
defer httpListener.Close()
proxyListener := test.StartSocks5Server("", "")
defer proxyListener.Close()
downloadWithProxy(httpListener, proxyListener, t)
}
func TestFetcher_Config(t *testing.T) { func TestFetcher_Config(t *testing.T) {
listener := test.StartTestFileServer() listener := test.StartTestFileServer()
defer listener.Close() defer listener.Close()
@@ -302,6 +312,26 @@ func downloadResume(listener net.Listener, connections int, t *testing.T) {
} }
} }
func downloadWithProxy(httpListener net.Listener, proxyListener net.Listener, t *testing.T) {
fetcher := downloadReady(httpListener, 4, t)
ctl := controller.NewController()
ctl.ProxyUrl = util.BuildProxyUrl("socks5", proxyListener.Addr().String(), "", "")
fetcher.Setup(ctl)
err := fetcher.Start()
if err != nil {
t.Fatal(err)
}
err = fetcher.Wait()
if err != nil {
t.Fatal(err)
}
want := test.FileMd5(test.BuildFile)
got := test.FileMd5(test.DownloadFile)
if want != got {
t.Errorf("Download() got = %v, want %v", got, want)
}
}
func buildFetcher() *Fetcher { func buildFetcher() *Fetcher {
fetcher := new(FetcherBuilder).Build() fetcher := new(FetcherBuilder).Build()
fetcher.Setup(controller.NewController()) fetcher.Setup(controller.NewController())
+22
View File
@@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/armon/go-socks5"
"io" "io"
"math/rand" "math/rand"
"net" "net"
@@ -315,3 +316,24 @@ func ifExistAndRemove(name string) error {
} }
return nil return nil
} }
func StartSocks5Server(usr, pwd string) net.Listener {
conf := &socks5.Config{}
if usr != "" && pwd != "" {
conf.Credentials = socks5.StaticCredentials{
usr: pwd,
}
}
server, err := socks5.New(conf)
if err != nil {
panic(err)
}
listener, err := net.Listen("tcp", "127.0.0.1:0") // 你可以根据需要更改监听地址
if err != nil {
panic(err)
}
go server.Serve(listener)
return listener
}
+3 -1
View File
@@ -16,10 +16,12 @@ const (
HttpCodePartialContent = 206 HttpCodePartialContent = 206
HttpHeaderRange = "Range" HttpHeaderRange = "Range"
HttpHeaderAcceptRanges = "Accept-Ranges"
HttpHeaderContentLength = "Content-Length" HttpHeaderContentLength = "Content-Length"
HttpHeaderContentRange = "Content-Range" HttpHeaderContentRange = "Content-Range"
HttpHeaderContentDisposition = "Content-Disposition" HttpHeaderContentDisposition = "Content-Disposition"
HttpHeaderUserAgent = "User-Agent" HttpHeaderUserAgent = "Usr-Agent"
HttpHeaderBytes = "bytes"
HttpHeaderRangeFormat = "bytes=%d-%d" HttpHeaderRangeFormat = "bytes=%d-%d"
) )
+64 -34
View File
@@ -6,8 +6,11 @@ import (
"github.com/GopeedLab/gopeed/internal/fetcher" "github.com/GopeedLab/gopeed/internal/fetcher"
"github.com/GopeedLab/gopeed/internal/logger" "github.com/GopeedLab/gopeed/internal/logger"
"github.com/GopeedLab/gopeed/pkg/base" "github.com/GopeedLab/gopeed/pkg/base"
"github.com/GopeedLab/gopeed/pkg/protocol/http"
"github.com/GopeedLab/gopeed/pkg/util" "github.com/GopeedLab/gopeed/pkg/util"
gonanoid "github.com/matoous/go-nanoid/v2" gonanoid "github.com/matoous/go-nanoid/v2"
"github.com/rs/zerolog"
"github.com/rs/zerolog/pkgerrors"
"github.com/virtuald/go-paniclog" "github.com/virtuald/go-paniclog"
"os" "os"
"path/filepath" "path/filepath"
@@ -91,6 +94,7 @@ func NewDownloader(cfg *DownloaderConfig) *Downloader {
} }
} }
zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
d.Logger = logger.NewLogger(cfg.ProductionMode, filepath.Join(cfg.StorageDir, "logs", "core.log")) d.Logger = logger.NewLogger(cfg.ProductionMode, filepath.Join(cfg.StorageDir, "logs", "core.log"))
d.ExtensionLogger = logger.NewLogger(cfg.ProductionMode, filepath.Join(cfg.StorageDir, "logs", "extension.log")) d.ExtensionLogger = logger.NewLogger(cfg.ProductionMode, filepath.Join(cfg.StorageDir, "logs", "extension.log"))
if cfg.ProductionMode { if cfg.ProductionMode {
@@ -215,6 +219,7 @@ func (d *Downloader) setupFetcher(fetcher fetcher.Fetcher) {
ctl.GetConfig = func(v any) bool { ctl.GetConfig = func(v any) bool {
return d.getProtocolConfig(fetcher.Name(), v) return d.getProtocolConfig(fetcher.Name(), v)
} }
ctl.ProxyUrl = d.cfg.ProxyUrl()
fetcher.Setup(ctl) fetcher.Setup(ctl)
} }
@@ -224,7 +229,10 @@ func (d *Downloader) Resolve(req *base.Request) (rr *ResolveResult, err error) {
return return
} }
res := d.triggerOnResolve(req) res, err := d.triggerOnResolve(req)
if err != nil {
return
}
if res != nil && len(res.Files) > 0 { if res != nil && len(res.Files) > 0 {
rr = &ResolveResult{ rr = &ResolveResult{
Res: res, Res: res,
@@ -524,9 +532,6 @@ func (d *Downloader) emit(eventKey EventKey, task *Task, errs ...error) {
Task: task, Task: task,
Err: err, Err: err,
}) })
if eventKey == EventKeyError {
d.emit(EventKeyFinally, task, err)
}
} }
} }
@@ -571,26 +576,56 @@ func (d *Downloader) getProtocolConfig(name string, v any) bool {
func (d *Downloader) watch(task *Task) { func (d *Downloader) watch(task *Task) {
err := task.fetcher.Wait() err := task.fetcher.Wait()
if err != nil { if err != nil {
task.Status = base.DownloadStatusError d.doOnError(task, err)
d.emit(EventKeyError, task, err) return
} else {
task.Progress.Used = task.timer.Used()
if task.Meta.Res.Size == 0 {
task.Meta.Res.Size = task.fetcher.Progress().TotalDownloaded()
}
used := task.Progress.Used / int64(time.Second)
if used == 0 {
used = 1
}
totalSize := task.Meta.Res.Size
task.Progress.Speed = totalSize / used
task.Progress.Downloaded = totalSize
task.Status = base.DownloadStatusDone
d.storage.Put(bucketTask, task.ID, task.clone())
d.emit(EventKeyDone, task)
d.emit(EventKeyFinally, task, err)
} }
task.Progress.Used = task.timer.Used()
if task.Meta.Res.Size == 0 {
task.Meta.Res.Size = task.fetcher.Progress().TotalDownloaded()
}
used := task.Progress.Used / int64(time.Second)
if used == 0 {
used = 1
}
totalSize := task.Meta.Res.Size
task.Progress.Speed = totalSize / used
task.Progress.Downloaded = totalSize
task.updateStatus(base.DownloadStatusDone)
d.storage.Put(bucketTask, task.ID, task.clone())
d.emit(EventKeyDone, task)
d.emit(EventKeyFinally, task, err)
d.notifyRunning() d.notifyRunning()
if e, ok := task.Meta.Opts.Extra.(*http.OptsExtra); ok {
downloadFilePath := task.Meta.SingleFilepath()
if e.AutoTorrent && strings.HasSuffix(downloadFilePath, ".torrent") {
go func() {
_, err2 := d.CreateDirect(
&base.Request{
URL: downloadFilePath,
},
&base.Options{
Path: task.Meta.Opts.Path,
SelectFiles: make([]int, 0),
})
if err2 != nil {
d.Logger.Error().Err(err2).Msgf("auto create torrent task failed, task id: %s", task.ID)
}
}()
}
}
}
func (d *Downloader) doOnError(task *Task, err error) {
d.Logger.Warn().Err(err).Msgf("task download failed, task id: %s", task.ID)
task.updateStatus(base.DownloadStatusError)
d.triggerOnError(task, err)
if task.Status == base.DownloadStatusError {
d.emit(EventKeyError, task, err)
d.emit(EventKeyFinally, task, err)
d.notifyRunning()
}
} }
func (d *Downloader) restoreFetcher(task *Task) error { func (d *Downloader) restoreFetcher(task *Task) error {
@@ -657,7 +692,6 @@ func (d *Downloader) doCreate(fetcher fetcher.Fetcher, opts *base.Options) (task
task.fetcher = fetcher task.fetcher = fetcher
task.Meta = fetcher.Meta() task.Meta = fetcher.Meta()
task.Progress = &Progress{} task.Progress = &Progress{}
task.Status = base.DownloadStatusReady
initTask(task) initTask(task)
if err = fetcher.Create(opts); err != nil { if err = fetcher.Create(opts); err != nil {
return return
@@ -696,25 +730,18 @@ func (d *Downloader) doStart(task *Task) (err error) {
} }
} }
cloneTask := task.clone()
isCreate := task.Status == base.DownloadStatusReady isCreate := task.Status == base.DownloadStatusReady
task.Status = base.DownloadStatusRunning
doStart := func() error { doStart := func() error {
task.lock.Lock() task.lock.Lock()
defer task.lock.Unlock() defer task.lock.Unlock()
req := d.triggerOnStart(cloneTask) d.triggerOnStart(task)
if req != nil { task.updateStatus(base.DownloadStatusRunning)
task.Meta.Req = req
task.fetcher.Meta().Req = req
}
if task.Meta.Res == nil { if task.Meta.Res == nil {
err := task.fetcher.Resolve(task.Meta.Req) err := task.fetcher.Resolve(task.Meta.Req)
if err != nil { if err != nil {
task.Status = base.DownloadStatusError
d.emit(EventKeyError, task, err)
return err return err
} }
task.Meta.Res = task.fetcher.Meta().Res task.Meta.Res = task.fetcher.Meta().Res
@@ -723,8 +750,10 @@ func (d *Downloader) doStart(task *Task) (err error) {
if isCreate { if isCreate {
d.checkDuplicateLock.Lock() d.checkDuplicateLock.Lock()
defer d.checkDuplicateLock.Unlock() defer d.checkDuplicateLock.Unlock()
task.Meta.Opts.Name = util.ReplaceInvalidFilename(task.Meta.Opts.Name)
// check if the download file is duplicated and rename it automatically. // check if the download file is duplicated and rename it automatically.
if task.Meta.Res.Name != "" { if task.Meta.Res.Name != "" {
task.Meta.Res.Name = util.ReplaceInvalidFilename(task.Meta.Res.Name)
fullDirPath := task.Meta.FolderPath() fullDirPath := task.Meta.FolderPath()
newName, err := util.CheckDuplicateAndRename(fullDirPath) newName, err := util.CheckDuplicateAndRename(fullDirPath)
if err != nil { if err != nil {
@@ -732,6 +761,7 @@ func (d *Downloader) doStart(task *Task) (err error) {
} }
task.Meta.Opts.Name = newName task.Meta.Opts.Name = newName
} else { } else {
task.Meta.Res.Files[0].Name = util.ReplaceInvalidFilename(task.Meta.Res.Files[0].Name)
fullFilePath := task.Meta.SingleFilepath() fullFilePath := task.Meta.SingleFilepath()
newName, err := util.CheckDuplicateAndRename(fullFilePath) newName, err := util.CheckDuplicateAndRename(fullFilePath)
if err != nil { if err != nil {
@@ -757,7 +787,7 @@ func (d *Downloader) doStart(task *Task) (err error) {
go func() { go func() {
err := doStart() err := doStart()
if err != nil { if err != nil {
d.Logger.Error().Stack().Err(err).Msgf("start task failed, task id: %s", task.ID) d.doOnError(task, err)
} }
}() }()
@@ -767,7 +797,7 @@ func (d *Downloader) doStart(task *Task) (err error) {
func (d *Downloader) doPause(task *Task) (err error) { func (d *Downloader) doPause(task *Task) (err error) {
err = func() error { err = func() error {
if task.Status != base.DownloadStatusDone { if task.Status != base.DownloadStatusDone {
task.Status = base.DownloadStatusPause task.updateStatus(base.DownloadStatusPause)
task.timer.Pause() task.timer.Pause()
if task.fetcher != nil { if task.fetcher != nil {
if err := task.fetcher.Pause(); err != nil { if err := task.fetcher.Pause(); err != nil {
+76
View File
@@ -84,6 +84,82 @@ func TestDownloader_Create(t *testing.T) {
} }
} }
func TestDownloader_CreateWithProxy(t *testing.T) {
// No proxy
doTestDownloaderCreateWithProxy(t, false, func(proxyCfg *DownloaderProxyConfig) *DownloaderProxyConfig {
return nil
})
// Disable proxy
doTestDownloaderCreateWithProxy(t, false, func(proxyCfg *DownloaderProxyConfig) *DownloaderProxyConfig {
proxyCfg.Enable = false
return proxyCfg
})
// Invalid proxy scheme
doTestDownloaderCreateWithProxy(t, false, func(proxyCfg *DownloaderProxyConfig) *DownloaderProxyConfig {
proxyCfg.Scheme = ""
return proxyCfg
})
// Invalid proxy host
doTestDownloaderCreateWithProxy(t, false, func(proxyCfg *DownloaderProxyConfig) *DownloaderProxyConfig {
proxyCfg.Host = ""
return proxyCfg
})
// Use proxy without auth
doTestDownloaderCreateWithProxy(t, false, func(proxyCfg *DownloaderProxyConfig) *DownloaderProxyConfig {
return proxyCfg
})
// Use proxy with auth
doTestDownloaderCreateWithProxy(t, true, func(proxyCfg *DownloaderProxyConfig) *DownloaderProxyConfig {
return proxyCfg
})
}
func doTestDownloaderCreateWithProxy(t *testing.T, auth bool, buildProxyConfig func(proxyCfg *DownloaderProxyConfig) *DownloaderProxyConfig) {
httpListener := test.StartTestFileServer()
defer httpListener.Close()
usr, pwd := "", ""
if auth {
usr, pwd = "admin", "123"
}
proxyListener := test.StartSocks5Server(usr, pwd)
defer proxyListener.Close()
downloader := NewDownloader(nil)
if err := downloader.Setup(); err != nil {
t.Fatal(err)
}
defer downloader.Clear()
downloader.cfg.DownloaderStoreConfig.Proxy = buildProxyConfig(&DownloaderProxyConfig{
Enable: true,
Scheme: "socks5",
Host: proxyListener.Addr().String(),
Usr: usr,
Pwd: pwd,
})
req := &base.Request{
URL: "http://" + httpListener.Addr().String() + "/" + test.BuildName,
}
rr, err := downloader.Resolve(req)
if err != nil {
t.Fatal(err)
}
want := &base.Resource{
Size: test.BuildSize,
Range: true,
Files: []*base.FileInfo{
{
Name: test.BuildName,
Path: "",
Size: test.BuildSize,
},
},
}
if !reflect.DeepEqual(want, rr.Res) {
t.Errorf("Resolve() got = %v, want %v", rr.Res, want)
}
}
func TestDownloader_CreateRename(t *testing.T) { func TestDownloader_CreateRename(t *testing.T) {
listener := test.StartTestFileServer() listener := test.StartTestFileServer()
defer listener.Close() defer listener.Close()
+22 -6
View File
@@ -3,13 +3,15 @@ package engine
import ( import (
_ "embed" _ "embed"
"errors" "errors"
gojaerror "github.com/GopeedLab/gopeed/pkg/download/engine/inject/error"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/file" "github.com/GopeedLab/gopeed/pkg/download/engine/inject/file"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/formdata" "github.com/GopeedLab/gopeed/pkg/download/engine/inject/formdata"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/vm" "github.com/GopeedLab/gopeed/pkg/download/engine/inject/vm"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/xhr" "github.com/GopeedLab/gopeed/pkg/download/engine/inject/xhr"
"github.com/dop251/goja" "github.com/dop251/goja"
"github.com/dop251/goja_nodejs/eventloop" "github.com/dop251/goja_nodejs/eventloop"
"github.com/dop251/goja_nodejs/url" gojaurl "github.com/dop251/goja_nodejs/url"
"net/url"
"time" "time"
) )
@@ -107,7 +109,14 @@ func (e *Engine) Close() {
e.loop.Stop() e.loop.Stop()
} }
func NewEngine() *Engine { type Config struct {
ProxyURL *url.URL
}
func NewEngine(cfg *Config) *Engine {
if cfg == nil {
cfg = &Config{}
}
loop := eventloop.NewEventLoop() loop := eventloop.NewEventLoop()
engine := &Engine{ engine := &Engine{
loop: loop, loop: loop,
@@ -116,14 +125,17 @@ func NewEngine() *Engine {
engine.Runtime = runtime engine.Runtime = runtime
runtime.SetFieldNameMapper(goja.TagFieldNameMapper("json", true)) runtime.SetFieldNameMapper(goja.TagFieldNameMapper("json", true))
vm.Enable(runtime) vm.Enable(runtime)
url.Enable(runtime) gojaurl.Enable(runtime)
if err := gojaerror.Enable(runtime); err != nil {
return
}
if err := file.Enable(runtime); err != nil { if err := file.Enable(runtime); err != nil {
return return
} }
if err := formdata.Enable(runtime); err != nil { if err := formdata.Enable(runtime); err != nil {
return return
} }
if err := xhr.Enable(runtime); err != nil { if err := xhr.Enable(runtime, cfg.ProxyURL); err != nil {
return return
} }
if _, err := runtime.RunString(polyfillScript); err != nil { if _, err := runtime.RunString(polyfillScript); err != nil {
@@ -143,7 +155,7 @@ func NewEngine() *Engine {
} }
func Run(script string) (value any, err error) { func Run(script string) (value any, err error) {
engine := NewEngine() engine := NewEngine(nil)
return engine.RunString(script) return engine.RunString(script)
} }
@@ -159,7 +171,11 @@ func resolveResult(value goja.Value) (any, error) {
case goja.PromiseStateFulfilled: case goja.PromiseStateFulfilled:
return p.Result().Export(), nil return p.Result().Export(), nil
case goja.PromiseStateRejected: case goja.PromiseStateRejected:
return nil, errors.New(p.Result().String()) if err, ok := p.Result().Export().(error); ok {
return nil, err
} else {
return nil, errors.New(p.Result().String())
}
} }
} }
return export, nil return export, nil
+49 -3
View File
@@ -7,7 +7,10 @@ import (
"errors" "errors"
"fmt" "fmt"
"github.com/GopeedLab/gopeed/internal/test" "github.com/GopeedLab/gopeed/internal/test"
gojaerror "github.com/GopeedLab/gopeed/pkg/download/engine/inject/error"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/file" "github.com/GopeedLab/gopeed/pkg/download/engine/inject/file"
gojautil "github.com/GopeedLab/gopeed/pkg/download/engine/util"
"github.com/GopeedLab/gopeed/pkg/util"
"github.com/dop251/goja" "github.com/dop251/goja"
"io" "io"
"net" "net"
@@ -19,6 +22,7 @@ import (
) )
func TestPolyfill(t *testing.T) { func TestPolyfill(t *testing.T) {
doTestPolyfill(t, "MessageError")
doTestPolyfill(t, "XMLHttpRequest") doTestPolyfill(t, "XMLHttpRequest")
doTestPolyfill(t, "Blob") doTestPolyfill(t, "Blob")
doTestPolyfill(t, "FormData") doTestPolyfill(t, "FormData")
@@ -26,10 +30,20 @@ func TestPolyfill(t *testing.T) {
doTestPolyfill(t, "__gopeed_create_vm") doTestPolyfill(t, "__gopeed_create_vm")
} }
func TestError(t *testing.T) {
engine := NewEngine(nil)
_, err := engine.RunString(`
throw new MessageError('test');
`)
if me, ok := gojautil.AssertError[*gojaerror.MessageError](err); !ok {
t.Fatalf("expect MessageError, but got %v", me)
}
}
func TestFetch(t *testing.T) { func TestFetch(t *testing.T) {
server := startServer() server := startServer()
defer server.Close() defer server.Close()
engine := NewEngine() engine := NewEngine(nil)
if _, err := engine.RunString(fmt.Sprintf("var host = 'http://%s';", server.Addr().String())); err != nil { if _, err := engine.RunString(fmt.Sprintf("var host = 'http://%s';", server.Addr().String())); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -192,8 +206,40 @@ function testTimeout(){
} }
} }
func TestFetchWithProxy(t *testing.T) {
doTestFetchWithProxy(t, "", "")
doTestFetchWithProxy(t, "admin", "123")
}
func doTestFetchWithProxy(t *testing.T, usr, pwd string) {
httpListener := startServer()
defer httpListener.Close()
proxyListener := test.StartSocks5Server(usr, pwd)
defer proxyListener.Close()
engine := NewEngine(&Config{ProxyURL: util.BuildProxyUrl("socks5", proxyListener.Addr().String(), usr, pwd)})
if _, err := engine.RunString(fmt.Sprintf("var host = 'http://%s';", httpListener.Addr().String())); err != nil {
t.Fatal(err)
}
respCode, err := engine.RunString(`
(async function(){
const resp = await fetch(host+'/get');
return resp.status;
})()
`)
if err != nil {
t.Fatal(err)
}
if respCode != int64(200) {
t.Fatalf("fetch with proxy failed, want %d, got %d", 200, respCode)
}
}
func TestVm(t *testing.T) { func TestVm(t *testing.T) {
engine := NewEngine() engine := NewEngine(nil)
value, err := engine.RunString(` value, err := engine.RunString(`
const vm = __gopeed_create_vm() const vm = __gopeed_create_vm()
@@ -221,7 +267,7 @@ out
} }
func TestNonStopLoop(t *testing.T) { func TestNonStopLoop(t *testing.T) {
engine := NewEngine() engine := NewEngine(nil)
_, err := engine.RunString(` _, err := engine.RunString(`
function leak(){ function leak(){
@@ -0,0 +1,29 @@
package error
import (
"github.com/dop251/goja"
)
type MessageError struct {
Message string `json:"message"`
}
func (e *MessageError) Error() string {
return e.Message
}
func Enable(runtime *goja.Runtime) error {
messageError := runtime.ToValue(func(call goja.ConstructorCall) *goja.Object {
var message string
if len(call.Arguments) > 0 {
message = call.Arguments[0].String()
}
instance := &MessageError{
Message: message,
}
instanceValue := runtime.ToValue(instance).(*goja.Object)
instanceValue.SetPrototype(call.This.Prototype())
return instanceValue
})
return runtime.Set("MessageError", messageError)
}
-9
View File
@@ -1,9 +0,0 @@
package inject
import (
"github.com/dop251/goja"
)
func ThrowTypeError(vm *goja.Runtime, msg string) {
panic(vm.NewTypeError(msg))
}
+12 -4
View File
@@ -2,14 +2,15 @@ package xhr
import ( import (
"bytes" "bytes"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/file" "github.com/GopeedLab/gopeed/pkg/download/engine/inject/file"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/formdata" "github.com/GopeedLab/gopeed/pkg/download/engine/inject/formdata"
"github.com/GopeedLab/gopeed/pkg/download/engine/util"
"github.com/dop251/goja" "github.com/dop251/goja"
"io" "io"
"mime/multipart" "mime/multipart"
"net" "net"
"net/http" "net/http"
"net/url"
"time" "time"
) )
@@ -119,6 +120,7 @@ type XMLHttpRequest struct {
requestHeaders map[string]string requestHeaders map[string]string
responseHeaders map[string]string responseHeaders map[string]string
aborted bool aborted bool
proxyUrl *url.URL
Upload *XMLHttpRequestUpload `json:"upload"` Upload *XMLHttpRequestUpload `json:"upload"`
Timeout int `json:"timeout"` Timeout int `json:"timeout"`
@@ -200,8 +202,13 @@ func (xhr *XMLHttpRequest) Send(data goja.Value) {
for k, v := range xhr.requestHeaders { for k, v := range xhr.requestHeaders {
req.Header.Set(k, v) req.Header.Set(k, v)
} }
transport := &http.Transport{}
if xhr.proxyUrl != nil {
transport.Proxy = http.ProxyURL(xhr.proxyUrl)
}
client := &http.Client{ client := &http.Client{
Timeout: time.Duration(xhr.Timeout) * time.Millisecond, Transport: transport,
Timeout: time.Duration(xhr.Timeout) * time.Millisecond,
} }
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
@@ -306,10 +313,10 @@ func (xhr *XMLHttpRequest) parseData(data goja.Value) any {
return data.String() return data.String()
} }
func Enable(runtime *goja.Runtime) error { func Enable(runtime *goja.Runtime, proxyUrl *url.URL) error {
progressEvent := runtime.ToValue(func(call goja.ConstructorCall) *goja.Object { progressEvent := runtime.ToValue(func(call goja.ConstructorCall) *goja.Object {
if len(call.Arguments) < 1 { if len(call.Arguments) < 1 {
inject.ThrowTypeError(runtime, "Failed to construct 'ProgressEvent': 1 argument required, but only 0 present.") util.ThrowTypeError(runtime, "Failed to construct 'ProgressEvent': 1 argument required, but only 0 present.")
} }
instance := &ProgressEvent{ instance := &ProgressEvent{
Type: call.Argument(0).String(), Type: call.Argument(0).String(),
@@ -320,6 +327,7 @@ func Enable(runtime *goja.Runtime) error {
}) })
xhr := runtime.ToValue(func(call goja.ConstructorCall) *goja.Object { xhr := runtime.ToValue(func(call goja.ConstructorCall) *goja.Object {
instance := &XMLHttpRequest{ instance := &XMLHttpRequest{
proxyUrl: proxyUrl,
Upload: &XMLHttpRequestUpload{ Upload: &XMLHttpRequestUpload{
EventProp: &EventProp{ EventProp: &EventProp{
eventListeners: make(map[string]func(event *ProgressEvent)), eventListeners: make(map[string]func(event *ProgressEvent)),
+24
View File
@@ -0,0 +1,24 @@
package util
import (
"github.com/dop251/goja"
)
func ThrowTypeError(vm *goja.Runtime, msg string) {
panic(vm.NewTypeError(msg))
}
func AssertError[T error](err error) (t T, r bool) {
if err == nil {
return
}
if e, ok := err.(T); ok {
return e, true
}
if e, ok := err.(*goja.Exception); ok {
if ee, okk := e.Value().Export().(T); okk {
return ee, true
}
}
return
}
+78 -17
View File
@@ -6,9 +6,12 @@ import (
"github.com/GopeedLab/gopeed/internal/logger" "github.com/GopeedLab/gopeed/internal/logger"
"github.com/GopeedLab/gopeed/pkg/base" "github.com/GopeedLab/gopeed/pkg/base"
"github.com/GopeedLab/gopeed/pkg/download/engine" "github.com/GopeedLab/gopeed/pkg/download/engine"
gojaerror "github.com/GopeedLab/gopeed/pkg/download/engine/inject/error"
gojautil "github.com/GopeedLab/gopeed/pkg/download/engine/util"
"github.com/GopeedLab/gopeed/pkg/util" "github.com/GopeedLab/gopeed/pkg/util"
"github.com/dop251/goja" "github.com/dop251/goja"
"github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/transport"
"io" "io"
"os" "os"
"path" "path"
@@ -34,7 +37,7 @@ type ActivationEvent string
const ( const (
EventOnResolve ActivationEvent = "onResolve" EventOnResolve ActivationEvent = "onResolve"
EventOnStart ActivationEvent = "onStart" EventOnStart ActivationEvent = "onStart"
//EventOnError ActivationEvent = "onError" EventOnError ActivationEvent = "onError"
//EventOnDone ActivationEvent = "onDone" //EventOnDone ActivationEvent = "onDone"
) )
@@ -195,11 +198,19 @@ func (d *Downloader) fetchExtensionByGit(url string, handler func(tempExtPath st
if err := util.RmAndMkDirAll(tempExtDir); err != nil { if err := util.RmAndMkDirAll(tempExtDir); err != nil {
return nil, err return nil, err
} }
proxyOptions := transport.ProxyOptions{}
proxyUrl := d.cfg.ProxyUrl()
if proxyUrl != nil {
proxyOptions.URL = proxyUrl.Scheme + "://" + proxyUrl.Host
proxyOptions.Username = proxyUrl.User.Username()
proxyOptions.Password, _ = proxyUrl.User.Password()
}
// clone project to extension temp dir // clone project to extension temp dir
gitUrl := parentPath + projectPath + gitSuffix gitUrl := parentPath + projectPath + gitSuffix
if _, err := git.PlainClone(tempExtDir, false, &git.CloneOptions{ if _, err := git.PlainClone(tempExtDir, false, &git.CloneOptions{
URL: gitUrl, URL: gitUrl,
Depth: 1, Depth: 1,
ProxyOptions: proxyOptions,
}); err != nil { }); err != nil {
return nil, err return nil, err
} }
@@ -229,8 +240,8 @@ func (d *Downloader) parseExtensionByPath(path string) (*Extension, error) {
return &ext, nil return &ext, nil
} }
func (d *Downloader) triggerOnResolve(req *base.Request) (res *base.Resource) { func (d *Downloader) triggerOnResolve(req *base.Request) (res *base.Resource, err error) {
doTrigger(d, err = doTrigger(d,
EventOnResolve, EventOnResolve,
req, req,
&OnResolveContext{ &OnResolveContext{
@@ -243,6 +254,10 @@ func (d *Downloader) triggerOnResolve(req *base.Request) (res *base.Resource) {
gopeed.Logger.logger.Warn().Err(err).Msgf("[%s] resource invalid", ext.buildIdentity()) gopeed.Logger.logger.Warn().Err(err).Msgf("[%s] resource invalid", ext.buildIdentity())
return return
} }
ctx.Res.Name = util.ReplaceInvalidFilename(ctx.Res.Name)
for _, file := range ctx.Res.Files {
file.Name = util.ReplaceInvalidFilename(file.Name)
}
ctx.Res.CalcSize(nil) ctx.Res.CalcSize(nil)
} }
res = ctx.Res res = ctx.Res
@@ -251,12 +266,12 @@ func (d *Downloader) triggerOnResolve(req *base.Request) (res *base.Resource) {
return return
} }
func (d *Downloader) triggerOnStart(task *Task) (req *base.Request) { func (d *Downloader) triggerOnStart(task *Task) {
doTrigger(d, doTrigger(d,
EventOnStart, EventOnStart,
task.Meta.Req, task.Meta.Req,
&OnStartContext{ &OnStartContext{
Task: task, Task: NewExtensionTask(d, task),
}, },
func(ext *Extension, gopeed *Instance, ctx *OnStartContext) { func(ext *Extension, gopeed *Instance, ctx *OnStartContext) {
// Validate request structure // Validate request structure
@@ -265,14 +280,25 @@ func (d *Downloader) triggerOnStart(task *Task) (req *base.Request) {
gopeed.Logger.logger.Warn().Err(err).Msgf("[%s] request invalid", ext.buildIdentity()) gopeed.Logger.logger.Warn().Err(err).Msgf("[%s] request invalid", ext.buildIdentity())
return return
} }
req = ctx.Task.Meta.Req
} }
}, },
) )
return return
} }
func doTrigger[T any](d *Downloader, event ActivationEvent, req *base.Request, ctx T, handler func(ext *Extension, gopeed *Instance, ctx T)) { func (d *Downloader) triggerOnError(task *Task, err error) {
doTrigger(d,
EventOnError,
task.Meta.Req,
&OnErrorContext{
Task: NewExtensionTask(d, task),
Error: err,
},
nil,
)
}
func doTrigger[T any](d *Downloader, event ActivationEvent, req *base.Request, ctx T, handler func(ext *Extension, gopeed *Instance, ctx T)) error {
// init extension global object // init extension global object
gopeed := &Instance{ gopeed := &Instance{
Events: make(InstanceEvents), Events: make(InstanceEvents),
@@ -314,7 +340,9 @@ func doTrigger[T any](d *Downloader, event ActivationEvent, req *base.Request, c
if req.Labels == nil { if req.Labels == nil {
req.Labels = make(map[string]string) req.Labels = make(map[string]string)
} }
engine := engine.NewEngine() engine := engine.NewEngine(&engine.Config{
ProxyURL: d.cfg.ProxyUrl(),
})
defer engine.Close() defer engine.Close()
err = engine.Runtime.Set("gopeed", gopeed) err = engine.Runtime.Set("gopeed", gopeed)
if err != nil { if err != nil {
@@ -332,13 +360,20 @@ func doTrigger[T any](d *Downloader, event ActivationEvent, req *base.Request, c
gopeed.Logger.logger.Error().Err(err).Msgf("[%s] call function failed: %s", ext.buildIdentity(), event) gopeed.Logger.logger.Error().Err(err).Msgf("[%s] call function failed: %s", ext.buildIdentity(), event)
return return
} }
handler(ext, gopeed, ctx) if handler != nil {
handler(ext, gopeed, ctx)
}
} }
}() }()
} }
} }
} }
return
// Only return MessageError
if me, ok := gojautil.AssertError[*gojaerror.MessageError](err); ok {
return me
}
return nil
} }
func (d *Downloader) ExtensionPath(ext *Extension) string { func (d *Downloader) ExtensionPath(ext *Extension) string {
@@ -566,10 +601,10 @@ func (h InstanceEvents) OnStart(fn goja.Callable) {
h.register(EventOnStart, fn) h.register(EventOnStart, fn)
} }
//func (h InstanceEvents) OnError(fn goja.Callable) { func (h InstanceEvents) OnError(fn goja.Callable) {
// h.register(HookEventOnError, fn) h.register(EventOnError, fn)
//} }
//
//func (h InstanceEvents) OnDone(fn goja.Callable) { //func (h InstanceEvents) OnDone(fn goja.Callable) {
// h.register(HookEventOnDone, fn) // h.register(HookEventOnDone, fn)
//} //}
@@ -638,7 +673,33 @@ type OnResolveContext struct {
} }
type OnStartContext struct { type OnStartContext struct {
Task *Task `json:"task"` Task *ExtensionTask `json:"task"`
}
type OnErrorContext struct {
Task *ExtensionTask `json:"task"`
Error error `json:"error"`
}
type ExtensionTask struct {
*Task
download *Downloader
}
func NewExtensionTask(download *Downloader, task *Task) *ExtensionTask {
return &ExtensionTask{
Task: task.clone(),
download: download,
}
}
func (t *ExtensionTask) Continue() error {
return t.download.Continue(t.ID)
}
func (t *ExtensionTask) Pause() error {
return t.download.Pause(t.ID)
} }
func parseSettings(settings []*Setting) map[string]any { func parseSettings(settings []*Setting) map[string]any {
+66 -20
View File
@@ -4,6 +4,7 @@ import (
"errors" "errors"
"github.com/GopeedLab/gopeed/internal/logger" "github.com/GopeedLab/gopeed/internal/logger"
"github.com/GopeedLab/gopeed/pkg/base" "github.com/GopeedLab/gopeed/pkg/base"
gojaerror "github.com/GopeedLab/gopeed/pkg/download/engine/inject/error"
"github.com/dop251/goja" "github.com/dop251/goja"
"os" "os"
"testing" "testing"
@@ -165,7 +166,7 @@ func TestDownloader_UpgradeExtension(t *testing.T) {
}) })
} }
func TestDownloader_ExtensionByOnStart(t *testing.T) { func TestDownloader_Extension_OnStart(t *testing.T) {
downloadAndCheck := func(req *base.Request) { downloadAndCheck := func(req *base.Request) {
setupDownloader(func(downloader *Downloader) { setupDownloader(func(downloader *Downloader) {
if _, err := downloader.InstallExtensionByFolder("./testdata/extensions/on_start", false); err != nil { if _, err := downloader.InstallExtensionByFolder("./testdata/extensions/on_start", false); err != nil {
@@ -192,10 +193,10 @@ func TestDownloader_ExtensionByOnStart(t *testing.T) {
} }
task := downloader.GetTask(id) task := downloader.GetTask(id)
if task.Meta.Req.URL != "https://github.com" { if task.Meta.Req.URL != "https://github.com" {
panic("extension on start modify url error") t.Fatalf("except url: https://github.com, actual: %s", task.Meta.Req.URL)
} }
if task.Meta.Req.Labels["modified"] != "true" { if task.Meta.Req.Labels["modified"] != "true" {
panic("extension on start modify label error") t.Fatalf("except label: modified=true, actual: %s", task.Meta.Req.Labels["modified"])
} }
}) })
} }
@@ -207,13 +208,54 @@ func TestDownloader_ExtensionByOnStart(t *testing.T) {
// label match // label match
downloadAndCheck(&base.Request{ downloadAndCheck(&base.Request{
URL: "https://xxx.com", URL: "https://test.com",
Labels: map[string]string{ Labels: map[string]string{
"test": "true", "test": "true",
}, },
}) })
} }
func TestDownloader_Extension_OnError(t *testing.T) {
setupDownloader(func(downloader *Downloader) {
if _, err := downloader.InstallExtensionByFolder("./testdata/extensions/on_error", false); err != nil {
t.Fatal(err)
}
errCh := make(chan error, 1)
downloader.Listener(func(event *Event) {
if event.Key == EventKeyFinally {
errCh <- event.Err
}
})
id, err := downloader.CreateDirect(&base.Request{
URL: "https://github.com/gopeed/test/404",
Labels: map[string]string{
"test": "true",
},
}, nil)
if err != nil {
t.Fatal(err)
}
select {
case err = <-errCh:
break
case <-time.After(time.Second * 10):
err = errors.New("timeout")
}
if err != nil {
panic("extension on error download error: " + err.Error())
}
// extension on error modify url and continue download
task := downloader.GetTask(id)
if task.Meta.Req.URL != "https://github.com" {
t.Fatalf("except url: https://github.com, actual: %s", task.Meta.Req.URL)
}
if task.Status != base.DownloadStatusDone {
t.Fatalf("except status is done, actual: %s", task.Status)
}
})
}
func TestDownloader_Extension_Errors(t *testing.T) { func TestDownloader_Extension_Errors(t *testing.T) {
setupDownloader(func(downloader *Downloader) { setupDownloader(func(downloader *Downloader) {
if _, err := downloader.InstallExtensionByFolder("./testdata/extensions/script_error", false); err != nil { if _, err := downloader.InstallExtensionByFolder("./testdata/extensions/script_error", false); err != nil {
@@ -244,6 +286,26 @@ func TestDownloader_Extension_Errors(t *testing.T) {
t.Fatal("function error catch failed") t.Fatal("function error catch failed")
} }
}) })
setupDownloader(func(downloader *Downloader) {
if _, err := downloader.InstallExtensionByFolder("./testdata/extensions/message_error", false); err != nil {
t.Fatal(err)
}
_, err := downloader.Resolve(&base.Request{
URL: "https://github.com/test",
})
if err == nil {
t.Fatalf("except error, but got nil")
}
me, ok := err.(*gojaerror.MessageError)
if !ok {
t.Fatalf("except MessageError type, but got %s", err)
}
want := "test"
if me.Error() != want {
t.Fatalf("except MessageError message %s, but got %s", want, me.Message)
}
})
} }
func TestDownloader_Extension_Settings(t *testing.T) { func TestDownloader_Extension_Settings(t *testing.T) {
@@ -336,22 +398,6 @@ func TestDownloader_DeleteExtension(t *testing.T) {
}) })
} }
func TestDownloader_Extension_OnResolve(t *testing.T) {
setupDownloader(func(downloader *Downloader) {
installedExt, err := downloader.InstallExtensionByFolder("./testdata/extensions/settings_all", false)
if err != nil {
t.Fatal(err)
}
if err := downloader.DeleteExtension(installedExt.Identity); err != nil {
t.Fatal(err)
}
extensions := downloader.GetExtensions()
if len(extensions) != 0 {
t.Fatal("extension delete fail")
}
})
}
func TestDownloader_Extension_Logger(t *testing.T) { func TestDownloader_Extension_Logger(t *testing.T) {
logger := logger.NewLogger(false, "") logger := logger.NewLogger(false, "")
il := newInstanceLogger(&Extension{ il := newInstanceLogger(&Extension{
+35 -4
View File
@@ -8,6 +8,7 @@ import (
"github.com/GopeedLab/gopeed/pkg/base" "github.com/GopeedLab/gopeed/pkg/base"
"github.com/GopeedLab/gopeed/pkg/util" "github.com/GopeedLab/gopeed/pkg/util"
gonanoid "github.com/matoous/go-nanoid/v2" gonanoid "github.com/matoous/go-nanoid/v2"
"net/url"
"sync" "sync"
"time" "time"
) )
@@ -23,6 +24,7 @@ type Task struct {
Status base.Status `json:"status"` Status base.Status `json:"status"`
Progress *Progress `json:"progress"` Progress *Progress `json:"progress"`
CreatedAt time.Time `json:"createdAt"` CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
fetcherBuilder fetcher.FetcherBuilder fetcherBuilder fetcher.FetcherBuilder
fetcher fetcher.Fetcher fetcher fetcher.Fetcher
@@ -40,9 +42,15 @@ func NewTask() *Task {
ID: id, ID: id,
Status: base.DownloadStatusReady, Status: base.DownloadStatusReady,
CreatedAt: time.Now(), CreatedAt: time.Now(),
UpdatedAt: time.Now(),
} }
} }
func (t *Task) updateStatus(status base.Status) {
t.UpdatedAt = time.Now()
t.Status = status
}
func (t *Task) clone() *Task { func (t *Task) clone() *Task {
return &Task{ return &Task{
ID: t.ID, ID: t.ID,
@@ -50,6 +58,7 @@ func (t *Task) clone() *Task {
Status: t.Status, Status: t.Status,
Progress: t.Progress, Progress: t.Progress,
CreatedAt: t.CreatedAt, CreatedAt: t.CreatedAt,
UpdatedAt: t.UpdatedAt,
} }
} }
@@ -101,15 +110,37 @@ func (cfg *DownloaderConfig) Init() *DownloaderConfig {
type DownloaderStoreConfig struct { type DownloaderStoreConfig struct {
FirstLoad bool `json:"-"` // FirstLoad is the flag that the config is first time init and not from store FirstLoad bool `json:"-"` // FirstLoad is the flag that the config is first time init and not from store
DownloadDir string `json:"downloadDir"` // DownloadDir is the default directory to save the downloaded files DownloadDir string `json:"downloadDir"` // DownloadDir is the default directory to save the downloaded files
MaxRunning int `json:"maxRunning"` // MaxRunning is the max running download count MaxRunning int `json:"maxRunning"` // MaxRunning is the max running download count
ProtocolConfig map[string]any `json:"protocolConfig"` // ProtocolConfig is special config for each protocol ProtocolConfig map[string]any `json:"protocolConfig"` // ProtocolConfig is special config for each protocol
Extra map[string]any `json:"extra"` // Extra is the extra config Extra map[string]any `json:"extra"`
Proxy *DownloaderProxyConfig `json:"proxy"`
} }
func (cfg *DownloaderStoreConfig) Init() *DownloaderStoreConfig { func (cfg *DownloaderStoreConfig) Init() *DownloaderStoreConfig {
if cfg.MaxRunning == 0 { if cfg.MaxRunning == 0 {
cfg.MaxRunning = 5 cfg.MaxRunning = 5
} }
if cfg.Proxy == nil {
cfg.Proxy = &DownloaderProxyConfig{}
}
return cfg return cfg
} }
func (cfg *DownloaderStoreConfig) ProxyUrl() *url.URL {
if cfg.Proxy == nil {
return nil
}
if cfg.Proxy.Enable == false || cfg.Proxy.Scheme == "" || cfg.Proxy.Host == "" {
return nil
}
return util.BuildProxyUrl(cfg.Proxy.Scheme, cfg.Proxy.Host, cfg.Proxy.Usr, cfg.Proxy.Pwd)
}
type DownloaderProxyConfig struct {
Enable bool `json:"enable"`
Scheme string `json:"scheme"`
Host string `json:"host"`
Usr string `json:"usr"`
Pwd string `json:"pwd"`
}
@@ -1,5 +1,6 @@
gopeed.events.onResolve(async function (ctx) { gopeed.events.onResolve(async function (ctx) {
const aaa = {}; const aaa = {};
// access undefined property
gopeed.logger.info(aaa.bbb.ccc); gopeed.logger.info(aaa.bbb.ccc);
ctx.res = { ctx.res = {
@@ -0,0 +1,3 @@
gopeed.events.onResolve(async function (ctx) {
throw new MessageError("test");
});
@@ -0,0 +1,16 @@
{
"name": "message-error",
"title": "gopeed extension message error test",
"version": "0.0.1",
"scripts": [
{
"event": "onResolve",
"match": {
"urls": [
"*://github.com/*"
]
},
"entry": "index.js"
}
]
}
+8
View File
@@ -0,0 +1,8 @@
gopeed.events.onError(async function (ctx) {
gopeed.logger.info("url", ctx.task.meta.req.url);
gopeed.logger.info("error", ctx.error);
ctx.task.meta.req.url = "https://github.com";
ctx.task.pause();
ctx.task.continue();
});
+16
View File
@@ -0,0 +1,16 @@
{
"name": "on-error",
"title": "gopeed extension on error event test",
"version": "0.0.1",
"scripts": [
{
"event": "onError",
"match": {
"labels": [
"test"
]
},
"entry": "index.js"
}
]
}
+1
View File
@@ -1,4 +1,5 @@
gopeed.events.onStart(async function (ctx) { gopeed.events.onStart(async function (ctx) {
gopeed.logger.info("url", ctx.task.meta.req.url);
ctx.task.meta.req.url = "https://github.com"; ctx.task.meta.req.url = "https://github.com";
ctx.task.meta.req.labels['modified'] = 'true'; ctx.task.meta.req.labels['modified'] = 'true';
}); });
+9
View File
@@ -3,3 +3,12 @@ package bt
type ReqExtra struct { type ReqExtra struct {
Trackers []string `json:"trackers"` Trackers []string `json:"trackers"`
} }
// Stats for download
type Stats struct {
// bt stats
// health indicators of torrents, from large to small, ConnectedSeeders are also the key to the health of seed resources
TotalPeers int `json:"totalPeers"`
ActivePeers int `json:"activePeers"`
ConnectedSeeders int `json:"connectedSeeders"`
}
+8
View File
@@ -8,4 +8,12 @@ type ReqExtra struct {
type OptsExtra struct { type OptsExtra struct {
Connections int `json:"connections"` Connections int `json:"connections"`
// AutoTorrent when task download complete, and it is a .torrent file, it will be auto create a new task for the torrent file
AutoTorrent bool `json:"autoTorrent"`
}
// Stats for download
type Stats struct {
// http stats
// health indicators of http
} }
+16
View File
@@ -3,11 +3,13 @@ package rest
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"fmt"
"github.com/GopeedLab/gopeed/pkg/download" "github.com/GopeedLab/gopeed/pkg/download"
"github.com/GopeedLab/gopeed/pkg/rest/model" "github.com/GopeedLab/gopeed/pkg/rest/model"
"github.com/GopeedLab/gopeed/pkg/util" "github.com/GopeedLab/gopeed/pkg/util"
"github.com/gorilla/handlers" "github.com/gorilla/handlers"
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/pkg/errors"
"net" "net"
"net/http" "net/http"
"os" "os"
@@ -131,6 +133,20 @@ func BuildServer(startCfg *model.StartConfig) (*http.Server, net.Listener, error
}) })
} }
// recover panic
r.Use(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil {
err := errors.WithStack(fmt.Errorf("%v", v))
Downloader.Logger.Error().Stack().Err(err).Msg("http server panic")
WriteJson(w, model.NewErrorResult(err.Error(), model.CodeError))
}
}()
h.ServeHTTP(w, r)
})
})
srv = &http.Server{Handler: handlers.CORS( srv = &http.Server{Handler: handlers.CORS(
handlers.AllowedHeaders([]string{"Content-Type", "X-Api-Token", "X-Target-Uri"}), handlers.AllowedHeaders([]string{"Content-Type", "X-Api-Token", "X-Target-Uri"}),
handlers.AllowedMethods([]string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"}), handlers.AllowedMethods([]string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"}),
+3 -1
View File
@@ -27,7 +27,7 @@ var (
Extra: map[string]any{ Extra: map[string]any{
"method": "", "method": "",
"header": map[string]string{ "header": map[string]string{
"User-Agent": "gopeed", "Usr-Agent": "gopeed",
}, },
"body": "", "body": "",
}, },
@@ -204,12 +204,14 @@ func TestPauseAllAndContinueALLTasks(t *testing.T) {
// continue all // continue all
httpRequestCheckOk[any](http.MethodPut, "/api/v1/tasks/continue", nil) httpRequestCheckOk[any](http.MethodPut, "/api/v1/tasks/continue", nil)
time.Sleep(time.Millisecond * 100)
tasks := httpRequestCheckOk[[]*download.Task](http.MethodGet, fmt.Sprintf("/api/v1/tasks?status=%s", base.DownloadStatusRunning), nil) tasks := httpRequestCheckOk[[]*download.Task](http.MethodGet, fmt.Sprintf("/api/v1/tasks?status=%s", base.DownloadStatusRunning), nil)
if len(tasks) != cfg.MaxRunning { if len(tasks) != cfg.MaxRunning {
t.Errorf("ContinueAllTasks() got = %v, want %v", len(tasks), cfg.MaxRunning) t.Errorf("ContinueAllTasks() got = %v, want %v", len(tasks), cfg.MaxRunning)
} }
// pause all // pause all
httpRequestCheckOk[any](http.MethodPut, "/api/v1/tasks/pause", nil) httpRequestCheckOk[any](http.MethodPut, "/api/v1/tasks/pause", nil)
time.Sleep(time.Millisecond * 100)
tasks = httpRequestCheckOk[[]*download.Task](http.MethodGet, fmt.Sprintf("/api/v1/tasks?status=%s", base.DownloadStatusPause), nil) tasks = httpRequestCheckOk[[]*download.Task](http.MethodGet, fmt.Sprintf("/api/v1/tasks?status=%s", base.DownloadStatusPause), nil)
if len(tasks) != total { if len(tasks) != total {
t.Errorf("PauseAllTasks() got = %v, want %v", len(tasks), total) t.Errorf("PauseAllTasks() got = %v, want %v", len(tasks), total)
+11
View File
@@ -183,3 +183,14 @@ func IsExistsFile(path string) bool {
} }
return false return false
} }
// ReplaceInvalidFilename replace invalid path characters
func ReplaceInvalidFilename(path string) string {
if path == "" {
return ""
}
for _, char := range invalidPathChars {
path = strings.ReplaceAll(path, char, "_")
}
return path
}
+6
View File
@@ -0,0 +1,6 @@
//go:build !windows
// +build !windows
package util
var invalidPathChars = []string{`/`, `:`}
+47
View File
@@ -178,3 +178,50 @@ func TestIsExistsFile(t *testing.T) {
}) })
} }
} }
func TestReplaceInvalidFilename(t *testing.T) {
type args struct {
path string
}
tests := []struct {
name string
args args
want string
}{
{
name: "blank",
args: args{
path: "",
},
want: "",
},
{
name: "normal",
args: args{
path: "test.txt",
},
want: "test.txt",
},
{
name: "case1",
args: args{
path: "te/st.txt",
},
want: "te_st.txt",
},
{
name: "case2",
args: args{
path: "te/st:.txt",
},
want: "te_st_.txt",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ReplaceInvalidFilename(tt.args.path); got != tt.want {
t.Errorf("ReplaceInvalidFilename() = %v, want %v", got, tt.want)
}
})
}
}
+3
View File
@@ -0,0 +1,3 @@
package util
var invalidPathChars = []string{`\`, `/`, `:`, `*`, `?`, `"`, `<`, `>`, `|`}
+14
View File
@@ -2,6 +2,7 @@ package util
import ( import (
"encoding/base64" "encoding/base64"
"net/url"
"regexp" "regexp"
"strings" "strings"
) )
@@ -37,3 +38,16 @@ func ParseDataUri(uri string) (string, []byte) {
} }
return mime, data return mime, data
} }
// BuildProxyUrl builds a proxy url with given host, username and password.
func BuildProxyUrl(scheme, host, usr, pwd string) *url.URL {
var user *url.Userinfo
if usr != "" && pwd != "" {
user = url.UserPassword(usr, pwd)
}
return &url.URL{
Scheme: scheme,
User: user,
Host: host,
}
}
-77
View File
@@ -1,77 +0,0 @@
{
"label": "English",
"error": "Error",
"tip": "Tip",
"confirm": "Confirm",
"cancel": "Cancel",
"selectAll": "Select All",
"task": "Tasks",
"downloading": "downloading",
"downloaded": "downloaded",
"setting": "Settings",
"donate": "Donate",
"exit": "Exit",
"create": "Create Task",
"directDownload": "Direct Download",
"advancedOptions": "Advanced Options",
"downloadLink": "Download Link",
"downloadLinkValid": "Please enter the download link",
"downloadLinkHit": "Please enter the download link, HTTP/HTTPS/MAGNET supported@append",
"downloadLinkHitDesktop": ", or drag the torrent file here directly",
"download": "Download",
"noFileSelected": "Please select at least one file to continue.",
"noStoragePermission": "Storage permission required",
"selectFile": "Select File",
"rename": "Rename",
"basic": "Basic",
"advanced": "Advanced",
"general": "General",
"downloadDir": "Download Directory",
"downloadDirValid": "Please select the download directory",
"connections": "Connections",
"maxRunning": "Max Running Tasks",
"items": "@count items",
"subscribeTracker": "Subscribe Tracker",
"subscribeFail": "Subscribe failed, please check network or try again later",
"update": "Update",
"updateDaily": "Update daily",
"lastUpdate": "Last update: @time",
"addTracker": "Add Tracker",
"addTrackerHit": "Please enter the tracker server url, one per line",
"ui": "UI",
"theme": "Theme",
"themeSystem": "System",
"themeLight": "Light",
"themeDark": "Dark",
"locale": "Language",
"about": "About",
"homepage": "Homepage",
"version": "Version",
"protocol": "Protocol",
"port": "Port",
"apiToken": "API Token",
"notSet": "NS",
"set": "SET",
"effectAfterRestart": "Effect after restart",
"startAll": "Start All",
"pauseAll": "Pause All",
"deleteTask": "Delete Task",
"deleteTaskTip": "Keep downloaded files",
"delete": "Delete",
"newVersionTitle": "Discover new version @version",
"newVersionUpdate": "Update Now",
"newVersionLater": "Later",
"extensions": "Extensions",
"extensionInstallUrl": "Install URL",
"extensionInstallSuccess": "Installed successfully",
"extensionUpdateSuccess": "Updated successfully",
"extensionDelete": "Delete Extension",
"extensionAlreadyLatest": "It's already the latest version",
"extensionFind": "Find Extensions",
"extensionDevelop": "Develop Extensions",
"history": "History",
"clearHistory": "Clear History",
"noHistoryFound": "No History Found",
"serviceTitle": "Download Service",
"serviceText": "Running"
}
-58
View File
@@ -1,58 +0,0 @@
{
"label": "فارسی",
"error": "اررور",
"tip": "Tip",
"confirm": "تایید",
"cancel": "انصراف",
"selectAll": "انتخاب همه",
"task": "کار",
"setting": "تنظیمات",
"donate": "کمک مالی",
"exit": "خروج",
"create": "ایجاد کار",
"downloading": "دانلود کردن",
"downloaded": "دانلود شدن",
"downloadLink": "لینک دانلود",
"downloadLinkValid": "لطفا لینک دانلود را وارد کنید",
"download": "دانلود",
"noFileSelected": "لطفا حداقل یک فایل را جهت دانلود انتخاب کنید.",
"noStoragePermission": "مجوز ذخیره سازی مورد نیاز است",
"selectFile": "انتخاب فایل",
"basic": "پایه",
"advanced": "پیشرفته",
"general": "عمومی",
"downloadDir": "دایرکتوری دانلود",
"downloadDirValid": "لطفا دایرکتوری دانلود را انتخاب کنید",
"connections": "اتصالات",
"items": "@count آیتم ها",
"subscribeTracker": "Subscribe Tracker",
"subscribeFail": "Subscribe failed, please check network or try again later",
"update": "بروزرسانی",
"updateDaily": "بروزرسانی روزانه",
"lastUpdate": "Last update: @time",
"addTracker": "Add Tracker",
"addTrackerHit": "Please enter the tracker server url, one per line",
"ui": "رابط کاربری",
"theme": "پوسته",
"themeSystem": "سیستم",
"themeLight": "روشن",
"themeDark": "تاریک",
"locale": "Language",
"about": "درباره ی",
"homepage": "صفحه اصلی",
"version": "نسخه",
"protocol": "پروتکل",
"port": "پورت",
"apiToken": "API توکن",
"notSet": "NS",
"set": "SET",
"effectAfterRestart": "Effect after restart",
"startAll": "شروع همه",
"pauseAll": "توقف همه",
"deleteTask": "پاک کردن کار",
"deleteTaskTip": "فایل های دانلود شده را نگه دارد",
"delete": "پاک کردن",
"newVersionTitle": "@version عنوان: کشف نسخه جدید",
"newVersionUpdate": "بروزرسانی",
"newVersionLater": "بعداً"
}
-61
View File
@@ -1,61 +0,0 @@
{
"label": "日本語",
"error": "エラー",
"tip": "ヒント",
"confirm": "確認",
"cancel": "キャンセル",
"selectAll": "すべてを選択",
"task": "タスク",
"downloading": "ダウンロード中",
"downloaded": "ダウンロード済",
"setting": "セッティング",
"donate": "寄付する",
"exit": "終了",
"create": "タスクを作成",
"downloadLink": "ダウンロードリンク",
"downloadLinkValid": "ダウンロードリンクを入力してください",
"downloadLinkHit": "ダウンロード リンクを入力してください、HTTP/HTTPS/MAGNET support@append",
"downloadLinkHitDesktop": "または、torrent ファイルを直接ここにドラッグします",
"download": "ダウンロード",
"noFileSelected": "続行するには少なくとも 1 つのファイルを選択してください。",
"noStoragePermission": "ストレージのパーミッションが必要",
"selectFile": "ファイルを選択",
"basic": "ベーシック",
"advanced": "アドバンスド",
"general": "ジェネラル",
"downloadDir": "ディレクトリのダウンロード",
"downloadDirValid": "ダウンロードディレクトリを選択してください",
"connections": "接続",
"maxRunning": "最大実行タスク",
"items": "@count アイテム",
"subscribeTracker": "トラッカーを購読",
"subscribeFail": "登録に失敗しました。ネットワークを確認するか、後でもう一度お試しください",
"update": "アップデート",
"updateDaily": "毎日アップデート",
"lastUpdate": "最終アップデート: @time",
"addTracker": "トラッカーを追加",
"addTrackerHit": "トラッカーサーバーの URL を 1 行に 1 つずつ入力してください",
"ui": "UI",
"theme": "テーマ",
"themeSystem": "システム",
"themeLight": "ライト",
"themeDark": "ダーク",
"locale": "言語",
"about": "概要",
"homepage": "ホームページ",
"version": "バージョン",
"protocol": "プロトコル",
"port": "ポート",
"apiToken": "API トークン",
"notSet": "未設置",
"set": "設置",
"effectAfterRestart": "再起動後の効果",
"startAll": "すべてを開始",
"pauseAll": "すべてを一時停止",
"deleteTask": "タスクを削除",
"deleteTaskTip": "ダウンロードしたファイルを保持",
"delete": "削除",
"newVersionTitle": "新しいバージョン @version を発見する",
"newVersionUpdate": "アップデート",
"newVersionLater": "後で"
}
-73
View File
@@ -1,73 +0,0 @@
{
"label": "Русский(Россия)",
"error": "Ошибка",
"tip": "Подсказка",
"confirm": "Подтвердить",
"cancel": "Отмена",
"selectAll": "Выбрать все",
"task": "Задачи",
"downloading": "Загрузка",
"downloaded": "Загружено",
"setting": "Настройки",
"donate": "Пожертвовать",
"exit": "Выход",
"create": "Создать задачу",
"advancedOptions": "Расширенные опции",
"downloadLink": "Ссылка на скачивание",
"downloadLinkValid": "Пожалуйста, введите ссылку для скачивания",
"downloadLinkHit": "Пожалуйста, введите ссылку для скачивания, HTTP/HTTPS/MAGNET поддерживаются@append",
"downloadLinkHitDesktop": ", или перетащите сюда торрент-файл",
"download": "Скачать",
"noFileSelected": "Файл не выбран",
"noStoragePermission": "Требуется доступ к хранилищу",
"selectFile": "Выбрать файл",
"rename": "Переименовать",
"basic": "Основные параметры",
"advanced": "Расширенные",
"general": "Общие",
"downloadDir": "Папка загрузки",
"downloadDirValid": "Пожалуйста, выберите папку для загрузки",
"connections": "Соединений",
"maxRunning": "Максимальное количество активных задач",
"items": "@подсчет элементов",
"subscribeTracker": "Подпись трекера",
"subscribeFail": "Подписка не удалась, пожалуйста, проверьте сеть или повторите попытку позже",
"update": "Обновить",
"updateDaily": "Обновлять ежедневно",
"lastUpdate": "Последнее обновление: @время",
"addTracker": "Добавить трекер",
"addTrackerHit": "Пожалуйста, введите url трекера, по одному в строке",
"ui": "UI",
"theme": "Тема",
"themeSystem": "Системная",
"themeLight": "Светлая",
"themeDark": "Темная",
"locale": "Язык",
"about": "О приложении",
"homepage": "Домашняя страница",
"version": "Версия",
"protocol": "Протокол",
"port": "Порт",
"apiToken": "API Токен",
"notSet": "Не установлено",
"set": "Установлено",
"effectAfterRestart": "Эффект после перезагрузки",
"startAll": "Запустить все",
"pauseAll": "Приостановить все",
"deleteTask": "Удалить задачу",
"deleteTaskTip": "Сохранить загруженные файлы",
"delete": "Удалить",
"newVersionTitle": "Обнаружена новая версия @version",
"newVersionUpdate": "Обновить",
"newVersionLater": "позже",
"extensions": "Расширения",
"extensionInstallSuccess": "Установка завершена",
"extensionUpdateSuccess": "Обновление завершено",
"extensionDelete": "Удалить расширение",
"extensionAlreadyLatest": "Это последняя версия",
"extensionFind": "Найти расширения",
"extensionDevelop": "Разработка расширений",
"history": "История",
"clearHistory": "Очистить историю",
"noHistoryFound": "История не найдена"
}
-77
View File
@@ -1,77 +0,0 @@
{
"label": "中文(简体)",
"error": "错误",
"tip": "提示",
"confirm": "确认",
"cancel": "取消",
"selectAll": "全选",
"task": "任务",
"downloading": "下载中",
"downloaded": "已完成",
"setting": "设置",
"donate": "打赏",
"exit": "退出",
"create": "创建任务",
"directDownload": "直接下载",
"advancedOptions": "高级选项",
"downloadLink": "下载链接",
"downloadLinkValid": "请输入下载链接",
"downloadLinkHit": "请输入下载链接,支持 HTTP/HTTPS/MAGNET@append",
"downloadLinkHitDesktop": ",也可以直接拖拽种子文件到此处",
"download": "下载",
"noFileSelected": "请至少选择一个文件下载",
"noStoragePermission": "需要开启存储权限",
"selectFile": "选择文件",
"rename": "重命名",
"basic": "基础",
"advanced": "高级",
"general": "通用",
"downloadDir": "下载目录",
"downloadDirValid": "请选择下载目录",
"connections": "连接数",
"maxRunning": "最大下载数",
"items": "@count 项",
"subscribeTracker": "订阅 Tracker",
"subscribeFail": "订阅失败,请检查网络或稍后重试",
"update": "更新",
"updateDaily": "每天自动更新",
"lastUpdate": "上次更新:@time",
"addTracker": "添加 Tracker",
"addTrackerHit": "请输入 tracker 服务器地址,每行一条",
"ui": "界面",
"theme": "主题",
"themeSystem": "跟随系统",
"themeLight": "明亮主题",
"themeDark": "暗黑主题",
"locale": "语言",
"about": "关于",
"homepage": "主页",
"version": "版本",
"protocol": "通讯协议",
"port": "端口",
"apiToken": "接口令牌",
"notSet": "未设置",
"set": "已设置",
"effectAfterRestart": "此配置项将在重启应用后生效",
"startAll": "全部开始",
"pauseAll": "全部暂停",
"deleteTask": "删除任务",
"deleteTaskTip": "保留已下载的文件",
"delete": "删除",
"newVersionTitle": "发现新版本 @version",
"newVersionUpdate": "立即更新",
"newVersionLater": "稍后再说",
"extensions": "扩展",
"extensionInstallUrl": "安装链接",
"extensionInstallSuccess": "安装成功",
"extensionUpdateSuccess": "更新成功",
"extensionDelete": "删除扩展",
"extensionAlreadyLatest": "已经是最新版本",
"extensionFind": "获取扩展",
"extensionDevelop": "开发扩展",
"history": "历史记录",
"clearHistory": "清空历史记录",
"noHistoryFound": "暂无历史记录",
"serviceTitle": "下载服务",
"serviceText": "运行中"
}
-77
View File
@@ -1,77 +0,0 @@
{
"label": "中文 (繁體) ",
"error": "錯誤",
"tip": "提示",
"confirm": "確定",
"cancel": "取消",
"selectAll": "全選",
"task": "任務",
"downloading": "下載中",
"downloaded": "已完成",
"setting": "設定",
"donate": "斗內",
"exit": "離開",
"create": "新增任務",
"directDownload": "直接下載",
"advancedOptions": "進階選項",
"downloadLink": "下載鏈接",
"downloadLinkValid": "請輸入下載鏈接",
"downloadLinkHit": "請輸入下載鏈接,支援 HTTP/HTTPS/MAGNET@append",
"downloadLinkHitDesktop": ",也可以通過拖拽Torrent文件至此以新增任務",
"download": "下載",
"noFileSelected": "沒有選取的文件",
"noStoragePermission": "沒有存儲權限",
"selectFile": "選擇文件",
"rename": "重命名",
"basic": "基礎",
"advanced": "進階",
"general": "通用設定",
"downloadDir": "下載目録",
"downloadDirValid": "請選擇下載目録",
"connections": "同時連接數",
"maxRunning": "最大同時下載數",
"items": "@count 項",
"subscribeTracker": "已訂閲的追蹤者列表",
"subscribeFail": "訂閲失敗",
"update": "更新",
"updateDaily": "每天自動更新",
"lastUpdate": "上次更新時間: @time",
"addTracker": "增加新的追蹤者",
"addTrackerHit": "請輸入追蹤者服務器地址,每行一條",
"ui": "介面",
"theme": "佈景主題",
"themeSystem": "跟隨系統",
"themeLight": "亮色主題",
"themeDark": "深色主題",
"locale": "語言",
"about": "關於",
"homepage": "訪問主頁",
"version": "版本資訊",
"protocol": "端口設定",
"port": "端口",
"apiToken": "接口秘鑰",
"notSet": "未設定",
"set": "已設定",
"effectAfterRestart": "重啟後生效",
"startAll": "全部開始",
"pauseAll": "全部暫停",
"deleteTask": "刪除任務",
"deleteTaskTip": "保留已經下載的文件",
"delete": "刪除",
"newVersionTitle": "發現新版本 @version",
"newVersionUpdate": "立刻更新",
"newVersionLater": "稍後更新",
"extensions": "外掛程序",
"extensionInstallUrl": "安裝URL",
"extensionInstallSuccess": "安裝成功",
"extensionUpdateSuccess": "更新完成",
"extensionDelete": "解除安裝",
"extensionAlreadyLatest": "已是最新版本",
"extensionFind": "取得外掛",
"extensionDevelop": "開發外掛",
"history": "歷史記錄",
"clearHistory": "清空記錄",
"noHistoryFound": "還沒有記錄",
"serviceTitle": "下載服務",
"serviceText": "執行中"
}
+1
View File
@@ -0,0 +1 @@
output: dist/
@@ -8,6 +8,7 @@ class DownloaderConfig {
int maxRunning = 0; int maxRunning = 0;
ProtocolConfig protocolConfig = ProtocolConfig(); ProtocolConfig protocolConfig = ProtocolConfig();
ExtraConfig extra = ExtraConfig(); ExtraConfig extra = ExtraConfig();
ProxyConfig proxy = ProxyConfig();
DownloaderConfig(); DownloaderConfig();
@@ -66,6 +67,22 @@ class ExtraConfig {
Map<String, dynamic> toJson() => _$ExtraConfigToJson(this); Map<String, dynamic> toJson() => _$ExtraConfigToJson(this);
} }
@JsonSerializable()
class ProxyConfig {
bool enable = false;
String scheme = '';
String host = '';
String usr = '';
String pwd = '';
ProxyConfig();
factory ProxyConfig.fromJson(Map<String, dynamic> json) =>
_$ProxyConfigFromJson(json);
Map<String, dynamic> toJson() => _$ProxyConfigToJson(this);
}
@JsonSerializable() @JsonSerializable()
class ExtraConfigBt { class ExtraConfigBt {
List<String> trackerSubscribeUrls = []; List<String> trackerSubscribeUrls = [];
@@ -12,7 +12,8 @@ DownloaderConfig _$DownloaderConfigFromJson(Map<String, dynamic> json) =>
..maxRunning = json['maxRunning'] as int ..maxRunning = json['maxRunning'] as int
..protocolConfig = ProtocolConfig.fromJson( ..protocolConfig = ProtocolConfig.fromJson(
json['protocolConfig'] as Map<String, dynamic>?) json['protocolConfig'] as Map<String, dynamic>?)
..extra = ExtraConfig.fromJson(json['extra'] as Map<String, dynamic>?); ..extra = ExtraConfig.fromJson(json['extra'] as Map<String, dynamic>?)
..proxy = ProxyConfig.fromJson(json['proxy'] as Map<String, dynamic>);
Map<String, dynamic> _$DownloaderConfigToJson(DownloaderConfig instance) => Map<String, dynamic> _$DownloaderConfigToJson(DownloaderConfig instance) =>
<String, dynamic>{ <String, dynamic>{
@@ -20,6 +21,7 @@ Map<String, dynamic> _$DownloaderConfigToJson(DownloaderConfig instance) =>
'maxRunning': instance.maxRunning, 'maxRunning': instance.maxRunning,
'protocolConfig': instance.protocolConfig.toJson(), 'protocolConfig': instance.protocolConfig.toJson(),
'extra': instance.extra.toJson(), 'extra': instance.extra.toJson(),
'proxy': instance.proxy.toJson(),
}; };
ProtocolConfig _$ProtocolConfigFromJson(Map<String, dynamic> json) => ProtocolConfig _$ProtocolConfigFromJson(Map<String, dynamic> json) =>
@@ -65,6 +67,22 @@ Map<String, dynamic> _$ExtraConfigToJson(ExtraConfig instance) =>
'bt': instance.bt.toJson(), 'bt': instance.bt.toJson(),
}; };
ProxyConfig _$ProxyConfigFromJson(Map<String, dynamic> json) => ProxyConfig()
..enable = json['enable'] as bool
..scheme = json['scheme'] as String
..host = json['host'] as String
..usr = json['usr'] as String
..pwd = json['pwd'] as String;
Map<String, dynamic> _$ProxyConfigToJson(ProxyConfig instance) =>
<String, dynamic>{
'enable': instance.enable,
'scheme': instance.scheme,
'host': instance.host,
'usr': instance.usr,
'pwd': instance.pwd,
};
ExtraConfigBt _$ExtraConfigBtFromJson(Map<String, dynamic> json) => ExtraConfigBt _$ExtraConfigBtFromJson(Map<String, dynamic> json) =>
ExtraConfigBt() ExtraConfigBt()
..trackerSubscribeUrls = (json['trackerSubscribeUrls'] as List<dynamic>) ..trackerSubscribeUrls = (json['trackerSubscribeUrls'] as List<dynamic>)
+1
View File
@@ -25,6 +25,7 @@ class Options {
@JsonSerializable() @JsonSerializable()
class OptsExtraHttp { class OptsExtraHttp {
int connections = 0; int connections = 0;
bool autoTorrent = false;
OptsExtraHttp(); OptsExtraHttp();
+4 -1
View File
@@ -32,9 +32,12 @@ Map<String, dynamic> _$OptionsToJson(Options instance) {
} }
OptsExtraHttp _$OptsExtraHttpFromJson(Map<String, dynamic> json) => OptsExtraHttp _$OptsExtraHttpFromJson(Map<String, dynamic> json) =>
OptsExtraHttp()..connections = json['connections'] as int; OptsExtraHttp()
..connections = json['connections'] as int
..autoTorrent = json['autoTorrent'] as bool;
Map<String, dynamic> _$OptsExtraHttpToJson(OptsExtraHttp instance) => Map<String, dynamic> _$OptsExtraHttpToJson(OptsExtraHttp instance) =>
<String, dynamic>{ <String, dynamic>{
'connections': instance.connections, 'connections': instance.connections,
'autoTorrent': instance.autoTorrent,
}; };
+2
View File
@@ -13,6 +13,7 @@ class Task {
Status status; Status status;
Progress progress; Progress progress;
DateTime createdAt; DateTime createdAt;
DateTime updatedAt;
Task({ Task({
required this.id, required this.id,
@@ -20,6 +21,7 @@ class Task {
required this.status, required this.status,
required this.progress, required this.progress,
required this.createdAt, required this.createdAt,
required this.updatedAt,
}); });
factory Task.fromJson(Map<String, dynamic> json) => _$TaskFromJson(json); factory Task.fromJson(Map<String, dynamic> json) => _$TaskFromJson(json);
+2
View File
@@ -12,6 +12,7 @@ Task _$TaskFromJson(Map<String, dynamic> json) => Task(
status: $enumDecode(_$StatusEnumMap, json['status']), status: $enumDecode(_$StatusEnumMap, json['status']),
progress: Progress.fromJson(json['progress'] as Map<String, dynamic>), progress: Progress.fromJson(json['progress'] as Map<String, dynamic>),
createdAt: DateTime.parse(json['createdAt'] as String), createdAt: DateTime.parse(json['createdAt'] as String),
updatedAt: DateTime.parse(json['updatedAt'] as String),
); );
Map<String, dynamic> _$TaskToJson(Task instance) => <String, dynamic>{ Map<String, dynamic> _$TaskToJson(Task instance) => <String, dynamic>{
@@ -20,6 +21,7 @@ Map<String, dynamic> _$TaskToJson(Task instance) => <String, dynamic>{
'status': _$StatusEnumMap[instance.status]!, 'status': _$StatusEnumMap[instance.status]!,
'progress': instance.progress.toJson(), 'progress': instance.progress.toJson(),
'createdAt': instance.createdAt.toIso8601String(), 'createdAt': instance.createdAt.toIso8601String(),
'updatedAt': instance.updatedAt.toIso8601String(),
}; };
const _$StatusEnumMap = { const _$StatusEnumMap = {
@@ -6,6 +6,7 @@ import 'package:app_links/app_links.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart'; import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:lecle_downloads_path_provider/lecle_downloads_path_provider.dart';
import 'package:path_provider/path_provider.dart'; import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:tray_manager/tray_manager.dart'; import 'package:tray_manager/tray_manager.dart';
@@ -16,11 +17,12 @@ import 'package:window_manager/window_manager.dart';
import '../../../../api/api.dart'; import '../../../../api/api.dart';
import '../../../../api/model/downloader_config.dart'; import '../../../../api/model/downloader_config.dart';
import '../../../../core/common/start_config.dart'; import '../../../../core/common/start_config.dart';
import '../../../../generated/locales.g.dart'; import '../../../../i18n/message.dart';
import '../../../../util/locale_manager.dart'; import '../../../../util/locale_manager.dart';
import '../../../../util/log_util.dart'; import '../../../../util/log_util.dart';
import '../../../../util/package_info.dart'; import '../../../../util/package_info.dart';
import '../../../../util/util.dart'; import '../../../../util/util.dart';
import '../../../../util/window_util.dart' as windows_util;
import '../../../routes/app_pages.dart'; import '../../../routes/app_pages.dart';
const _startConfigNetwork = "start.network"; const _startConfigNetwork = "start.network";
@@ -49,7 +51,12 @@ const allTrackerCdns = [
[ [
"https://ghproxy.com/https://raw.githubusercontent.com", "https://ghproxy.com/https://raw.githubusercontent.com",
r".*github.com(/.*)/raw(/.*)" r".*github.com(/.*)/raw(/.*)"
] ],
// mirror.ghproxy.com: https://mirror.ghproxy.com/https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_all.txt
[
"https://mirror.ghproxy.com/https://raw.githubusercontent.com",
r".*github.com(/.*)/raw(/.*)"
],
]; ];
final allTrackerSubscribeUrlCdns = Map.fromIterable(allTrackerSubscribeUrls, final allTrackerSubscribeUrlCdns = Map.fromIterable(allTrackerSubscribeUrls,
key: (v) => v as String, key: (v) => v as String,
@@ -118,6 +125,26 @@ class AppController extends GetxController with WindowListener, TrayListener {
trayManager.popUpContextMenu(); trayManager.popUpContextMenu();
} }
@override
void onWindowMaximize() {
windows_util.saveState(isMaximized: true);
}
@override
void onWindowUnmaximize() {
windows_util.saveState(isMaximized: false);
}
final _windowsResizeSave = Util.debounce(() async {
final size = await windowManager.getSize();
windows_util.saveState(width: size.width, height: size.height);
}, 500);
@override
void onWindowResize() {
_windowsResizeSave();
}
Future<void> _initDeepLinks() async { Future<void> _initDeepLinks() async {
// currently only support android // currently only support android
if (!Util.isAndroid()) { if (!Util.isAndroid()) {
@@ -185,9 +212,7 @@ class AppController extends GetxController with WindowListener, TrayListener {
MenuItem( MenuItem(
label: 'donate'.tr, label: 'donate'.tr,
onClick: (menuItem) => { onClick: (menuItem) => {
launchUrl( launchUrl(Uri.parse("https://docs.gopeed.com/donate.html"),
Uri.parse(
"https://github.com/GopeedLab/gopeed/blob/main/.donate/index.md#donate"),
mode: LaunchMode.externalApplication) mode: LaunchMode.externalApplication)
}, },
), ),
@@ -376,7 +401,7 @@ class AppController extends GetxController with WindowListener, TrayListener {
} }
if (extra.locale.isEmpty) { if (extra.locale.isEmpty) {
final systemLocale = getLocaleKey(PlatformDispatcher.instance.locale); final systemLocale = getLocaleKey(PlatformDispatcher.instance.locale);
extra.locale = AppTranslation.translations.containsKey(systemLocale) extra.locale = messages.keys.containsKey(systemLocale)
? systemLocale ? systemLocale
: getLocaleKey(fallbackLocale); : getLocaleKey(fallbackLocale);
} }
@@ -384,14 +409,21 @@ class AppController extends GetxController with WindowListener, TrayListener {
// default select all tracker subscribe urls // default select all tracker subscribe urls
extra.bt.trackerSubscribeUrls.addAll(allTrackerSubscribeUrls); extra.bt.trackerSubscribeUrls.addAll(allTrackerSubscribeUrls);
} }
final proxy = config.proxy;
if (proxy.scheme.isEmpty) {
proxy.scheme = 'http';
}
if (config.downloadDir.isEmpty) { if (config.downloadDir.isEmpty) {
if (Util.isDesktop()) { if (Util.isDesktop()) {
config.downloadDir = (await getDownloadsDirectory())?.path ?? "./"; config.downloadDir = (await getDownloadsDirectory())?.path ?? "./";
} else if (Util.isAndroid()) { } else if (Util.isAndroid()) {
config.downloadDir = (await getExternalStorageDirectory())?.path ?? final downloadDir = (await DownloadsPath.downloadsDirectory())?.path;
(await getApplicationDocumentsDirectory()).path; if (downloadDir != null) {
return; config.downloadDir = '$downloadDir/Gopeed';
} else {
config.downloadDir = (await getApplicationDocumentsDirectory()).path;
}
} else if (Util.isIOS()) { } else if (Util.isIOS()) {
config.downloadDir = (await getApplicationDocumentsDirectory()).path; config.downloadDir = (await getApplicationDocumentsDirectory()).path;
} else { } else {
@@ -1,8 +1,9 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import '../../../../generated/locales.g.dart'; import '../../../../i18n/message.dart';
import '../../../../theme/theme.dart'; import '../../../../theme/theme.dart';
import '../../../../util/locale_manager.dart'; import '../../../../util/locale_manager.dart';
import '../../../routes/app_pages.dart'; import '../../../routes/app_pages.dart';
@@ -14,24 +15,24 @@ class AppView extends GetView<AppController> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final config = controller.downloaderConfig.value; final config = controller.downloaderConfig.value;
return GetMaterialApp.router( return WithForegroundTask(
useInheritedMediaQuery: true, child: GetMaterialApp.router(
debugShowCheckedModeBanner: false, useInheritedMediaQuery: true,
theme: GopeedTheme.light, debugShowCheckedModeBanner: false,
darkTheme: GopeedTheme.dark, theme: GopeedTheme.light,
themeMode: ThemeMode.values.byName(config.extra.themeMode), darkTheme: GopeedTheme.dark,
// translations: messages, themeMode: ThemeMode.values.byName(config.extra.themeMode),
translationsKeys: AppTranslation.translations, translations: messages,
locale: toLocale(config.extra.locale), locale: toLocale(config.extra.locale),
fallbackLocale: fallbackLocale, fallbackLocale: fallbackLocale,
localizationsDelegates: const [ localizationsDelegates: const [
GlobalMaterialLocalizations.delegate, GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate, GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate, GlobalCupertinoLocalizations.delegate,
], ],
supportedLocales: supportedLocales: messages.keys.keys.map((e) => toLocale(e)).toList(),
AppTranslation.translations.keys.map((e) => toLocale(e)).toList(), getPages: AppPages.routes,
getPages: AppPages.routes, ),
); );
} }
} }
@@ -4,16 +4,14 @@ import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:gopeed/app/modules/history/controller/history_controller.dart';
import 'package:gopeed/app/modules/history/views/history_view.dart';
import 'package:path/path.dart' as path; import 'package:path/path.dart' as path;
import 'package:rounded_loading_button/rounded_loading_button.dart'; import 'package:rounded_loading_button/rounded_loading_button.dart';
import '../../../../api/api.dart'; import '../../../../api/api.dart';
import '../../../../api/model/create_task.dart'; import '../../../../api/model/create_task.dart';
import '../../../../api/model/options.dart'; import '../../../../api/model/options.dart';
import '../../../../api/model/request.dart'; import '../../../../api/model/request.dart';
import '../../../../api/model/resolve_result.dart'; import '../../../../api/model/resolve_result.dart';
import '../../../../api/model/resource.dart';
import '../../../../util/input_formatter.dart'; import '../../../../util/input_formatter.dart';
import '../../../../util/message.dart'; import '../../../../util/message.dart';
import '../../../../util/util.dart'; import '../../../../util/util.dart';
@@ -21,6 +19,8 @@ import '../../../routes/app_pages.dart';
import '../../../views/directory_selector.dart'; import '../../../views/directory_selector.dart';
import '../../../views/file_list_view.dart'; import '../../../views/file_list_view.dart';
import '../../app/controllers/app_controller.dart'; import '../../app/controllers/app_controller.dart';
import '../../history/controller/history_controller.dart';
import '../../history/views/history_view.dart';
import '../controllers/create_controller.dart'; import '../controllers/create_controller.dart';
class CreateView extends GetView<CreateController> { class CreateView extends GetView<CreateController> {
@@ -409,15 +409,20 @@ class CreateView extends GetView<CreateController> {
try { try {
_confirmController.start(); _confirmController.start();
if (_confirmFormKey.currentState!.validate()) { if (_confirmFormKey.currentState!.validate()) {
final submitUrl = Util.isWeb() && controller.fileDataUri.isNotEmpty final isWebFileChosen =
Util.isWeb() && controller.fileDataUri.isNotEmpty;
final submitUrl = isWebFileChosen
? controller.fileDataUri.value ? controller.fileDataUri.value
: _urlController.text; : _urlController.text;
final urls = Util.textToLines(submitUrl); final urls = Util.textToLines(submitUrl);
// Add url to the history // Add url to the history
for (final url in urls) { if (!isWebFileChosen) {
_historyController.addHistory(url); for (final url in urls) {
_historyController.addHistory(url);
}
} }
/* /*
Check if is direct download, there has two ways to direct download Check if is direct download, there has two ways to direct download
1. Direct download option is checked 1. Direct download option is checked
@@ -433,7 +438,7 @@ class CreateView extends GetView<CreateController> {
name: isMultiLine ? "" : _renameController.text, name: isMultiLine ? "" : _renameController.text,
path: _pathController.text, path: _pathController.text,
selectFiles: [], selectFiles: [],
extra: parseReqOpts()))); extra: parseReqOptsExtra())));
})); }));
Get.rootDelegate.offNamed(Routes.TASK); Get.rootDelegate.offNamed(Routes.TASK);
} else { } else {
@@ -471,11 +476,10 @@ class CreateView extends GetView<CreateController> {
return reqExtra; return reqExtra;
} }
Object? parseReqOpts() { Object? parseReqOptsExtra() {
return _connectionsController.text.isEmpty return OptsExtraHttp()
? null ..connections = int.tryParse(_connectionsController.text) ?? 0
: (OptsExtraHttp() ..autoTorrent = true;
..connections = int.parse(_connectionsController.text));
} }
String _hitText() { String _hitText() {
@@ -541,7 +545,7 @@ class CreateView extends GetView<CreateController> {
showMessage('tip'.tr, 'noFileSelected'.tr); showMessage('tip'.tr, 'noFileSelected'.tr);
return; return;
} }
final optExtra = parseReqOpts(); final optExtra = parseReqOptsExtra();
if (createFormKey.currentState!.validate()) { if (createFormKey.currentState!.validate()) {
if (rr.id.isEmpty) { if (rr.id.isEmpty) {
// from extension resolve result // from extension resolve result
@@ -41,10 +41,8 @@ class ExtensionView extends GetView<ExtensionController> {
children: [ children: [
TextButton.icon( TextButton.icon(
onPressed: () { onPressed: () {
launchUrl( launchUrl(Uri.parse(
Uri.parse( 'https://github.com/search?q=topic%3Agopeed-extension&type=repositories'));
'https://github.com/search?q=topic%3Agopeed-extension&type=repositories'),
mode: LaunchMode.externalApplication);
}, },
icon: const Icon(Icons.search), icon: const Icon(Icons.search),
label: Text('extensionFind'.tr), label: Text('extensionFind'.tr),
@@ -53,8 +51,7 @@ class ExtensionView extends GetView<ExtensionController> {
TextButton.icon( TextButton.icon(
onPressed: () { onPressed: () {
launchUrl( launchUrl(
Uri.parse('https://docs.gopeed.com/dev-extension.html'), Uri.parse('https://docs.gopeed.com/dev-extension.html'));
mode: LaunchMode.externalApplication);
}, },
icon: const Icon(Icons.edit), icon: const Icon(Icons.edit),
label: Text('extensionDevelop'.tr), label: Text('extensionDevelop'.tr),
@@ -208,20 +205,15 @@ class ExtensionView extends GetView<ExtensionController> {
? IconButton( ? IconButton(
onPressed: () { onPressed: () {
launchUrl( launchUrl(
Uri.parse(extension.homepage), Uri.parse(extension.homepage));
mode: LaunchMode
.externalApplication);
}, },
icon: const Icon(Icons.home)) icon: const Icon(Icons.home))
: null, : null,
extension.repository?.url.isNotEmpty == true extension.repository?.url.isNotEmpty == true
? IconButton( ? IconButton(
onPressed: () { onPressed: () {
launchUrl( launchUrl(Uri.parse(
Uri.parse( extension.repository!.url));
extension.repository!.url),
mode: LaunchMode
.externalApplication);
}, },
icon: const Icon(Icons.code)) icon: const Icon(Icons.code))
: null, : null,
@@ -1,5 +1,4 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import '../../../routes/app_pages.dart'; import '../../../routes/app_pages.dart';
@@ -12,7 +11,7 @@ class HomeView extends GetView<HomeController> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return GetRouterOutlet.builder(builder: (context, delegate, currentRoute) { return GetRouterOutlet.builder(builder: (context, delegate, currentRoute) {
switch (currentRoute?.location) { switch (currentRoute?.uri.path) {
case Routes.EXTENSION: case Routes.EXTENSION:
controller.currentIndex.value = 1; controller.currentIndex.value = 1;
break; break;
@@ -24,141 +23,139 @@ class HomeView extends GetView<HomeController> {
break; break;
} }
return WithForegroundTask( return Scaffold(
child: Scaffold( // extendBody: true,
// extendBody: true, body: Row(
body: Row( // crossAxisAlignment: CrossAxisAlignment.start,
// crossAxisAlignment: CrossAxisAlignment.start, children: [
children: [ !ResponsiveBuilder.isNarrow(context)
!ResponsiveBuilder.isNarrow(context) ? NavigationRail(
? NavigationRail( extended: true,
extended: true, labelType: NavigationRailLabelType.none,
labelType: NavigationRailLabelType.none, minExtendedWidth: 170,
minExtendedWidth: 170, groupAlignment: 0,
groupAlignment: 0, // useIndicator: false,
// useIndicator: false, onDestinationSelected: (int index) {
onDestinationSelected: (int index) { controller.currentIndex.value = index;
controller.currentIndex.value = index; switch (index) {
switch (index) { case 0:
case 0: delegate.offAndToNamed(Routes.TASK);
delegate.offAndToNamed(Routes.TASK); break;
break; case 1:
case 1: delegate.offAndToNamed(Routes.EXTENSION);
delegate.offAndToNamed(Routes.EXTENSION); break;
break; case 2:
case 2: delegate.offAndToNamed(Routes.SETTING);
delegate.offAndToNamed(Routes.SETTING); break;
break; }
} },
}, destinations: [
destinations: [ NavigationRailDestination(
NavigationRailDestination( icon: const Icon(Icons.task),
icon: const Icon(Icons.task), selectedIcon: const Icon(Icons.task),
selectedIcon: const Icon(Icons.task), label: Text('task'.tr),
label: Text('task'.tr), ),
), NavigationRailDestination(
NavigationRailDestination( icon: const Icon(Icons.extension),
icon: const Icon(Icons.extension), selectedIcon: const Icon(Icons.extension),
selectedIcon: const Icon(Icons.extension), label: Text('extensions'.tr),
label: Text('extensions'.tr), ),
), NavigationRailDestination(
NavigationRailDestination( icon: const Icon(Icons.settings),
icon: const Icon(Icons.settings), selectedIcon: const Icon(Icons.settings),
selectedIcon: const Icon(Icons.settings), label: Text('setting'.tr),
label: Text('setting'.tr), ),
), ],
], selectedIndex: controller.currentIndex.value,
selectedIndex: controller.currentIndex.value, leading: const Icon(Icons.menu),
leading: const Icon(Icons.menu), // trailing: const Icon(Icons.info_outline),
// trailing: const Icon(Icons.info_outline), )
) : const SizedBox.shrink(),
: const SizedBox.shrink(), Expanded(
Expanded( child: GetRouterOutlet(
child: GetRouterOutlet( initialRoute: Routes.TASK,
initialRoute: Routes.TASK, // anchorRoute: '/',
// anchorRoute: '/', // filterPages: (afterAnchor) {
// filterPages: (afterAnchor) { // logger.w(afterAnchor);
// logger.w(afterAnchor); // logger.w(afterAnchor.take(1));
// logger.w(afterAnchor.take(1)); // return afterAnchor.take(1);
// return afterAnchor.take(1); // },
// }, ))
)) ]),
]), bottomNavigationBar: ResponsiveBuilder.isNarrow(context)
bottomNavigationBar: ResponsiveBuilder.isNarrow(context) ? BottomNavigationBar(
? BottomNavigationBar( items: <BottomNavigationBarItem>[
items: <BottomNavigationBarItem>[ BottomNavigationBarItem(
BottomNavigationBarItem( icon: const Icon(Icons.task),
icon: const Icon(Icons.task), label: 'task'.tr,
label: 'task'.tr, ),
), BottomNavigationBarItem(
BottomNavigationBarItem( icon: const Icon(Icons.extension),
icon: const Icon(Icons.extension), label: 'extensions'.tr,
label: 'extensions'.tr, ),
), BottomNavigationBarItem(
BottomNavigationBarItem( icon: const Icon(Icons.settings),
icon: const Icon(Icons.settings), label: 'setting'.tr,
label: 'setting'.tr, ),
), ],
], currentIndex: controller.currentIndex.value,
currentIndex: controller.currentIndex.value, // selectedItemColor: Get.theme.highlightColor,
// selectedItemColor: Get.theme.highlightColor, onTap: (index) {
onTap: (index) { controller.currentIndex.value = index;
controller.currentIndex.value = index; switch (index) {
switch (index) { case 0:
case 0: delegate.offAndToNamed(Routes.TASK);
delegate.offAndToNamed(Routes.TASK); break;
break; case 1:
case 1: delegate.offAndToNamed(Routes.EXTENSION);
delegate.offAndToNamed(Routes.EXTENSION); break;
break; case 2:
case 2: delegate.offAndToNamed(Routes.SETTING);
delegate.offAndToNamed(Routes.SETTING); break;
break; }
} },
}, )
) // StylishBottomBar(
// StylishBottomBar( // option: AnimatedBarOptions(
// option: AnimatedBarOptions( // iconSize: 32,
// iconSize: 32, // barAnimation: BarAnimation.blink,
// barAnimation: BarAnimation.blink, // iconStyle: IconStyle.Default,
// iconStyle: IconStyle.Default, // opacity: 0.3,
// opacity: 0.3, // ),
// ), // items: [
// items: [ // BottomBarItem(
// BottomBarItem( // icon: const Icon(Icons.file_download),
// icon: const Icon(Icons.file_download), // selectedColor: Get.theme.primaryColor,
// selectedColor: Get.theme.primaryColor, // title: Text('downloading'.tr)),
// title: Text('downloading'.tr)), // BottomBarItem(
// BottomBarItem( // icon: const Icon(Icons.done),
// icon: const Icon(Icons.done), // selectedColor: Get.theme.primaryColor,
// selectedColor: Get.theme.primaryColor, // title: Text('downloaded'.tr)),
// title: Text('downloaded'.tr)), // BottomBarItem(
// BottomBarItem( // icon: const Icon(Icons.settings),
// icon: const Icon(Icons.settings), // selectedColor: Get.theme.primaryColor,
// selectedColor: Get.theme.primaryColor, // title: Text('setting'.tr)),
// title: Text('setting'.tr)), // ],
// ], // // hasNotch: true,
// // hasNotch: true, // currentIndex: controller.currentIndex.value,
// currentIndex: controller.currentIndex.value, // onTap: (index) {
// onTap: (index) { // switch (index) {
// switch (index) { // case 0:
// case 0: // delegate.toNamed(Routes.DOWNLOADING);
// delegate.toNamed(Routes.DOWNLOADING); // controller.currentIndex.value = 0;
// controller.currentIndex.value = 0; // break;
// break; // case 1:
// case 1: // delegate.toNamed(Routes.DOWNLOADED);
// delegate.toNamed(Routes.DOWNLOADED); // controller.currentIndex.value = 1;
// controller.currentIndex.value = 1; // break;
// break; // case 2:
// case 2: // delegate.toNamed(Routes.SETTING);
// delegate.toNamed(Routes.SETTING); // controller.currentIndex.value = 2;
// controller.currentIndex.value = 2; // break;
// break; // }
// } // },
// }, // )
// ) : const SizedBox.shrink(),
: const SizedBox.shrink(),
),
); );
}); });
} }
@@ -7,7 +7,7 @@ import 'package:get/get.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher/url_launcher.dart';
import '../../../../generated/locales.g.dart'; import '../../../../i18n/message.dart';
import '../../../../util/input_formatter.dart'; import '../../../../util/input_formatter.dart';
import '../../../../util/locale_manager.dart'; import '../../../../util/locale_manager.dart';
import '../../../../util/message.dart'; import '../../../../util/message.dart';
@@ -272,8 +272,7 @@ class SettingView extends GetView<SettingController> {
)); ));
final buildLocale = _buildConfigItem( final buildLocale = _buildConfigItem(
'locale', 'locale',
() => AppTranslation () => messages.keys[downloaderCfg.value.extra.locale]!['label']!,
.translations[downloaderCfg.value.extra.locale]!['label']!,
(Key key) => DropdownButton<String>( (Key key) => DropdownButton<String>(
key: key, key: key,
value: downloaderCfg.value.extra.locale, value: downloaderCfg.value.extra.locale,
@@ -287,23 +286,26 @@ class SettingView extends GetView<SettingController> {
await debounceSave(); await debounceSave();
}, },
items: AppTranslation.translations.keys items: messages.keys.keys
.map((e) => DropdownMenuItem<String>( .map((e) => DropdownMenuItem<String>(
value: e, value: e,
child: Text(AppTranslation.translations[e]!['label']!), child: Text(messages.keys[e]!['label']!),
)) ))
.toList(), .toList(),
)); ));
// about config items start // about config items start
buildHomepage() => ListTile( buildHomepage() {
title: Text('homepage'.tr), const homePage = 'https://gopeed.com';
subtitle: const Text('https://github.com/GopeedLab/gopeed'), return ListTile(
onTap: () { title: Text('homepage'.tr),
launchUrl(Uri.parse('https://github.com/GopeedLab/gopeed'), subtitle: const Text(homePage),
mode: LaunchMode.externalApplication); onTap: () {
}, launchUrl(Uri.parse(homePage), mode: LaunchMode.externalApplication);
); },
);
}
buildVersion() { buildVersion() {
bool isNewVersion(String current, String latest) { bool isNewVersion(String current, String latest) {
if (latest == "") { if (latest == "") {
@@ -363,7 +365,160 @@ class SettingView extends GetView<SettingController> {
); );
} }
// advanced config items start buildThanks() {
const thankPage =
'https://github.com/GopeedLab/gopeed/graphs/contributors';
return ListTile(
title: Text('thanks'.tr),
subtitle: Text('thanksDesc'.tr),
onTap: () {
launchUrl(Uri.parse(thankPage), mode: LaunchMode.externalApplication);
},
);
}
// advanced config proxy items start
final buildProxy = _buildConfigItem(
'proxy',
() => downloaderCfg.value.proxy.enable
? '${downloaderCfg.value.proxy.scheme}://${downloaderCfg.value.proxy.host}'
: 'notSet'.tr,
(Key key) {
final proxy = downloaderCfg.value.proxy;
final switcher = Switch(
value: proxy.enable,
onChanged: (bool value) async {
if (value != proxy.enable) {
downloaderCfg.update((val) {
val!.proxy.enable = value;
});
await debounceSave();
}
},
);
final scheme = SizedBox(
width: 100,
child: DropdownButtonFormField<String>(
value: proxy.scheme,
onChanged: (value) async {
if (value != null && value != proxy.scheme) {
proxy.scheme = value;
await debounceSave();
}
},
items: const [
DropdownMenuItem<String>(
value: 'http',
child: Text('HTTP'),
),
DropdownMenuItem<String>(
value: 'https',
child: Text('HTTPS'),
),
DropdownMenuItem<String>(
value: 'socks5',
child: Text('SOCKS5'),
),
],
),
);
final arr = proxy.host.split(':');
var host = '';
var port = '';
if (arr.length > 1) {
host = arr[0];
port = arr[1];
}
final ipController = TextEditingController(text: host);
final portController = TextEditingController(text: port);
updateAddress() async {
final newAddress = '${ipController.text}:${portController.text}';
if (newAddress != startCfg.value.address) {
proxy.host = newAddress;
await debounceSave();
}
}
ipController.addListener(updateAddress);
portController.addListener(updateAddress);
final server = [
Flexible(
child: TextFormField(
controller: ipController,
decoration: InputDecoration(
labelText: 'server'.tr,
contentPadding: const EdgeInsets.all(0.0),
),
),
),
const Padding(padding: EdgeInsets.only(left: 10)),
Flexible(
child: TextFormField(
controller: portController,
decoration: InputDecoration(
labelText: 'port'.tr,
contentPadding: const EdgeInsets.all(0.0),
),
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
NumericalRangeFormatter(min: 0, max: 65535),
],
),
),
];
final usrController = TextEditingController(text: proxy.usr);
final pwdController = TextEditingController(text: proxy.pwd);
final auth = [
Flexible(
child: TextFormField(
controller: usrController,
decoration: InputDecoration(
labelText: 'username'.tr,
contentPadding: const EdgeInsets.all(0.0),
),
),
),
const Padding(padding: EdgeInsets.only(left: 10)),
Flexible(
child: TextFormField(
controller: pwdController,
decoration: InputDecoration(
labelText: 'password'.tr,
contentPadding: const EdgeInsets.all(0.0),
),
),
),
];
return Form(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: _addPadding([
switcher,
scheme,
Row(
children: server,
),
Row(
children: auth,
),
]),
),
);
},
);
// advanced config API items start
final buildApiProtocol = _buildConfigItem( final buildApiProtocol = _buildConfigItem(
'protocol', 'protocol',
() => startCfg.value.network == 'tcp' () => startCfg.value.network == 'tcp'
@@ -372,7 +527,7 @@ class SettingView extends GetView<SettingController> {
(Key key) { (Key key) {
final items = <Widget>[ final items = <Widget>[
SizedBox( SizedBox(
width: 150, width: 80,
child: DropdownButtonFormField<String>( child: DropdownButtonFormField<String>(
value: startCfg.value.network, value: startCfg.value.network,
onChanged: Util.isDesktop() onChanged: Util.isDesktop()
@@ -423,8 +578,7 @@ class SettingView extends GetView<SettingController> {
portController.addListener(updateAddress); portController.addListener(updateAddress);
items.addAll([ items.addAll([
const Padding(padding: EdgeInsets.only(left: 20)), const Padding(padding: EdgeInsets.only(left: 20)),
SizedBox( Flexible(
width: 200,
child: TextFormField( child: TextFormField(
controller: ipController, controller: ipController,
decoration: const InputDecoration( decoration: const InputDecoration(
@@ -438,8 +592,7 @@ class SettingView extends GetView<SettingController> {
), ),
), ),
const Padding(padding: EdgeInsets.only(left: 10)), const Padding(padding: EdgeInsets.only(left: 10)),
SizedBox( Flexible(
width: 200,
child: TextFormField( child: TextFormField(
controller: portController, controller: portController,
decoration: InputDecoration( decoration: InputDecoration(
@@ -548,26 +701,48 @@ class SettingView extends GetView<SettingController> {
children: _addDivider([ children: _addDivider([
buildHomepage(), buildHomepage(),
buildVersion(), buildVersion(),
buildThanks(),
]), ]),
)), )),
]), ]),
), ),
), ),
Column( // Column(
children: [ // children: [
// Card(
// child: Column(
// children: [
// ..._addDivider([
// buildApiProtocol(),
// Util.isDesktop() && startCfg.value.network == 'tcp'
// ? buildApiToken()
// : null,
// ]),
// ],
// )),
// ],
// ),
SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: _addPadding([
Text('network'.tr),
Card( Card(
child: Column( child: Column(
children: [ children: _addDivider([buildProxy()]),
..._addDivider([
buildApiProtocol(),
Util.isDesktop() && startCfg.value.network == 'tcp'
? buildApiToken()
: null,
]),
],
)), )),
], const Text('API'),
), Card(
child: Column(
children: _addDivider([
buildApiProtocol(),
Util.isDesktop() && startCfg.value.network == 'tcp'
? buildApiToken()
: null,
]),
)),
]),
))
], ],
).paddingOnly(left: 16, right: 16, top: 16, bottom: 16)), ).paddingOnly(left: 16, right: 16, top: 16, bottom: 16)),
), ),
@@ -3,5 +3,6 @@ import 'package:gopeed/app/modules/task/controllers/task_list_controller.dart';
import '../../../../api/model/task.dart'; import '../../../../api/model/task.dart';
class TaskDownloadedController extends TaskListController { class TaskDownloadedController extends TaskListController {
TaskDownloadedController() : super([Status.done], SortDirection.asc); TaskDownloadedController()
: super([Status.done], (a, b) => b.updatedAt.compareTo(a.updatedAt));
} }
@@ -9,5 +9,5 @@ class TaskDownloadingController extends TaskListController {
Status.pause, Status.pause,
Status.wait, Status.wait,
Status.error Status.error
], SortDirection.desc); ], (a, b) => b.createdAt.compareTo(a.createdAt));
} }
@@ -5,13 +5,11 @@ import 'package:get/get.dart';
import '../../../../api/api.dart'; import '../../../../api/api.dart';
import '../../../../api/model/task.dart'; import '../../../../api/model/task.dart';
enum SortDirection { asc, desc }
abstract class TaskListController extends GetxController { abstract class TaskListController extends GetxController {
List<Status> statuses; List<Status> statuses;
SortDirection sortDirection; int Function(Task a, Task b) compare;
TaskListController(this.statuses, this.sortDirection); TaskListController(this.statuses, this.compare);
final tasks = <Task>[].obs; final tasks = <Task>[].obs;
final isRunning = false.obs; final isRunning = false.obs;
@@ -48,13 +46,7 @@ abstract class TaskListController extends GetxController {
getTasksState() async { getTasksState() async {
final tasks = await getTasks(statuses); final tasks = await getTasks(statuses);
// sort tasks by create time // sort tasks by create time
tasks.sort((a, b) { tasks.sort(compare);
if (sortDirection == SortDirection.asc) {
return a.createdAt.compareTo(b.createdAt);
} else {
return b.createdAt.compareTo(a.createdAt);
}
});
this.tasks.value = tasks; this.tasks.value = tasks;
} }
} }
@@ -1,6 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:open_file/open_file.dart'; import 'package:open_filex/open_filex.dart';
import 'package:path/path.dart'; import 'package:path/path.dart';
import 'package:share_plus/share_plus.dart'; import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher.dart'; import 'package:url_launcher/url_launcher.dart';
@@ -57,8 +57,9 @@ class TaskFilesView extends GetView<TaskFilesController> {
final meta = controller.task.value!.meta; final meta = controller.task.value!.meta;
final file = fileList[index]; final file = fileList[index];
// if resource is single file, use opts.name as file name // if resource is single file, use opts.name as file name
final realFileName = final realFileName = meta.res!.name.isEmpty
meta.res!.name.isEmpty ? file.name : ""; ? (meta.opts.name.isEmpty ? file.name : meta.opts.name)
: "";
final fileRelativePath = file.filePath(realFileName); final fileRelativePath = file.filePath(realFileName);
final filePath = Util.safePathJoin( final filePath = Util.safePathJoin(
[meta.opts.path, meta.res!.name, fileRelativePath]); [meta.opts.path, meta.res!.name, fileRelativePath]);
@@ -66,7 +67,7 @@ class TaskFilesView extends GetView<TaskFilesController> {
return ListTile( return ListTile(
leading: file.isDirectory leading: file.isDirectory
? const Icon(Icons.folder) ? const Icon(Icons.folder)
: Icon(FaIcons.allIcons[findIcon(file.name)]), : Icon(FaIcons.allIcons[findIcon(fileName)]),
title: Text(fileName), title: Text(fileName),
subtitle: file.isDirectory subtitle: file.isDirectory
? Text('items'.trParams({ ? Text('items'.trParams({
@@ -104,8 +105,13 @@ class TaskFilesView extends GetView<TaskFilesController> {
: [ : [
IconButton( IconButton(
icon: const Icon(Icons.play_circle), icon: const Icon(Icons.play_circle),
onPressed: () { onPressed: () async {
OpenFile.open(filePath); print(filePath);
try {
await OpenFilex.open(filePath);
} catch (e) {
print(e);
}
}), }),
IconButton( IconButton(
icon: const Icon(Icons.share), icon: const Icon(Icons.share),
@@ -205,9 +205,11 @@ class BuildTaskListView extends GetView {
)), )),
], ],
), ),
LinearProgressIndicator( isDone()
value: getProgress(), ? Container()
), : LinearProgressIndicator(
value: getProgress(),
),
], ],
), ),
)).padding(horizontal: 14, top: 8); )).padding(horizontal: 14, top: 8);
@@ -35,7 +35,7 @@ class _DirectorySelectorState extends State<DirectorySelector> {
return v!.trim().isNotEmpty ? null : 'downloadDirValid'.tr; return v!.trim().isNotEmpty ? null : 'downloadDirValid'.tr;
}, },
)), )),
!Util.isWeb() && !Util.isIOS() !Util.isWeb() && !Util.isAndroid() && !Util.isIOS()
? IconButton( ? IconButton(
icon: const Icon(Icons.folder_open), icon: const Icon(Icons.folder_open),
onPressed: () async { onPressed: () async {
-524
View File
@@ -1,524 +0,0 @@
// DO NOT EDIT. This is code generated via package:get_cli/get_cli.dart
// ignore_for_file: lines_longer_than_80_chars
// ignore: avoid_classes_with_only_static_members
class AppTranslation {
static Map<String, Map<String, String>> translations = {
'en_US': Locales.en_US,
'fa_IR': Locales.fa_IR,
'ja_JP': Locales.ja_JP,
'ru_RU': Locales.ru_RU,
'zh_CN': Locales.zh_CN,
'zh_TW': Locales.zh_TW,
};
}
class LocaleKeys {
LocaleKeys._();
static const label = 'label';
static const error = 'error';
static const tip = 'tip';
static const confirm = 'confirm';
static const cancel = 'cancel';
static const selectAll = 'selectAll';
static const task = 'task';
static const downloading = 'downloading';
static const downloaded = 'downloaded';
static const setting = 'setting';
static const donate = 'donate';
static const exit = 'exit';
static const create = 'create';
static const directDownload = 'directDownload';
static const advancedOptions = 'advancedOptions';
static const downloadLink = 'downloadLink';
static const downloadLinkValid = 'downloadLinkValid';
static const downloadLinkHit = 'downloadLinkHit';
static const downloadLinkHitDesktop = 'downloadLinkHitDesktop';
static const download = 'download';
static const noFileSelected = 'noFileSelected';
static const noStoragePermission = 'noStoragePermission';
static const selectFile = 'selectFile';
static const rename = 'rename';
static const basic = 'basic';
static const advanced = 'advanced';
static const general = 'general';
static const downloadDir = 'downloadDir';
static const downloadDirValid = 'downloadDirValid';
static const connections = 'connections';
static const maxRunning = 'maxRunning';
static const items = 'items';
static const subscribeTracker = 'subscribeTracker';
static const subscribeFail = 'subscribeFail';
static const update = 'update';
static const updateDaily = 'updateDaily';
static const lastUpdate = 'lastUpdate';
static const addTracker = 'addTracker';
static const addTrackerHit = 'addTrackerHit';
static const ui = 'ui';
static const theme = 'theme';
static const themeSystem = 'themeSystem';
static const themeLight = 'themeLight';
static const themeDark = 'themeDark';
static const locale = 'locale';
static const about = 'about';
static const homepage = 'homepage';
static const version = 'version';
static const protocol = 'protocol';
static const port = 'port';
static const apiToken = 'apiToken';
static const notSet = 'notSet';
static const set = 'set';
static const effectAfterRestart = 'effectAfterRestart';
static const startAll = 'startAll';
static const pauseAll = 'pauseAll';
static const deleteTask = 'deleteTask';
static const deleteTaskTip = 'deleteTaskTip';
static const delete = 'delete';
static const newVersionTitle = 'newVersionTitle';
static const newVersionUpdate = 'newVersionUpdate';
static const newVersionLater = 'newVersionLater';
static const extensions = 'extensions';
static const extensionInstallUrl = 'extensionInstallUrl';
static const extensionInstallSuccess = 'extensionInstallSuccess';
static const extensionUpdateSuccess = 'extensionUpdateSuccess';
static const extensionDelete = 'extensionDelete';
static const extensionAlreadyLatest = 'extensionAlreadyLatest';
static const extensionFind = 'extensionFind';
static const extensionDevelop = 'extensionDevelop';
static const history = 'history';
static const clearHistory = 'clearHistory';
static const noHistoryFound = 'noHistoryFound';
static const serviceTitle = 'serviceTitle';
static const serviceText = 'serviceText';
}
class Locales {
static const en_US = {
'label': 'English',
'error': 'Error',
'tip': 'Tip',
'confirm': 'Confirm',
'cancel': 'Cancel',
'selectAll': 'Select All',
'task': 'Tasks',
'downloading': 'downloading',
'downloaded': 'downloaded',
'setting': 'Settings',
'donate': 'Donate',
'exit': 'Exit',
'create': 'Create Task',
'directDownload': 'Direct Download',
'advancedOptions': 'Advanced Options',
'downloadLink': 'Download Link',
'downloadLinkValid': 'Please enter the download link',
'downloadLinkHit':
'Please enter the download link, HTTP/HTTPS/MAGNET supported@append',
'downloadLinkHitDesktop': ', or drag the torrent file here directly',
'download': 'Download',
'noFileSelected': 'Please select at least one file to continue.',
'noStoragePermission': 'Storage permission required',
'selectFile': 'Select File',
'rename': 'Rename',
'basic': 'Basic',
'advanced': 'Advanced',
'general': 'General',
'downloadDir': 'Download Directory',
'downloadDirValid': 'Please select the download directory',
'connections': 'Connections',
'maxRunning': 'Max Running Tasks',
'items': '@count items',
'subscribeTracker': 'Subscribe Tracker',
'subscribeFail':
'Subscribe failed, please check network or try again later',
'update': 'Update',
'updateDaily': 'Update daily',
'lastUpdate': 'Last update: @time',
'addTracker': 'Add Tracker',
'addTrackerHit': 'Please enter the tracker server url, one per line',
'ui': 'UI',
'theme': 'Theme',
'themeSystem': 'System',
'themeLight': 'Light',
'themeDark': 'Dark',
'locale': 'Language',
'about': 'About',
'homepage': 'Homepage',
'version': 'Version',
'protocol': 'Protocol',
'port': 'Port',
'apiToken': 'API Token',
'notSet': 'NS',
'set': 'SET',
'effectAfterRestart': 'Effect after restart',
'startAll': 'Start All',
'pauseAll': 'Pause All',
'deleteTask': 'Delete Task',
'deleteTaskTip': 'Keep downloaded files',
'delete': 'Delete',
'newVersionTitle': 'Discover new version @version',
'newVersionUpdate': 'Update Now',
'newVersionLater': 'Later',
'extensions': 'Extensions',
'extensionInstallUrl': 'Install URL',
'extensionInstallSuccess': 'Installed successfully',
'extensionUpdateSuccess': 'Updated successfully',
'extensionDelete': 'Delete Extension',
'extensionAlreadyLatest': 'It\'s already the latest version',
'extensionFind': 'Find Extensions',
'extensionDevelop': 'Develop Extensions',
'history': 'History',
'clearHistory': 'Clear History',
'noHistoryFound': 'No History Found',
'serviceTitle': 'Download Service',
'serviceText': 'Running',
};
static const fa_IR = {
'label': 'فارسی',
'error': 'اررور',
'tip': 'Tip',
'confirm': 'تایید',
'cancel': 'انصراف',
'selectAll': 'انتخاب همه',
'task': 'کار',
'setting': 'تنظیمات',
'donate': 'کمک مالی',
'exit': 'خروج',
'create': 'ایجاد کار',
'downloading': 'دانلود کردن',
'downloaded': 'دانلود شدن',
'downloadLink': 'لینک دانلود',
'downloadLinkValid': 'لطفا لینک دانلود را وارد کنید',
'download': 'دانلود',
'noFileSelected': 'لطفا حداقل یک فایل را جهت دانلود انتخاب کنید.',
'noStoragePermission': 'مجوز ذخیره سازی مورد نیاز است',
'selectFile': 'انتخاب فایل',
'basic': 'پایه',
'advanced': 'پیشرفته',
'general': 'عمومی',
'downloadDir': 'دایرکتوری دانلود',
'downloadDirValid': 'لطفا دایرکتوری دانلود را انتخاب کنید',
'connections': 'اتصالات',
'items': '@count آیتم ها',
'subscribeTracker': 'Subscribe Tracker',
'subscribeFail':
'Subscribe failed, please check network or try again later',
'update': 'بروزرسانی',
'updateDaily': 'بروزرسانی روزانه',
'lastUpdate': 'Last update: @time',
'addTracker': 'Add Tracker',
'addTrackerHit': 'Please enter the tracker server url, one per line',
'ui': 'رابط کاربری',
'theme': 'پوسته',
'themeSystem': 'سیستم',
'themeLight': 'روشن',
'themeDark': 'تاریک',
'locale': 'Language',
'about': 'درباره ی',
'homepage': 'صفحه اصلی',
'version': 'نسخه',
'protocol': 'پروتکل',
'port': 'پورت',
'apiToken': 'API توکن',
'notSet': 'NS',
'set': 'SET',
'effectAfterRestart': 'Effect after restart',
'startAll': 'شروع همه',
'pauseAll': 'توقف همه',
'deleteTask': 'پاک کردن کار',
'deleteTaskTip': 'فایل های دانلود شده را نگه دارد',
'delete': 'پاک کردن',
'newVersionTitle': '@version عنوان: کشف نسخه جدید',
'newVersionUpdate': 'بروزرسانی',
'newVersionLater': 'بعداً',
};
static const ja_JP = {
'label': '日本語',
'error': 'エラー',
'tip': 'ヒント',
'confirm': '確認',
'cancel': 'キャンセル',
'selectAll': 'すべてを選択',
'task': 'タスク',
'downloading': 'ダウンロード中',
'downloaded': 'ダウンロード済',
'setting': 'セッティング',
'donate': '寄付する',
'exit': '終了',
'create': 'タスクを作成',
'downloadLink': 'ダウンロードリンク',
'downloadLinkValid': 'ダウンロードリンクを入力してください',
'downloadLinkHit': 'ダウンロード リンクを入力してください、HTTP/HTTPS/MAGNET support@append',
'downloadLinkHitDesktop': 'または、torrent ファイルを直接ここにドラッグします',
'download': 'ダウンロード',
'noFileSelected': '続行するには少なくとも 1 つのファイルを選択してください。',
'noStoragePermission': 'ストレージのパーミッションが必要',
'selectFile': 'ファイルを選択',
'basic': 'ベーシック',
'advanced': 'アドバンスド',
'general': 'ジェネラル',
'downloadDir': 'ディレクトリのダウンロード',
'downloadDirValid': 'ダウンロードディレクトリを選択してください',
'connections': '接続',
'maxRunning': '最大実行タスク',
'items': '@count アイテム',
'subscribeTracker': 'トラッカーを購読',
'subscribeFail': '登録に失敗しました。ネットワークを確認するか、後でもう一度お試しください',
'update': 'アップデート',
'updateDaily': '毎日アップデート',
'lastUpdate': '最終アップデート: @time',
'addTracker': 'トラッカーを追加',
'addTrackerHit': 'トラッカーサーバーの URL を 1 行に 1 つずつ入力してください',
'ui': 'UI',
'theme': 'テーマ',
'themeSystem': 'システム',
'themeLight': 'ライト',
'themeDark': 'ダーク',
'locale': '言語',
'about': '概要',
'homepage': 'ホームページ',
'version': 'バージョン',
'protocol': 'プロトコル',
'port': 'ポート',
'apiToken': 'API トークン',
'notSet': '未設置',
'set': '設置',
'effectAfterRestart': '再起動後の効果',
'startAll': 'すべてを開始',
'pauseAll': 'すべてを一時停止',
'deleteTask': 'タスクを削除',
'deleteTaskTip': 'ダウンロードしたファイルを保持',
'delete': '削除',
'newVersionTitle': '新しいバージョン @version を発見する',
'newVersionUpdate': 'アップデート',
'newVersionLater': '後で',
};
static const ru_RU = {
'label': 'Русский(Россия)',
'error': 'Ошибка',
'tip': 'Подсказка',
'confirm': 'Подтвердить',
'cancel': 'Отмена',
'selectAll': 'Выбрать все',
'task': 'Задачи',
'downloading': 'Загрузка',
'downloaded': 'Загружено',
'setting': 'Настройки',
'donate': 'Пожертвовать',
'exit': 'Выход',
'create': 'Создать задачу',
'advancedOptions': 'Расширенные опции',
'downloadLink': 'Ссылка на скачивание',
'downloadLinkValid': 'Пожалуйста, введите ссылку для скачивания',
'downloadLinkHit':
'Пожалуйста, введите ссылку для скачивания, HTTP/HTTPS/MAGNET поддерживаются@append',
'downloadLinkHitDesktop': ', или перетащите сюда торрент-файл',
'download': 'Скачать',
'noFileSelected': 'Файл не выбран',
'noStoragePermission': 'Требуется доступ к хранилищу',
'selectFile': 'Выбрать файл',
'rename': 'Переименовать',
'basic': 'Основные параметры',
'advanced': 'Расширенные',
'general': 'Общие',
'downloadDir': 'Папка загрузки',
'downloadDirValid': 'Пожалуйста, выберите папку для загрузки',
'connections': 'Соединений',
'maxRunning': 'Максимальное количество активных задач',
'items': '@подсчет элементов',
'subscribeTracker': 'Подпись трекера',
'subscribeFail':
'Подписка не удалась, пожалуйста, проверьте сеть или повторите попытку позже',
'update': 'Обновить',
'updateDaily': 'Обновлять ежедневно',
'lastUpdate': 'Последнее обновление: @время',
'addTracker': 'Добавить трекер',
'addTrackerHit': 'Пожалуйста, введите url трекера, по одному в строке',
'ui': 'UI',
'theme': 'Тема',
'themeSystem': 'Системная',
'themeLight': 'Светлая',
'themeDark': 'Темная',
'locale': 'Язык',
'about': 'О приложении',
'homepage': 'Домашняя страница',
'version': 'Версия',
'protocol': 'Протокол',
'port': 'Порт',
'apiToken': 'API Токен',
'notSet': 'Не установлено',
'set': 'Установлено',
'effectAfterRestart': 'Эффект после перезагрузки',
'startAll': 'Запустить все',
'pauseAll': 'Приостановить все',
'deleteTask': 'Удалить задачу',
'deleteTaskTip': 'Сохранить загруженные файлы',
'delete': 'Удалить',
'newVersionTitle': 'Обнаружена новая версия @version',
'newVersionUpdate': 'Обновить',
'newVersionLater': 'позже',
'extensions': 'Расширения',
'extensionInstallSuccess': 'Установка завершена',
'extensionUpdateSuccess': 'Обновление завершено',
'extensionDelete': 'Удалить расширение',
'extensionAlreadyLatest': 'Это последняя версия',
'extensionFind': 'Найти расширения',
'extensionDevelop': 'Разработка расширений',
'history': 'История',
'clearHistory': 'Очистить историю',
'noHistoryFound': 'История не найдена',
};
static const zh_CN = {
'label': '中文(简体)',
'error': '错误',
'tip': '提示',
'confirm': '确认',
'cancel': '取消',
'selectAll': '全选',
'task': '任务',
'downloading': '下载中',
'downloaded': '已完成',
'setting': '设置',
'donate': '打赏',
'exit': '退出',
'create': '创建任务',
'directDownload': '直接下载',
'advancedOptions': '高级选项',
'downloadLink': '下载链接',
'downloadLinkValid': '请输入下载链接',
'downloadLinkHit': '请输入下载链接,支持 HTTP/HTTPS/MAGNET@append',
'downloadLinkHitDesktop': ',也可以直接拖拽种子文件到此处',
'download': '下载',
'noFileSelected': '请至少选择一个文件下载',
'noStoragePermission': '需要开启存储权限',
'selectFile': '选择文件',
'rename': '重命名',
'basic': '基础',
'advanced': '高级',
'general': '通用',
'downloadDir': '下载目录',
'downloadDirValid': '请选择下载目录',
'connections': '连接数',
'maxRunning': '最大下载数',
'items': '@count 项',
'subscribeTracker': '订阅 Tracker',
'subscribeFail': '订阅失败,请检查网络或稍后重试',
'update': '更新',
'updateDaily': '每天自动更新',
'lastUpdate': '上次更新:@time',
'addTracker': '添加 Tracker',
'addTrackerHit': '请输入 tracker 服务器地址,每行一条',
'ui': '界面',
'theme': '主题',
'themeSystem': '跟随系统',
'themeLight': '明亮主题',
'themeDark': '暗黑主题',
'locale': '语言',
'about': '关于',
'homepage': '主页',
'version': '版本',
'protocol': '通讯协议',
'port': '端口',
'apiToken': '接口令牌',
'notSet': '未设置',
'set': '已设置',
'effectAfterRestart': '此配置项将在重启应用后生效',
'startAll': '全部开始',
'pauseAll': '全部暂停',
'deleteTask': '删除任务',
'deleteTaskTip': '保留已下载的文件',
'delete': '删除',
'newVersionTitle': '发现新版本 @version',
'newVersionUpdate': '立即更新',
'newVersionLater': '稍后再说',
'extensions': '扩展',
'extensionInstallUrl': '安装链接',
'extensionInstallSuccess': '安装成功',
'extensionUpdateSuccess': '更新成功',
'extensionDelete': '删除扩展',
'extensionAlreadyLatest': '已经是最新版本',
'extensionFind': '获取扩展',
'extensionDevelop': '开发扩展',
'history': '历史记录',
'clearHistory': '清空历史记录',
'noHistoryFound': '暂无历史记录',
'serviceTitle': '下载服务',
'serviceText': '运行中',
};
static const zh_TW = {
'label': '中文 (繁體) ',
'error': '錯誤',
'tip': '提示',
'confirm': '確定',
'cancel': '取消',
'selectAll': '全選',
'task': '任務',
'downloading': '下載中',
'downloaded': '已完成',
'setting': '設定',
'donate': '斗內',
'exit': '離開',
'create': '新增任務',
'directDownload': '直接下載',
'advancedOptions': '進階選項',
'downloadLink': '下載鏈接',
'downloadLinkValid': '請輸入下載鏈接',
'downloadLinkHit': '請輸入下載鏈接,支援 HTTP/HTTPS/MAGNET@append',
'downloadLinkHitDesktop': ',也可以通過拖拽Torrent文件至此以新增任務',
'download': '下載',
'noFileSelected': '沒有選取的文件',
'noStoragePermission': '沒有存儲權限',
'selectFile': '選擇文件',
'rename': '重命名',
'basic': '基礎',
'advanced': '進階',
'general': '通用設定',
'downloadDir': '下載目録',
'downloadDirValid': '請選擇下載目録',
'connections': '同時連接數',
'maxRunning': '最大同時下載數',
'items': '@count 項',
'subscribeTracker': '已訂閲的追蹤者列表',
'subscribeFail': '訂閲失敗',
'update': '更新',
'updateDaily': '每天自動更新',
'lastUpdate': '上次更新時間: @time',
'addTracker': '增加新的追蹤者',
'addTrackerHit': '請輸入追蹤者服務器地址,每行一條',
'ui': '介面',
'theme': '佈景主題',
'themeSystem': '跟隨系統',
'themeLight': '亮色主題',
'themeDark': '深色主題',
'locale': '語言',
'about': '關於',
'homepage': '訪問主頁',
'version': '版本資訊',
'protocol': '端口設定',
'port': '端口',
'apiToken': '接口秘鑰',
'notSet': '未設定',
'set': '已設定',
'effectAfterRestart': '重啟後生效',
'startAll': '全部開始',
'pauseAll': '全部暫停',
'deleteTask': '刪除任務',
'deleteTaskTip': '保留已經下載的文件',
'delete': '刪除',
'newVersionTitle': '發現新版本 @version',
'newVersionUpdate': '立刻更新',
'newVersionLater': '稍後更新',
'extensions': '外掛程序',
'extensionInstallUrl': '安裝URL',
'extensionInstallSuccess': '安裝成功',
'extensionUpdateSuccess': '更新完成',
'extensionDelete': '解除安裝',
'extensionAlreadyLatest': '已是最新版本',
'extensionFind': '取得外掛',
'extensionDevelop': '開發外掛',
'history': '歷史記錄',
'clearHistory': '清空記錄',
'noHistoryFound': '還沒有記錄',
'serviceTitle': '下載服務',
'serviceText': '執行中',
};
}
+89
View File
@@ -0,0 +1,89 @@
const enUS = {
'en_US': {
'label': 'English',
'error': 'Error',
'tip': 'Tip',
'confirm': 'Confirm',
'cancel': 'Cancel',
'selectAll': 'Select All',
'task': 'Tasks',
'downloading': 'downloading',
'downloaded': 'downloaded',
'setting': 'Settings',
'donate': 'Donate',
'exit': 'Exit',
'create': 'Create Task',
'directDownload': 'Direct Download',
'advancedOptions': 'Advanced Options',
'downloadLink': 'Download Link',
'downloadLinkValid': 'Please enter the download link',
'downloadLinkHit':
'Please enter the download link, HTTP/HTTPS/MAGNET supported@append',
'downloadLinkHitDesktop': ', or drag the torrent file here directly',
'download': 'Download',
'noFileSelected': 'Please select at least one file to continue.',
'noStoragePermission': 'Storage permission required',
'selectFile': 'Select File',
'rename': 'Rename',
'basic': 'Basic',
'advanced': 'Advanced',
'general': 'General',
'downloadDir': 'Download Directory',
'downloadDirValid': 'Please select the download directory',
'connections': 'Connections',
'maxRunning': 'Max Running Tasks',
'items': '@count items',
'subscribeTracker': 'Subscribe Tracker',
'subscribeFail':
'Subscribe failed, please check network or try again later',
'update': 'Update',
'updateDaily': 'Update daily',
'lastUpdate': 'Last update: @time',
'addTracker': 'Add Tracker',
'addTrackerHit': 'Please enter the tracker server url, one per line',
'ui': 'UI',
'theme': 'Theme',
'themeSystem': 'System',
'themeLight': 'Light',
'themeDark': 'Dark',
'locale': 'Language',
'about': 'About',
'homepage': 'Homepage',
'version': 'Version',
'protocol': 'Protocol',
'port': 'Port',
'apiToken': 'API Token',
'notSet': 'NS',
'set': 'SET',
'effectAfterRestart': 'Effect after restart',
'startAll': 'Start All',
'pauseAll': 'Pause All',
'deleteTask': 'Delete Task',
'deleteTaskTip': 'Keep downloaded files',
'delete': 'Delete',
'newVersionTitle': 'Discover new version @version',
'newVersionUpdate': 'Update Now',
'newVersionLater': 'Later',
'extensions': 'Extensions',
'extensionInstallUrl': 'Install URL',
'extensionInstallSuccess': 'Installed successfully',
'extensionUpdateSuccess': 'Updated successfully',
'extensionDelete': 'Delete Extension',
'extensionAlreadyLatest': 'It\'s already the latest version',
'extensionFind': 'Find Extensions',
'extensionDevelop': 'Develop Extensions',
'history': 'History',
'clearHistory': 'Clear History',
'noHistoryFound': 'No History Found',
'serviceTitle': 'Download Service',
'serviceText': 'Running',
'network': 'Network',
'proxy': 'Proxy',
'server': 'Server',
'username': 'Username',
'password': 'Password',
'thanks': 'Thanks',
'thanksDesc':
'Thanks to all the contributors who have helped build and develop the Gopeed community!',
},
};
+64
View File
@@ -0,0 +1,64 @@
const faIR = {
"fa_IR": {
'label': 'فارسی',
'error': 'اررور',
'tip': 'Tip',
'confirm': 'تایید',
'cancel': 'انصراف',
'selectAll': 'انتخاب همه',
'task': 'کار',
'setting': 'تنظیمات',
'donate': 'کمک مالی',
'exit': 'خروج',
'create': 'ایجاد کار',
'downloading': 'دانلود کردن',
'downloaded': 'دانلود شدن',
'downloadLink': 'لینک دانلود',
'downloadLinkValid': 'لطفا لینک دانلود را وارد کنید',
'download': 'دانلود',
'noFileSelected': 'لطفا حداقل یک فایل را جهت دانلود انتخاب کنید.',
'noStoragePermission': 'مجوز ذخیره سازی مورد نیاز است',
'selectFile': 'انتخاب فایل',
'basic': 'پایه',
'advanced': 'پیشرفته',
'general': 'عمومی',
'downloadDir': 'دایرکتوری دانلود',
'downloadDirValid': 'لطفا دایرکتوری دانلود را انتخاب کنید',
'connections': 'اتصالات',
'items': '@count آیتم ها',
'subscribeTracker': 'Subscribe Tracker',
'subscribeFail':
'Subscribe failed, please check network or try again later',
'update': 'بروزرسانی',
'updateDaily': 'بروزرسانی روزانه',
'lastUpdate': 'Last update: @time',
'addTracker': 'Add Tracker',
'addTrackerHit': 'Please enter the tracker server url, one per line',
'ui': 'رابط کاربری',
'theme': 'پوسته',
'themeSystem': 'سیستم',
'themeLight': 'روشن',
'themeDark': 'تاریک',
'locale': 'Language',
'about': 'درباره ی',
'homepage': 'صفحه اصلی',
'version': 'نسخه',
'protocol': 'پروتکل',
'port': 'پورت',
'apiToken': 'API توکن',
'notSet': 'NS',
'set': 'SET',
'effectAfterRestart': 'Effect after restart',
'startAll': 'شروع همه',
'pauseAll': 'توقف همه',
'deleteTask': 'پاک کردن کار',
'deleteTaskTip': 'فایل های دانلود شده را نگه دارد',
'delete': 'پاک کردن',
'newVersionTitle': '@version عنوان: کشف نسخه جدید',
'newVersionUpdate': 'بروزرسانی',
'newVersionLater': 'بعداً',
'thanks': 'تشکر',
'thanksDesc':
'از تمامی افرادی که در ساخت و توسعه‌ی جامعه‌ی Gopeed مشارکت کرده‌اند، سپاسگزاری می‌کنیم!',
}
};
+65
View File
@@ -0,0 +1,65 @@
const jaJP = {
"ja_JP": {
'label': '日本語',
'error': 'エラー',
'tip': 'ヒント',
'confirm': '確認',
'cancel': 'キャンセル',
'selectAll': 'すべてを選択',
'task': 'タスク',
'downloading': 'ダウンロード中',
'downloaded': 'ダウンロード済',
'setting': 'セッティング',
'donate': '寄付する',
'exit': '終了',
'create': 'タスクを作成',
'downloadLink': 'ダウンロードリンク',
'downloadLinkValid': 'ダウンロードリンクを入力してください',
'downloadLinkHit': 'ダウンロード リンクを入力してください、HTTP/HTTPS/MAGNET support@append',
'downloadLinkHitDesktop': 'または、torrent ファイルを直接ここにドラッグします',
'download': 'ダウンロード',
'noFileSelected': '続行するには少なくとも 1 つのファイルを選択してください。',
'noStoragePermission': 'ストレージのパーミッションが必要',
'selectFile': 'ファイルを選択',
'basic': 'ベーシック',
'advanced': 'アドバンスド',
'general': 'ジェネラル',
'downloadDir': 'ディレクトリのダウンロード',
'downloadDirValid': 'ダウンロードディレクトリを選択してください',
'connections': '接続',
'maxRunning': '最大実行タスク',
'items': '@count アイテム',
'subscribeTracker': 'トラッカーを購読',
'subscribeFail': '登録に失敗しました。ネットワークを確認するか、後でもう一度お試しください',
'update': 'アップデート',
'updateDaily': '毎日アップデート',
'lastUpdate': '最終アップデート: @time',
'addTracker': 'トラッカーを追加',
'addTrackerHit': 'トラッカーサーバーの URL を 1 行に 1 つずつ入力してください',
'ui': 'UI',
'theme': 'テーマ',
'themeSystem': 'システム',
'themeLight': 'ライト',
'themeDark': 'ダーク',
'locale': '言語',
'about': '概要',
'homepage': 'ホームページ',
'version': 'バージョン',
'protocol': 'プロトコル',
'port': 'ポート',
'apiToken': 'API トークン',
'notSet': '未設置',
'set': '設置',
'effectAfterRestart': '再起動後の効果',
'startAll': 'すべてを開始',
'pauseAll': 'すべてを一時停止',
'deleteTask': 'タスクを削除',
'deleteTaskTip': 'ダウンロードしたファイルを保持',
'delete': '削除',
'newVersionTitle': '新しいバージョン @version を発見する',
'newVersionUpdate': 'アップデート',
'newVersionLater': '後で',
'thanks': '感謝',
'thanksDesc': 'Gopeedコミュニティの建設に協力してくださったすべての貢献者の方々に感謝します!',
}
};
+80
View File
@@ -0,0 +1,80 @@
const ruRU = {
'ru_RU': {
'label': 'Русский(Россия)',
'error': 'Ошибка',
'tip': 'Подсказка',
'confirm': 'Подтвердить',
'cancel': 'Отмена',
'selectAll': 'Выбрать все',
'task': 'Задачи',
'downloading': 'Загрузка',
'downloaded': 'Загружено',
'setting': 'Настройки',
'donate': 'Пожертвовать',
'exit': 'Выход',
'create': 'Создать задачу',
'advancedOptions': 'Расширенные опции',
'downloadLink': 'Ссылка на скачивание',
'downloadLinkValid': 'Пожалуйста, введите ссылку для скачивания',
'downloadLinkHit':
'Пожалуйста, введите ссылку для скачивания, HTTP/HTTPS/MAGNET поддерживаются@append',
'downloadLinkHitDesktop': ', или перетащите сюда торрент-файл',
'download': 'Скачать',
'noFileSelected': 'Файл не выбран',
'noStoragePermission': 'Требуется доступ к хранилищу',
'selectFile': 'Выбрать файл',
'rename': 'Переименовать',
'basic': 'Основные параметры',
'advanced': 'Расширенные',
'general': 'Общие',
'downloadDir': 'Папка загрузки',
'downloadDirValid': 'Пожалуйста, выберите папку для загрузки',
'connections': 'Соединений',
'maxRunning': 'Максимальное количество активных задач',
'items': '@подсчет элементов',
'subscribeTracker': 'Подпись трекера',
'subscribeFail':
'Подписка не удалась, пожалуйста, проверьте сеть или повторите попытку позже',
'update': 'Обновить',
'updateDaily': 'Обновлять ежедневно',
'lastUpdate': 'Последнее обновление: @время',
'addTracker': 'Добавить трекер',
'addTrackerHit': 'Пожалуйста, введите url трекера, по одному в строке',
'ui': 'UI',
'theme': 'Тема',
'themeSystem': 'Системная',
'themeLight': 'Светлая',
'themeDark': 'Темная',
'locale': 'Язык',
'about': 'О приложении',
'homepage': 'Домашняя страница',
'version': 'Версия',
'protocol': 'Протокол',
'port': 'Порт',
'apiToken': 'API Токен',
'notSet': 'Не установлено',
'set': 'Установлено',
'effectAfterRestart': 'Эффект после перезагрузки',
'startAll': 'Запустить все',
'pauseAll': 'Приостановить все',
'deleteTask': 'Удалить задачу',
'deleteTaskTip': 'Сохранить загруженные файлы',
'delete': 'Удалить',
'newVersionTitle': 'Обнаружена новая версия @version',
'newVersionUpdate': 'Обновить',
'newVersionLater': 'позже',
'extensions': 'Расширения',
'extensionInstallSuccess': 'Установка завершена',
'extensionUpdateSuccess': 'Обновление завершено',
'extensionDelete': 'Удалить расширение',
'extensionAlreadyLatest': 'Это последняя версия',
'extensionFind': 'Найти расширения',
'extensionDevelop': 'Разработка расширений',
'history': 'История',
'clearHistory': 'Очистить историю',
'noHistoryFound': 'История не найдена',
'thanks': 'Благодарности',
'thanksDesc':
'Благодарим всех участников за их вклад в строительство и развитие сообщества Gopeed!',
}
};
+86
View File
@@ -0,0 +1,86 @@
const zhCN = {
'zh_CN': {
'label': '中文(简体)',
'error': '错误',
'tip': '提示',
'confirm': '确认',
'cancel': '取消',
'selectAll': '全选',
'task': '任务',
'downloading': '下载中',
'downloaded': '已完成',
'setting': '设置',
'donate': '打赏',
'exit': '退出',
'create': '创建任务',
'directDownload': '直接下载',
'advancedOptions': '高级选项',
'downloadLink': '下载链接',
'downloadLinkValid': '请输入下载链接',
'downloadLinkHit': '请输入下载链接,支持 HTTP/HTTPS/MAGNET@append',
'downloadLinkHitDesktop': ',也可以直接拖拽种子文件到此处',
'download': '下载',
'noFileSelected': '请至少选择一个文件下载',
'noStoragePermission': '需要开启存储权限',
'selectFile': '选择文件',
'rename': '重命名',
'basic': '基础',
'advanced': '高级',
'general': '通用',
'downloadDir': '下载目录',
'downloadDirValid': '请选择下载目录',
'connections': '连接数',
'maxRunning': '最大下载数',
'items': '@count 项',
'subscribeTracker': '订阅 Tracker',
'subscribeFail': '订阅失败,请检查网络或稍后重试',
'update': '更新',
'updateDaily': '每天自动更新',
'lastUpdate': '上次更新:@time',
'addTracker': '添加 Tracker',
'addTrackerHit': '请输入 tracker 服务器地址,每行一条',
'ui': '界面',
'theme': '主题',
'themeSystem': '跟随系统',
'themeLight': '明亮主题',
'themeDark': '暗黑主题',
'locale': '语言',
'about': '关于',
'homepage': '主页',
'version': '版本',
'protocol': '通讯协议',
'port': '端口',
'apiToken': '接口令牌',
'notSet': '未设置',
'set': '已设置',
'effectAfterRestart': '此配置项将在重启应用后生效',
'startAll': '全部开始',
'pauseAll': '全部暂停',
'deleteTask': '删除任务',
'deleteTaskTip': '保留已下载的文件',
'delete': '删除',
'newVersionTitle': '发现新版本 @version',
'newVersionUpdate': '立即更新',
'newVersionLater': '稍后再说',
'extensions': '扩展',
'extensionInstallUrl': '安装链接',
'extensionInstallSuccess': '安装成功',
'extensionUpdateSuccess': '更新成功',
'extensionDelete': '删除扩展',
'extensionAlreadyLatest': '已经是最新版本',
'extensionFind': '获取扩展',
'extensionDevelop': '开发扩展',
'history': '历史记录',
'clearHistory': '清空历史记录',
'noHistoryFound': '暂无历史记录',
'serviceTitle': '下载服务',
'serviceText': '运行中',
'network': '网络',
'proxy': '代理',
'server': '服务器',
'username': '用户名',
'password': '密码',
'thanks': '鸣谢',
'thanksDesc': '感谢所有为 Gopeed 社区建设添砖加瓦的贡献者们!',
}
};
+86
View File
@@ -0,0 +1,86 @@
const zhTW = {
"zh_TW": {
'label': '中文 (繁體) ',
'error': '錯誤',
'tip': '提示',
'confirm': '確定',
'cancel': '取消',
'selectAll': '全選',
'task': '任務',
'downloading': '下載中',
'downloaded': '已完成',
'setting': '設定',
'donate': '斗內',
'exit': '離開',
'create': '新增任務',
'directDownload': '直接下載',
'advancedOptions': '進階選項',
'downloadLink': '下載鏈接',
'downloadLinkValid': '請輸入下載鏈接',
'downloadLinkHit': '請輸入下載鏈接,支援 HTTP/HTTPS/MAGNET@append',
'downloadLinkHitDesktop': ',也可以通過拖拽Torrent文件至此以新增任務',
'download': '下載',
'noFileSelected': '沒有選取的文件',
'noStoragePermission': '沒有存儲權限',
'selectFile': '選擇文件',
'rename': '重命名',
'basic': '一般',
'advanced': '進階',
'general': '通用設定',
'downloadDir': '下載目録',
'downloadDirValid': '請選擇下載目録',
'connections': '同時連接數',
'maxRunning': '最大同時下載數',
'items': '@count 項',
'subscribeTracker': '已訂閲的追蹤者列表',
'subscribeFail': '訂閲失敗',
'update': '更新',
'updateDaily': '每天自動更新',
'lastUpdate': '上次更新時間: @time',
'addTracker': '增加新的追蹤者',
'addTrackerHit': '請輸入追蹤者服務器地址,每行一條',
'ui': '介面',
'theme': '佈景主題',
'themeSystem': '跟隨系統',
'themeLight': '亮色主題',
'themeDark': '深色主題',
'locale': '語言',
'about': '關於',
'homepage': '訪問主頁',
'version': '版本資訊',
'protocol': '端口設定',
'port': '端口',
'apiToken': '接口秘鑰',
'notSet': '未設定',
'set': '已設定',
'effectAfterRestart': '重啟後生效',
'startAll': '全部開始',
'pauseAll': '全部暫停',
'deleteTask': '刪除任務',
'deleteTaskTip': '保留已經下載的文件',
'delete': '刪除',
'newVersionTitle': '現新版本 @version 已發佈',
'newVersionUpdate': '下載',
'newVersionLater': '取消',
'extensions': '擴充程序',
'extensionInstallUrl': '安裝URL',
'extensionInstallSuccess': '安裝成功',
'extensionUpdateSuccess': '更新完成',
'extensionDelete': '解除安裝',
'extensionAlreadyLatest': '已是最新版本',
'extensionFind': '取得擴充程序',
'extensionDevelop': '開發擴充程序',
'history': '歷史記錄',
'clearHistory': '清空記錄',
'noHistoryFound': '還沒有記錄',
'serviceTitle': '下載服務',
'serviceText': '執行中',
'network': '網路',
'proxy': '代理',
'server': '伺服器',
'username': '名稱',
'password': '密碼',
'thanks': '鳴謝',
'thanksDesc': '感謝所有為 Gopeed 社群建設添磚加瓦的貢獻者們!'
}
};
+23
View File
@@ -0,0 +1,23 @@
import 'package:get/get.dart';
import 'package:gopeed/i18n/langs/fa_ir.dart';
import 'package:gopeed/i18n/langs/ja_jp.dart';
import 'package:gopeed/i18n/langs/zh_tw.dart';
import 'langs/en_us.dart';
import 'langs/ru_ru.dart';
import 'langs/zh_cn.dart';
final messages = _Messages();
class _Messages extends Translations {
// just include available locales here
@override
Map<String, Map<String, String>> get keys => {
...zhCN,
...enUS,
...ruRU,
...zhTW,
...faIR,
...jaJP,
};
}
+15 -10
View File
@@ -7,12 +7,13 @@ import 'api/api.dart' as api;
import 'app/modules/app/controllers/app_controller.dart'; import 'app/modules/app/controllers/app_controller.dart';
import 'app/modules/app/views/app_view.dart'; import 'app/modules/app/views/app_view.dart';
import 'core/libgopeed_boot.dart'; import 'core/libgopeed_boot.dart';
import 'generated/locales.g.dart'; import 'i18n/message.dart';
import 'util/locale_manager.dart'; import 'util/locale_manager.dart';
import 'util/log_util.dart'; import 'util/log_util.dart';
import 'util/mac_secure_util.dart'; import 'util/mac_secure_util.dart';
import 'util/package_info.dart'; import 'util/package_info.dart';
import 'util/util.dart'; import 'util/util.dart';
import 'util/window_util.dart' as windows_util;
void main() async { void main() async {
await init(); await init();
@@ -25,15 +26,21 @@ Future<void> init() async {
WidgetsFlutterBinding.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized();
if (Util.isDesktop()) { if (Util.isDesktop()) {
await windowManager.ensureInitialized(); await windowManager.ensureInitialized();
const windowOptions = WindowOptions( final windowState = await windows_util.loadState();
size: Size(800, 600), final windowOptions = WindowOptions(
size: Size(windowState.width, windowState.height),
center: true, center: true,
skipTaskbar: false, skipTaskbar: false,
); );
windowManager.waitUntilReadyToShow(windowOptions, () async { await windowManager.waitUntilReadyToShow(windowOptions, () async {
await windowManager.show(); await windowManager.show();
await windowManager.focus(); await windowManager.focus();
await windowManager.setPreventClose(true); await windowManager.setPreventClose(true);
// windows_manager has a bug where when window to be maximized, it will be unmaximized immediately, so can't implement this feature currently.
// https://github.com/leanflutter/window_manager/issues/412
// if (windowState.isMaximized) {
// await windowManager.maximize();
// }
}); });
} }
@@ -72,12 +79,10 @@ Future<void> onStart() async {
// if is debug mode, check language message is complete,change debug locale to your comfortable language if you want // if is debug mode, check language message is complete,change debug locale to your comfortable language if you want
if (kDebugMode) { if (kDebugMode) {
final mainLang = getLocaleKey(debugLocale); final debugLang = getLocaleKey(debugLocale);
final fullMessages = AppTranslation.translations[mainLang]; final fullMessages = messages.keys[debugLang];
AppTranslation.translations.keys messages.keys.keys.where((e) => e != debugLang).forEach((lang) {
.where((e) => e != mainLang) final langMessages = messages.keys[lang];
.forEach((lang) {
final langMessages = AppTranslation.translations[lang];
if (langMessages == null) { if (langMessages == null) {
logger.w("missing language: $lang"); logger.w("missing language: $lang");
return; return;
+8
View File
@@ -143,4 +143,12 @@ class Util {
} }
return completer.future; return completer.future;
} }
static void Function() debounce(Function() fn, int ms) {
Timer? timer;
return () {
timer?.cancel();
timer = Timer(Duration(milliseconds: ms), fn);
};
}
} }
+39
View File
@@ -0,0 +1,39 @@
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
class WindowState {
late bool isMaximized;
late double width;
late double height;
WindowState(this.isMaximized, this.width, this.height);
}
const String _windowStateIsMaximized = "window.isMaximized";
const String _windowStateWidth = "window.width";
const String _windowStateHeight = "window.height";
/// Save window state to storage.
void saveState({bool? isMaximized, double? width, double? height}) async {
final prefs = await SharedPreferences.getInstance();
if (isMaximized != null) {
await prefs.setBool(_windowStateIsMaximized, isMaximized);
}
if (width != null) {
await prefs.setDouble(_windowStateWidth, width);
}
if (height != null) {
await prefs.setDouble(_windowStateHeight, height);
}
}
/// Load window state from storage.
Future<WindowState> loadState() async {
final prefs = await SharedPreferences.getInstance();
return WindowState(
prefs.getBool(_windowStateIsMaximized) ?? false,
prefs.getDouble(_windowStateWidth) ?? 800,
prefs.getDouble(_windowStateHeight) ?? 600,
);
}
@@ -11,4 +11,4 @@ Exec=gopeed
Icon=com.gopeed.Gopeed Icon=com.gopeed.Gopeed
Type=Application Type=Application
Categories=Utility;Internet Categories=Utility;Internet
Keywords=Bittorrent;Downloader; Keywords=Bittorrent;Downloader;
@@ -0,0 +1,17 @@
display_name: Gopeed
icon: assets/icon/icon.svg
keywords:
- Application
- DownloadManager
- Network
- Utility
generic_name: Download Manager
categories:
- Network
- Utility
startup_notify: true
@@ -0,0 +1,31 @@
display_name: Gopeed
package_name: gopeed
maintainer:
name: monkeyWie
email: [email protected]
co_authors:
- name: madoka773
email: [email protected]
priority: optional
section: x11
installed_size: 52360
essential: false
icon: assets/icon/icon.svg
dependencies:
- libappindicator3-1 | libayatana-appindicator3-1
- gir1.2-appindicator3-0.1 | gir1.2-ayatanaappindicator3-0.1
keywords:
- Application
- DownloadManager
- Network
- Utility
generic_name: Download Manager
categories:
- Network
- Utility
startup_notify: true
@@ -0,0 +1,24 @@
display_name: Gopeed
icon: assets/icon/icon.svg
summary: A modern download manager that supports all platforms. Built with Golang and Flutter.
group: Applications/Internet
vendor: monkeyWie
packager: madoka773
packagerEmail: [email protected]
license: GPL-3.0-or-later
url: https://github.com/GopeedLab/gopeed
description: A modern download manager that supports all platforms. Built with Golang and Flutter.
keywords:
- Application
- DownloadManager
- Network
- Utility
generic_name: Download Manager
categories:
- Network
- Utility
startup_notify: true
+17 -10
View File
@@ -477,6 +477,14 @@ packages:
url: "https://pub.flutter-io.cn" url: "https://pub.flutter-io.cn"
source: hosted source: hosted
version: "6.7.1" version: "6.7.1"
lecle_downloads_path_provider:
dependency: "direct main"
description:
name: lecle_downloads_path_provider
sha256: "111f6d6d21e18acddda515eba8fd445658aa14defcbd59513d6d1b02b9ed47a0"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.0.2+8"
lint: lint:
dependency: transitive dependency: transitive
description: description:
@@ -581,14 +589,14 @@ packages:
url: "https://pub.flutter-io.cn" url: "https://pub.flutter-io.cn"
source: hosted source: hosted
version: "1.0.4" version: "1.0.4"
open_file: open_filex:
dependency: "direct main" dependency: "direct main"
description: description:
name: open_file name: open_filex
sha256: a5a32d44acb7c899987d0999e1e3cbb0a0f1adebbf41ac813ec6d2d8faa0af20 sha256: a6c95237767c5647e68b71a476602fcf4f1bfc530c126265e53addae22ef5fc2
url: "https://pub.flutter-io.cn" url: "https://pub.flutter-io.cn"
source: hosted source: hosted
version: "3.3.2" version: "4.3.4"
package_config: package_config:
dependency: transitive dependency: transitive
description: description:
@@ -973,12 +981,11 @@ packages:
tray_manager: tray_manager:
dependency: "direct main" dependency: "direct main"
description: description:
path: "." name: tray_manager
ref: "fix/libayatana-set-icon-deprecation" sha256: "4ab709d70a4374af172f8c39e018db33a4271265549c6fc9d269a65e5f4b0225"
resolved-ref: "056da3fef20e75877e8d2a4ae73d93f51a0f77cc" url: "https://pub.flutter-io.cn"
url: "https://github.com/provokateurin/tray_manager.git" source: hosted
source: git version: "0.2.1"
version: "0.2.0"
typed_data: typed_data:
dependency: transitive dependency: transitive
description: description:
+4 -6
View File
@@ -15,7 +15,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at # Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.5.0+1 version: 1.5.3+1
environment: environment:
sdk: '>=3.0.0 <4.0.0' sdk: '>=3.0.0 <4.0.0'
@@ -56,16 +56,14 @@ dependencies:
app_links: ^3.4.2 app_links: ^3.4.2
uri_to_file: ^0.2.0 uri_to_file: ^0.2.0
window_manager: ^0.3.4 window_manager: ^0.3.4
tray_manager:
git:
url: https://github.com/provokateurin/tray_manager.git
ref: fix/libayatana-set-icon-deprecation
autoscale_tabbarview: ^1.0.2 autoscale_tabbarview: ^1.0.2
share_plus: ^7.1.0 share_plus: ^7.1.0
open_file: ^3.3.2
flutter_form_builder: ^9.1.1 flutter_form_builder: ^9.1.1
form_builder_validators: ^9.0.0 form_builder_validators: ^9.0.0
flutter_foreground_task: ^6.1.2 flutter_foreground_task: ^6.1.2
open_filex: ^4.3.4
tray_manager: ^0.2.1
lecle_downloads_path_provider: ^0.0.2+8
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:
sdk: flutter sdk: flutter