youtube_explode/lib/src/playlists/playlist_client.dart

76 lines
2.2 KiB
Dart
Raw Normal View History

2021-03-04 10:46:37 +01:00
import 'package:youtube_explode_dart/src/channels/channel_id.dart';
import 'package:youtube_explode_dart/src/reverse_engineering/responses/playlist_page.dart';
2020-06-03 23:02:21 +02:00
import '../common/common.dart';
import '../reverse_engineering/youtube_http_client.dart';
import '../videos/video.dart';
import '../videos/video_id.dart';
import 'playlist.dart';
import 'playlist_id.dart';
/// Queries related to YouTube playlists.
class PlaylistClient {
final YoutubeHttpClient _httpClient;
/// Initializes an instance of [PlaylistClient]
PlaylistClient(this._httpClient);
/// Gets the metadata associated with the specified playlist.
2020-06-05 20:08:04 +02:00
Future<Playlist> get(dynamic id) async {
id = PlaylistId.fromString(id);
2021-03-04 10:46:37 +01:00
var response = await PlaylistPage.get(_httpClient, id.value);
2020-06-03 23:02:21 +02:00
return Playlist(
id,
2021-03-11 14:20:10 +01:00
response.initialData.title ?? '',
response.initialData.author ?? '',
response.initialData.description ?? '',
2021-03-04 10:46:37 +01:00
ThumbnailSet(id.value),
Engagement(response.initialData.viewCount ?? 0, null, null));
2020-06-03 23:02:21 +02:00
}
/// Enumerates videos included in the specified playlist.
2020-06-05 20:08:04 +02:00
Stream<Video> getVideos(dynamic id) async* {
id = PlaylistId.fromString(id);
2020-06-03 23:02:21 +02:00
var encounteredVideoIds = <String>{};
2021-03-11 14:20:10 +01:00
String? continuationToken = '';
2021-03-04 10:46:37 +01:00
2020-06-10 00:08:16 +02:00
// ignore: literal_only_boolean_expressions
2020-06-03 23:02:21 +02:00
while (true) {
2021-03-04 10:46:37 +01:00
var response = await PlaylistPage.get(_httpClient, id.value,
token: continuationToken);
2021-03-11 14:20:10 +01:00
for (final video in response.initialData.playlistVideos) {
2020-06-03 23:02:21 +02:00
var videoId = video.id;
// Already added
2020-06-05 16:17:08 +02:00
if (!encounteredVideoIds.add(videoId)) {
2020-06-03 23:02:21 +02:00
continue;
}
2021-03-04 10:46:37 +01:00
if (video.channelId.isEmpty) {
continue;
}
2020-06-03 23:02:21 +02:00
yield Video(
VideoId(videoId),
video.title,
video.author,
2021-03-04 10:46:37 +01:00
ChannelId(video.channelId),
null,
2021-03-24 06:17:49 +01:00
null,
2020-06-03 23:02:21 +02:00
video.description,
video.duration,
ThumbnailSet(videoId),
2021-03-04 10:46:37 +01:00
null,
Engagement(video.viewCount, null, null),
false);
2020-06-03 23:02:21 +02:00
}
2021-03-04 10:46:37 +01:00
continuationToken = response.initialData.continuationToken;
if (response.initialData.continuationToken?.isEmpty ?? true) {
2020-06-03 23:02:21 +02:00
break;
}
}
}
}