opt download (#1755)

Signed-off-by: bggRGjQaUbCoE <githubaccount56556@proton.me>
This commit is contained in:
dom
2025-11-27 21:00:13 +08:00
committed by GitHub
parent ded78e534f
commit 9ccaa3072b
25 changed files with 1161 additions and 410 deletions

View File

@@ -41,7 +41,12 @@ class MultiSelectAppBarWidget extends StatelessWidget
style: TextButton.styleFrom( style: TextButton.styleFrom(
visualDensity: VisualDensity.compact, visualDensity: VisualDensity.compact,
), ),
onPressed: ctr.onRemove, onPressed: () {
if (ctr.checkedCount == 0) {
return;
}
ctr.onRemove();
},
child: Text( child: Text(
'移除', '移除',
style: TextStyle(color: Get.theme.colorScheme.error), style: TextStyle(color: Get.theme.colorScheme.error),

View File

@@ -5,7 +5,7 @@ Future<bool> showConfirmDialog({
required BuildContext context, required BuildContext context,
required String title, required String title,
Object? content, Object? content,
@Deprecated('use `bool result = await showConfirmDialog()` instead') // @Deprecated('use `bool result = await showConfirmDialog()` instead')
VoidCallback? onConfirm, VoidCallback? onConfirm,
}) async { }) async {
assert(content is String? || content is Widget); assert(content is String? || content is Widget);

View File

@@ -1,13 +1,11 @@
import 'package:PiliPlus/common/constants.dart';
import 'package:PiliPlus/models/common/video/video_type.dart'; import 'package:PiliPlus/models/common/video/video_type.dart';
import 'package:PiliPlus/services/download/download_service.dart'; import 'package:PiliPlus/pages/common/multi_select/base.dart'
import 'package:PiliPlus/utils/cache_manager.dart'; show MultiSelectData;
import 'package:PiliPlus/utils/page_utils.dart'; import 'package:PiliPlus/utils/page_utils.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:get/get_state_manager/src/rx_flutter/rx_obx_widget.dart';
import 'package:get/route_manager.dart'; import 'package:get/route_manager.dart';
class BiliDownloadEntryInfo { class BiliDownloadEntryInfo with MultiSelectData {
int mediaType; int mediaType;
final bool hasDashAudio; final bool hasDashAudio;
bool isCompleted; bool isCompleted;
@@ -114,76 +112,6 @@ class BiliDownloadEntryInfo {
), ),
); );
Widget progressWidget({
required ThemeData theme,
required DownloadService downloadService,
required bool isPage,
}) {
return RepaintBoundary(
// TODO: refresh `downloadedBytes` only cause unnecessary repaint
child: Obx(() {
final curDownload = downloadService.curDownload.value;
final isCurr =
curDownload != null &&
(isPage ? curDownload.pageId == pageId : curDownload.cid == cid);
late final status = curDownload?.status;
late final isDownloading = status == DownloadStatus.downloading;
late final color = isCurr && status != DownloadStatus.pause
? theme.colorScheme.primary
: theme.colorScheme.outline;
return Column(
spacing: 6,
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
isCurr ? status!.message : '暂停中',
style: TextStyle(
fontSize: 12,
height: 1,
color: color,
),
),
Text(
isCurr
? isDownloading || status == DownloadStatus.pause
? ' ${CacheManager.formatSize(curDownload.downloadedBytes)}/${CacheManager.formatSize(curDownload.totalBytes)}'
: ''
: totalBytes == 0
? ''
: ' ${CacheManager.formatSize(downloadedBytes)}/${CacheManager.formatSize(totalBytes)}',
style: TextStyle(
fontSize: 12,
height: 1,
color: color,
),
),
],
),
LinearProgressIndicator(
// ignore: deprecated_member_use
year2023: true,
minHeight: 2.5,
borderRadius: StyleString.mdRadius,
color: color,
backgroundColor: theme.highlightColor,
value: isCurr
? curDownload.totalBytes == 0
? 0
: curDownload.downloadedBytes / curDownload.totalBytes
: totalBytes == 0
? 0
: downloadedBytes / totalBytes,
),
],
);
}),
);
}
BiliDownloadEntryInfo({ BiliDownloadEntryInfo({
this.mediaType = 1, this.mediaType = 1,
this.hasDashAudio = false, this.hasDashAudio = false,

View File

@@ -1,6 +1,8 @@
import 'package:PiliPlus/models_new/download/bili_download_entry_info.dart'; import 'package:PiliPlus/models_new/download/bili_download_entry_info.dart';
import 'package:PiliPlus/pages/common/multi_select/base.dart'
show MultiSelectData;
class DownloadPageInfo { class DownloadPageInfo with MultiSelectData {
final String pageId; final String pageId;
final String dirPath; final String dirPath;
final String title; final String title;
@@ -8,7 +10,6 @@ class DownloadPageInfo {
int sortKey; int sortKey;
final int? seasonType; final int? seasonType;
final List<BiliDownloadEntryInfo> entrys; final List<BiliDownloadEntryInfo> entrys;
BiliDownloadEntryInfo? entry;
DownloadPageInfo({ DownloadPageInfo({
required this.pageId, required this.pageId,
@@ -18,6 +19,5 @@ class DownloadPageInfo {
required this.sortKey, required this.sortKey,
this.seasonType, this.seasonType,
required this.entrys, required this.entrys,
this.entry,
}); });
} }

View File

@@ -6,7 +6,7 @@ mixin MultiSelectData {
bool? checked; bool? checked;
} }
abstract class MultiSelectBase<T> { mixin MultiSelectBase<T extends MultiSelectData> {
RxBool get enableMultiSelect; RxBool get enableMultiSelect;
RxBool get allSelected; RxBool get allSelected;
@@ -17,6 +17,52 @@ abstract class MultiSelectBase<T> {
void onRemove(); void onRemove();
} }
mixin BaseMultiSelectMixin<T extends MultiSelectData>
implements MultiSelectBase<T> {
@override
late final allSelected = false.obs;
late final RxInt rxCount = 0.obs;
@override
int get checkedCount => rxCount.value;
@override
final RxBool enableMultiSelect = false.obs;
RxObjectMixin get state;
List<T> get list;
Iterable<T> get allChecked => list.where((v) => v.checked == true);
@override
void handleSelect({bool checked = false, bool disableSelect = true}) {
for (var item in list) {
item.checked = checked;
}
state.refresh();
rxCount.value = checked ? list.length : 0;
if (disableSelect && !checked) {
enableMultiSelect.value = false;
}
}
@override
void onSelect(T item) {
item.checked = !(item.checked ?? false);
if (item.checked!) {
rxCount.value++;
} else {
rxCount.value--;
}
state.refresh();
if (checkedCount == 0) {
enableMultiSelect.value = false;
} else {
allSelected.value = checkedCount == list.length;
}
}
}
mixin CommonMultiSelectMixin<T extends MultiSelectData> mixin CommonMultiSelectMixin<T extends MultiSelectData>
implements MultiSelectBase<T> { implements MultiSelectBase<T> {
@override @override

View File

@@ -7,11 +7,7 @@ import 'package:PiliPlus/pages/common/search/common_search_controller.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
abstract class CommonSearchPage extends StatefulWidget { abstract class CommonSearchPageState<S extends StatefulWidget, R, T>
const CommonSearchPage({super.key});
}
abstract class CommonSearchPageState<S extends CommonSearchPage, R, T>
extends State<S> { extends State<S> {
CommonSearchController<R, T> get controller; CommonSearchController<R, T> get controller;

View File

@@ -1,14 +1,25 @@
import 'dart:async'; import 'dart:async';
import 'package:PiliPlus/common/widgets/dialog/dialog.dart';
import 'package:PiliPlus/models_new/download/download_info.dart'; import 'package:PiliPlus/models_new/download/download_info.dart';
import 'package:PiliPlus/pages/common/multi_select/base.dart'
show BaseMultiSelectMixin;
import 'package:PiliPlus/services/download/download_service.dart'; import 'package:PiliPlus/services/download/download_service.dart';
import 'package:PiliPlus/utils/storage.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
class DownloadPageController extends GetxController { class DownloadPageController extends GetxController
with BaseMultiSelectMixin<DownloadPageInfo> {
final _downloadService = Get.find<DownloadService>(); final _downloadService = Get.find<DownloadService>();
final pages = RxList<DownloadPageInfo>(); final pages = RxList<DownloadPageInfo>();
final flag = RxInt(0); final flag = RxInt(0);
@override
List<DownloadPageInfo> get list => pages;
@override
RxList<DownloadPageInfo> get state => pages;
@override @override
void onInit() { void onInit() {
super.onInit(); super.onInit();
@@ -35,15 +46,6 @@ class DownloadPageController extends GetxController {
final page = list.firstWhereOrNull((e) => e.pageId == pageId); final page = list.firstWhereOrNull((e) => e.pageId == pageId);
if (page != null) { if (page != null) {
final aSortKey = entry.sortKey; final aSortKey = entry.sortKey;
if (!entry.isCompleted) {
if (page.entry case final lastEntry?) {
if (aSortKey < lastEntry.sortKey) {
page.entry = entry;
}
} else {
page.entry = entry;
}
}
final bSortKey = page.sortKey; final bSortKey = page.sortKey;
if (aSortKey < bSortKey) { if (aSortKey < bSortKey) {
page page
@@ -61,7 +63,6 @@ class DownloadPageController extends GetxController {
sortKey: entry.sortKey, sortKey: entry.sortKey,
seasonType: entry.ep?.seasonType, seasonType: entry.ep?.seasonType,
entrys: [entry], entrys: [entry],
entry: entry.isCompleted ? null : entry,
), ),
); );
} }
@@ -69,4 +70,32 @@ class DownloadPageController extends GetxController {
pages.value = list; pages.value = list;
flag.value++; flag.value++;
} }
@override
void onRemove() {
showConfirmDialog(
context: Get.context!,
title: '确定删除选中视频?',
onConfirm: () async {
SmartDialog.showLoading();
final allChecked = this.allChecked.toList();
final watchProgress = GStorage.watchProgress;
for (var page in allChecked) {
await watchProgress.deleteAll(
page.entrys.map((e) => e.cid.toString()),
);
await _downloadService.deletePage(
pageDirPath: page.dirPath,
refresh: false,
);
}
_downloadService.flagNotifier.refresh();
if (enableMultiSelect.value) {
rxCount.value = 0;
enableMultiSelect.value = false;
}
SmartDialog.dismiss();
},
);
}
} }

View File

@@ -1,14 +1,20 @@
import 'dart:async'; import 'dart:async';
import 'package:PiliPlus/common/widgets/appbar/appbar.dart';
import 'package:PiliPlus/common/widgets/dialog/dialog.dart';
import 'package:PiliPlus/common/widgets/loading_widget/http_error.dart'; import 'package:PiliPlus/common/widgets/loading_widget/http_error.dart';
import 'package:PiliPlus/common/widgets/view_sliver_safe_area.dart'; import 'package:PiliPlus/common/widgets/view_sliver_safe_area.dart';
import 'package:PiliPlus/models_new/download/bili_download_entry_info.dart'; import 'package:PiliPlus/models_new/download/bili_download_entry_info.dart';
import 'package:PiliPlus/pages/common/multi_select/base.dart'
show BaseMultiSelectMixin;
import 'package:PiliPlus/pages/download/controller.dart'; import 'package:PiliPlus/pages/download/controller.dart';
import 'package:PiliPlus/pages/download/detail/widgets/item.dart'; import 'package:PiliPlus/pages/download/detail/widgets/item.dart';
import 'package:PiliPlus/services/download/download_service.dart'; import 'package:PiliPlus/services/download/download_service.dart';
import 'package:PiliPlus/utils/grid.dart'; import 'package:PiliPlus/utils/grid.dart';
import 'package:PiliPlus/utils/storage.dart'; import 'package:PiliPlus/utils/storage.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart'
hide SliverGridDelegateWithMaxCrossAxisExtent;
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
class DownloadDetailPage extends StatefulWidget { class DownloadDetailPage extends StatefulWidget {
@@ -28,11 +34,15 @@ class DownloadDetailPage extends StatefulWidget {
} }
class _DownloadDetailPageState extends State<DownloadDetailPage> class _DownloadDetailPageState extends State<DownloadDetailPage>
with GridMixin { with BaseMultiSelectMixin<BiliDownloadEntryInfo> {
StreamSubscription? _sub; StreamSubscription? _sub;
final _downloadItems = RxList<BiliDownloadEntryInfo>(); final _downloadItems = RxList<BiliDownloadEntryInfo>();
final _controller = Get.find<DownloadPageController>(); final _controller = Get.find<DownloadPageController>();
final _downloadService = Get.find<DownloadService>(); final _downloadService = Get.find<DownloadService>();
@override
RxList<BiliDownloadEntryInfo> get list => _downloadItems;
@override
RxList<BiliDownloadEntryInfo> get state => _downloadItems;
@override @override
void initState() { void initState() {
@@ -71,16 +81,48 @@ class _DownloadDetailPageState extends State<DownloadDetailPage>
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Obx(() {
final enableMultiSelect = this.enableMultiSelect.value;
return PopScope(
canPop: !enableMultiSelect,
onPopInvokedWithResult: (didPop, result) {
if (enableMultiSelect) {
handleSelect();
}
},
child: Scaffold(
resizeToAvoidBottomInset: false, resizeToAvoidBottomInset: false,
appBar: AppBar(title: Text(widget.title)), appBar: MultiSelectAppBarWidget(
ctr: this,
child: AppBar(
title: Text(widget.title),
actions: [
IconButton(
tooltip: '多选',
onPressed: () {
if (enableMultiSelect) {
handleSelect();
} else {
this.enableMultiSelect.value = true;
}
},
icon: const Icon(Icons.edit_note),
),
const SizedBox(width: 6),
],
),
),
body: CustomScrollView( body: CustomScrollView(
slivers: [ slivers: [
ViewSliverSafeArea( ViewSliverSafeArea(
sliver: Obx(() { sliver: Obx(() {
if (_downloadItems.isNotEmpty) { if (_downloadItems.isNotEmpty) {
return SliverGrid.builder( return SliverGrid.builder(
gridDelegate: gridDelegate, gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
mainAxisSpacing: 2,
mainAxisExtent: 100,
maxCrossAxisExtent: Grid.smallCardWidth * 2,
),
itemBuilder: (context, index) { itemBuilder: (context, index) {
final entry = _downloadItems[index]; final entry = _downloadItems[index];
return DetailItem( return DetailItem(
@@ -94,14 +136,18 @@ class _DownloadDetailPageState extends State<DownloadDetailPage>
await _downloadService.deletePage( await _downloadService.deletePage(
pageDirPath: entry.pageDirPath, pageDirPath: entry.pageDirPath,
); );
if (context.mounted) { if (mounted) {
Get.back(); Get.back();
} }
} else { } else {
_downloadService.deleteDownload(entry: entry); _downloadService.deleteDownload(
entry: entry,
removeList: true,
);
} }
GStorage.watchProgress.delete(entry.cid.toString()); GStorage.watchProgress.delete(entry.cid.toString());
}, },
controller: this,
); );
}, },
itemCount: _downloadItems.length, itemCount: _downloadItems.length,
@@ -112,6 +158,48 @@ class _DownloadDetailPageState extends State<DownloadDetailPage>
), ),
], ],
), ),
),
);
});
}
@override
void onRemove() {
showConfirmDialog(
context: context,
title: '确定删除选中视频?',
onConfirm: () async {
SmartDialog.showLoading();
final watchProgress = GStorage.watchProgress;
final allChecked = this.allChecked.toSet();
final isDeleteAll = allChecked.length == _downloadItems.length;
if (isDeleteAll) {
await _closeSub();
}
for (var entry in allChecked) {
await watchProgress.deleteAll(
allChecked.map((e) => e.cid.toString()),
);
await _downloadService.deleteDownload(
entry: entry,
removeList: true,
refresh: false,
);
}
_downloadService.flagNotifier.refresh();
if (isDeleteAll) {
SmartDialog.dismiss();
if (mounted) {
Get.back();
}
} else {
if (enableMultiSelect.value) {
rxCount.value = 0;
enableMultiSelect.value = false;
}
SmartDialog.dismiss();
}
},
); );
} }
} }

View File

@@ -5,10 +5,13 @@ import 'package:PiliPlus/common/widgets/badge.dart';
import 'package:PiliPlus/common/widgets/dialog/dialog.dart'; import 'package:PiliPlus/common/widgets/dialog/dialog.dart';
import 'package:PiliPlus/common/widgets/image/network_img_layer.dart'; import 'package:PiliPlus/common/widgets/image/network_img_layer.dart';
import 'package:PiliPlus/common/widgets/progress_bar/video_progress_indicator.dart'; import 'package:PiliPlus/common/widgets/progress_bar/video_progress_indicator.dart';
import 'package:PiliPlus/common/widgets/select_mask.dart';
import 'package:PiliPlus/models/common/badge_type.dart'; import 'package:PiliPlus/models/common/badge_type.dart';
import 'package:PiliPlus/models/common/video/source_type.dart'; import 'package:PiliPlus/models/common/video/source_type.dart';
import 'package:PiliPlus/models/common/video/video_quality.dart'; import 'package:PiliPlus/models/common/video/video_quality.dart';
import 'package:PiliPlus/models_new/download/bili_download_entry_info.dart'; import 'package:PiliPlus/models_new/download/bili_download_entry_info.dart';
import 'package:PiliPlus/pages/common/multi_select/base.dart';
import 'package:PiliPlus/pages/download/downloading/view.dart';
import 'package:PiliPlus/services/download/download_service.dart'; import 'package:PiliPlus/services/download/download_service.dart';
import 'package:PiliPlus/utils/cache_manager.dart'; import 'package:PiliPlus/utils/cache_manager.dart';
import 'package:PiliPlus/utils/duration_utils.dart'; import 'package:PiliPlus/utils/duration_utils.dart';
@@ -26,24 +29,36 @@ class DetailItem extends StatelessWidget {
const DetailItem({ const DetailItem({
super.key, super.key,
required this.entry, required this.entry,
required this.progress, this.progress,
required this.downloadService, required this.downloadService,
required this.onDelete, this.onDelete,
required this.showTitle, required this.showTitle,
this.isCurr = false,
//
required this.controller,
this.checked,
this.onSelect,
}); });
final BiliDownloadEntryInfo entry; final BiliDownloadEntryInfo entry;
final ValueNotifier progress; final ValueNotifier? progress;
final DownloadService downloadService; final DownloadService downloadService;
final VoidCallback onDelete; final VoidCallback? onDelete;
final bool showTitle; final bool showTitle;
final bool isCurr;
//
final MultiSelectBase controller;
final bool? checked;
final ValueChanged<BiliDownloadEntryInfo>? onSelect;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
final outline = theme.colorScheme.outline; final outline = theme.colorScheme.outline;
final cid = entry.source?.cid ?? entry.pageData?.cid; final cid = entry.source?.cid ?? entry.pageData?.cid;
void onLongPress() => showDialog( final canDel = onDelete != null;
void onLongPress() => canDel
? showDialog(
context: context, context: context,
builder: (context) { builder: (context) {
return AlertDialog( return AlertDialog(
@@ -90,11 +105,21 @@ class DetailItem extends StatelessWidget {
), ),
); );
}, },
); )
: null;
return Material( return Material(
type: MaterialType.transparency, type: MaterialType.transparency,
child: InkWell( child: InkWell(
onTap: () async { onTap: () async {
if (!canDel) {
Get.to(const DownloadingPage());
return;
}
if (controller.enableMultiSelect.value) {
(onSelect ?? controller.onSelect).call(entry);
return;
}
if (entry.isCompleted) { if (entry.isCompleted) {
await PageUtils.toVideoPage( await PageUtils.toVideoPage(
aid: entry.avid, aid: entry.avid,
@@ -111,7 +136,7 @@ class DetailItem extends StatelessWidget {
Future.delayed(const Duration(milliseconds: 400), () { Future.delayed(const Duration(milliseconds: 400), () {
if (context.mounted) { if (context.mounted) {
// ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member // ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member
progress.notifyListeners(); progress?.notifyListeners();
} }
}); });
} }
@@ -125,9 +150,6 @@ class DetailItem extends StatelessWidget {
downloadNext: false, downloadNext: false,
); );
} else { } else {
if (entry.status == DownloadStatus.wait) {
downloadService.waitDownloadQueue.remove(entry);
}
downloadService.startDownload(entry); downloadService.startDownload(entry);
} }
} }
@@ -186,8 +208,9 @@ class DetailItem extends StatelessWidget {
top: 6.0, top: 6.0,
type: PBadgeType.gray, type: PBadgeType.gray,
), ),
if (progress != null)
ValueListenableBuilder( ValueListenableBuilder(
valueListenable: progress, valueListenable: progress!,
builder: (_, _, _) { builder: (_, _, _) {
final progress = GStorage.watchProgress.get( final progress = GStorage.watchProgress.get(
cid.toString(), cid.toString(),
@@ -229,6 +252,18 @@ class DetailItem extends StatelessWidget {
type: PBadgeType.gray, type: PBadgeType.gray,
); );
}, },
)
else if (entry.totalTimeMilli != 0)
PBadge(
text: DurationUtils.formatDuration(
entry.totalTimeMilli ~/ 1000,
),
right: 6,
bottom: 7,
type: PBadgeType.gray,
),
Positioned.fill(
child: selectMask(theme, checked ?? entry.checked ?? false),
), ),
], ],
), ),
@@ -303,11 +338,40 @@ class DetailItem extends StatelessWidget {
left: 0, left: 0,
right: 0, right: 0,
bottom: 0, bottom: 0,
child: entry.progressWidget( child: isCurr
theme: theme, ? RepaintBoundary(
downloadService: downloadService, child: Obx(
isPage: false, () {
final curDownload =
downloadService.curDownload.value;
if (curDownload != null) {
final status = curDownload.status;
final color =
status != DownloadStatus.pause
? theme.colorScheme.primary
: theme.colorScheme.outline;
return progressWidget(
statusMsg: status!.message,
progressStr:
status ==
DownloadStatus
.downloading ||
status == DownloadStatus.pause
? '${CacheManager.formatSize(curDownload.downloadedBytes)}/${CacheManager.formatSize(curDownload.totalBytes)}'
: '',
progress: curDownload.totalBytes == 0
? 0
: curDownload.downloadedBytes /
curDownload.totalBytes,
color: color,
highlightColor: theme.highlightColor,
);
}
return entryProgress(theme);
},
), ),
)
: entryProgress(theme),
), ),
], ],
), ),
@@ -318,4 +382,62 @@ class DetailItem extends StatelessWidget {
), ),
); );
} }
Widget entryProgress(ThemeData theme) => progressWidget(
statusMsg: entry.status?.message ?? '暂停中',
progressStr: entry.totalBytes == 0
? ''
: '${CacheManager.formatSize(entry.downloadedBytes)}/${CacheManager.formatSize(entry.totalBytes)}',
progress: entry.totalBytes == 0
? 0
: entry.downloadedBytes / entry.totalBytes,
color: theme.colorScheme.outline,
highlightColor: theme.highlightColor,
);
Widget progressWidget({
required String statusMsg,
required String progressStr,
required double progress,
required Color color,
required Color highlightColor,
}) {
return Column(
spacing: 6,
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
statusMsg,
style: TextStyle(
fontSize: 12,
height: 1,
color: color,
),
),
Text(
progressStr,
style: TextStyle(
fontSize: 12,
height: 1,
color: color,
),
),
],
),
LinearProgressIndicator(
// ignore: deprecated_member_use
year2023: true,
minHeight: 2.5,
borderRadius: StyleString.mdRadius,
color: color,
backgroundColor: highlightColor,
value: progress,
),
],
);
}
} }

