下载管理器

This commit is contained in:
xkeyC 2024-02-24 14:42:33 +08:00
parent 65ffd6a92f
commit e0ca3377ac
8 changed files with 363 additions and 31 deletions

View File

@ -251,4 +251,10 @@ foreach ($adapter in $adapterMemory) {
.padLeft(hexDigits, '0') .padLeft(hexDigits, '0')
.toUpperCase(); .toUpperCase();
} }
static Future openDir(path) async {
dPrint("SystemHelper.openDir path === $path");
await Process.run(
SystemHelper.powershellPath, ["explorer.exe", "/select,\"$path\""]);
}
} }

View File

@ -62,12 +62,13 @@ class Aria2cManager {
"--save-session=${sessionFile.absolute.path.trim()}", "--save-session=${sessionFile.absolute.path.trim()}",
"--save-session-interval=60", "--save-session-interval=60",
"--file-allocation=trunc", "--file-allocation=trunc",
// TODO for debug
"--max-overall-download-limit=100k"
], ],
workingDirectory: _aria2cDir, workingDirectory: _aria2cDir);
runInShell: false);
p.stdout.transform(utf8.decoder).listen((event) { p.stdout.transform(utf8.decoder).listen((event) {
if (event.trim().isEmpty) return; if (event.trim().isEmpty) return;
dPrint("[aria2c]: $event"); dPrint("[aria2c]: ${event.trim()}");
if (event.contains("IPv4 RPC: listening on TCP port")) { if (event.contains("IPv4 RPC: listening on TCP port")) {
_isDaemonRunning = true; _isDaemonRunning = true;
aria2c; aria2c;

View File

@ -0,0 +1,172 @@
import 'package:file_sizes/file_sizes.dart';
import 'package:intl/intl.dart';
import 'package:starcitizen_doctor/base/ui.dart';
import 'package:starcitizen_doctor/base/ui_model.dart';
import 'downloads_ui_model.dart';
class DownloadsUI extends BaseUI<DownloadsUIModel> {
final DateFormat formatter = DateFormat('yyyy-MM-dd HH:mm:ss');
@override
Widget? buildBody(BuildContext context, DownloadsUIModel model) {
return makeDefaultPage(context, model,
content: Column(
children: [
const SizedBox(height: 12),
Expanded(
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
final (task, type, isFirstType) = model.getTaskAndType(index);
final nt = model.getTaskTypeAndName(task);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (isFirstType)
Column(
children: [
Container(
padding: const EdgeInsets.only(
left: 24, right: 24, top: 12, bottom: 12),
margin: const EdgeInsets.only(top: 6, bottom: 6),
child: Row(
children: [
Expanded(
child: Text(
"${model.listHeaderStatusMap[type]}",
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold),
)),
],
),
),
],
),
Container(
padding: const EdgeInsets.only(
left: 12, right: 12, top: 12, bottom: 12),
margin: const EdgeInsets.only(
left: 12, right: 12, top: 6, bottom: 6),
decoration: BoxDecoration(
color:
FluentTheme.of(context).cardColor.withOpacity(.03),
borderRadius: BorderRadius.circular(7),
),
child: Row(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
nt.value,
style: const TextStyle(
fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 6),
Row(
children: [
Text(
"总大小:${FileSize.getSize(task.totalLength ?? 0)}",
style: const TextStyle(fontSize: 14),
),
const SizedBox(width: 12),
if (nt.key == "torrent" &&
task.verifiedLength != null &&
task.verifiedLength != 0)
Text(
"校验中...${FileSize.getSize(task.verifiedLength)}",
style: const TextStyle(fontSize: 14),
)
else if (task.status == "active")
Text(
"下载中... (${((task.completedLength ?? 0) / (task.totalLength ?? 1)).toStringAsFixed(4)}%)")
else
Text(
"状态:${model.statusMap[task.status]}",
style: const TextStyle(fontSize: 14),
),
const SizedBox(width: 24),
if (task.status == "active" &&
task.verifiedLength == null)
Text(
"ETA: ${formatter.format(DateTime.now().add(Duration(seconds: model.getETA(task))))}"),
],
),
],
),
const Spacer(),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"已上传:${FileSize.getSize(task.uploadLength)}"),
Text(
"已下载:${FileSize.getSize(task.completedLength)}"),
],
),
const SizedBox(width: 18),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("↑:${FileSize.getSize(task.uploadSpeed)}/s"),
Text(
"↓:${FileSize.getSize(task.downloadSpeed)}/s"),
],
),
const SizedBox(width: 32),
if (type != "stopped")
DropDownButton(
closeAfterClick: false,
title: const Padding(
padding: EdgeInsets.all(3),
child: Text('选项'),
),
items: [
if (task.status == "paused")
MenuFlyoutItem(
leading: const Icon(FluentIcons.download),
text: const Text('继续下载'),
onPressed: () =>
model.resumeTask(task.gid))
else if (task.status == "active")
MenuFlyoutItem(
leading: const Icon(FluentIcons.pause),
text: const Text('暂停下载'),
onPressed: () =>
model.pauseTask(task.gid)),
const MenuFlyoutSeparator(),
MenuFlyoutItem(
leading: const Icon(
FluentIcons.chrome_close,
size: 14,
),
text: const Text('取消下载'),
onPressed: () =>
model.cancelTask(task.gid)),
MenuFlyoutItem(
leading: const Icon(
FluentIcons.folder_open,
size: 14,
),
text: const Text('打开文件夹'),
onPressed: () =>
model.openFolder(task)),
],
),
const SizedBox(width: 12),
],
),
),
],
);
},
itemCount: model.getTasksLen(),
))
],
));
}
@override
String getUITitle(BuildContext context, DownloadsUIModel model) => "下载管理";
}

