The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(android): 分享链接快捷下载与移动端适配
XiaoYouChR0d043758a7b5
diff --git a/android/Dockerfile b/android/Dockerfileindex fc5aaa34..a1bcc4ec 100644--- a/android/Dockerfile+++ b/android/Dockerfile@@ -89,6 +89,8 @@ RUN git clone --depth 1 -b develop "${P4A_GIT_URL}" /opt/p4a \&& grep -q 'super.onActivityResult' "$QTPA" && echo "[patch] qt PythonActivity super.onActivityResult OK" \&& sed -i '/public boolean onKeyDown(int keyCode, KeyEvent event) {/a\ if (keyCode == KeyEvent.KEYCODE_BACK) { moveTaskToBack(true); return true; }' "$QTPA" \&& grep -q 'moveTaskToBack' "$QTPA" && echo "[patch] qt PythonActivity 返回键退后台 OK" \+ && sed -i '/protected void onNewIntent(Intent intent) {/a\ setIntent(intent);' "$QTPA" \+ && grep -q 'setIntent(intent)' "$QTPA" && echo "[patch] qt PythonActivity onNewIntent setIntent(热启分享 getIntent 生效) OK" \&& QTSTR=/opt/p4a/pythonforandroid/bootstraps/qt/build/templates/strings.tmpl.xml \&& sed -i '/<item name="android:windowNoTitle">true<\/item>/a\ <item name="android:windowBackground">@drawable/gd3_splash</item>\n <item name="android:windowSplashScreenBackground">@color/gd3_splash_bg</item>' "$QTSTR" \&& sed -i '/<resources>/a\ <color name="gd3_splash_bg">#f3f3f3</color>' "$QTSTR" \@@ -150,12 +152,14 @@ COPY java/org/ghostdownloader/KeepAliveService.java /opt/p4a/pythonforandroid/boRUN QTMAN=/opt/p4a/pythonforandroid/bootstraps/qt/build/templates/AndroidManifest.tmpl.xml \&& sed -i '/<\/application>/i\ <service android:name="org.ghostdownloader.KeepAliveService" android:exported="false" android:foregroundServiceType="dataSync" />' "$QTMAN" \&& sed -i '0,/<\/activity>/{s## <meta-data android:name="android.app.background_running" android:value="true" />\n </activity>#}' "$QTMAN" \+ && sed -i '0,/<\/activity>/{s## <intent-filter>\n <action android:name="android.intent.action.SEND" />\n <category android:name="android.intent.category.DEFAULT" />\n <data android:mimeType="text/plain" />\n </intent-filter>\n </activity>#}' "$QTMAN" \&& sed -i 's/<application /<application android:requestLegacyExternalStorage="true" /' "$QTMAN" \&& grep -q 'KeepAliveService' "$QTMAN" \&& grep -q 'background_running' "$QTMAN" \&& grep -q 'requestLegacyExternalStorage' "$QTMAN" \+ && grep -q 'android.intent.action.SEND' "$QTMAN" \&& chown -R builder:builder /opt/p4a/pythonforandroid/bootstraps/common/build/src/main/java/org/ghostdownloader \- && echo "[patch] KeepAliveService + background_running + requestLegacyExternalStorage(Android10 legacy 存储) 注入 OK"+ && echo "[patch] KeepAliveService + background_running + requestLegacyExternalStorage + SEND intent-filter(分享入口) 注入 OK"# 隔离的新版 cmake 专供 wreq 的 btls-sys/BoringSSL(系统 cmake 3.25 在 NDK toolchain 下 FindThreads 会炸)RUN python3 -m venv /opt/cmake4 \diff --git a/android/build_apk.sh b/android/build_apk.shindex 0ef6d992..047261c0 100644--- a/android/build_apk.sh+++ b/android/build_apk.sh@@ -27,7 +27,7 @@ BUILD_MARKER="$STAGE/.build_marker"touch "$BUILD_MARKER"export GD3_EXTRA_REQ="${GD3_EXTRA_REQ:-,pyjnius,wreq,charset-normalizer,idna,PySide6-Fluent-Widgets,PySideSix-Frameless-Window,darkdetect,loguru,qrcode,pypng,m3u8,mpegdash,aioftp,gd3ffmpeg}"-export GD3_EXTRA_PERM="${GD3_EXTRA_PERM:-,MANAGE_EXTERNAL_STORAGE,POST_NOTIFICATIONS,FOREGROUND_SERVICE,FOREGROUND_SERVICE_DATA_SYNC,REQUEST_IGNORE_BATTERY_OPTIMIZATIONS}"+export GD3_EXTRA_PERM="${GD3_EXTRA_PERM:-,MANAGE_EXTERNAL_STORAGE,POST_NOTIFICATIONS,FOREGROUND_SERVICE,FOREGROUND_SERVICE_DATA_SYNC,REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,WAKE_LOCK}"export GD3_ICON="${GD3_ICON:-$REPO/app/assets/logo.png}"diff --git a/android/main.py b/android/main.pyindex d11b0ee2..af20d09a 100644--- a/android/main.py+++ b/android/main.py@@ -80,6 +80,7 @@ def startApp(application):mainWindow = MobileMainWindow()mainWindow.show()setupTouchScrolling(mainWindow)+ signalBus.exceptionCaught.connect(mainWindow.alertException)requestNotificationPermission()requestIgnoreBatteryOptimizations()@@ -87,6 +88,8 @@ def startApp(application):taskService.taskCompleted.connect(notifyTaskCompleted)taskService.taskStarted.connect(lambda _: keepAlive.holdFor(REASON_DOWNLOAD))taskService.tasksAllCompleted.connect(lambda: keepAlive.release(REASON_DOWNLOAD))+ taskService.taskStarted.connect(lambda _: speedMeter.start())+ taskService.tasksAllCompleted.connect(speedMeter.stop)speedMeter.speedChanged.connect(keepAlive.setSpeed)def onBrowserTaskDraftRequested(tasks):diff --git a/app/platform/android.py b/app/platform/android.pyindex 82f76cd3..061a94fb 100644--- a/app/platform/android.py+++ b/app/platform/android.py@@ -1,3 +1,4 @@+import reimport sysfrom functools import lru_cache@@ -102,3 +103,34 @@ def openFolder(folder) -> None:if not IS_ANDROID:return_launchView(str(folder), "vnd.android.document/directory")+++def toTaskUrls(text: str) -> list[str]:+ matches = re.findall(r'(?i)(?:https?|ftp)://[^\s"\'<>,。!?、;:)》】」]+', text)+ return [url.rstrip(".,!?;:)]}>") for url in matches]+++def sharedText() -> str | None:+ if not IS_ANDROID:+ return None+ from jnius import autoclass+ Intent = autoclass("android.content.Intent")+ activity = autoclass("org.kivy.android.PythonActivity").mActivity+ intent = activity.getIntent()+ if intent is None or intent.getAction() != Intent.ACTION_SEND:+ return None+ text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT) # 用 CharSequence 版: getStringExtra 对带样式文本返回 null+ if text is None:+ return ""+ return text if isinstance(text, str) else text.toString() # pyjnius 把 String 转 str, 带样式 CharSequence 才是包装对象+++def clearShare() -> None:+ if not IS_ANDROID:+ return+ from jnius import autoclass+ Intent = autoclass("android.content.Intent")+ activity = autoclass("org.kivy.android.PythonActivity").mActivity+ intent = activity.getIntent()+ if intent is not None:+ intent.setAction(Intent.ACTION_MAIN) # 分享已取走, 防回前台重复添加同一分享diff --git a/app/view/mobile/device.py b/app/view/mobile/device.pyindex 28ac31c4..f616e08a 100644--- a/app/view/mobile/device.py+++ b/app/view/mobile/device.py@@ -3,10 +3,12 @@ def setupAccentColor() -> None:from PySide6.QtWidgets import QApplicationfrom qfluentwidgets import setThemeColor+ from app.config.cfg import cfg+palette = QApplication.palette()for role in (QPalette.ColorRole.Accent, QPalette.ColorRole.Highlight):color = palette.color(role)- if color.isValid():+ if color.isValid() and cfg.themeColor.value != color:setThemeColor(color, save=False)returndiff --git a/app/view/mobile/setting_page.py b/app/view/mobile/setting_page.pyindex 18e043ac..0fd8dd02 100644--- a/app/view/mobile/setting_page.py+++ b/app/view/mobile/setting_page.py@@ -1,6 +1,6 @@from PySide6.QtCore import Qtfrom PySide6.QtGui import QColor, QPalette-from PySide6.QtWidgets import QHBoxLayout, QVBoxLayout, QWidget+from PySide6.QtWidgets import QHBoxLayout, QSizePolicy, QVBoxLayout, QWidgetfrom qfluentwidgets import SettingCard, SwitchButton, isDarkTheme, qconfigfrom app.view.components.setting_card_group import CollapsibleSettingCardGroup@@ -68,9 +68,18 @@ class MobileSettingPage(SettingPage):controlRow = QHBoxLayout()controlRow.setContentsMargins(32, 0, 0, 0)controlRow.setSpacing(8)+ # 桌面控件(滑块 268 / 下拉 200 / 选择框 180 / 商店按钮 等)自带硬最小宽, 窄屏会把整页撑出屏外。+ # 让行内最宽的主控件填满并可收缩到 0, 辅助控件(数值标签 / 图标按钮)保持原宽, 整页便不再被撑宽。+ primary = max(controls, key=lambda w: w.sizeHint().width())for widget in controls:- controlRow.addWidget(widget)- controlRow.addStretch(1)+ widget.setMinimumWidth(0)+ if widget is primary:+ policy = widget.sizePolicy()+ policy.setHorizontalPolicy(QSizePolicy.Policy.Ignored) # 仅放开水平轴, 使其填满行宽并可收缩+ widget.setSizePolicy(policy)+ controlRow.addWidget(widget, 1)+ else:+ controlRow.addWidget(widget)outer.addLayout(controlRow)card.setMinimumHeight(0)diff --git a/app/view/mobile/task_page.py b/app/view/mobile/task_page.pyindex bc377c1d..a6b492b8 100644--- a/app/view/mobile/task_page.py+++ b/app/view/mobile/task_page.py@@ -39,7 +39,7 @@ class MobileTaskPage(TaskPage):def _initLayout(self) -> None:toolBarLayout = QHBoxLayout(self.toolBar)- toolBarLayout.setContentsMargins(10, 6, 10, 0)+ toolBarLayout.setContentsMargins(10, 4, 10, 0)toolBarLayout.setSpacing(6)toolBarLayout.addWidget(self.startAllButton)toolBarLayout.addWidget(self.pauseAllButton)@@ -49,7 +49,7 @@ class MobileTaskPage(TaskPage):toolBarLayout.addWidget(self.planButton)filterToolBarLayout = QHBoxLayout(self.filterToolBar)- filterToolBarLayout.setContentsMargins(10, 0, 10, 6)+ filterToolBarLayout.setContentsMargins(10, 0, 10, 4)filterToolBarLayout.setSpacing(6)filterToolBarLayout.addWidget(self.sortButton)filterToolBarLayout.addWidget(self.filterButton)@@ -58,7 +58,7 @@ class MobileTaskPage(TaskPage):layout = QVBoxLayout(self)layout.setContentsMargins(0, 0, 0, 0)- layout.setSpacing(0)+ layout.setSpacing(6)layout.addWidget(self.toolBar)layout.addWidget(self.filterToolBar)layout.addWidget(self.scrollArea)diff --git a/app/view/mobile/window.py b/app/view/mobile/window.pyindex 2ac7a92f..542702f0 100644--- a/app/view/mobile/window.py+++ b/app/view/mobile/window.py@@ -1,15 +1,15 @@from __future__ import annotations-from PySide6.QtCore import QSize, Qt+from PySide6.QtCore import QEvent, QSize, Qtfrom PySide6.QtGui import QColor, QIcon, QPainterfrom PySide6.QtWidgets import QApplication, QStackedWidget, QVBoxLayout, QWidgetfrom qfluentwidgets import (FluentIcon, InfoBar, InfoBarPosition, PrimaryToolButton,- Theme, isDarkTheme, qconfig, setTheme,+ Theme, isDarkTheme, qconfig,)from app.config.cfg import cfg-from app.platform.android import isStorageGranted, requestStoragePermission+from app.platform.android import clearShare, isStorageGranted, requestStoragePermission, sharedText, toTaskUrlsfrom app.services.task_draft import TaskDraftfrom app.services.task_service import taskServicefrom app.view.dialogs.task_draft import TaskDraftDialog@@ -19,6 +19,8 @@ from app.view.mobile.permission import PermissionBannerfrom app.view.mobile.setting_page import MobileSettingPagefrom app.view.mobile.task_page import MobileTaskPage+TASK_PAGE_INDEX = 0+class MobileMainWindow(QWidget):def __init__(self):@@ -35,6 +37,7 @@ class MobileMainWindow(QWidget):self._draft = TaskDraft(parent=self)self._draftDialog = TaskDraftDialog(self._draft, parent=self)+ self._shareDraft = TaskDraft(parent=self)self._initWidget()self._initLayout()@@ -67,8 +70,9 @@ class MobileMainWindow(QWidget):self.taskPage.selectionModeChanged.connect(lambda *_: self._updateAddButtonVisibility())self.addButton.clicked.connect(self._showAddTaskDialog)self._draft.taskConfirmed.connect(taskService.add)+ self._shareDraft.taskConfirmed.connect(taskService.add)QApplication.instance().applicationStateChanged.connect(self._onApplicationStateChanged)- cfg.themeMode.valueChanged.connect(self._onThemeModeChanged)+ cfg.themeChanged.connect(self._setTheme)QApplication.instance().styleHints().colorSchemeChanged.connect(self._onSystemColorSchemeChanged)qconfig.themeChanged.connect(self.update)@@ -76,22 +80,56 @@ class MobileMainWindow(QWidget):self.stackedWidget.addWidget(page)self.navigationBar.addItem(icon, text)- def _onThemeModeChanged(self, value):- setTheme(value if isinstance(value, Theme) else Theme.AUTO, save=False)-- def _onSystemColorSchemeChanged(self, _scheme):- if cfg.themeMode.value == Theme.AUTO:- setTheme(Theme.AUTO, save=False)+ def _onSystemColorSchemeChanged(self, colorScheme):+ if cfg.themeMode.value != Theme.AUTO:+ return+ if colorScheme == Qt.ColorScheme.Dark:+ self._setTheme(Theme.DARK)+ elif colorScheme == Qt.ColorScheme.Light:+ self._setTheme(Theme.LIGHT)+ else:+ self._setTheme(Theme.AUTO)++ def _setTheme(self, value):+ from qfluentwidgets.common.style_sheet import updateStyleSheet+ prevTheme = qconfig.theme+ qconfig.theme = value+ if qconfig.theme != prevTheme:+ qconfig.themeChanged.emit(qconfig.theme)+ updateStyleSheet()+ qconfig.themeChangedFinished.emit()++ def changeEvent(self, event):+ super().changeEvent(event)+ if event.type() == QEvent.Type.PaletteChange:+ setupAccentColor()def _onApplicationStateChanged(self, state: Qt.ApplicationState):if state == Qt.ApplicationState.ApplicationActive:self._updatePermissionBanner()+ self._addSharedTasks()++ def _addSharedTasks(self) -> None:+ text = sharedText()+ if text is None:+ return+ clearShare()+ urls = toTaskUrls(text)+ if not urls:+ return+ if cfg.shouldRaiseWindowOnBrowserTask.value or not isStorageGranted():+ self._draftDialog.addUrls(urls)+ self._draftDialog.showMask()+ return+ self.navigationBar.setCurrentIndex(TASK_PAGE_INDEX)+ self._shareDraft.setUrls(urls)+ self._shareDraft.confirm()def _updatePermissionBanner(self):self.permissionBanner.setVisible(not isStorageGranted())def _updateAddButtonVisibility(self):- onTaskPage = self.stackedWidget.currentIndex() == 0+ onTaskPage = self.stackedWidget.currentIndex() == TASK_PAGE_INDEXself.addButton.setVisible(onTaskPage and not self.taskPage.isSelectionMode)def _showAddTaskDialog(self):@@ -112,6 +150,39 @@ class MobileMainWindow(QWidget):returnself._draftDialog.showMask()+ def alertException(self, message: str) -> None:+ from PySide6.QtCore import QUrl+ from PySide6.QtGui import QDesktopServices+ from PySide6.QtWidgets import QHBoxLayout+ from qfluentwidgets import MessageBox, ToolTipFilter, TransparentToolButton++ from app.config.constants import FEEDBACK_URL+ from app.config.paths import APP_DATA_DIR+ from app.platform.android import openFile++ dialog = MessageBox(+ self.tr("程序发生异常"),+ self.tr('点击"确定"后将复制错误信息并打开反馈页面。\n\n{0}').format(message),+ self,+ )+ logButton = TransparentToolButton(FluentIcon.DOCUMENT, dialog)+ logButton.setToolTip(self.tr("查看日志"))+ logButton.installEventFilter(ToolTipFilter(logButton))+ logButton.clicked.connect(lambda: openFile(f"{APP_DATA_DIR}/GhostDownloader.log"))++ dialog.contentLabel.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)++ titleLayout = dialog.textLayout+ titleLayout.removeWidget(dialog.titleLabel)+ titleRow = QHBoxLayout()+ titleRow.addWidget(dialog.titleLabel, 1)+ titleRow.addWidget(logButton)+ titleLayout.insertLayout(0, titleRow)++ if dialog.exec():+ QApplication.clipboard().setText(message)+ QDesktopServices.openUrl(QUrl(FEEDBACK_URL))+def resizeEvent(self, event):super().resizeEvent(event)margin = 16