View File

@@ -0,0 +1,130 @@
import 'package:PiliPlus/common/widgets/appbar/appbar.dart';
import 'package:PiliPlus/common/widgets/dialog/dialog.dart';
import 'package:PiliPlus/common/widgets/loading_widget/http_error.dart';
import 'package:PiliPlus/common/widgets/view_sliver_safe_area.dart';
import 'package:PiliPlus/models_new/download/bili_download_entry_info.dart';
import 'package:PiliPlus/pages/common/multi_select/base.dart'
show BaseMultiSelectMixin;
import 'package:PiliPlus/pages/download/detail/widgets/item.dart';
import 'package:PiliPlus/services/download/download_service.dart';
import 'package:PiliPlus/utils/grid.dart';
import 'package:flutter/material.dart'
hide SliverGridDelegateWithMaxCrossAxisExtent;
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
class DownloadingPage extends StatefulWidget {
const DownloadingPage({super.key});
@override
State<DownloadingPage> createState() => _DownloadingPageState();
}
class _DownloadingPageState extends State<DownloadingPage>
with BaseMultiSelectMixin<BiliDownloadEntryInfo> {
final _downloadService = Get.find<DownloadService>();
late final _waitDownloadQueue = _downloadService.waitDownloadQueue;
@override
RxList<BiliDownloadEntryInfo> get list => _waitDownloadQueue;
@override
RxList<BiliDownloadEntryInfo> get state => _waitDownloadQueue;
@override
Widget build(BuildContext context) {
return Obx(() {
final enableMultiSelect = this.enableMultiSelect.value;
return PopScope(
canPop: !enableMultiSelect,
onPopInvokedWithResult: (didPop, result) {
if (enableMultiSelect) {
handleSelect();
}
},
child: Scaffold(
appBar: MultiSelectAppBarWidget(
ctr: this,
child: AppBar(
title: const Text('正在缓存'),
actions: [
IconButton(
tooltip: '多选',
onPressed: () {
if (enableMultiSelect) {
handleSelect();
} else {
this.enableMultiSelect.value = true;
}
},
icon: const Icon(Icons.edit_note),
),
const SizedBox(width: 6),
],
),
),
body: CustomScrollView(
slivers: [
ViewSliverSafeArea(
sliver: Obx(() {
if (_waitDownloadQueue.isNotEmpty) {
return SliverGrid.builder(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
mainAxisSpacing: 2,
mainAxisExtent: 100,
maxCrossAxisExtent: Grid.smallCardWidth * 2,
),
itemCount: _waitDownloadQueue.length,
itemBuilder: (context, index) {
final entry = _waitDownloadQueue[index];
final isCurr = entry.cid == _downloadService.curCid;
return DetailItem(
entry: entry,
downloadService: _downloadService,
showTitle: true,
isCurr: isCurr,
onDelete: () => _downloadService.deleteDownload(
entry: entry,
removeQueue: true,
),
controller: this,
);
},
);
}
return const HttpError();
}),
),
],
),
),
);
});
}
@override
void onRemove() {
showConfirmDialog(
context: context,
title: '确定删除选中视频?',
onConfirm: () async {
SmartDialog.showLoading();
final allChecked = this.allChecked.toList();
for (var entry in allChecked) {
await _downloadService.deleteDownload(
entry: entry,
refresh: false,
downloadNext: false,
);
}
_downloadService.waitDownloadQueue.removeWhere(allChecked.contains);
if (_downloadService.curDownload.value == null) {
_downloadService.nextDownload();
}
if (enableMultiSelect.value) {
rxCount.value = 0;
enableMultiSelect.value = false;
}
SmartDialog.dismiss();
},
);
}
}