View File

@ -0,0 +1,138 @@
import 'dart:io';
import 'package:aria2/aria2.dart';
import 'package:starcitizen_doctor/base/ui_model.dart';
import 'package:starcitizen_doctor/common/helper/system_helper.dart';
import 'package:starcitizen_doctor/common/io/aria2c.dart';
class DownloadsUIModel extends BaseUIModel {
List<Aria2Task> tasks = [];
List<Aria2Task> waitingTasks = [];
List<Aria2Task> stoppedTasks = [];
final statusMap = {
"active": "下载中...",
"waiting": "等待中",
"paused": "已暂停",
"error": "下载失败",
"complete": "下载完成",
"removed": "已删除",
};
final listHeaderStatusMap = {
"active": "下载中",
"waiting": "等待中",
"stopped": "已结束",
};
@override
initModel() {
super.initModel();
_listenDownloader();
}
onTapButton(String key) {}
_listenDownloader() async {
try {
while (true) {
if (!mounted) return;
tasks.clear();
tasks = await Aria2cManager.aria2c.tellActive();
waitingTasks = await Aria2cManager.aria2c.tellWaiting(0, 1000000);
stoppedTasks = await Aria2cManager.aria2c.tellStopped(0, 1000000);
notifyListeners();
await Future.delayed(const Duration(seconds: 1));
}
} catch (e) {
dPrint("[DownloadsUIModel]._listenDownloader Error: $e");
}
}
int getTasksLen() {
return tasks.length + waitingTasks.length + stoppedTasks.length;
}
(Aria2Task, String, bool) getTaskAndType(int index) {
final tempList = <Aria2Task>[...tasks, ...waitingTasks, ...stoppedTasks];
if (index >= 0 && index < tasks.length) {
return (tempList[index], "active", index == 0);
}
if (index >= tasks.length && index < tasks.length + waitingTasks.length) {
return (tempList[index], "waiting", index == tasks.length);
}
if (index >= tasks.length + waitingTasks.length &&
index < tempList.length) {
return (
tempList[index],
"stopped",
index == tasks.length + waitingTasks.length
);
}
throw Exception("Index out of range or element is null");
}
MapEntry<String, String> getTaskTypeAndName(Aria2Task task) {
if (task.bittorrent == null) {
String uri = task.files?[0]['uris'][0]['uri'] as String;
return MapEntry("url", uri.split('/').last);
} else if (task.bittorrent != null) {
if (task.bittorrent!.containsKey('info')) {
var btName = task.bittorrent?["info"]["name"];
return MapEntry("torrent", btName ?? 'torrent');
} else {
return MapEntry("magnet", '[METADATA]${task.infoHash}');
}
} else {
return const MapEntry("metaLink", '==========metaLink============');
}
}
List<Aria2File> getFilesFormTask(Aria2Task task) {
List<Aria2File> l = [];
if (task.files != null) {
for (var element in task.files!) {
final f = Aria2File.fromJson(element);
l.add(f);
}
}
return l;
}
int getETA(Aria2Task task) {
if (task.downloadSpeed == null || task.downloadSpeed == 0) return 0;
final remainingBytes =
(task.totalLength ?? 0) - (task.completedLength ?? 0);
return remainingBytes ~/ (task.downloadSpeed!);
}
Future<void> resumeTask(String? gid) async {
if (gid != null) {
await Aria2cManager.aria2c.unpause(gid);
}
}
Future<void> pauseTask(String? gid) async {
if (gid != null) {
await Aria2cManager.aria2c.pause(gid);
}
}
Future<void> cancelTask(String? gid) async {
await Future.delayed(const Duration(milliseconds: 300));
if (gid != null) {
final ok = await showConfirmDialogs(
context!, "确认取消下载?", const Text("你可能需要手动删除下载文件。"));
if (ok == true) {
await Aria2cManager.aria2c.remove(gid);
}
}
}
openFolder(Aria2Task task) {
final f = getFilesFormTask(task).firstOrNull;
if (f != null) {
SystemHelper.openDir(File(f.path!).absolute.path.replaceAll("/", "\\"));
}
}
}

