fix(yt): fallback to different search result if all streaming url is inaccessible

This commit is contained in:
Kingkor Roy Tirtho 2025-09-02 20:56:28 +06:00
parent b248f90403
commit ea329f40e8
7 changed files with 71 additions and 29 deletions

View File

@ -60,8 +60,8 @@ class TrackDetailsDialog extends HookConsumerWidget {
context.l10n.channel: Text(sourceInfo.artists), context.l10n.channel: Text(sourceInfo.artists),
if (sourcedTrack.asData?.value.url != null) if (sourcedTrack.asData?.value.url != null)
context.l10n.streamUrl: Hyperlink( context.l10n.streamUrl: Hyperlink(
sourcedTrack.asData!.value.url, sourcedTrack.asData!.value.url ?? "",
sourcedTrack.asData!.value.url, sourcedTrack.asData!.value.url ?? "",
maxLines: 2, maxLines: 2,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
), ),

View File

@ -130,7 +130,7 @@ class DownloadManagerProvider extends ChangeNotifier {
download.status.value == DownloadStatus.queued, download.status.value == DownloadStatus.queued,
) )
.map((e) => e.request.url) .map((e) => e.request.url)
.contains(sourcedTrack.getUrlOfCodec(downloadCodec)); .contains(sourcedTrack.getUrlOfCodec(downloadCodec)!);
} }
/// For singular downloads /// For singular downloads
@ -152,7 +152,9 @@ class DownloadManagerProvider extends ChangeNotifier {
if (sourcedTrack.codec == downloadCodec) { if (sourcedTrack.codec == downloadCodec) {
final downloadTask = await dl.addDownload( final downloadTask = await dl.addDownload(
sourcedTrack.getUrlOfCodec(downloadCodec), savePath); sourcedTrack.getUrlOfCodec(downloadCodec)!,
savePath,
);
if (downloadTask != null) { if (downloadTask != null) {
$history.add(sourcedTrack); $history.add(sourcedTrack);
} }
@ -169,7 +171,7 @@ class DownloadManagerProvider extends ChangeNotifier {
return d; return d;
}); });
final downloadTask = await dl.addDownload( final downloadTask = await dl.addDownload(
sourcedTrack.getUrlOfCodec(downloadCodec), sourcedTrack.getUrlOfCodec(downloadCodec)!,
savePath, savePath,
); );
if (downloadTask != null) { if (downloadTask != null) {
@ -202,18 +204,18 @@ class DownloadManagerProvider extends ChangeNotifier {
Future<void> removeFromQueue(SpotubeFullTrackObject track) async { Future<void> removeFromQueue(SpotubeFullTrackObject track) async {
final sourcedTrack = await mapToSourcedTrack(track); final sourcedTrack = await mapToSourcedTrack(track);
await dl.removeDownload(sourcedTrack.getUrlOfCodec(downloadCodec)); await dl.removeDownload(sourcedTrack.getUrlOfCodec(downloadCodec)!);
$history.remove(sourcedTrack); $history.remove(sourcedTrack);
} }
Future<void> pause(SpotubeFullTrackObject track) async { Future<void> pause(SpotubeFullTrackObject track) async {
final sourcedTrack = await mapToSourcedTrack(track); final sourcedTrack = await mapToSourcedTrack(track);
return dl.pauseDownload(sourcedTrack.getUrlOfCodec(downloadCodec)); return dl.pauseDownload(sourcedTrack.getUrlOfCodec(downloadCodec)!);
} }
Future<void> resume(SpotubeFullTrackObject track) async { Future<void> resume(SpotubeFullTrackObject track) async {
final sourcedTrack = await mapToSourcedTrack(track); final sourcedTrack = await mapToSourcedTrack(track);
return dl.resumeDownload(sourcedTrack.getUrlOfCodec(downloadCodec)); return dl.resumeDownload(sourcedTrack.getUrlOfCodec(downloadCodec)!);
} }
Future<void> retry(SpotubeFullTrackObject track) { Future<void> retry(SpotubeFullTrackObject track) {
@ -222,7 +224,7 @@ class DownloadManagerProvider extends ChangeNotifier {
void cancel(SpotubeFullTrackObject track) async { void cancel(SpotubeFullTrackObject track) async {
final sourcedTrack = await mapToSourcedTrack(track); final sourcedTrack = await mapToSourcedTrack(track);
return dl.cancelDownload(sourcedTrack.getUrlOfCodec(downloadCodec)); return dl.cancelDownload(sourcedTrack.getUrlOfCodec(downloadCodec)!);
} }
void cancelAll() { void cancelAll() {
@ -256,7 +258,7 @@ class DownloadManagerProvider extends ChangeNotifier {
if (sourcedTrack == null) { if (sourcedTrack == null) {
return null; return null;
} }
return dl.getDownload(sourcedTrack.getUrlOfCodec(downloadCodec))?.status; return dl.getDownload(sourcedTrack.getUrlOfCodec(downloadCodec)!)?.status;
} }
ValueNotifier<double>? getProgressNotifier(SpotubeFullTrackObject track) { ValueNotifier<double>? getProgressNotifier(SpotubeFullTrackObject track) {
@ -266,7 +268,7 @@ class DownloadManagerProvider extends ChangeNotifier {
if (sourcedTrack == null) { if (sourcedTrack == null) {
return null; return null;
} }
return dl.getDownload(sourcedTrack.getUrlOfCodec(downloadCodec))?.progress; return dl.getDownload(sourcedTrack.getUrlOfCodec(downloadCodec)!)?.progress;
} }
} }

View File

@ -61,13 +61,20 @@ class ServerPlaybackRoutes {
); );
final trackPartialCacheFile = File("${trackCacheFile.path}.part"); final trackPartialCacheFile = File("${trackCacheFile.path}.part");
String? url = track.url;
url ??= await ref
.read(trackSourcesProvider(track.query).notifier)
.swapWithNextSibling()
.then((track) => track.url!);
var options = Options( var options = Options(
headers: { headers: {
...headers, ...headers,
"user-agent": _randomUserAgent, "user-agent": _randomUserAgent,
"Cache-Control": "max-age=3600", "Cache-Control": "max-age=3600",
"Connection": "keep-alive", "Connection": "keep-alive",
"host": Uri.parse(track.url).host, "host": Uri.parse(url!).host,
}, },
responseType: ResponseType.bytes, responseType: ResponseType.bytes,
validateStatus: (status) => status! < 400, validateStatus: (status) => status! < 400,
@ -75,7 +82,7 @@ class ServerPlaybackRoutes {
final headersRes = await Future<dio_lib.Response?>.value( final headersRes = await Future<dio_lib.Response?>.value(
dio.head( dio.head(
track.url, url,
options: options, options: options,
), ),
).catchError((_) async => null); ).catchError((_) async => null);
@ -95,7 +102,7 @@ class ServerPlaybackRoutes {
"accept-ranges": ["bytes"], "accept-ranges": ["bytes"],
"content-range": ["bytes 0-$cachedFileLength/$cachedFileLength"], "content-range": ["bytes 0-$cachedFileLength/$cachedFileLength"],
}), }),
requestOptions: RequestOptions(path: track.url), requestOptions: RequestOptions(path: url),
), ),
bytes: bytes, bytes: bytes,
); );
@ -118,7 +125,7 @@ class ServerPlaybackRoutes {
final res = await dio final res = await dio
.get<Uint8List>( .get<Uint8List>(
track.url, url,
options: options.copyWith(headers: { options: options.copyWith(headers: {
...?options.headers, ...?options.headers,
"user-agent": _randomUserAgent, "user-agent": _randomUserAgent,
@ -136,7 +143,7 @@ class ServerPlaybackRoutes {
// } // }
return await dio.get<Uint8List>( return await dio.get<Uint8List>(
sourcedTrack.url, sourcedTrack.url!,
options: options.copyWith(headers: { options: options.copyWith(headers: {
...?options.headers, ...?options.headers,
"user-agent": _randomUserAgent, "user-agent": _randomUserAgent,

View File

@ -34,6 +34,12 @@ class TrackSourcesNotifier
return await prev.swapWithSibling(sibling) ?? prev; return await prev.swapWithSibling(sibling) ?? prev;
}); });
} }
Future<SourcedTrack> swapWithNextSibling() async {
return await update((prev) async {
return await prev.swapWithSibling(prev.siblings.first) as SourcedTrack;
});
}
} }
final trackSourcesProvider = AsyncNotifierProviderFamily<TrackSourcesNotifier, final trackSourcesProvider = AsyncNotifierProviderFamily<TrackSourcesNotifier,

View File

@ -141,7 +141,7 @@ abstract class SourcedTrack extends BasicSourcedTrack {
} }
Future<SourcedTrack> refreshStream(); Future<SourcedTrack> refreshStream();
String get url { String? get url {
final preferences = ref.read(userPreferencesProvider); final preferences = ref.read(userPreferencesProvider);
final codec = preferences.audioSource == AudioSource.jiosaavn final codec = preferences.audioSource == AudioSource.jiosaavn
@ -157,7 +157,7 @@ abstract class SourcedTrack extends BasicSourcedTrack {
/// ///
/// If no sources match the codec, it will return the first or last source /// If no sources match the codec, it will return the first or last source
/// based on the user's audio quality preference. /// based on the user's audio quality preference.
String getUrlOfCodec(SourceCodecs codec) { String? getUrlOfCodec(SourceCodecs codec) {
final preferences = ref.read(userPreferencesProvider); final preferences = ref.read(userPreferencesProvider);
final exactMatch = sources.firstWhereOrNull( final exactMatch = sources.firstWhereOrNull(
@ -191,8 +191,8 @@ abstract class SourcedTrack extends BasicSourcedTrack {
}); });
return preferences.audioQuality != SourceQualities.low return preferences.audioQuality != SourceQualities.low
? fallbackSource.first.url ? fallbackSource.firstOrNull?.url
: fallbackSource.last.url; : fallbackSource.lastOrNull?.url;
} }
SourceCodecs get codec { SourceCodecs get codec {

View File

@ -204,6 +204,8 @@ class YoutubeSourcedTrack extends SourcedTrack {
AppLogger.log AppLogger.log
.d("${track.title} ISRC $isrc Total ${searchedVideos.length}"); .d("${track.title} ISRC $isrc Total ${searchedVideos.length}");
final stringBuffer = StringBuffer();
final filteredMatches = searchedVideos final filteredMatches = searchedVideos
.map<YoutubeVideoInfo>(YoutubeVideoInfo.fromVideo) .map<YoutubeVideoInfo>(YoutubeVideoInfo.fromVideo)
.map((YoutubeVideoInfo videoInfo) { .map((YoutubeVideoInfo videoInfo) {
@ -224,6 +226,10 @@ class YoutubeSourcedTrack extends SourcedTrack {
.abs() .abs()
.inMilliseconds <= .inMilliseconds <=
3000) { 3000) {
stringBuffer.writeln(
"ISRC MATCH: ${videoInfo.id} ${videoInfo.title} by ${videoInfo.channelName} ${videoInfo.duration}",
);
return videoInfo; return videoInfo;
} }
return null; return null;
@ -231,11 +237,7 @@ class YoutubeSourcedTrack extends SourcedTrack {
.nonNulls .nonNulls
.toList(); .toList();
for (final match in filteredMatches) { AppLogger.log.d(stringBuffer.toString());
AppLogger.log.d(
"ISRC MATCH: ${match.id} ${match.title} by ${match.channelName} ${match.duration}",
);
}
isrcResults.addAll(filteredMatches); isrcResults.addAll(filteredMatches);
} }
@ -262,9 +264,16 @@ class YoutubeSourcedTrack extends SourcedTrack {
final links = await SongLinkService.links(query.id); final links = await SongLinkService.links(query.id);
for (final link in links) { final stringBuffer = links.fold(
AppLogger.log.d("SongLink ${query.id} ${link.platform} ${link.url}"); StringBuffer(),
} (previousValue, element) {
previousValue.writeln(
"SongLink ${query.id} ${element.platform} ${element.url}");
return previousValue;
},
);
AppLogger.log.d(stringBuffer.toString());
final ytLink = links.firstWhereOrNull( final ytLink = links.firstWhereOrNull(
(link) => link.platform == "youtube", (link) => link.platform == "youtube",

View File

@ -1,6 +1,7 @@
import 'dart:isolate'; import 'dart:isolate';
import 'package:dio/dio.dart'; import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:spotube/services/dio/dio.dart'; import 'package:spotube/services/dio/dio.dart';
import 'package:spotube/services/logger/logger.dart'; import 'package:spotube/services/logger/logger.dart';
import 'package:spotube/services/youtube_engine/youtube_engine.dart'; import 'package:spotube/services/youtube_engine/youtube_engine.dart';
@ -60,6 +61,7 @@ class IsolatedYoutubeExplode {
static void _isolateEntry(SendPort mainSendPort) { static void _isolateEntry(SendPort mainSendPort) {
final receivePort = ReceivePort(); final receivePort = ReceivePort();
final youtubeExplode = YoutubeExplode(); final youtubeExplode = YoutubeExplode();
final stopWatch = kDebugMode ? Stopwatch() : null;
/// Send the main port to the main isolate /// Send the main port to the main isolate
mainSendPort.send(receivePort.sendPort); mainSendPort.send(receivePort.sendPort);
@ -69,6 +71,19 @@ class IsolatedYoutubeExplode {
final String methodName = message[1]; final String methodName = message[1];
final List<dynamic> arguments = message[2]; final List<dynamic> arguments = message[2];
if (stopWatch != null) {
if (stopWatch.isRunning) {
stopWatch.stop();
final symbol = stopWatch.elapsedMilliseconds < 1000 ? "⚠️" : "⏱️";
debugPrint(
"$symbol YoutubeExplode operation gap ${stopWatch.elapsedMilliseconds} ms",
);
stopWatch.reset();
} else {
stopWatch.start();
}
}
// Run the requested method on YoutubeExplode // Run the requested method on YoutubeExplode
var result = switch (methodName) { var result = switch (methodName) {
"search" => youtubeExplode.search "search" => youtubeExplode.search
@ -156,6 +171,7 @@ class YouTubeExplodeEngine implements YouTubeEngine {
); );
final accessibleStreams = <AudioOnlyStreamInfo>[]; final accessibleStreams = <AudioOnlyStreamInfo>[];
final stringBuffer = StringBuffer();
for (final stream in streamManifest.audioOnly) { for (final stream in streamManifest.audioOnly) {
// Call dio head request to check if the stream is accessible // Call dio head request to check if the stream is accessible
@ -169,7 +185,7 @@ class YouTubeExplodeEngine implements YouTubeEngine {
), ),
); );
AppLogger.log.d( stringBuffer.writeln(
"Stream $videoId Status ${response.statusCode} Codec ${stream.audioCodec} " "Stream $videoId Status ${response.statusCode} Codec ${stream.audioCodec} "
"Bitrate ${stream.bitrate} Container ${stream.container}", "Bitrate ${stream.bitrate} Container ${stream.container}",
); );
@ -199,6 +215,8 @@ class YouTubeExplodeEngine implements YouTubeEngine {
} }
} }
AppLogger.log.d(stringBuffer.toString());
return StreamManifest(accessibleStreams); return StreamManifest(accessibleStreams);
} }