View File

@@ -0,0 +1,79 @@
import 'package:PiliPlus/common/widgets/dialog/dialog.dart';
import 'package:PiliPlus/http/loading_state.dart';
import 'package:PiliPlus/models_new/download/bili_download_entry_info.dart';
import 'package:PiliPlus/pages/common/multi_select/base.dart'
show BaseMultiSelectMixin;
import 'package:PiliPlus/pages/common/search/common_search_controller.dart';
import 'package:PiliPlus/services/download/download_service.dart';
import 'package:PiliPlus/utils/storage.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
class DownloadSearchController
extends
CommonSearchController<
List<BiliDownloadEntryInfo>,
BiliDownloadEntryInfo
>
with BaseMultiSelectMixin<BiliDownloadEntryInfo> {
final _downloadService = Get.find<DownloadService>();
@override
List<BiliDownloadEntryInfo> get list => loadingState.value.data!;
@override
Rx<LoadingState<List<BiliDownloadEntryInfo>?>> get state => loadingState;
@override
Future<LoadingState<List<BiliDownloadEntryInfo>>> customGetData() async {
final text = editController.text.toLowerCase();
return Success(
_downloadService.downloadList
.where(
(e) =>
e.title.toLowerCase().contains(text) ||
e.showTitle.toLowerCase().contains(text),
)
.toList(),
);
}
void onRemoveSingle(int index, BiliDownloadEntryInfo entry) {
loadingState
..value.data!.removeAt(index)
..refresh();
_downloadService.deleteDownload(
entry: entry,
removeList: true,
);
GStorage.watchProgress.delete(entry.cid.toString());
}
@override
void onRemove() {
showConfirmDialog(
context: Get.context!,
title: '确定删除选中视频?',
onConfirm: () async {
SmartDialog.showLoading();
final allChecked = this.allChecked.toList();
for (var entry in allChecked) {
await GStorage.watchProgress.delete(entry.cid.toString());
await _downloadService.deleteDownload(
entry: entry,
removeList: true,
refresh: false,
);
}
loadingState
..value.data!.removeWhere(allChecked.contains)
..refresh();
_downloadService.flagNotifier.refresh();
if (enableMultiSelect.value) {
rxCount.value = 0;
enableMultiSelect.value = false;
}
SmartDialog.dismiss();
},
);
}
}

