From 6f51330a8f7b1cdadc3c27898b6f1cf295c58229 Mon Sep 17 00:00:00 2001 From: teikengstudio <337756906+teikengstudio@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:27:04 +0800 Subject: [PATCH] fix: guard player semantics and improve creator browsing (#288) --- lib/api/xmly_anchor.dart | 349 ++++++++++++- lib/api/xmly_client.dart | 68 ++- lib/pages/anchor_following_page.dart | 23 +- lib/pages/anchor_page.dart | 704 ++++++++++++++++++++++++--- lib/pages/catalogue_page.dart | 81 ++- lib/pages/playback_skip_control.dart | 17 +- lib/pages/player_panel.dart | 152 +++--- lib/pages/player_queue_panel.dart | 32 ++ lib/pages/shell_page.dart | 6 +- lib/services/player_service.dart | 102 +++- 10 files changed, 1312 insertions(+), 222 deletions(-) diff --git a/lib/api/xmly_anchor.dart b/lib/api/xmly_anchor.dart index 647e0ff..10735ec 100644 --- a/lib/api/xmly_anchor.dart +++ b/lib/api/xmly_anchor.dart @@ -27,9 +27,10 @@ class AnchorProfile { } class AnchorAlbum { - const AnchorAlbum({required this.album, this.playCount}); + const AnchorAlbum({required this.album, this.playCount, this.createdAt}); final Album album; final int? playCount; + final DateTime? createdAt; } class AnchorContentPage { @@ -37,8 +38,9 @@ class AnchorContentPage { required List items, required this.page, required this.hasMore, - required this.pageSize, + this.pageSize = 20, this.total, + this.reportedTotal, }) : items = List.unmodifiable(items) { AppLog.instance.trace("lib/api/xmly_anchor.dart::AnchorContentPage.new"); } @@ -47,15 +49,17 @@ class AnchorContentPage { final int page, pageSize; final bool hasMore; final int? total; + final int? reportedTotal; } -/// Public creator endpoints deliberately use no account cookies. +/// Public creator content uses no cookies; following belongs to its account. class XmlyAnchor { XmlyAnchor(this.client) { AppLog.instance.trace("lib/api/xmly_anchor.dart::XmlyAnchor.new"); } final XmlyClient client; + final Map _albumDates = {}; static const pageSize = 20; static const _invalid = XmlyException('invalid_anchor', '主播资料暂时无法读取,请重试'); @@ -179,16 +183,55 @@ class XmlyAnchor { ); } + Future isFollowing(String uid) async { + AppLog.instance.trace("lib/api/xmly_anchor.dart::XmlyAnchor.isFollowing"); + if (client.credentials == null) { + throw const XmlyException('login_required', '请先登录后关注主播'); + } + final id = xmlyIdentifier(uid); + final response = await client.request( + 'GET', + XmlyClient.searchOrigin, + '/revision/user/basic', + query: {'uid': id}, + ); + final data = xmlyMap(response['data']); + final followed = xmlyMap(data['relation'])['isFollow']; + if ('${data['uid']}' != id || followed is! bool) throw _invalid; + return followed; + } + + Future setFollowing(String uid, {required bool following}) async { + AppLog.instance.trace("lib/api/xmly_anchor.dart::XmlyAnchor.setFollowing"); + if (client.credentials == null) { + throw const XmlyException('login_required', '请先登录后关注主播'); + } + final id = xmlyIdentifier(uid); + if (id == client.credentials!.uid) { + throw const XmlyException('invalid_anchor', '不能关注自己'); + } + await client.request( + 'POST', + XmlyClient.searchOrigin, + following + ? '/revision/follow/setFollow' + : '/revision/follow/cancelFollow', + data: {'followingUid': id}, + ); + } + Future> albums( String uid, { int page = 1, + int pageSize = 10, }) async { AppLog.instance.trace("lib/api/xmly_anchor.dart::XmlyAnchor.albums"); + final pc = pageSize == 10; return _content( uid, page, - '/simple-revision-for-pc/user/pub', + pc ? '/simple-revision-for-pc/user/pub' : '/revision/user/pub', 'albumList', (row) { AppLog.instance.trace( @@ -199,6 +242,7 @@ class XmlyAnchor { album: Album.fromApi({ ...row, 'albumId': xmlyIdentifier('${row['id'] ?? row['albumId'] ?? ''}'), + 'uid': row['anchorUid'] ?? row['uid'], 'nickname': row['anchorNickName'], 'cover_url': _image(row['coverPath'])?.toString(), 'intro': row['description'], @@ -207,36 +251,281 @@ class XmlyAnchor { playCount: _count(row['playCount']), ); }, - requestedSize: 10, - pc: true, + requestedSize: pageSize, + filters: const {'orderType': 2}, + pc: pc, ); } - Future> tracks(String uid, {int page = 1}) async { + Future> tracks( + String uid, { + int page = 1, + int pageSize = XmlyAnchor.pageSize, + }) async { AppLog.instance.trace("lib/api/xmly_anchor.dart::XmlyAnchor.tracks"); - return _content( - uid, - page, - '/simple-revision-for-pc/user/track', - 'trackList', - (row) { + if (page < 1 || page > 10000 || pageSize < 1 || pageSize > 100) { + throw const XmlyException('invalid_page', '无法继续翻页,请刷新后重试'); + } + final id = xmlyIdentifier(uid); + final response = await client.request( + 'GET', + XmlyClient.welfare, + '/m-revision/common/anchor/queryAnchorTracksByPage', + query: {'anchorId': id, 'page': page, 'pageSize': pageSize, 'asc': false}, + account: false, + ); + final data = xmlyMap(response['data']); + final returnedSize = _count(data['pageSize']); + if (_count(data['page']) != page || + returnedSize == null || + returnedSize > pageSize) { + throw const XmlyException('repeated_page', '列表分页未前进,请刷新后重试'); + } + final rows = data['trackDetailInfos']; + final reportedTotal = _count(data['totalCount']); + if (rows is! List || + rows.length > pageSize || + (returnedSize != pageSize && returnedSize != rows.length) || + reportedTotal == null) { + throw _invalid; + } + final total = reportedTotal > 5000 ? 5000 : reportedTotal; + final items = []; + for (final row in rows) { + if (row is! Map) throw _invalid; + final info = xmlyMap(row['trackInfo']); + final stats = xmlyMap(row['statCountInfo']); + final number = xmlyPositive(info['id']); + final createdTime = xmlyPositive(info['createdTime']); + if (number == null || + '${row['id']}' != '$number' || + '${info['anchorId']}' != id || + createdTime == null || + createdTime > 8640000000000000 || + _text(info['title']).isEmpty) { + throw _invalid; + } + items.add( + Track.fromApi({ + ...info, + 'trackId': number, + 'uid': id, + 'cover_url': _mobileImage(info['cover'])?.toString(), + // These public raw fields already survive Track serialization. + 'date': createdTime, + 'play': _count(stats['playCount']) ?? 0, + }), + ); + } + return AnchorContentPage( + items: items, + page: page, + pageSize: pageSize, + total: total, + reportedTotal: reportedTotal, + hasMore: page * pageSize < total, + ); + } + + static Uri? _mobileImage(Object? value) { + AppLog.instance.trace("lib/api/xmly_anchor.dart::XmlyAnchor._mobileImage"); + + final text = _text(value); + if (text.isEmpty) return null; + if (text.startsWith('https://') || + text.startsWith('http://') || + text.startsWith('//')) { + return _image(text); + } + if (!RegExp(r'^(?:group[0-9]+|storages)/').hasMatch(text) || + text.contains('\\') || + text.split('/').contains('..') || + RegExp(r'[\x00-\x20?#]').hasMatch(text)) { + return null; + } + return _image('https://imagev2.xmcdn.com/$text'); + } + + Future> allAlbums( + String uid, { + void Function(int, int?)? onProgress, + bool withDates = false, + }) async { + AppLog.instance.trace("lib/api/xmly_anchor.dart::XmlyAnchor.allAlbums"); + + final source = await _all( + (page) { AppLog.instance.trace( - "lib/api/xmly_anchor.dart::XmlyAnchor.tracks.closure#1", + "lib/api/xmly_anchor.dart::XmlyAnchor.allAlbums.closure#1", ); + return albums(uid, page: page, pageSize: 100); + }, + (item) { + AppLog.instance.trace( + "lib/api/xmly_anchor.dart::XmlyAnchor.allAlbums.closure#2", + ); + return item.album.id; + }, + onProgress, + allowFilteredItems: true, + ); + return withDates ? _withAlbumDates(uid, source, onProgress) : source; + } + + Future> _withAlbumDates( + String uid, + AnchorContentPage source, + void Function(int, int?)? onProgress, + ) async { + AppLog.instance.trace( + "lib/api/xmly_anchor.dart::XmlyAnchor._withAlbumDates", + ); + + final id = xmlyIdentifier(uid); + final enriched = List.filled(source.items.length, null); + var cursor = 0; + var completed = 0; + var failed = false; + onProgress?.call(0, source.items.length); + Future worker() async { + AppLog.instance.trace( + "lib/api/xmly_anchor.dart::XmlyAnchor._withAlbumDates.worker", + ); + + try { + while (!failed && cursor < source.items.length) { + final index = cursor++; + final item = source.items[index]; + final key = '$id:${item.album.id}'; + var date = item.createdAt ?? _albumDates[key]; + if (date == null) { + final data = await _get('/revision/album/v1/simple', { + 'albumId': item.album.id, + }); + final main = xmlyMap(data['albumPageMainInfo']); + if ('${data['albumId']}' != item.album.id || + '${main['anchorUid']}' != id) { + throw _invalid; + } + final value = _text(main['createDate']); + if (!RegExp(r'^[0-9]{4}-[0-9]{2}-[0-9]{2}$').hasMatch(value)) { + throw _invalid; + } + date = DateTime.tryParse(value); + if (date == null || + date.year != int.parse(value.substring(0, 4)) || + date.month != int.parse(value.substring(5, 7)) || + date.day != int.parse(value.substring(8, 10))) { + throw _invalid; + } + _albumDates[key] = date; + } + enriched[index] = AnchorAlbum( + album: item.album, + playCount: item.playCount, + createdAt: date, + ); + onProgress?.call(++completed, source.items.length); + } + } catch (_) { + failed = true; + rethrow; + } + } - return Track.fromApi({ - ...row, - 'trackId': xmlyIdentifier('${row['trackId'] ?? row['id'] ?? ''}'), - 'cover_url': _image(row['coverPath'])?.toString(), - 'duration': row['length'] is num ? row['length'] : 0, - }); + await Future.wait([for (var i = 0; i < 4; i++) worker()]); + final items = []; + for (final item in enriched) { + if (item == null) throw _invalid; + items.add(item); + } + return AnchorContentPage( + items: items, + page: source.page, + pageSize: source.pageSize, + hasMore: false, + total: source.total, + reportedTotal: source.reportedTotal, + ); + } + + Future> allTracks( + String uid, { + void Function(int, int?)? onProgress, + }) { + AppLog.instance.trace("lib/api/xmly_anchor.dart::XmlyAnchor.allTracks"); + + return _all( + (page) { + AppLog.instance.trace( + "lib/api/xmly_anchor.dart::XmlyAnchor.allTracks.closure#1", + ); + return tracks(uid, page: page, pageSize: 100); }, - requestedSize: 15, - pc: true, + (item) { + AppLog.instance.trace( + "lib/api/xmly_anchor.dart::XmlyAnchor.allTracks.closure#2", + ); + return item.id; + }, + onProgress, ); } + Future> _all( + Future> Function(int) fetch, + String Function(T) id, + void Function(int, int?)? onProgress, { + bool allowFilteredItems = false, + }) async { + AppLog.instance.trace("lib/api/xmly_anchor.dart::XmlyAnchor._all"); + + final items = []; + final seen = {}; + int? expectedTotal; + int? reportedTotal; + for (var page = 1; page <= 10000; page++) { + final result = await fetch(page); + expectedTotal ??= result.total; + reportedTotal ??= result.reportedTotal; + if (result.total != expectedTotal || + result.reportedTotal != reportedTotal) { + throw const XmlyException('catalogue_changed', '列表已更新,请重新排序'); + } + for (final item in result.items) { + if (!seen.add(id(item))) { + throw const XmlyException('repeated_page', '列表分页重复,请刷新后重试'); + } + items.add(item); + } + onProgress?.call(items.length, expectedTotal); + if (!result.hasMore) { + // Public album pages can omit unavailable entries after calculating + // their total and offsets. Keep paging through those holes, then use + // the visible count. Other endpoints still require their complete total. + if (expectedTotal != null && + (items.length > expectedTotal || + !allowFilteredItems && items.length != expectedTotal)) { + throw const XmlyException('incomplete_catalogue', '列表尚未加载完整,请重试'); + } + return AnchorContentPage( + items: items, + page: page, + pageSize: result.pageSize, + hasMore: false, + total: items.length, + reportedTotal: reportedTotal, + ); + } + if (result.items.isEmpty && + (!allowFilteredItems || expectedTotal == null)) { + throw const XmlyException('repeated_page', '列表分页未前进,请刷新后重试'); + } + } + throw const XmlyException('invalid_page', '无法继续翻页,请刷新后重试'); + } + Future> following( String uid, { int page = 1, @@ -281,12 +570,13 @@ class XmlyAnchor { String key, T Function(Map) decode, { int requestedSize = pageSize, + int? maximumTotal, Map filters = const {}, bool pc = false, }) async { AppLog.instance.trace("lib/api/xmly_anchor.dart::XmlyAnchor._content"); - if (page < 1 || page > 10000) { + if (page < 1 || page > 10000 || requestedSize < 1 || requestedSize > 100) { throw const XmlyException('invalid_page', '无法继续翻页,请刷新后重试'); } final identifier = xmlyIdentifier(uid); @@ -307,24 +597,33 @@ class XmlyAnchor { final maximum = _count(data['maxCount']); if (maximum != null && (total == null || maximum < total)) total = maximum; final size = _count(data['pageSize']); + final filteredAlbum = !pc && path == '/revision/user/pub'; if ((pc && (total == null || size == null)) || (data['pageSize'] != null && size == null) || (size != null && size > 100) || - (size == 0 && (total != 0 || rows.isNotEmpty)) || + (size == 0 && (rows.isNotEmpty || total != 0 && !filteredAlbum)) || (size != null && rows.length > size) || (total != null && rows.length > total)) throw _invalid; - final effectiveSize = size == 0 ? 1 : size ?? requestedSize; + // PC endpoints report their actual fixed page stride. The website album + // endpoint instead shrinks pageSize on partial/filtered pages while its + // offsets keep using the requested size. + final effectiveSize = pc && size != null && size > 0 ? size : requestedSize; final items = []; for (final row in rows) { if (row is! Map) throw _invalid; items.add(decode(row)); } + final reportedTotal = total; + if (maximumTotal != null && total != null && total > maximumTotal) { + total = maximumTotal; + } return AnchorContentPage( items: items, page: page, pageSize: effectiveSize, total: total, + reportedTotal: reportedTotal, hasMore: total != null ? page * effectiveSize < total : items.length >= effectiveSize, diff --git a/lib/api/xmly_client.dart b/lib/api/xmly_client.dart index 215c041..73162d3 100644 --- a/lib/api/xmly_client.dart +++ b/lib/api/xmly_client.dart @@ -174,21 +174,22 @@ class XmlyClient { RegExp(r'^/mobile/track/pay/[1-9][0-9]{0,18}/ts-[0-9]+$') .hasMatch(path); if (origin == searchOrigin) - return method == 'GET' && - const { - '/revision/search', - '/revision/track/simple', - '/revision/comment/queryReplies', - '/revision/user/basic', - '/revision/user/pub', - '/revision/user/track', - '/revision/user/following', - '/revision/album/v1/simple', - '/revision/category/v2/allCategory', - '/revision/category/v2/albums', - '/revision/rank/v3/cluster', - '/revision/rank/v3/element', - }.contains(path); + return _webAccountEndpoint(method, path) || + (method == 'GET' && + const { + '/revision/search', + '/revision/track/simple', + '/revision/comment/queryReplies', + '/revision/user/basic', + '/revision/user/pub', + '/revision/user/track', + '/revision/user/following', + '/revision/album/v1/simple', + '/revision/category/v2/allCategory', + '/revision/category/v2/albums', + '/revision/rank/v3/cluster', + '/revision/rank/v3/element', + }.contains(path)); if (origin == pcOrigin) return method == 'GET' && const { @@ -208,7 +209,8 @@ class XmlyClient { if (origin == collector) return method == 'POST' && path == '/nyx/v1/history/merge/android'; if (origin == welfare) - return (method == 'GET' && + return _publicAnchorTrackEndpoint(method, origin, path) || + (method == 'GET' && RegExp( r'^/lite-earn/ting/welfare/queryVipDurationTask/ts-[0-9]+$', ).hasMatch(path)) || @@ -260,6 +262,31 @@ class XmlyClient { .hasMatch(path)); } + static bool _webAccountEndpoint(String method, String path) { + AppLog.instance.trace( + "lib/api/xmly_client.dart::XmlyClient._webAccountEndpoint", + ); + return (method == 'GET' && path == '/revision/user/basic') || + (method == 'POST' && + const { + '/revision/follow/setFollow', + '/revision/follow/cancelFollow', + }.contains(path)); + } + + static bool _publicAnchorTrackEndpoint( + String method, + String origin, + String path, + ) { + AppLog.instance.trace( + "lib/api/xmly_client.dart::XmlyClient._publicAnchorTrackEndpoint", + ); + return method == 'GET' && + origin == welfare && + path == '/m-revision/common/anchor/queryAnchorTracksByPage'; + } + static Duration _retryAfter(String? value) { AppLog.instance.trace("lib/api/xmly_client.dart::XmlyClient._retryAfter"); return serverRetryAfter(value) ?? const Duration(seconds: 30); @@ -436,8 +463,11 @@ class XmlyClient { throw const XmlyException('client_closed', '连接已关闭', definitive: true); method = method.toUpperCase(); if (!_endpoint(method, origin, path) || + (account && _publicAnchorTrackEndpoint(method, origin, path)) || + (account && const {pcOrigin, hotWordsOrigin}.contains(origin)) || (account && - const {searchOrigin, pcOrigin, hotWordsOrigin}.contains(origin))) + origin == searchOrigin && + !_webAccountEndpoint(method, path))) throw const XmlyException( 'invalid_endpoint', '请求地址不受支持', @@ -619,6 +649,10 @@ class XmlyClient { 'Accept': origin == collector ? '*/*' : 'application/json', if (origin == collector) 'User-Agent': 'ting_3.4.10.3(Android,30)', if (authenticated) 'Cookie': credentials!.cookie, + if (authenticated && origin == searchOrigin) ...{ + 'Origin': searchOrigin, + 'Referer': '$searchOrigin/', + }, if (signed) 'x-tk': XmlyCrypto.freshTicket( credentials!, diff --git a/lib/pages/anchor_following_page.dart b/lib/pages/anchor_following_page.dart index 21bd167..ba66961 100644 --- a/lib/pages/anchor_following_page.dart +++ b/lib/pages/anchor_following_page.dart @@ -280,13 +280,18 @@ class _AnchorFollowingPageState extends State { unawaited(_load()); } - void _open(AnchorProfile anchor) { + Future _open(AnchorProfile anchor) async { AppLog.instance.trace( "lib/pages/anchor_following_page.dart::_AnchorFollowingPageState._open", ); + final generation = _generation; + final identities = Map.of(widget.accountIdentities); final accountIdentity = _originIdentities[anchor.uid]; - Navigator.of(context).push( + final runtime = widget.runtime, revision = runtime.libraryRevision; + final primary = runtime.accounts.primaryAccountId; + final uids = _uids, accounts = runtime.accounts.accountIds.toSet(); + await Navigator.of(context).push( MaterialPageRoute( settings: const RouteSettings(name: AnchorPage.routeName), builder: (_) { @@ -304,6 +309,20 @@ class _AnchorFollowingPageState extends State { }, ), ); + if (!_current(generation) || + !mapEquals(widget.accountIdentities, identities) || + !identical(widget.runtime, runtime) || + runtime.libraryRevision == revision) + return; + final currentUids = _uids; + final currentAccounts = runtime.accounts.accountIds.toSet(); + if (runtime.accounts.primaryAccountId != primary || + currentUids.length != uids.length || + !currentUids.containsAll(uids) || + currentAccounts.length != accounts.length || + !currentAccounts.containsAll(accounts)) + return; + await _refresh(); } Widget _footer() { diff --git a/lib/pages/anchor_page.dart b/lib/pages/anchor_page.dart index 237304c..6d7c19c 100644 --- a/lib/pages/anchor_page.dart +++ b/lib/pages/anchor_page.dart @@ -2,13 +2,14 @@ import 'dart:async'; import 'dart:math' as math; import 'package:flutter/material.dart'; -import 'package:url_launcher/url_launcher.dart'; import '../common/widgets/app_scrollbar.dart'; import '../api/xmly_anchor.dart'; +import '../api/xmly_client.dart'; import '../common/widgets/adaptive_text.dart'; import '../common/widgets/app_header.dart'; import '../common/widgets/content_paging.dart'; +import '../common/widgets/app_tab_button.dart'; import '../common/widgets/logged_network_image.dart'; import '../models/xmly_models.dart'; import '../services/app_log.dart'; @@ -45,13 +46,33 @@ class AnchorPage extends StatefulWidget { } } +enum _AnchorOrder { defaultOrder, latest, oldest, popular } + class _AnchorListing { - List items = []; - int page = 0, pageSize = 1, requestedPage = 1, generation = 0; - int? total; - bool busy = false; + _AnchorListing({required this.pageSize}) { + AppLog.instance.trace("lib/pages/anchor_page.dart::_AnchorListing.new"); + } + + List items = [], source = []; + int page = 0, requestedPage = 1, pageSize; + int? total, reportedTotal, sourceReportedTotal; + _AnchorOrder order = _AnchorOrder.defaultOrder; Completer? cancelled; + int request = 0, loaded = 0; + int? loadingTotal; + bool busy = false, + sourceReady = false, + refreshNeeded = false, + datesReady = false; String? error; + + void cancel() { + AppLog.instance.trace("lib/pages/anchor_page.dart::_AnchorListing.cancel"); + request++; + cancelled?.complete(); + cancelled = null; + busy = false; + } } class _AnchorPageState extends State @@ -70,10 +91,14 @@ class _AnchorPageState extends State String? _uid, _resolveError, _profileError; AnchorProfile? _profile; bool _resolving = true, _profileBusy = false; - bool _openingFollow = false; bool _expanded = false; - _AnchorListing _albums = _AnchorListing(); - _AnchorListing _tracks = _AnchorListing(); + XmlyClient? _followClient; + String? _followKey, _followError; + bool? _following; + bool _followBusy = false, _followMutating = false; + int _followRequest = 0, _libraryRevision = -1; + _AnchorListing _albums = _AnchorListing(pageSize: 10); + _AnchorListing _tracks = _AnchorListing(pageSize: 20); @override void initState() { @@ -83,6 +108,7 @@ class _AnchorPageState extends State super.initState(); _tabs = TabController(length: 2, vsync: this)..addListener(_selectTab); + widget.runtime.addListener(_runtimeChanged); _refresh(); } @@ -93,6 +119,10 @@ class _AnchorPageState extends State ); super.didUpdateWidget(oldWidget); + if (oldWidget.runtime != widget.runtime) { + oldWidget.runtime.removeListener(_runtimeChanged); + widget.runtime.addListener(_runtimeChanged); + } if (oldWidget.runtime != widget.runtime || oldWidget.accountIdentity != widget.accountIdentity || oldWidget.uid != widget.uid || @@ -110,10 +140,12 @@ class _AnchorPageState extends State _generation++; _playRequest++; + _followRequest++; + widget.runtime.removeListener(_runtimeChanged); _cancelled.complete(); + _albums.cancel(); + _tracks.cancel(); _tabs.dispose(); - _albums.cancelled?.complete(); - _tracks.cancelled?.complete(); for (final scroll in _scrolls) { scroll.dispose(); } @@ -143,7 +175,9 @@ class _AnchorPageState extends State return action(XmlyAnchor(client)); }, rateLimitRetries: 0, - cancelled: cancelled ?? _cancelled.future, + cancelled: cancelled == null + ? _cancelled.future + : Future.any([_cancelled.future, cancelled]), ); } @@ -169,11 +203,11 @@ class _AnchorPageState extends State ); final generation = ++_generation; + _albums.cancel(); + _tracks.cancel(); _cancelled.complete(); _cancelled = Completer(); _playRequest++; - _albums.cancelled?.complete(); - _tracks.cancelled?.complete(); setState(() { AppLog.instance.trace( "lib/pages/anchor_page.dart::_AnchorPageState._refresh.closure#1", @@ -185,8 +219,12 @@ class _AnchorPageState extends State _resolving = true; _profileBusy = false; _expanded = false; - _albums = _AnchorListing(); - _tracks = _AnchorListing(); + _albums = _AnchorListing(pageSize: 10)..order = _albums.order; + _tracks = _AnchorListing(pageSize: 20)..order = _tracks.order; + _followRequest++; + _following = null; + _followError = null; + _followBusy = _followMutating = false; }); try { final uid = widget.uid != null @@ -208,7 +246,7 @@ class _AnchorPageState extends State _uid = uid; _resolving = false; }); - await Future.wait([_loadProfile(), _loadSelected()]); + await Future.wait([_loadProfile(), _loadSelected(), _loadFollowing()]); } catch (error, stack) { if (!_current(generation)) return; _record('Resolving anchor failed', error, stack); @@ -225,10 +263,23 @@ class _AnchorPageState extends State Future _reload() async { AppLog.instance.trace( - 'lib/pages/anchor_page.dart::_AnchorPageState._reload', + "lib/pages/anchor_page.dart::_AnchorPageState._reload", ); if (_uid == null) return _refresh(); - await Future.wait([_loadProfile(), _loadSelected(page: 1)]); + if (_selected == 0) { + _albums.cancel(); + _albums.source = []; + _albums.sourceReady = _albums.datesReady = false; + } else { + _tracks.cancel(); + _tracks.source = []; + _tracks.sourceReady = _tracks.datesReady = false; + } + await Future.wait([ + _loadProfile(), + _loadSelected(page: 1), + _loadFollowing(), + ]); } Future _loadProfile() async { @@ -286,75 +337,351 @@ class _AnchorPageState extends State ); if (_selected == 0) { - return _load(_albums, (api, uid, page) { + return _load( + _albums, + (api, uid, page) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._loadSelected.closure#1", + ); + return api.albums(uid, page: page); + }, + (album) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._loadSelected.closure#2", + ); + return album.album.id; + }, + (api, uid, progress) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._loadSelected.closure#3", + ); + return api.allAlbums( + uid, + withDates: + _albums.order == _AnchorOrder.latest || + _albums.order == _AnchorOrder.oldest, + onProgress: progress, + ); + }, + (item) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._loadSelected.closure#4", + ); + return item.playCount ?? 0; + }, + page: page ?? _albums.requestedPage, + ); + } + return _load( + _tracks, + (api, uid, page) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._loadSelected.closure#5", + ); + return api.tracks(uid, page: page); + }, + (track) { AppLog.instance.trace( - "lib/pages/anchor_page.dart::_AnchorPageState._loadSelected.closure#1", + "lib/pages/anchor_page.dart::_AnchorPageState._loadSelected.closure#6", ); - return api.albums(uid, page: page); - }, page: page ?? _albums.requestedPage); + return track.id; + }, + (api, uid, progress) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._loadSelected.closure#7", + ); + return api.allTracks(uid, onProgress: progress); + }, + _trackPlays, + page: page ?? _tracks.requestedPage, + ); + } + + int _trackPlays(Track track) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._trackPlays", + ); + + return xmlyPositive(track.raw['play']) ?? 0; + } + + String _trackDescription(Track track) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._trackDescription", + ); + + final timestamp = xmlyPositive(track.raw['date']); + final date = timestamp == null + ? '' + : DateTime.fromMillisecondsSinceEpoch(timestamp) + .toIso8601String() + .substring(0, 10); + return [ + if (track.album.isNotEmpty) track.album, + if (date.isNotEmpty) date, + '${track.duration ~/ 60}:${(track.duration.toInt() % 60).toString().padLeft(2, '0')}', + '${_count(_trackPlays(track))} 次播放', + ].join(' · '); + } + + int? _createdAt(Object? item) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._createdAt", + ); + + return switch (item) { + AnchorAlbum() => item.createdAt?.millisecondsSinceEpoch, + Track() => xmlyPositive(item.raw['date']), + _ => null, + }; + } + + bool _hasDate(Object? item) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._hasDate", + ); + + return _createdAt(item) != null; + } + + List _ordered(_AnchorListing listing, int Function(T) plays) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._ordered", + ); + + switch (listing.order) { + case _AnchorOrder.defaultOrder: + return List.of(listing.source); + case _AnchorOrder.latest: + case _AnchorOrder.oldest: + case _AnchorOrder.popular: + final ranked = listing.source.asMap().entries.toList(); + ranked.sort((a, b) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._ordered.closure#1", + ); + + final int result; + if (listing.order == _AnchorOrder.popular) { + result = plays(b.value).compareTo(plays(a.value)); + } else { + final aDate = _createdAt(a.value), bDate = _createdAt(b.value); + result = aDate == null + ? (bDate == null ? 0 : 1) + : bDate == null + ? -1 + : listing.order == _AnchorOrder.latest + ? bDate.compareTo(aDate) + : aDate.compareTo(bDate); + } + return result == 0 ? a.key.compareTo(b.key) : result; + }); + return ranked.map((entry) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._ordered.closure#2", + ); + return entry.value; + }).toList(); } - return _load(_tracks, (api, uid, page) { + } + + void _setListingOrder(_AnchorListing listing, _AnchorOrder order) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._setListingOrder", + ); + if (listing.order == order) return; + listing.cancel(); + setState(() { AppLog.instance.trace( - "lib/pages/anchor_page.dart::_AnchorPageState._loadSelected.closure#2", + "lib/pages/anchor_page.dart::_AnchorPageState._setListingOrder.closure#1", ); - return api.tracks(uid, page: page); - }, page: page ?? _tracks.requestedPage); + listing.order = order; + listing.requestedPage = 1; + listing.error = null; + listing.items = []; + }); + unawaited(_loadSelected(page: 1)); + } + + void _showSourcePage( + _AnchorListing listing, + int Function(T) plays, + int page, + ) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._showSourcePage", + ); + final ordered = _ordered(listing, plays); + final last = math.max(1, (ordered.length / listing.pageSize).ceil()); + final target = page.clamp(1, last).toInt(); + listing.items = ordered + .skip((target - 1) * listing.pageSize) + .take(listing.pageSize) + .toList(); + listing.page = listing.requestedPage = target; + listing.total = ordered.length; + listing.reportedTotal = listing.sourceReportedTotal; + } + + Widget _orderControls() { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._orderControls", + ); + + final order = _selected == 0 ? _albums.order : _tracks.order; + return AppTabStrip( + children: [ + for (final entry in const { + _AnchorOrder.defaultOrder: '默认', + _AnchorOrder.latest: '最新', + _AnchorOrder.oldest: '最早', + _AnchorOrder.popular: '最多播放', + }.entries) + AppTabButton( + key: ValueKey('anchorOrder-${entry.key.name}'), + label: entry.value, + selected: order == entry.key, + onPressed: () { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._orderControls.closure#1", + ); + + if (_selected == 0) { + _setListingOrder(_albums, entry.key); + } else { + _setListingOrder(_tracks, entry.key); + } + }, + ), + ], + ); } Future _load( _AnchorListing listing, - Future> Function(XmlyAnchor, String, int) fetch, { + Future> Function(XmlyAnchor, String, int) fetch, + String Function(T) id, + Future> Function( + XmlyAnchor, + String, + void Function(int, int?), + ) + fetchAll, + int Function(T) plays, { required int page, }) async { - AppLog.instance.trace('lib/pages/anchor_page.dart::_AnchorPageState._load'); + AppLog.instance.trace("lib/pages/anchor_page.dart::_AnchorPageState._load"); final generation = _generation; final uid = _uid; - if (uid == null) return; - final request = ++listing.generation; - listing.cancelled?.complete(); + if (uid == null || page < 1) return; + listing.cancel(); + final request = listing.request; + final complete = listing.order != _AnchorOrder.defaultOrder; + final timeOrder = + listing.order == _AnchorOrder.latest || + listing.order == _AnchorOrder.oldest; + final scroll = identical(listing, _albums) ? _scrolls[0] : _scrolls[1]; + if (complete && listing.sourceReady && (!timeOrder || listing.datesReady)) { + setState(() { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._load.closure#1", + ); + listing.error = null; + listing.refreshNeeded = false; + _showSourcePage(listing, plays, page); + }); + if (scroll.hasClients) scroll.jumpTo(0); + return; + } final cancelled = listing.cancelled = Completer(); + bool active() { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._load.active", + ); + return _current(generation) && listing.request == request; + } + setState(() { AppLog.instance.trace( - 'lib/pages/anchor_page.dart::_AnchorPageState._load.closure#1', + "lib/pages/anchor_page.dart::_AnchorPageState._load.closure#2", ); listing.requestedPage = page; listing.busy = true; listing.error = null; + listing.refreshNeeded = false; + listing.loaded = 0; + listing.loadingTotal = listing.total; }); try { final next = await _read((api) { AppLog.instance.trace( - 'lib/pages/anchor_page.dart::_AnchorPageState._load.closure#2', + "lib/pages/anchor_page.dart::_AnchorPageState._load.closure#3", ); + if (complete) { + return fetchAll(api, uid, (loaded, total) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._load.closure#3.closure#1", + ); + if (!active()) return; + setState(() { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._load.closure#3.closure#1.closure#1", + ); + listing.loaded = loaded; + listing.loadingTotal = total; + }); + }); + } return fetch(api, uid, page); }, cancelled: cancelled.future); - if (!_current(generation) || request != listing.generation) return; + if (!active()) return; + final seen = {}; + for (final item in next.items) { + if (!seen.add(id(item))) { + throw const XmlyException('repeated_page', '列表分页重复,请刷新后重试'); + } + } setState(() { AppLog.instance.trace( - 'lib/pages/anchor_page.dart::_AnchorPageState._load.closure#3', + "lib/pages/anchor_page.dart::_AnchorPageState._load.closure#4", ); - listing.items = next.items; - listing.page = next.page; - listing.pageSize = next.pageSize; - listing.total = next.total; + listing.reportedTotal = next.reportedTotal; + if (complete) { + listing.source = next.items; + listing.sourceReportedTotal = next.reportedTotal; + listing.sourceReady = true; + listing.datesReady = listing.source.every(_hasDate); + _showSourcePage(listing, plays, page); + } else { + if (listing.sourceReady && + next.reportedTotal != listing.sourceReportedTotal) { + listing.source = []; + listing.sourceReady = listing.datesReady = false; + } + listing.items = next.items; + listing.page = next.page; + listing.pageSize = next.pageSize; + listing.total = next.total; + } }); - final scroll = identical(listing, _albums) ? _scrolls[0] : _scrolls[1]; if (scroll.hasClients) scroll.jumpTo(0); } catch (error, stack) { - if (!_current(generation) || request != listing.generation) return; + if (!active()) return; _record('Loading anchor content failed', error, stack); setState(() { AppLog.instance.trace( - 'lib/pages/anchor_page.dart::_AnchorPageState._load.closure#4', + "lib/pages/anchor_page.dart::_AnchorPageState._load.closure#5", ); + listing.refreshNeeded = + error is XmlyException && error.code == 'repeated_page'; listing.error = error is XmlyException ? error.message : '列表加载失败'; }); } finally { if (identical(listing.cancelled, cancelled)) listing.cancelled = null; - if (_current(generation) && request == listing.generation) { + if (active()) { setState(() { AppLog.instance.trace( - 'lib/pages/anchor_page.dart::_AnchorPageState._load.closure#5', + "lib/pages/anchor_page.dart::_AnchorPageState._load.closure#6", ); listing.busy = false; }); @@ -464,40 +791,206 @@ class _AnchorPageState extends State return '$value'; } - Future _openFollowPage() async { + XmlyClient get _primaryClient { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._primaryClient.get", + ); + + final accounts = widget.runtime.accounts; + final identity = accounts.primaryAccountId; + return identity != null && accounts.accountIds.contains(identity) + ? accounts.clientFor(identity) + : widget.runtime.anonymous; + } + + bool _sameFollow(XmlyClient client, String key, String uid, int request) { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._sameFollow", + ); + + return mounted && + request == _followRequest && + _uid == uid && + identical(client, _primaryClient) && + client.cacheIdentity == key; + } + + void _runtimeChanged() { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._runtimeChanged", + ); + + if (!mounted || _uid == null) return; + final client = _primaryClient; + final accountChanged = + !identical(client, _followClient) || client.cacheIdentity != _followKey; + final libraryChanged = widget.runtime.libraryRevision != _libraryRevision; + if (accountChanged) { + unawaited(_refresh()); + } else if (libraryChanged && !_followMutating) { + unawaited(_loadFollowing()); + } + } + + Future _loadFollowing() async { AppLog.instance.trace( - "lib/pages/anchor_page.dart::_AnchorPageState._openFollowPage", + "lib/pages/anchor_page.dart::_AnchorPageState._loadFollowing", ); final uid = _uid; - if (uid == null || _openingFollow) return; - final generation = _generation; + if (uid == null) return; + final client = _primaryClient, key = _primaryClient.cacheIdentity; + final request = ++_followRequest; + _followClient = client; + _followKey = key; + _libraryRevision = widget.runtime.libraryRevision; + final canRead = client.accountAvailable && client.credentials!.uid != uid; setState(() { AppLog.instance.trace( - "lib/pages/anchor_page.dart::_AnchorPageState._openFollowPage.closure#1", + "lib/pages/anchor_page.dart::_AnchorPageState._loadFollowing.closure#1", ); - _openingFollow = true; + + _following = null; + _followError = null; + _followBusy = canRead; + _followMutating = false; }); + if (!canRead) return; try { - if (!await launchUrl( - Uri.https('www.ximalaya.com', '/zhubo/$uid/'), - mode: LaunchMode.externalApplication, - )) { - throw StateError('The official anchor page could not be opened'); + final followed = await client.withReadPolicy( + () { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._loadFollowing.closure#2", + ); + return XmlyAnchor(client).isFollowing(uid); + }, + rateLimitRetries: 0, + cancelled: _cancelled.future, + ); + if (_sameFollow(client, key, uid, request)) { + setState(() { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._loadFollowing.closure#3", + ); + _following = followed; + }); } } catch (error, stack) { - _record('Opening official anchor page failed', error, stack); - if (_current(generation)) - ScaffoldMessenger.of(context) - .showSnackBar(const SnackBar(content: Text('网页打开失败,请重试'))); + if (!_sameFollow(client, key, uid, request)) return; + _record('Loading following status failed', error, stack); + setState(() { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._loadFollowing.closure#4", + ); + + _followError = error is XmlyException ? error.message : '关注状态加载失败,请重试'; + }); } finally { - if (mounted) + if (_sameFollow(client, key, uid, request)) { setState(() { AppLog.instance.trace( - "lib/pages/anchor_page.dart::_AnchorPageState._openFollowPage.closure#2", + "lib/pages/anchor_page.dart::_AnchorPageState._loadFollowing.closure#5", ); - _openingFollow = false; + _followBusy = false; }); + } + } + } + + Future _changeFollowing() async { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._changeFollowing", + ); + + final uid = _uid; + if (_followBusy || uid == null) return; + final runtime = widget.runtime; + final client = _primaryClient, key = _primaryClient.cacheIdentity; + if (!client.accountAvailable) { + setState(() { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._changeFollowing.closure#1", + ); + _followError = '请先登录主账号后关注主播'; + }); + return; + } + if (_following == null || + !identical(client, _followClient) || + key != _followKey) { + return _loadFollowing(); + } + final desired = !_following!, request = ++_followRequest; + var attempted = false; + setState(() { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._changeFollowing.closure#2", + ); + + _followBusy = _followMutating = true; + _followError = null; + }); + try { + await runtime.accounts.runWithAccount(client.identity, (admitted) async { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._changeFollowing.closure#3", + ); + + if (!_sameFollow(client, key, uid, request) || + !identical(client, admitted)) { + throw const XmlyException('account_changed', '主账号已变更,请重试'); + } + attempted = true; + await XmlyAnchor(admitted).setFollowing(uid, following: desired); + }); + runtime.libraryChanged(); + if (_sameFollow(client, key, uid, request)) { + setState(() { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._changeFollowing.closure#4", + ); + _following = desired; + }); + } + } catch (error, stack) { + _record('Changing following failed', error, stack); + if (attempted) runtime.libraryChanged(); + if (!_sameFollow(client, key, uid, request)) return; + setState(() { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._changeFollowing.closure#5", + ); + + _following = null; + _followError = error is XmlyException ? error.message : '关注操作未完成,请重试'; + }); + // Reconcile uncertain writes with a read; never replay a follow request. + if (attempted) { + try { + final followed = await XmlyAnchor(client).isFollowing(uid); + if (_sameFollow(client, key, uid, request)) { + setState(() { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._changeFollowing.closure#6", + ); + + _following = followed; + if (followed == desired) _followError = null; + }); + } + } catch (error, stack) { + _record('Reconciling following failed', error, stack); + } + } + } finally { + if (_sameFollow(client, key, uid, request)) { + setState(() { + AppLog.instance.trace( + "lib/pages/anchor_page.dart::_AnchorPageState._changeFollowing.closure#7", + ); + _followBusy = _followMutating = false; + }); + } } } @@ -506,17 +999,28 @@ class _AnchorPageState extends State "lib/pages/anchor_page.dart::_AnchorPageState._followButton", ); + final client = _primaryClient; + if (client.credentials?.uid == _uid) return const SizedBox.shrink(); return Tooltip( - message: '在喜马拉雅关注', + message: _following == true ? '使用主账号取消关注' : '使用主账号关注主播', child: OutlinedButton.icon( - onPressed: _openingFollow ? null : _openFollowPage, - icon: _openingFollow + key: const ValueKey('anchorFollow'), + onPressed: _followBusy ? null : _changeFollowing, + icon: _followBusy ? const SizedBox.square( dimension: 16, child: CircularProgressIndicator(strokeWidth: 2), ) - : const Icon(Icons.add, size: 18), - label: const Text('去关注'), + : Icon(_following == true ? Icons.check : Icons.add, size: 18), + label: Text( + !client.accountAvailable + ? '登录后关注' + : _following == true + ? '已关注' + : _following == null && _followError != null + ? '重试关注状态' + : '关注', + ), ), ); } @@ -773,6 +1277,14 @@ class _AnchorPageState extends State child: LinearProgressIndicator(minHeight: 2), ), if (_profileError != null) _retry(_profileError!, _loadProfile), + if (_followError != null) + Padding( + padding: const EdgeInsets.only(top: 12), + child: Text( + _followError!, + style: TextStyle(color: theme.colorScheme.error), + ), + ), ], ), ); @@ -803,14 +1315,28 @@ class _AnchorPageState extends State Widget _footer(_AnchorListing listing, String empty) { AppLog.instance.trace( - 'lib/pages/anchor_page.dart::_AnchorPageState._footer', + "lib/pages/anchor_page.dart::_AnchorPageState._footer", ); return Column( children: [ - if (listing.busy) + if (listing.busy) ...[ const LinearProgressIndicator(semanticsLabel: '正在加载作品'), - if (listing.error != null) _retry(listing.error!, _loadSelected), - if (listing.page > 0 && listing.items.isEmpty) + if (listing.order != _AnchorOrder.defaultOrder) + Padding( + padding: const EdgeInsets.all(12), + child: Text( + '正在排序 ${listing.loaded}' + '${listing.loadingTotal == null ? "" : " / ${listing.loadingTotal}"}', + ), + ), + ], + if (listing.error != null) + _retry( + listing.error!, + listing.refreshNeeded ? _refresh : _loadSelected, + label: listing.refreshNeeded ? '刷新' : '重试', + ), + if (!listing.busy && listing.page > 0 && listing.items.isEmpty) Padding( padding: const EdgeInsets.all(32), child: Center(child: Text(empty)), @@ -823,7 +1349,7 @@ class _AnchorPageState extends State busy: listing.busy, onPage: (page) { AppLog.instance.trace( - 'lib/pages/anchor_page.dart::_AnchorPageState._footer.closure#1', + "lib/pages/anchor_page.dart::_AnchorPageState._footer.closure#1", ); return _loadSelected(page: page); }, @@ -971,8 +1497,8 @@ class _AnchorPageState extends State tabAlignment: TabAlignment.start, dividerColor: Colors.transparent, indicatorSize: TabBarIndicatorSize.label, - labelPadding: const EdgeInsets.only( - right: 28, + labelPadding: const EdgeInsets.symmetric( + horizontal: 16, ), labelStyle: theme.textTheme.titleMedium ?.copyWith( @@ -1004,6 +1530,27 @@ class _AnchorPageState extends State ), ), ), + SliverPadding( + padding: EdgeInsets.symmetric(horizontal: padding), + sliver: SliverToBoxAdapter( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _orderControls(), + if (_selected == 1 && + (_tracks.reportedTotal ?? 0) > + (_tracks.total ?? 0)) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + '仅可查看前 ${_tracks.total} 条声音,排序限于这些内容', + style: theme.textTheme.bodySmall, + ), + ), + ], + ), + ), + ), if (_selected == 0) ...[ if (_albums.items.isNotEmpty) SliverPadding( @@ -1043,8 +1590,7 @@ class _AnchorPageState extends State overflow: TextOverflow.ellipsis, ), subtitle: AdaptiveText( - '${track.album}${track.album.isEmpty ? '' : ' · '}' - '${track.duration ~/ 60}:${(track.duration.toInt() % 60).toString().padLeft(2, '0')}', + _trackDescription(track), ), onTap: track.albumId.isEmpty ? null @@ -1293,7 +1839,11 @@ class _AnchorAlbumCard extends StatelessWidget { ), const SizedBox(height: 8), Text( - album.intro, + [ + if (item.createdAt case final date?) + date.toIso8601String().substring(0, 10), + if (album.intro.isNotEmpty) album.intro, + ].join(' · '), maxLines: 1, overflow: TextOverflow.ellipsis, style: theme.textTheme.bodyMedium?.copyWith( diff --git a/lib/pages/catalogue_page.dart b/lib/pages/catalogue_page.dart index 40e887c..0cfcb55 100644 --- a/lib/pages/catalogue_page.dart +++ b/lib/pages/catalogue_page.dart @@ -60,6 +60,8 @@ void _recordCatalogueError( 'insufficient_quota', 'usage_uncertain', 'rate_limited', + 'rejected', + 'permission_denied', 'queue_full', 'catalogue_limit', 'invalid_id', @@ -697,7 +699,7 @@ class _DiscoveryPageState extends State return Padding( padding: EdgeInsets.fromLTRB(padding, 12, padding, 8), child: Column( - crossAxisAlignment: CrossAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, children: [ ConstrainedBox( constraints: const BoxConstraints(maxWidth: 620), @@ -770,8 +772,8 @@ class _DiscoveryPageState extends State key: const ValueKey('searchCategoryTabs'), controller: _tabs, isScrollable: true, - tabAlignment: TabAlignment.start, - labelPadding: const EdgeInsets.only(left: 4, right: 28), + tabAlignment: TabAlignment.center, + labelPadding: const EdgeInsets.symmetric(horizontal: 16), labelColor: colors.primary, unselectedLabelColor: colors.onSurface, labelStyle: const TextStyle( @@ -1213,6 +1215,23 @@ class _DiscoveryPageState extends State ), sliver: SliverMainAxisGroup( slivers: [ + if (result.anchors.isNotEmpty) ...[ + _section( + '主播', + 'user', + result.totals['user'] ?? result.total, + result.anchors.length, + ), + SliverList.builder( + itemCount: result.anchors.length, + itemBuilder: (_, index) { + AppLog.instance.trace( + "lib/pages/catalogue_page.dart::_DiscoveryPageState.build.closure#1.closure#3", + ); + return _anchorTile(result.anchors[index]); + }, + ), + ], if (result.albums.isNotEmpty) ...[ _section( '专辑', @@ -1232,7 +1251,7 @@ class _DiscoveryPageState extends State itemCount: result.albums.length, itemBuilder: (_, index) { AppLog.instance.trace( - "lib/pages/catalogue_page.dart::_DiscoveryPageState.build.closure#1.closure#3", + "lib/pages/catalogue_page.dart::_DiscoveryPageState.build.closure#1.closure#4", ); return _albumCard( result.albums[index], @@ -1250,28 +1269,11 @@ class _DiscoveryPageState extends State ), SliverList.builder( itemCount: result.tracks.length, - itemBuilder: (_, index) { - AppLog.instance.trace( - "lib/pages/catalogue_page.dart::_DiscoveryPageState.build.closure#1.closure#4", - ); - return _trackTile(result.tracks[index]); - }, - ), - ], - if (result.anchors.isNotEmpty) ...[ - _section( - '主播', - 'user', - result.totals['user'] ?? result.total, - result.anchors.length, - ), - SliverList.builder( - itemCount: result.anchors.length, itemBuilder: (_, index) { AppLog.instance.trace( "lib/pages/catalogue_page.dart::_DiscoveryPageState.build.closure#1.closure#5", ); - return _anchorTile(result.anchors[index]); + return _trackTile(result.tracks[index]); }, ), ], @@ -2224,17 +2226,47 @@ class _AlbumPageViewState extends State { value: 'ascending', checked: _ascending, enabled: !_busy, - child: const Text('最早在前'), + child: const Text('正序(最早在前)'), ), CheckedPopupMenuItem( value: 'descending', checked: !_ascending, enabled: !_busy, - child: const Text('最新在前'), + child: const Text('倒序(最新在前)'), ), ]; } + Widget _orderControl() { + AppLog.instance.trace( + "lib/pages/catalogue_page.dart::_AlbumPageViewState._orderControl", + ); + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), + child: Row( + children: [ + Expanded(child: Text('声音 ($_total)')), + Tooltip( + message: _ascending ? '切换为最新在前' : '切换为最早在前', + child: TextButton.icon( + key: const ValueKey('albumOrderToggle'), + onPressed: _busy + ? null + : () { + AppLog.instance.trace( + "lib/pages/catalogue_page.dart::_AlbumPageViewState._orderControl.closure#1", + ); + _setOrder(!_ascending); + }, + icon: const Icon(Icons.swap_vert_rounded, size: 20), + label: Text(_ascending ? '正序' : '倒序'), + ), + ), + ], + ), + ); + } + Future> _all() async { AppLog.instance.trace( "lib/pages/catalogue_page.dart::_AlbumPageViewState._all", @@ -3221,6 +3253,7 @@ class _AlbumPageViewState extends State { ], ), ), + _orderControl(), if (_busy) const LinearProgressIndicator(), if (_error != null) Padding( diff --git a/lib/pages/playback_skip_control.dart b/lib/pages/playback_skip_control.dart index bc91b79..56c7540 100644 --- a/lib/pages/playback_skip_control.dart +++ b/lib/pages/playback_skip_control.dart @@ -23,8 +23,9 @@ Future showSkipSegmentsSettings( } class PlaybackSkipButton extends StatelessWidget { - const PlaybackSkipButton({required this.runtime, super.key}); + const PlaybackSkipButton({required this.runtime, this.onPressed, super.key}); final AppRuntime runtime; + final VoidCallback? onPressed; @override Widget build(BuildContext context) { @@ -49,12 +50,14 @@ class PlaybackSkipButton extends StatelessWidget { : '跳过片头片尾', color: enabled ? Theme.of(context).colorScheme.primary : null, icon: const Icon(Icons.content_cut_rounded), - onPressed: () { - AppLog.instance.trace( - "lib/pages/playback_skip_control.dart::PlaybackSkipButton.build.closure#1.closure#1", - ); - showSkipSegmentsSettings(context, runtime); - }, + onPressed: + onPressed ?? + () { + AppLog.instance.trace( + "lib/pages/playback_skip_control.dart::PlaybackSkipButton.build.closure#1.closure#1", + ); + showSkipSegmentsSettings(context, runtime); + }, ); }, ); diff --git a/lib/pages/player_panel.dart b/lib/pages/player_panel.dart index f86f47e..1deceb5 100644 --- a/lib/pages/player_panel.dart +++ b/lib/pages/player_panel.dart @@ -1466,6 +1466,13 @@ class _PlayerPanelState extends State { ); } + void _skipSegments() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._skipSegments", + ); + showSkipSegmentsSettings(_navigator.context, _runtime); + } + void _openAlbum(String albumId) { AppLog.instance.trace( "lib/pages/player_panel.dart::_PlayerPanelState._openAlbum", @@ -1695,77 +1702,83 @@ class _PlayerPanelState extends State { AppLog.instance.trace( "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider", ); - return SliderTheme( - data: SliderTheme.of(context).copyWith( - trackHeight: 3, - thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 5), - overlayShape: const RoundSliderOverlayShape(overlayRadius: 18), - inactiveTrackColor: colors.onSurface.withValues(alpha: 0.12), - ), - child: KeyedSubtree( - key: ValueKey((player, epoch, dock)), - child: Slider( - key: dock ? const ValueKey('dockSeekSlider') : null, - padding: EdgeInsets.symmetric( - vertical: dock ? 12 : 22, - horizontal: 5, - ), - value: position, - max: max > 0 ? max : 1, - label: playbackTime(position), - semanticFormatterCallback: playbackTime, - onChangeStart: track == null || max == 0 || _busy - ? null - : (_) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#1", - ); - _dragEpoch = epoch; - }, - onChanged: track == null || max == 0 || _busy - ? null - : (value) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#2", - ); - - if (_dragEpoch == epoch && - player.playbackEpoch == epoch) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#2.closure#1", - ); - _dragPosition = value; - }); - } - }, - onChangeEnd: track == null || max == 0 || _busy - ? null - : (value) async { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#3", - ); - - final selectedEpoch = _dragEpoch; - setState(() { + // A track change can remount this slider while a popup excludes the + // dock's semantics. Keep its value-indicator portal in that subtree. + return Overlay.wrap( + alwaysSizeToContent: true, + clipBehavior: Clip.none, + child: SliderTheme( + data: SliderTheme.of(context).copyWith( + trackHeight: 3, + thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 5), + overlayShape: const RoundSliderOverlayShape(overlayRadius: 18), + inactiveTrackColor: colors.onSurface.withValues(alpha: 0.12), + ), + child: KeyedSubtree( + key: ValueKey((player, epoch, dock)), + child: Slider( + key: dock ? const ValueKey('dockSeekSlider') : null, + padding: EdgeInsets.symmetric( + vertical: dock ? 12 : 22, + horizontal: 5, + ), + value: position, + max: max > 0 ? max : 1, + label: playbackTime(position), + semanticFormatterCallback: playbackTime, + onChangeStart: track == null || max == 0 || _busy + ? null + : (_) { AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#3.closure#1", + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#1", + ); + _dragEpoch = epoch; + }, + onChanged: track == null || max == 0 || _busy + ? null + : (value) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#2", ); - _dragPosition = null; - _dragEpoch = null; - }); - if (selectedEpoch != epoch || - player.playbackEpoch != epoch) { - return; - } - await _act(() { + if (_dragEpoch == epoch && + player.playbackEpoch == epoch) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#2.closure#1", + ); + _dragPosition = value; + }); + } + }, + onChangeEnd: track == null || max == 0 || _busy + ? null + : (value) async { AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#3.closure#2", + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#3", ); - return player.seek(value, expectedEpoch: epoch); - }); - }, + + final selectedEpoch = _dragEpoch; + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#3.closure#1", + ); + + _dragPosition = null; + _dragEpoch = null; + }); + if (selectedEpoch != epoch || + player.playbackEpoch != epoch) { + return; + } + await _act(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#3.closure#2", + ); + return player.seek(value, expectedEpoch: epoch); + }); + }, + ), ), ), ); @@ -1915,7 +1928,10 @@ class _PlayerPanelState extends State { if (availableWidth >= 1080) PlaybackModeButton(runtime: _runtime), if (availableWidth >= 1200) - PlaybackSkipButton(runtime: _runtime), + PlaybackSkipButton( + runtime: _runtime, + onPressed: _skipSegments, + ), if (showProgress) PlaybackActionButton( size: 48, @@ -2157,7 +2173,7 @@ class _PlayerPanelState extends State { : null, ), PlaybackVolumeControl(runtime: _runtime, vertical: true), - PlaybackSkipButton(runtime: _runtime), + PlaybackSkipButton(runtime: _runtime, onPressed: _skipSegments), PlaybackActionButton( onPressed: () { AppLog.instance.trace( diff --git a/lib/pages/player_queue_panel.dart b/lib/pages/player_queue_panel.dart index 82e55dc..2f763df 100644 --- a/lib/pages/player_queue_panel.dart +++ b/lib/pages/player_queue_panel.dart @@ -41,6 +41,8 @@ void _recordQueueError( 'rate_limited', 'queue_full', 'catalogue_limit', + 'queue_changed', + 'catalogue_changed', }.contains(error.code); log.write( recoverable || expected ? AppLogLevel.warning : AppLogLevel.error, @@ -216,6 +218,22 @@ class _PlayerQueuePanelState extends State { await _run(widget.runtime.player.clearQueue); } + Future _reverse() async { + AppLog.instance.trace( + "lib/pages/player_queue_panel.dart::_PlayerQueuePanelState._reverse", + ); + + await _run(widget.runtime.player.reverseQueue); + if (!mounted || _error != null) return; + WidgetsBinding.instance.addPostFrameCallback((_) { + AppLog.instance.trace( + "lib/pages/player_queue_panel.dart::_PlayerQueuePanelState._reverse.closure#1", + ); + + if (mounted) _showCurrent(); + }); + } + @override Widget build(BuildContext context) { AppLog.instance.trace( @@ -344,6 +362,20 @@ class _PlayerQueuePanelState extends State { child: Wrap( spacing: 8, children: [ + TextButton.icon( + key: const ValueKey('reversePlayerQueue'), + onPressed: + _busy || + (_tracks.length < 2 && + player.queueSource != 'album') + ? null + : _reverse, + icon: const Icon( + Icons.swap_vert_rounded, + size: 20, + ), + label: const Text('倒序'), + ), if (player.queueSource == 'album' && player.sourceAlbumId.isNotEmpty) TextButton( diff --git a/lib/pages/shell_page.dart b/lib/pages/shell_page.dart index beda1ce..1a88b71 100644 --- a/lib/pages/shell_page.dart +++ b/lib/pages/shell_page.dart @@ -524,7 +524,11 @@ class _ShellPageStackState extends State<_ShellPageStack> { ); _finishTransition(index); }, - child: RepaintBoundary(child: widget.children[index]), + child: RepaintBoundary( + // Keep portal children under the same visibility and + // semantics gates as their page while it fades out. + child: Overlay.wrap(child: widget.children[index]), + ), ), ), ), diff --git a/lib/services/player_service.dart b/lib/services/player_service.dart index 4930094..342ec87 100644 --- a/lib/services/player_service.dart +++ b/lib/services/player_service.dart @@ -226,7 +226,7 @@ class PlayerService { AppLog.instance.trace( "lib/services/player_service.dart::PlayerService.queueOrderLabel.get", ); - return queueSource == 'updates' ? '倒序(由旧到新)' : '队列顺序'; + return queueSource == 'updates' ? '由旧到新' : '队列顺序'; } bool playing = false, buffering = false; @@ -538,6 +538,7 @@ class PlayerService { 'duplicate_page', 'catalogue_changed', 'queue_full', + 'queue_changed', }.contains(failure.code); if (expected) return; AppLog.instance.requestUploadPrompt(); @@ -3703,6 +3704,105 @@ class PlayerService { }); } + Future reverseQueue() { + AppLog.instance.trace( + "lib/services/player_service.dart::PlayerService.reverseQueue", + ); + + return _run(() async { + AppLog.instance.trace( + "lib/services/player_service.dart::PlayerService.reverseQueue.closure#1", + ); + + if (_queue.isEmpty) return; + final selected = current!; + final version = generation, epoch = _epoch, request = _request; + final advanceIntent = _advanceIntent; + final client = currentClient, identity = libraryIdentity; + final album = sourceAlbumId, source = queueSource; + bool active() { + AppLog.instance.trace( + "lib/services/player_service.dart::PlayerService.reverseQueue.closure#1.active", + ); + + return !_closed && + version == generation && + epoch == _epoch && + request == _request && + current?.id == selected.id && + sourceAlbumId == album && + queueSource == source && + identical(client, currentClient) && + !accounts.admissionPaused; + } + + var tracks = _queue; + if (!_completeAlbumQueue) { + // Reversing a paged album must include chapters outside the loaded page. + tracks = await client.withReadPolicy( + () { + AppLog.instance.trace( + "lib/services/player_service.dart::PlayerService.reverseQueue.closure#1.closure#1", + ); + return XmlyCatalogue(client).album(album); + }, + rateLimitRetries: 0, + cancelled: _requestChanged.future, + checkpoint: () async { + AppLog.instance.trace( + "lib/services/player_service.dart::PlayerService.reverseQueue.closure#1.closure#2", + ); + + if (!active()) throw const DownloadStopped(); + }, + ); + } + await _commands.synchronized(() async { + AppLog.instance.trace( + "lib/services/player_service.dart::PlayerService.reverseQueue.closure#1.closure#3", + ); + + if (!active()) { + throw const XmlyException('queue_changed', '播放列表已变化,请重新排序'); + } + final byId = {for (final track in tracks) track.id: track}; + for (final track in _queue) { + final candidate = byId[track.id]; + if (candidate == null || + (source == 'album' && + track.officialPosition != null && + candidate.officialPosition != track.officialPosition)) { + throw const XmlyException('catalogue_changed', '专辑内容已更新,请重试'); + } + } + final next = tracks.reversed.toList(); + final index = next.indexWhere((track) { + AppLog.instance.trace( + "lib/services/player_service.dart::PlayerService.reverseQueue.closure#1.closure#3.closure#1", + ); + return track.id == selected.id; + }); + final owners = { + for (final track in next) + if (_queueAccountIdentities[track.id] ?? + (source == 'album' ? identity : null) + case final owner?) + track.id: owner, + }; + // As with dragging, an explicit reorder becomes a complete custom queue. + await _saveQueue(next, index, '', accountIdentities: owners); + _queue = next; + cursor = index; + sourceAlbumId = ''; + // A newer playback request may arrive while storage commits the queue. + if (generation == version) ++generation; + if (_advanceIntent == advanceIntent) ++_advanceIntent; + _shuffle.reset(); + _notify(); + }); + }); + } + Future clearQueue() { AppLog.instance.trace( "lib/services/player_service.dart::PlayerService.clearQueue",