feat:riverpod 迁移

This commit is contained in:
2024-03-07 23:01:32 +08:00
parent c6b69c4e08
commit 8e37ebece5
66 changed files with 1126 additions and 10749 deletions

View File

@ -1,247 +0,0 @@
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 'package:starcitizen_doctor/common/io/aria2c.dart';
import 'downloader_ui_model.dart';
class DownloaderUI extends BaseUI<DownloaderUIModel> {
final DateFormat formatter = DateFormat('yyyy-MM-dd HH:mm:ss');
@override
Widget? buildBody(BuildContext context, DownloaderUIModel model) {
return makeDefaultPage(context, model,
content: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 12),
Row(
children: [
const Spacer(),
const SizedBox(width: 24),
const SizedBox(width: 12),
for (final item in <MapEntry<String, IconData>, String>{
const MapEntry("settings", FluentIcons.settings): "限速设置",
if (model.tasks.isNotEmpty)
const MapEntry("pause_all", FluentIcons.pause): "全部暂停",
if (model.waitingTasks.isNotEmpty)
const MapEntry("resume_all", FluentIcons.download): "恢复全部",
if (model.tasks.isNotEmpty || model.waitingTasks.isNotEmpty)
const MapEntry("cancel_all", FluentIcons.cancel): "全部取消",
}.entries)
Padding(
padding: const EdgeInsets.only(left: 6, right: 6),
child: Button(
child: Padding(
padding: const EdgeInsets.all(4),
child: Row(
children: [
Icon(item.key.value),
const SizedBox(width: 6),
Text(item.value),
],
),
),
onPressed: () => model.onTapButton(item.key.key)),
),
const SizedBox(width: 12),
],
),
if (model.getTasksLen() == 0)
const Expanded(
child: Center(
child: Text("无下载任务"),
))
else
Expanded(
child: ListView.builder(
itemBuilder: (BuildContext context, int index) {
final (task, type, isFirstType) = model.getTaskAndType(index);
final nt = DownloaderUIModel.getTaskTypeAndName(task);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (isFirstType)
Column(
children: [
Container(
padding: EdgeInsets.only(
left: 24,
right: 24,
top: index == 0 ? 0 : 12,
bottom: 12),
margin: const EdgeInsets.only(top: 6, bottom: 6),
child: Row(
children: [
Expanded(
child: Row(
children: [
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(.06),
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) * 100 / (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(),
)),
Container(
color: FluentTheme.of(context).cardColor.withOpacity(.06),
child: Padding(
padding: const EdgeInsets.only(left: 12, bottom: 3, top: 3),
child: Row(
children: [
Container(
width: 8,
height: 8,
decoration: BoxDecoration(
color: Aria2cManager.isAvailable
? Colors.green
: Colors.white,
borderRadius: BorderRadius.circular(1000),
),
),
const SizedBox(width: 12),
Text(
"下载: ${FileSize.getSize(model.globalStat?.downloadSpeed ?? 0)}/s 上传:${FileSize.getSize(model.globalStat?.uploadSpeed ?? 0)}/s",
style: const TextStyle(fontSize: 12),
)
],
),
),
),
],
));
}
@override
String getUITitle(BuildContext context, DownloaderUIModel model) => "下载管理";
}

View File

@ -1,251 +0,0 @@
import 'dart:io';
import 'package:aria2/aria2.dart';
import 'package:flutter/services.dart';
import 'package:hive/hive.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 DownloaderUIModel extends BaseUIModel {
List<Aria2Task> tasks = [];
List<Aria2Task> waitingTasks = [];
List<Aria2Task> stoppedTasks = [];
Aria2GlobalStat? globalStat;
final statusMap = {
"active": "下载中...",
"waiting": "等待中",
"paused": "已暂停",
"error": "下载失败",
"complete": "下载完成",
"removed": "已删除",
};
final listHeaderStatusMap = {
"active": "下载中",
"waiting": "等待中",
"stopped": "已结束",
};
@override
initModel() {
super.initModel();
_listenDownloader();
}
onTapButton(String key) async {
switch (key) {
case "pause_all":
if (!Aria2cManager.isAvailable) return;
await Aria2cManager.getClient().pauseAll();
await Aria2cManager.getClient().saveSession();
return;
case "resume_all":
if (!Aria2cManager.isAvailable) return;
await Aria2cManager.getClient().unpauseAll();
await Aria2cManager.getClient().saveSession();
return;
case "cancel_all":
final userOK = await showConfirmDialogs(
context!, "确认取消全部任务?", const Text("如果文件不再需要,你可能需要手动删除下载文件。"));
if (userOK == true) {
if (!Aria2cManager.isAvailable) return;
try {
for (var value in [...tasks, ...waitingTasks]) {
await Aria2cManager.getClient().remove(value.gid!);
}
await Aria2cManager.getClient().saveSession();
} catch (e) {
dPrint("DownloadsUIModel cancel_all Error: $e");
}
}
return;
case "settings":
_showDownloadSpeedSettings();
return;
}
}
_listenDownloader() async {
try {
while (true) {
if (!mounted) return;
if (Aria2cManager.isAvailable) {
final aria2c = Aria2cManager.getClient();
tasks.clear();
tasks = await aria2c.tellActive();
waitingTasks = await aria2c.tellWaiting(0, 1000000);
stoppedTasks = await aria2c.tellStopped(0, 1000000);
globalStat = await aria2c.getGlobalStat();
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");
}
static 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 {
final aria2c = Aria2cManager.getClient();
if (gid != null) {
await aria2c.unpause(gid);
}
}
Future<void> pauseTask(String? gid) async {
final aria2c = Aria2cManager.getClient();
if (gid != null) {
await 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) {
final aria2c = Aria2cManager.getClient();
await aria2c.remove(gid);
await Aria2cManager.getClient().saveSession();
}
}
}
openFolder(Aria2Task task) {
final f = getFilesFormTask(task).firstOrNull;
if (f != null) {
SystemHelper.openDir(File(f.path!).absolute.path.replaceAll("/", "\\"));
}
}
Future<void> _showDownloadSpeedSettings() async {
final box = await Hive.openBox("app_conf");
final upCtrl = TextEditingController(
text: box.get("downloader_up_limit", defaultValue: ""));
final downCtrl = TextEditingController(
text: box.get("downloader_down_limit", defaultValue: ""));
final ifr = FilteringTextInputFormatter.allow(RegExp(r'^\d*[km]?$'));
final ok = await showConfirmDialogs(
context!,
"限速设置",
Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"SC 汉化盒子使用 p2p 网络来加速文件下载,如果您流量有限,可在此处将上传带宽设置为 1(byte)。",
style: TextStyle(
fontSize: 14,
color: Colors.white.withOpacity(.6),
),
),
const SizedBox(height: 24),
const Text("请输入下载单位1、100k、10m 0或留空为不限速。"),
const SizedBox(height: 12),
const Text("上传限速:"),
const SizedBox(height: 6),
TextFormBox(
placeholder: "1、100k、10m、0",
controller: upCtrl,
placeholderStyle: TextStyle(color: Colors.white.withOpacity(.6)),
inputFormatters: [ifr],
),
const SizedBox(height: 12),
const Text("下载限速:"),
const SizedBox(height: 6),
TextFormBox(
placeholder: "1、100k、10m、0",
controller: downCtrl,
placeholderStyle: TextStyle(color: Colors.white.withOpacity(.6)),
inputFormatters: [ifr],
),
const SizedBox(height: 24),
Text(
"* P2P 上传仅在下载文件时进行,下载完成后会关闭 p2p 连接。如您想参与做种,请通过关于页面联系我们。",
style: TextStyle(
fontSize: 13,
color: Colors.white.withOpacity(.6),
),
)
],
));
if (ok == true) {
await handleError(() => Aria2cManager.launchDaemon());
final aria2c = Aria2cManager.getClient();
final upByte = Aria2cManager.textToByte(upCtrl.text.trim());
final downByte = Aria2cManager.textToByte(downCtrl.text.trim());
final r = await handleError(() => aria2c.changeGlobalOption(Aria2Option()
..maxOverallUploadLimit = upByte
..maxOverallDownloadLimit = downByte));
if (r != null) {
await box.put('downloader_up_limit', upCtrl.text.trim());
await box.put('downloader_down_limit', downCtrl.text.trim());
notifyListeners();
}
}
}
}