View File

@@ -0,0 +1,75 @@
import 'package:PiliPlus/common/widgets/loading_widget/http_error.dart';
import 'package:PiliPlus/models_new/download/bili_download_entry_info.dart';
import 'package:PiliPlus/pages/common/search/common_search_page.dart';
import 'package:PiliPlus/pages/download/detail/widgets/item.dart';
import 'package:PiliPlus/pages/download/search/controller.dart';
import 'package:PiliPlus/services/download/download_service.dart';
import 'package:PiliPlus/utils/grid.dart';
import 'package:flutter/material.dart'
hide SliverGridDelegateWithMaxCrossAxisExtent;
import 'package:get/get.dart';
class DownloadSearchPage extends StatefulWidget {
const DownloadSearchPage({
super.key,
required this.progress,
});
final ValueNotifier progress;
@override
State<DownloadSearchPage> createState() => _DownloadSearchPageState();
}
class _DownloadSearchPageState
extends
CommonSearchPageState<
DownloadSearchPage,
List<BiliDownloadEntryInfo>,
BiliDownloadEntryInfo
> {
@override
DownloadSearchController controller = Get.put(DownloadSearchController());
final _downloadService = Get.find<DownloadService>();
@override
List<Widget>? get extraActions => [
IconButton(
tooltip: '多选',
onPressed: () {
if (controller.enableMultiSelect.value) {
controller.handleSelect();
} else {
controller.enableMultiSelect.value = true;
}
},
icon: const Icon(Icons.edit_note),
),
];
@override
Widget buildList(List<BiliDownloadEntryInfo> list) {
if (list.isNotEmpty) {
return SliverGrid.builder(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
mainAxisSpacing: 2,
mainAxisExtent: 100,
maxCrossAxisExtent: Grid.smallCardWidth * 2,
),
itemBuilder: (context, index) {
final entry = list[index];
return DetailItem(
entry: entry,
progress: widget.progress,
downloadService: _downloadService,
showTitle: true,
onDelete: () => controller.onRemoveSingle(index, entry),
controller: controller,
);
},
itemCount: list.length,
);
}
return const HttpError();
}
}

