Skip to content

Commit 35773de

Browse files
committed
fix(player): restore cloud progress asynchronously on track start (teikengstudio#268)
1 parent 7356c27 commit 35773de

5 files changed

Lines changed: 115 additions & 44 deletions

File tree

‎lib/api/xmly_client.dart‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,8 @@ class XmlyClient {
115115
RegExp(r'^/fmobile-album/album/track/ts-[0-9]+$').hasMatch(path);
116116
static bool _endpoint(String method, String origin, String path) {
117117
if (origin == cachedAlbumOrigin)
118-
return _cachedAlbumEndpoint(method, origin, path);
118+
return _cachedAlbumEndpoint(method, origin, path) ||
119+
(method == 'GET' && path == '/nyx/v1/history/query/android');
119120
if (origin == paidOrigin)
120121
return method == 'GET' &&
121122
RegExp(r'^/mobile/track/pay/[1-9][0-9]{0,18}/ts-[0-9]+$')
@@ -152,7 +153,6 @@ class XmlyClient {
152153
return method == 'GET' &&
153154
(const [
154155
'/mobile/v1/album/track/v2',
155-
'/nyx/v1/history/query/android',
156156
'/lite-mobile/like/v1/user-likes',
157157
].contains(path) ||
158158
RegExp(r'^/mobile/track/[1-9][0-9]{0,18}$').hasMatch(path) ||

‎lib/api/xmly_history.dart‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ class XmlyHistory {
112112
if (isActive != null && !isActive()) return const [];
113113
final response = await client.request(
114114
'GET',
115-
XmlyClient.mobile,
115+
XmlyClient.cachedAlbumOrigin,
116116
'/nyx/v1/history/query/android',
117117
query: {
118118
'pageId': '$page',
@@ -174,6 +174,7 @@ class XmlyHistory {
174174
String albumId = '',
175175
String trackId = '',
176176
Duration? timeout,
177+
bool Function()? isActive,
177178
}) async {
178179
final album = albumId.isEmpty ? '' : _id(albumId);
179180
final track = trackId.isEmpty ? '' : 'xmly:${_id(trackId)}';
@@ -184,7 +185,7 @@ class XmlyHistory {
184185
var active = true;
185186
Map<String, dynamic>? latest;
186187
final scan = _records(
187-
isActive: () => active,
188+
isActive: () => active && (isActive?.call() ?? true),
188189
onPage: (items) {
189190
latest = null;
190191
for (final item in items) {

‎lib/pages/listening_page.dart‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -950,15 +950,11 @@ class _ListeningPageState extends State<ListeningPage>
950950
position: row.position,
951951
play: () => _act(
952952
() => row.track.albumId.isEmpty
953-
? _runtime.player.playTrack(
954-
row.track,
955-
resumePosition: row.position,
956-
)
953+
? _runtime.player.playTrack(row.track)
957954
: _runtime.player.playAlbum(
958955
row.track.albumId,
959956
row.track.id,
960957
track: row.track,
961-
resumePosition: row.position,
962958
),
963959
),
964960
),

‎lib/pages/playback_settings_page.dart‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -359,16 +359,16 @@ class _PlaybackSettingsPageState extends State<PlaybackSettingsPage> {
359359
final allowed = await showDialog<bool>(
360360
context: context,
361361
builder: (context) => AlertDialog(
362-
title: const Text('同步收听历史?'),
363-
content: const Text('开启后会读取并写入当前账号的喜马拉雅收听历史。本地文件播放也会同步实际进度。'),
362+
title: const Text('上传收听进度?'),
363+
content: const Text('开播时会自动读取云进度。开启后,还会上传当前账号在线播放与本地文件播放的实际进度。'),
364364
actions: [
365365
TextButton(
366366
onPressed: () => Navigator.pop(context, false),
367367
child: const Text('取消'),
368368
),
369369
FilledButton(
370370
onPressed: () => Navigator.pop(context, true),
371-
child: const Text('开启同步'),
371+
child: const Text('开启上传'),
372372
),
373373
],
374374
),
@@ -598,12 +598,13 @@ class _PlaybackSettingsPageState extends State<PlaybackSettingsPage> {
598598
_section('历史同步', [
599599
SwitchListTile(
600600
key: const ValueKey('syncHistory'),
601-
title: const Text('同步云端收听历史'),
601+
title: const Text('上传云端收听进度'),
602+
subtitle: const Text('开播时自动读取云进度,此开关仅控制上传'),
602603
value: _global['syncHistory'] == true,
603604
onChanged: _busy ? null : _sync,
604605
),
605606
ListTile(
606-
title: const Text('重试历史同步'),
607+
title: const Text('重试进度上传'),
607608
subtitle: _historyResult == null
608609
? null
609610
: Text(_historyResult!),

‎lib/services/player_service.dart‎

Lines changed: 103 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ class PlayerService {
6666
_clock = clock ?? DateTime.now,
6767
policy = PlaybackPolicy(clock: clock) {
6868
_driverEvents = _driver.snapshots.listen((snapshot) {
69+
final seekRevision = _seekRevision;
6970
final recorded =
7071
!_closed &&
7172
_source != null &&
@@ -86,7 +87,11 @@ class PlayerService {
8687
}
8788
_background(
8889
() => _commands.synchronized(
89-
() => _observe(snapshot, stateAlreadyRecorded: recorded),
90+
() => _observe(
91+
snapshot,
92+
seekRevision: seekRevision,
93+
stateAlreadyRecorded: recorded,
94+
),
9095
),
9196
);
9297
});
@@ -164,6 +169,7 @@ class PlayerService {
164169
int _prefetchEpoch = -1, _prefetchGeneration = -1;
165170
bool _loading = false;
166171
int _seekRevision = 0;
172+
int? _cloudResumeEpoch;
167173
int _playbackRecoveryRevision = 0;
168174

169175
Stream<void> get changes => _changes.stream;
@@ -720,30 +726,87 @@ class PlayerService {
720726
return (position: saved.toDouble(), updatedAt: updated);
721727
}
722728

723-
Future<double> _resumePosition(Track track, int request) async {
724-
final local = _localProgress(track);
729+
Future<void> _restoreCloudProgress(
730+
Track track,
731+
PlaybackSource source,
732+
int request,
733+
int epoch,
734+
({double position, int updatedAt})? local, {
735+
required bool preservePosition,
736+
}) async {
725737
final client = _historyClient;
726-
if (!_syncHistory || client == null) return local?.position ?? 0;
738+
if (client == null || !client.accountAvailable) return;
739+
final identity = client.cacheIdentity;
740+
final listener = accounts.activeClient;
741+
final revision = _seekRevision;
742+
final expectedGeneration = generation;
743+
bool sameSource() =>
744+
!_closed && epoch == _epoch && identical(source, _source);
745+
bool active() =>
746+
sameSource() &&
747+
request == _request &&
748+
expectedGeneration == generation &&
749+
current?.id == track.id &&
750+
revision == _seekRevision &&
751+
!accounts.admissionPaused &&
752+
identical(listener, accounts.activeClient) &&
753+
identical(client, _historyClient) &&
754+
identity == client.cacheIdentity;
755+
// Local samples and billing continue, but the initial fallback must not
756+
// overwrite the remote position before this source's read has settled.
757+
_cloudResumeEpoch = epoch;
758+
Map<String, dynamic>? cloud;
759+
var failed = false;
727760
try {
728-
final cloud = await XmlyHistory(client, clock: _clock).progress(
729-
albumId: track.albumId,
730-
trackId: track.id,
731-
timeout: const Duration(seconds: 2),
732-
);
733-
if (cloud != null &&
734-
(local == null ||
735-
(cloud['updated_at'] as num) * 1000 > local.updatedAt)) {
736-
if (request == _request && cloud['incomplete'] == true) {
737-
_sourceWarning = '云历史查询较慢,已使用本次查到的最新进度';
738-
}
739-
return (cloud['position'] as num).toDouble();
761+
try {
762+
cloud = await XmlyHistory(client, clock: _clock).progress(
763+
albumId: track.albumId,
764+
trackId: track.id,
765+
timeout: const Duration(seconds: 2),
766+
isActive: active,
767+
);
768+
} catch (_) {
769+
failed = true;
740770
}
771+
await _commands.synchronized(() async {
772+
try {
773+
if (!active() || preservePosition || _atEnd) return;
774+
final remote = cloud;
775+
if (remote != null &&
776+
(local == null ||
777+
(remote['updated_at'] as num) * 1000 > local.updatedAt)) {
778+
final restored = policy.start(
779+
duration: duration,
780+
resumePosition: (remote['position'] as num).toDouble(),
781+
settings: effectiveSettings,
782+
);
783+
await _driver.seek(restored);
784+
if (!active()) return;
785+
++_seekRevision;
786+
position = restored;
787+
// Only a subsequent device observation may persist the restored
788+
// position; the pre-seek fallback is not an official observation.
789+
_actual = false;
790+
_observedAt = 0;
791+
if (remote['incomplete'] == true) {
792+
_sourceWarning = '云历史查询较慢,已使用本次查到的最新进度';
793+
}
794+
} else if (failed) {
795+
_sourceWarning = local == null
796+
? '云进度暂不可用,继续当前播放'
797+
: '云进度暂不可用,已使用本地进度';
798+
}
799+
_notify();
800+
} finally {
801+
if (sameSource() && _cloudResumeEpoch == epoch) {
802+
_cloudResumeEpoch = null;
803+
}
804+
}
805+
});
741806
} catch (_) {
742-
if (request == _request) {
743-
_sourceWarning = local == null ? '云进度暂不可用,将从片头开始' : '云进度暂不可用,已使用本地进度';
744-
}
807+
// A background restore never fails or pauses an otherwise playable source.
808+
if (sameSource() && _cloudResumeEpoch == epoch) _cloudResumeEpoch = null;
745809
}
746-
return local?.position ?? 0;
747810
}
748811

749812
Future<void> _openCurrent(
@@ -822,15 +885,9 @@ class PlayerService {
822885
return;
823886
}
824887
_source = source;
888+
final local = _localProgress(track);
825889
try {
826-
final resume =
827-
saved ??
828-
await _admission(request, () => _resumePosition(track, request)) ??
829-
0.0;
830-
if (request != _request) {
831-
await _release();
832-
return;
833-
}
890+
final resume = saved ?? local?.position ?? 0.0;
834891
if (source.requiresReward &&
835892
source.kind == 'online' &&
836893
ledger.isBlocked(source.identity)) {
@@ -871,6 +928,16 @@ class PlayerService {
871928
return;
872929
}
873930
_official.start('player', track, source.identity);
931+
unawaited(
932+
_restoreCloudProgress(
933+
track,
934+
source,
935+
request,
936+
epoch,
937+
local,
938+
preservePosition: saved != null || manualReplay,
939+
),
940+
);
874941
final sleep = policy.pollSleep();
875942
if (sleep != null) {
876943
await _sleep(sleep);
@@ -1263,6 +1330,7 @@ class PlayerService {
12631330
: null;
12641331
}
12651332
++_seekRevision;
1333+
_cloudResumeEpoch = null;
12661334
// Seeking itself is never an actual listening observation or history POST.
12671335
_notify();
12681336
}),
@@ -1349,11 +1417,15 @@ class PlayerService {
13491417

13501418
Future<void> _observe(
13511419
AudioSnapshot snapshot, {
1420+
required int seekRevision,
13521421
bool stateAlreadyRecorded = false,
13531422
}) async {
13541423
if (_closed || _source == null || snapshot.epoch != _epoch) return;
13551424
if (snapshot.error != null)
13561425
throw const XmlyException('audio_device', '音频播放失败');
1426+
// Billing captured the event at arrival; stale pre-seek positions must not
1427+
// become fresh local/cloud progress when the command queue catches up.
1428+
if (seekRevision != _seekRevision) return;
13571429
if (!snapshot.position.isFinite ||
13581430
snapshot.position < 0 ||
13591431
!snapshot.duration.isFinite ||
@@ -1388,7 +1460,7 @@ class PlayerService {
13881460
speed: rate,
13891461
stateAlreadyRecorded: stateAlreadyRecorded,
13901462
);
1391-
if (_actual)
1463+
if (_actual && _cloudResumeEpoch != _epoch)
13921464
await _official.observe(
13931465
'player',
13941466
_observedPosition,
@@ -1796,7 +1868,7 @@ class PlayerService {
17961868
});
17971869
}
17981870
_savedAt = _clock().millisecondsSinceEpoch;
1799-
if (sync)
1871+
if (sync && _cloudResumeEpoch != _epoch)
18001872
await _official.observe('player', actualPosition, terminal: terminal);
18011873
}
18021874

@@ -2022,6 +2094,7 @@ class PlayerService {
20222094
Future<void> _release() async {
20232095
final source = _source;
20242096
_source = null;
2097+
_cloudResumeEpoch = null;
20252098
await source?.release?.call();
20262099
}
20272100

0 commit comments

Comments
 (0)