View File

@ -245,20 +245,15 @@ class GameDoctorUIModel extends BaseUIModel {
case "rsi_log": case "rsi_log":
final path = await SCLoggerHelper.getLogFilePath(); final path = await SCLoggerHelper.getLogFilePath();
if (path == null) return; if (path == null) return;
openDir(path); SystemHelper.openDir(path);
return; return;
case "game_log": case "game_log":
if (scInstalledPath == "not_install") { if (scInstalledPath == "not_install") {
showToast(context!, "请在首页选择游戏安装目录。"); showToast(context!, "请在首页选择游戏安装目录。");
return; return;
} }
openDir("$scInstalledPath\\Game.log"); SystemHelper.openDir("$scInstalledPath\\Game.log");
return; return;
} }
} }
openDir(path) async {
await Process.run(
SystemHelper.powershellPath, ["explorer.exe", "/select,\"$path\""]);
}
} }

View File

@ -7,6 +7,8 @@ import 'package:starcitizen_doctor/common/helper/system_helper.dart';
import 'package:starcitizen_doctor/common/io/aria2c.dart'; import 'package:starcitizen_doctor/common/io/aria2c.dart';
import 'package:starcitizen_doctor/global_ui_model.dart'; import 'package:starcitizen_doctor/global_ui_model.dart';
import 'package:starcitizen_doctor/ui/about/about_ui_model.dart'; import 'package:starcitizen_doctor/ui/about/about_ui_model.dart';
import 'package:starcitizen_doctor/ui/home/downloads/downloads_ui.dart';
import 'package:starcitizen_doctor/ui/home/downloads/downloads_ui_model.dart';
import 'package:starcitizen_doctor/ui/home/home_ui_model.dart'; import 'package:starcitizen_doctor/ui/home/home_ui_model.dart';
import 'package:starcitizen_doctor/ui/settings/settings_ui_model.dart'; import 'package:starcitizen_doctor/ui/settings/settings_ui_model.dart';
import 'package:starcitizen_doctor/ui/tools/tools_ui_model.dart'; import 'package:starcitizen_doctor/ui/tools/tools_ui_model.dart';
@ -98,8 +100,10 @@ class IndexUIModel extends BaseUIModel {
} }
} }
void goDownloader() { Future<void> goDownloader() async {
await BaseUIContainer(
uiCreate: () => DownloadsUI(),
modelCreate: () => DownloadsUIModel()).push(context!);
} }
void _listenAria2c() async { void _listenAria2c() async {

View File

@ -9,8 +9,12 @@ import 'package:starcitizen_doctor/common/conf/app_conf.dart';
import 'package:starcitizen_doctor/common/helper/log_helper.dart'; import 'package:starcitizen_doctor/common/helper/log_helper.dart';
import 'package:starcitizen_doctor/common/helper/system_helper.dart'; import 'package:starcitizen_doctor/common/helper/system_helper.dart';
import 'package:starcitizen_doctor/common/io/aria2c.dart'; import 'package:starcitizen_doctor/common/io/aria2c.dart';
import 'package:starcitizen_doctor/common/io/rs_http.dart';
import 'package:starcitizen_doctor/ui/home/downloads/downloads_ui.dart';
import 'package:xml/xml.dart'; import 'package:xml/xml.dart';
import '../home/downloads/downloads_ui_model.dart';
class ToolsUIModel extends BaseUIModel { class ToolsUIModel extends BaseUIModel {
bool _working = false; bool _working = false;
@ -50,7 +54,7 @@ class ToolsUIModel extends BaseUIModel {
), ),
_ToolsItemData( _ToolsItemData(
"p4k_downloader", "p4k_downloader",
"P4K 分流下载", "P4K 分流下载 / 修复",
"使用星际公民中文百科提供的分流下载服务。 \n\n资源有限,请勿滥用。请确保您的硬盘拥有至少大于 200G 的可用空间。", "使用星际公民中文百科提供的分流下载服务。 \n\n资源有限,请勿滥用。请确保您的硬盘拥有至少大于 200G 的可用空间。",
const Icon(FontAwesomeIcons.download, size: 28), const Icon(FontAwesomeIcons.download, size: 28),
onTap: _downloadP4k, onTap: _downloadP4k,
@ -340,11 +344,6 @@ class ToolsUIModel extends BaseUIModel {
String savePath = scInstalledPath; String savePath = scInstalledPath;
String fileName = "Data.p4k"; String fileName = "Data.p4k";
var downloadUrl = AppConf.networkVersionData?.p4kDownloadUrl;
if (downloadUrl == null || downloadUrl.isEmpty) {
showToast(context!, "该功能维护中,请稍后再试!");
return;
}
if ((await SystemHelper.getPID("\"RSI Launcher\"")).isNotEmpty) { if ((await SystemHelper.getPID("\"RSI Launcher\"")).isNotEmpty) {
showToast(context!, "RSI启动器正在运行请先关闭启动器再使用此功能", showToast(context!, "RSI启动器正在运行请先关闭启动器再使用此功能",
constraints: BoxConstraints( constraints: BoxConstraints(
@ -354,20 +353,20 @@ class ToolsUIModel extends BaseUIModel {
await showToast( await showToast(
context!, context!,
"P4k 是星际公民的核心游戏文件,高达 100GB+盒子提供的离线下载是为了帮助一些p4k文件下载超级慢的用户" "P4k 是星际公民的核心游戏文件,高达 100GB+盒子提供的离线下载是为了帮助一些p4k文件下载超级慢的用户 或用于修复官方启动器无法修复的 p4k 文件"
"\n\n接下来会弹窗询问您保存位置(可以选择星际公民文件夹也可以选择别处),下载完成后请确保 P4K 文件夹位于 LIVE 文件夹内,之后使用星际公民启动器校验更新即可。"); "\n\n接下来会弹窗询问您保存位置(可以选择星际公民文件夹也可以选择别处),下载完成后请确保 P4K 文件夹位于 LIVE 文件夹内,之后使用星际公民启动器校验更新即可。");
// AnalyticsApi.touch("p4k_download"); // AnalyticsApi.touch("p4k_download");
final userSelect = await FilePicker.platform.saveFile( final userSelect = await FilePicker.platform.saveFile(
initialDirectory: savePath, fileName: fileName, lockParentWindow: true); initialDirectory: savePath, fileName: fileName, lockParentWindow: true);
if (userSelect == null) { if (userSelect == null) {
Navigator.pop(context!);
return; return;
} }
final f = File(userSelect); // p4k
if (await f.exists()) { // final f = File(userSelect);
await f.delete(); // if (await f.exists()) {
} // await f.delete();
// }
savePath = userSelect; savePath = userSelect;
dPrint(savePath); dPrint(savePath);
notifyListeners(); notifyListeners();
@ -375,14 +374,29 @@ class ToolsUIModel extends BaseUIModel {
savePath = savePath.substring(0, savePath.length - fileName.length - 1); savePath = savePath.substring(0, savePath.length - fileName.length - 1);
} }
final gid = await Aria2cManager.aria2c.addUri( _working = true;
["https://release.scbox.org/data_3.22.0A-LIVE.9035564.p4k.torrent"], final btData = await handleError(() => RSHttp.get(
extraParams: {"dir": savePath}); "https://p4k.42kit.com/3.22.1-LIVE.9072370/Data.p4k.torrent"));
if (btData == null || btData.data == null) {
_working = false;
return;
}
try {
final b64Str = base64Encode(btData.data!);
dPrint(b64Str);
final gid = await Aria2cManager.aria2c
.addTorrent(b64Str, extraParams: {"dir": savePath});
_working = false;
dPrint("Aria2cManager.aria2c.addUri resp === $gid"); dPrint("Aria2cManager.aria2c.addUri resp === $gid");
await Aria2cManager.aria2c.saveSession();
showToast(context!, "添加下载任务成功!请留意盒子右上角的下载管理器。"); await showToast(context!, "创建下载任务成功!");
BaseUIContainer(
uiCreate: () => DownloadsUI(),
modelCreate: () => DownloadsUIModel()).push(context!);
} catch (e) {
showToast(context!, "初始化失败!");
}
// launchUrlString("https://citizenwiki.cn/SC%E6%B1%89%E5%8C%96%E7%9B%92%E5%AD%90#%E5%88%86%E6%B5%81%E4%B8%8B%E8%BD%BD%E6%95%99%E7%A8%8B"); // launchUrlString("https://citizenwiki.cn/SC%E6%B1%89%E5%8C%96%E7%9B%92%E5%AD%90#%E5%88%86%E6%B5%81%E4%B8%8B%E8%BD%BD%E6%95%99%E7%A8%8B");
} }

View File

@ -73,7 +73,9 @@ dependencies:
rust_builder: rust_builder:
path: rust_builder path: rust_builder
aria2: aria2:
#git: https://github.com/xkeyC/dart_aria2_rpc.git
path: ../../xkeyC/dart_aria2_rpc path: ../../xkeyC/dart_aria2_rpc
intl: ^0.18.0
dependency_overrides: dependency_overrides:
http: ^1.1.2 http: ^1.1.2