View File

@@ -1,21 +1,24 @@
import 'dart:async'; import 'dart:async';
import 'package:PiliPlus/common/constants.dart'; import 'package:PiliPlus/common/constants.dart';
import 'package:PiliPlus/common/widgets/appbar/appbar.dart';
import 'package:PiliPlus/common/widgets/badge.dart'; import 'package:PiliPlus/common/widgets/badge.dart';
import 'package:PiliPlus/common/widgets/dialog/dialog.dart'; import 'package:PiliPlus/common/widgets/dialog/dialog.dart';
import 'package:PiliPlus/common/widgets/image/network_img_layer.dart'; import 'package:PiliPlus/common/widgets/image/network_img_layer.dart';
import 'package:PiliPlus/common/widgets/loading_widget/http_error.dart'; import 'package:PiliPlus/common/widgets/loading_widget/http_error.dart';
import 'package:PiliPlus/common/widgets/view_sliver_safe_area.dart'; import 'package:PiliPlus/common/widgets/select_mask.dart';
import 'package:PiliPlus/models/common/badge_type.dart'; import 'package:PiliPlus/models/common/badge_type.dart';
import 'package:PiliPlus/models_new/download/download_info.dart'; import 'package:PiliPlus/models_new/download/download_info.dart';
import 'package:PiliPlus/pages/download/controller.dart'; import 'package:PiliPlus/pages/download/controller.dart';
import 'package:PiliPlus/pages/download/detail/view.dart'; import 'package:PiliPlus/pages/download/detail/view.dart';
import 'package:PiliPlus/pages/download/detail/widgets/item.dart'; import 'package:PiliPlus/pages/download/detail/widgets/item.dart';
import 'package:PiliPlus/pages/download/search/view.dart';
import 'package:PiliPlus/services/download/download_service.dart'; import 'package:PiliPlus/services/download/download_service.dart';
import 'package:PiliPlus/utils/grid.dart'; import 'package:PiliPlus/utils/grid.dart';
import 'package:PiliPlus/utils/storage.dart'; import 'package:PiliPlus/utils/storage.dart';
import 'package:PiliPlus/utils/utils.dart'; import 'package:PiliPlus/utils/utils.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart'
hide SliverGridDelegateWithMaxCrossAxisExtent;
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
@@ -26,7 +29,7 @@ class DownloadPage extends StatefulWidget {
State<DownloadPage> createState() => _DownloadPageState(); State<DownloadPage> createState() => _DownloadPageState();
} }
class _DownloadPageState extends State<DownloadPage> with GridMixin { class _DownloadPageState extends State<DownloadPage> {
final _downloadService = Get.find<DownloadService>(); final _downloadService = Get.find<DownloadService>();
final _controller = Get.put(DownloadPageController()); final _controller = Get.put(DownloadPageController());
final _progress = ValueNotifier(null); final _progress = ValueNotifier(null);
@@ -40,16 +43,109 @@ class _DownloadPageState extends State<DownloadPage> with GridMixin {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
return Scaffold( final padding = MediaQuery.viewPaddingOf(context);
return Obx(() {
final enableMultiSelect = _controller.enableMultiSelect.value;
return PopScope(
canPop: !enableMultiSelect,
onPopInvokedWithResult: (didPop, result) {
if (enableMultiSelect) {
_controller.handleSelect();
}
},
child: Scaffold(
resizeToAvoidBottomInset: false, resizeToAvoidBottomInset: false,
appBar: AppBar(title: const Text('离线缓存')), appBar: MultiSelectAppBarWidget(
body: CustomScrollView( ctr: _controller,
child: AppBar(
title: const Text('离线缓存'),
actions: [
IconButton(
tooltip: '搜索',
onPressed: () async {
await _downloadService.waitForInitialization;
if (!mounted) return;
Get.to(DownloadSearchPage(progress: _progress));
},
icon: const Icon(Icons.search),
),
IconButton(
tooltip: '多选',
onPressed: () {
if (enableMultiSelect) {
_controller.handleSelect();
} else {
_controller.enableMultiSelect.value = true;
}
},
icon: const Icon(Icons.edit_note),
),
const SizedBox(width: 6),
],
),
),
body: Padding(
padding: EdgeInsets.only(left: padding.left, right: padding.right),
child: CustomScrollView(
slivers: [ slivers: [
ViewSliverSafeArea( Obx(() {
sliver: Obx(() { final entry =
_downloadService.waitDownloadQueue.firstWhereOrNull(
(e) => e.cid == _downloadService.curCid,
) ??
_downloadService.waitDownloadQueue.firstOrNull;
if (entry != null) {
return SliverMainAxisGroup(
slivers: [
SliverPadding(
padding: const EdgeInsets.only(left: 12, bottom: 7),
sliver: SliverToBoxAdapter(
child: Text(
'正在缓存 (${_downloadService.waitDownloadQueue.length})',
),
),
),
SliverToBoxAdapter(
child: SizedBox(
height: 100,
child: DetailItem(
entry: entry,
progress: _progress,
downloadService: _downloadService,
showTitle: true,
isCurr: true,
controller: _controller,
),
),
),
],
);
}
return const SliverToBoxAdapter();
}),
Obx(() {
if (_controller.pages.isNotEmpty) { if (_controller.pages.isNotEmpty) {
return SliverGrid.builder( return SliverMainAxisGroup(
gridDelegate: gridDelegate, slivers: [
SliverPadding(
padding: EdgeInsets.only(
left: 12,
bottom: 7,
top: _downloadService.waitDownloadQueue.isEmpty
? 0
: 7,
),
sliver: const SliverToBoxAdapter(
child: Text('已缓存视频'),
),
),
SliverGrid.builder(
gridDelegate:
SliverGridDelegateWithMaxCrossAxisExtent(
mainAxisSpacing: 2,
mainAxisExtent: 100,
maxCrossAxisExtent: Grid.smallCardWidth * 2,
),
itemBuilder: (context, index) { itemBuilder: (context, index) {
final item = _controller.pages[index]; final item = _controller.pages[index];
if (item.entrys.length == 1) { if (item.entrys.length == 1) {
@@ -60,30 +156,44 @@ class _DownloadPageState extends State<DownloadPage> with GridMixin {
downloadService: _downloadService, downloadService: _downloadService,
showTitle: true, showTitle: true,
onDelete: () { onDelete: () {
_downloadService.deleteDownload(entry: entry); _downloadService.deleteDownload(
GStorage.watchProgress.delete(entry.cid.toString()); entry: entry,
removeList: true,
);
GStorage.watchProgress.delete(
entry.cid.toString(),
);
}, },
checked: item.checked ?? false,
onSelect: (_) => _controller.onSelect(item),
controller: _controller,
); );
} }
return _buildItem(theme, item); return _buildItem(theme, item);
}, },
itemCount: _controller.pages.length, itemCount: _controller.pages.length,
),
],
); );
} }
if (_downloadService.waitDownloadQueue.isNotEmpty) {
return const SliverToBoxAdapter();
}
return const HttpError(); return const HttpError();
}), }),
SliverToBoxAdapter(
child: SizedBox(height: padding.bottom + 100),
), ),
], ],
), ),
),
),
); );
});
} }
Widget _buildItem(ThemeData theme, DownloadPageInfo pageInfo) { Widget _buildItem(ThemeData theme, DownloadPageInfo pageInfo) {
final outline = theme.colorScheme.outline; void onLongPress() => showDialog(
final entry = pageInfo.entry;
final isCompleted = entry == null;
void onLongPress() => isCompleted
? showDialog(
context: context, context: context,
builder: (context) { builder: (context) {
return AlertDialog( return AlertDialog(
@@ -99,12 +209,8 @@ class _DownloadPageState extends State<DownloadPage> with GridMixin {
context: context, context: context,
title: '确定删除?', title: '确定删除?',
onConfirm: () async { onConfirm: () async {
final watchProgress = GStorage.watchProgress; await GStorage.watchProgress.deleteAll(
await Future.wait( pageInfo.entrys.map((e) => e.cid.toString()),
pageInfo.entrys.map((e) {
final cid = e.pageData?.cid ?? e.source?.cid;
return watchProgress.delete(cid.toString());
}),
); );
_downloadService.deletePage( _downloadService.deletePage(
pageDirPath: pageInfo.dirPath, pageDirPath: pageInfo.dirPath,
@@ -145,18 +251,24 @@ class _DownloadPageState extends State<DownloadPage> with GridMixin {
), ),
); );
}, },
) );
: null; final first = pageInfo.entrys.first;
return Material( return Material(
type: MaterialType.transparency, type: MaterialType.transparency,
child: InkWell( child: InkWell(
onTap: () => Get.to( onTap: () {
if (_controller.enableMultiSelect.value) {
_controller.onSelect(pageInfo);
return;
}
Get.to(
DownloadDetailPage( DownloadDetailPage(
pageId: pageInfo.pageId, pageId: pageInfo.pageId,
title: pageInfo.title, title: pageInfo.title,
progress: _progress, progress: _progress,
), ),
), );
},
onLongPress: onLongPress, onLongPress: onLongPress,
onSecondaryTap: Utils.isMobile ? null : onLongPress, onSecondaryTap: Utils.isMobile ? null : onLongPress,
child: Padding( child: Padding(
@@ -202,6 +314,9 @@ class _DownloadPageState extends State<DownloadPage> with GridMixin {
right: 6.0, right: 6.0,
top: 6.0, top: 6.0,
), ),
Positioned.fill(
child: selectMask(theme, pageInfo.checked ?? false),
),
], ],
), ),
Expanded( Expanded(
@@ -222,21 +337,23 @@ class _DownloadPageState extends State<DownloadPage> with GridMixin {
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
), ),
), ),
if (isCompleted) Row(
crossAxisAlignment: .end,
mainAxisAlignment: .spaceBetween,
children: [
if (first.ownerName case final ownerName?)
Text( Text(
'已完成', ownerName,
maxLines: 1,
style: TextStyle( style: TextStyle(
fontSize: 12, fontSize: 12,
height: 1, height: 1.6,
color: outline, color: theme.colorScheme.outline,
), ),
) )
else else
entry.progressWidget( const Spacer(),
theme: theme, pageInfo.entrys.first.moreBtn(theme),
downloadService: _downloadService, ],
isPage: true,
), ),
], ],
), ),

View File

@@ -7,7 +7,8 @@ import 'package:PiliPlus/models_new/fav/fav_topic/topic_item.dart';
import 'package:PiliPlus/pages/fav/topic/controller.dart'; import 'package:PiliPlus/pages/fav/topic/controller.dart';
import 'package:PiliPlus/utils/grid.dart'; import 'package:PiliPlus/utils/grid.dart';
import 'package:PiliPlus/utils/utils.dart'; import 'package:PiliPlus/utils/utils.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart'
hide SliverGridDelegateWithMaxCrossAxisExtent;
import 'package:get/get.dart'; import 'package:get/get.dart';
class FavTopicPage extends StatefulWidget { class FavTopicPage extends StatefulWidget {

View File

@@ -9,7 +9,7 @@ import 'package:PiliPlus/utils/utils.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
class FavSearchPage extends CommonSearchPage { class FavSearchPage extends StatefulWidget {
const FavSearchPage({super.key}); const FavSearchPage({super.key});
@override @override

View File

@@ -7,7 +7,7 @@ import 'package:PiliPlus/utils/utils.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
class FollowSearchPage extends CommonSearchPage { class FollowSearchPage extends StatefulWidget {
const FollowSearchPage({ const FollowSearchPage({
super.key, super.key,
this.mid, this.mid,

View File

@@ -7,7 +7,8 @@ import 'package:PiliPlus/models_new/follow/list.dart';
import 'package:PiliPlus/pages/follow/widgets/follow_item.dart'; import 'package:PiliPlus/pages/follow/widgets/follow_item.dart';
import 'package:PiliPlus/pages/follow_type/controller.dart'; import 'package:PiliPlus/pages/follow_type/controller.dart';
import 'package:PiliPlus/utils/grid.dart'; import 'package:PiliPlus/utils/grid.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart'
hide SliverGridDelegateWithMaxCrossAxisExtent;
import 'package:get/get.dart'; import 'package:get/get.dart';
abstract class FollowTypePageState<T extends StatefulWidget> extends State<T> { abstract class FollowTypePageState<T extends StatefulWidget> extends State<T> {

View File

@@ -8,7 +8,7 @@ import 'package:PiliPlus/utils/utils.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
class HistorySearchPage extends CommonSearchPage { class HistorySearchPage extends StatefulWidget {
const HistorySearchPage({super.key}); const HistorySearchPage({super.key});
@override @override

View File

@@ -10,7 +10,7 @@ import 'package:PiliPlus/utils/utils.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
class LaterSearchPage extends CommonSearchPage { class LaterSearchPage extends StatefulWidget {
const LaterSearchPage({super.key}); const LaterSearchPage({super.key});
@override @override

View File

@@ -9,7 +9,8 @@ import 'package:PiliPlus/pages/live_search/child/controller.dart';
import 'package:PiliPlus/pages/live_search/widgets/live_search_room.dart'; import 'package:PiliPlus/pages/live_search/widgets/live_search_room.dart';
import 'package:PiliPlus/pages/live_search/widgets/live_search_user.dart'; import 'package:PiliPlus/pages/live_search/widgets/live_search_user.dart';
import 'package:PiliPlus/utils/grid.dart'; import 'package:PiliPlus/utils/grid.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart'
hide SliverGridDelegateWithMaxCrossAxisExtent;
import 'package:get/get.dart'; import 'package:get/get.dart';
class LiveSearchChildPage extends StatefulWidget { class LiveSearchChildPage extends StatefulWidget {

View File

@@ -5,7 +5,8 @@ import 'package:PiliPlus/pages/search_panel/controller.dart';
import 'package:PiliPlus/pages/search_panel/pgc/widgets/item.dart'; import 'package:PiliPlus/pages/search_panel/pgc/widgets/item.dart';
import 'package:PiliPlus/pages/search_panel/view.dart'; import 'package:PiliPlus/pages/search_panel/view.dart';
import 'package:PiliPlus/utils/grid.dart'; import 'package:PiliPlus/utils/grid.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart'
hide SliverGridDelegateWithMaxCrossAxisExtent;
import 'package:get/get.dart'; import 'package:get/get.dart';
class SearchPgcPanel extends CommonSearchPanel { class SearchPgcPanel extends CommonSearchPanel {

View File

@@ -5,7 +5,8 @@ import 'package:PiliPlus/pages/search_panel/user/controller.dart';
import 'package:PiliPlus/pages/search_panel/user/widgets/item.dart'; import 'package:PiliPlus/pages/search_panel/user/widgets/item.dart';
import 'package:PiliPlus/pages/search_panel/view.dart'; import 'package:PiliPlus/pages/search_panel/view.dart';
import 'package:PiliPlus/utils/grid.dart'; import 'package:PiliPlus/utils/grid.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart'
hide SliverGridDelegateWithMaxCrossAxisExtent;
import 'package:get/get.dart'; import 'package:get/get.dart';
class SearchUserPanel extends CommonSearchPanel { class SearchUserPanel extends CommonSearchPanel {

View File

@@ -1885,7 +1885,8 @@ class VideoDetailController extends GetxController
if (!context.mounted) { if (!context.mounted) {
return; return;
} }
final Set<int?> cidSet = downloadService.downloadList final Set<int?> cidSet =
(downloadService.downloadList + downloadService.waitDownloadQueue)
.map((e) => e.cid) .map((e) => e.cid)
.toSet(); .toSet();
final index = episodes!.indexWhere( final index = episodes!.indexWhere(

View File

@@ -34,9 +34,11 @@ class DownloadService extends GetxService {
final _lock = Lock(); final _lock = Lock();
final flagNotifier = <void Function()>{}; final flagNotifier = <void Function()>{};
final waitDownloadQueue = <BiliDownloadEntryInfo>[]; final waitDownloadQueue = RxList<BiliDownloadEntryInfo>();
final downloadList = RxList<BiliDownloadEntryInfo>(); final downloadList = <BiliDownloadEntryInfo>[];
int? _curCid;
int? get curCid => _curCid;
final curDownload = Rxn<BiliDownloadEntryInfo>(); final curDownload = Rxn<BiliDownloadEntryInfo>();
void _updateCurStatus(DownloadStatus status) { void _updateCurStatus(DownloadStatus status) {
if (curDownload.value != null) { if (curDownload.value != null) {
@@ -62,15 +64,14 @@ class DownloadService extends GetxService {
} }
Future<void> _readDownloadList() async { Future<void> _readDownloadList() async {
downloadList.clear();
final downloadDir = Directory(await _getDownloadPath()); final downloadDir = Directory(await _getDownloadPath());
final list = <BiliDownloadEntryInfo>[];
await for (final dir in downloadDir.list()) { await for (final dir in downloadDir.list()) {
if (dir is Directory) { if (dir is Directory) {
list.addAll(await _readDownloadDirectory(dir)); downloadList.addAll(await _readDownloadDirectory(dir));
} }
} }
downloadList.value = list downloadList.sort((a, b) => b.timeUpdateStamp.compareTo(a.timeUpdateStamp));
..sort((a, b) => b.timeUpdateStamp.compareTo(a.timeUpdateStamp));
} }
@pragma('vm:notify-debugger-on-exception') @pragma('vm:notify-debugger-on-exception')
@@ -92,8 +93,9 @@ class DownloadService extends GetxService {
final entry = BiliDownloadEntryInfo.fromJson(jsonDecode(entryJson)) final entry = BiliDownloadEntryInfo.fromJson(jsonDecode(entryJson))
..pageDirPath = pageDir.path ..pageDirPath = pageDir.path
..entryDirPath = entryDir.path; ..entryDirPath = entryDir.path;
if (entry.isCompleted) {
result.add(entry); result.add(entry);
if (!entry.isCompleted) { } else {
waitDownloadQueue.add(entry..status = DownloadStatus.wait); waitDownloadQueue.add(entry..status = DownloadStatus.wait);
} }
} catch (_) {} } catch (_) {}
@@ -114,6 +116,9 @@ class DownloadService extends GetxService {
if (downloadList.indexWhere((e) => e.cid == cid) != -1) { if (downloadList.indexWhere((e) => e.cid == cid) != -1) {
return; return;
} }
if (waitDownloadQueue.indexWhere((e) => e.cid == cid) != -1) {
return;
}
final pageData = PageInfo( final pageData = PageInfo(
cid: cid, cid: cid,
page: page.page!, page: page.page!,
@@ -171,6 +176,9 @@ class DownloadService extends GetxService {
if (downloadList.indexWhere((e) => e.cid == cid) != -1) { if (downloadList.indexWhere((e) => e.cid == cid) != -1) {
return; return;
} }
if (waitDownloadQueue.indexWhere((e) => e.cid == cid) != -1) {
return;
}
final currentTime = DateTime.now().millisecondsSinceEpoch ~/ 1000; final currentTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;
final source = SourceInfo( final source = SourceInfo(
avId: episode.aid!, avId: episode.aid!,
@@ -235,13 +243,10 @@ class DownloadService extends GetxService {
..pageDirPath = entryDir.parent.path ..pageDirPath = entryDir.parent.path
..entryDirPath = entryDir.path ..entryDirPath = entryDir.path
..status = DownloadStatus.wait; ..status = DownloadStatus.wait;
downloadList.insert(0, entry); waitDownloadQueue.add(entry);
flagNotifier.refresh();
final currStatus = curDownload.value?.status?.index; final currStatus = curDownload.value?.status?.index;
if (currStatus == null || currStatus > 3) { if (currStatus == null || currStatus > 3) {
startDownload(entry); startDownload(entry);
} else {
waitDownloadQueue.add(entry);
} }
} }
@@ -283,7 +288,9 @@ class DownloadService extends GetxService {
curDownload.value?.status = DownloadStatus.pause; curDownload.value?.status = DownloadStatus.pause;
} }
_curCid = entry.cid;
curDownload.value = entry; curDownload.value = entry;
waitDownloadQueue.refresh();
await _startDownload(entry); await _startDownload(entry);
}); });
} }
@@ -450,6 +457,11 @@ class DownloadService extends GetxService {
} }
void _onDone([Object? error]) { void _onDone([Object? error]) {
if (error != null) {
_updateCurStatus(DownloadStatus.failDownload);
return;
}
final status = switch (_audioDownloadManager?.status) { final status = switch (_audioDownloadManager?.status) {
DownloadStatus.downloading => DownloadStatus.audioDownloading, DownloadStatus.downloading => DownloadStatus.audioDownloading,
DownloadStatus.failDownload => DownloadStatus.failDownloadAudio, DownloadStatus.failDownload => DownloadStatus.failDownloadAudio,
@@ -458,9 +470,7 @@ class DownloadService extends GetxService {
_updateCurStatus(status); _updateCurStatus(status);
if (curDownload.value case final curEntryInfo?) { if (curDownload.value case final curEntryInfo?) {
if (error == null) {
curEntryInfo.downloadedBytes = curEntryInfo.totalBytes; curEntryInfo.downloadedBytes = curEntryInfo.totalBytes;
}
if (status == DownloadStatus.completed) { if (status == DownloadStatus.completed) {
_completeDownload(); _completeDownload();
} else { } else {
@@ -493,29 +503,40 @@ class DownloadService extends GetxService {
..downloadedBytes = entry.totalBytes ..downloadedBytes = entry.totalBytes
..isCompleted = true; ..isCompleted = true;
await _updateBiliDownloadEntryJson(entry); await _updateBiliDownloadEntryJson(entry);
waitDownloadQueue.remove(entry);
downloadList.insert(0, entry);
flagNotifier.refresh(); flagNotifier.refresh();
_curCid = null;
curDownload.value = null; curDownload.value = null;
_downloadManager = null; _downloadManager = null;
_audioDownloadManager = null; _audioDownloadManager = null;
_nextDownload(); nextDownload();
} }
void _nextDownload() { void nextDownload() {
if (waitDownloadQueue.isNotEmpty) { if (waitDownloadQueue.isNotEmpty) {
final next = waitDownloadQueue.removeAt(0); startDownload(waitDownloadQueue.first);
if (!next.isCompleted && downloadList.contains(next)) {
startDownload(next);
} else {
_nextDownload();
}
} }
} }
Future<void> deleteDownload({ Future<void> deleteDownload({
required BiliDownloadEntryInfo entry, required BiliDownloadEntryInfo entry,
bool removeList = false,
bool removeQueue = false,
bool refresh = true,
bool downloadNext = true,
}) async { }) async {
if (removeList) {
downloadList.remove(entry);
}
if (removeQueue) {
waitDownloadQueue.remove(entry);
}
if (curDownload.value?.cid == entry.cid) { if (curDownload.value?.cid == entry.cid) {
await cancelDownload(isDelete: true); await cancelDownload(
isDelete: true,
downloadNext: downloadNext,
);
} }
final downloadDir = Directory(entry.pageDirPath); final downloadDir = Directory(entry.pageDirPath);
if (downloadDir.existsSync()) { if (downloadDir.existsSync()) {
@@ -528,16 +549,21 @@ class DownloadService extends GetxService {
} }
} }
} }
downloadList.remove(entry); if (refresh) {
waitDownloadQueue.remove(entry);
flagNotifier.refresh(); flagNotifier.refresh();
} }
}
Future<void> deletePage({required String pageDirPath}) async { Future<void> deletePage({
required String pageDirPath,
bool refresh = true,
}) async {
await Directory(pageDirPath).tryDel(recursive: true); await Directory(pageDirPath).tryDel(recursive: true);
downloadList.removeWhere((e) => e.pageDirPath == pageDirPath); downloadList.removeWhere((e) => e.pageDirPath == pageDirPath);
if (refresh) {
flagNotifier.refresh(); flagNotifier.refresh();
} }
}
Future<void> cancelDownload({ Future<void> cancelDownload({
required bool isDelete, required bool isDelete,
@@ -554,17 +580,18 @@ class DownloadService extends GetxService {
} }
} }
if (isDelete) { if (isDelete) {
_curCid = null;
curDownload.value = null; curDownload.value = null;
} else { } else {
_updateCurStatus(DownloadStatus.pause); _updateCurStatus(DownloadStatus.pause);
} }
if (downloadNext) { if (downloadNext) {
_nextDownload(); nextDownload();
} }
} }
} }
extension on Set<void Function()> { extension SetExt on Set<void Function()> {
void refresh() { void refresh() {
for (var i in this) { for (var i in this) {
i(); i();

View File

@@ -137,3 +137,106 @@ class SliverGridDelegateWithExtentAndRatio extends SliverGridDelegate {
return flag; return flag;
} }
} }
class SliverGridDelegateWithMaxCrossAxisExtent extends SliverGridDelegate {
/// Creates a delegate that makes grid layouts with tiles that have a maximum
/// cross-axis extent.
///
/// The [maxCrossAxisExtent], [mainAxisExtent], [mainAxisSpacing],
/// and [crossAxisSpacing] arguments must not be negative.
/// The [childAspectRatio] argument must be greater than zero.
SliverGridDelegateWithMaxCrossAxisExtent({
required this.maxCrossAxisExtent,
this.mainAxisSpacing = 0.0,
this.crossAxisSpacing = 0.0,
this.childAspectRatio = 1.0,
this.mainAxisExtent,
}) : assert(maxCrossAxisExtent > 0),
assert(mainAxisSpacing >= 0),
assert(crossAxisSpacing >= 0),
assert(childAspectRatio > 0),
assert(mainAxisExtent == null || mainAxisExtent >= 0);
/// The maximum extent of tiles in the cross axis.
///
/// This delegate will select a cross-axis extent for the tiles that is as
/// large as possible subject to the following conditions:
///
/// - The extent evenly divides the cross-axis extent of the grid.
/// - The extent is at most [maxCrossAxisExtent].
///
/// For example, if the grid is vertical, the grid is 500.0 pixels wide, and
/// [maxCrossAxisExtent] is 150.0, this delegate will create a grid with 4
/// columns that are 125.0 pixels wide.
final double maxCrossAxisExtent;
/// The number of logical pixels between each child along the main axis.
final double mainAxisSpacing;
/// The number of logical pixels between each child along the cross axis.
final double crossAxisSpacing;
/// The ratio of the cross-axis to the main-axis extent of each child.
final double childAspectRatio;
/// The extent of each tile in the main axis. If provided it would define the
/// logical pixels taken by each tile in the main-axis.
///
/// If null, [childAspectRatio] is used instead.
final double? mainAxisExtent;
bool _debugAssertIsValid(double crossAxisExtent) {
assert(crossAxisExtent > 0.0);
assert(maxCrossAxisExtent > 0.0);
assert(mainAxisSpacing >= 0.0);
assert(crossAxisSpacing >= 0.0);
assert(childAspectRatio > 0.0);
return true;
}
SliverGridLayout? layoutCache;
double? crossAxisExtentCache;
@override
SliverGridLayout getLayout(SliverConstraints constraints) {
assert(_debugAssertIsValid(constraints.crossAxisExtent));
if (layoutCache != null &&
constraints.crossAxisExtent == crossAxisExtentCache) {
return layoutCache!;
}
crossAxisExtentCache = constraints.crossAxisExtent;
int crossAxisCount =
(constraints.crossAxisExtent / (maxCrossAxisExtent + crossAxisSpacing))
.ceil();
// Ensure a minimum count of 1, can be zero and result in an infinite extent
// below when the window size is 0.
crossAxisCount = max(1, crossAxisCount);
final double usableCrossAxisExtent = max(
0.0,
constraints.crossAxisExtent - crossAxisSpacing * (crossAxisCount - 1),
);
final double childCrossAxisExtent = usableCrossAxisExtent / crossAxisCount;
final double childMainAxisExtent =
mainAxisExtent ?? childCrossAxisExtent / childAspectRatio;
return layoutCache = SliverGridRegularTileLayout(
crossAxisCount: crossAxisCount,
mainAxisStride: childMainAxisExtent + mainAxisSpacing,
crossAxisStride: childCrossAxisExtent + crossAxisSpacing,
childMainAxisExtent: childMainAxisExtent,
childCrossAxisExtent: childCrossAxisExtent,
reverseCrossAxis: axisDirectionIsReversed(constraints.crossAxisDirection),
);
}
@override
bool shouldRelayout(SliverGridDelegateWithMaxCrossAxisExtent oldDelegate) {
final flag =
oldDelegate.maxCrossAxisExtent != maxCrossAxisExtent ||
oldDelegate.mainAxisSpacing != mainAxisSpacing ||
oldDelegate.crossAxisSpacing != crossAxisSpacing ||
oldDelegate.childAspectRatio != childAspectRatio ||
oldDelegate.mainAxisExtent != mainAxisExtent;
if (flag) layoutCache = null;
return flag;
}
}