-
Notifications
You must be signed in to change notification settings - Fork 0
/
youtube_downloader_totalxsoftware.dart
235 lines (208 loc) · 7.24 KB
/
youtube_downloader_totalxsoftware.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// ignore_for_file: use_build_context_synchronously
import 'dart:async';
import 'dart:collection';
import 'dart:io';
import 'dart:isolate';
import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:permission_handler/permission_handler.dart';
import 'package:video_url_validator/video_url_validator.dart';
import 'package:youtube_downloader_totalxsoftware/service/get_youtube_id_from_url.dart';
import 'package:youtube_downloader_totalxsoftware/service/merge_video_and_audio.dart';
import 'package:youtube_explode_dart/youtube_explode_dart.dart';
class YoutubeDownloaderTotalxsoftware {
static final YoutubeDownloaderTotalxsoftware _instance =
YoutubeDownloaderTotalxsoftware._internal();
YoutubeDownloaderTotalxsoftware._internal();
factory YoutubeDownloaderTotalxsoftware() {
return _instance;
}
static bool _isDownloading = false;
// Initialize notifications and permissions
static Future<void> initialize({
required String androidNotificationIcon,
}) async {
if (Platform.isAndroid) {
PermissionStatus notificationPermissionStatus =
await Permission.notification.status;
if (!notificationPermissionStatus.isGranted) {
await Permission.notification.request();
}
}
AwesomeNotifications().initialize(
androidNotificationIcon,
[
NotificationChannel(
channelKey: 'basic_channel',
channelName: 'Basic Notifications',
channelDescription: 'Basic notifications for the app.',
defaultColor: const Color(0xFF9D50DD),
ledColor: Colors.white,
),
NotificationChannel(
channelKey: 'download_channel',
channelName: 'Download Progress',
channelDescription: 'Displays download progress notifications.',
defaultColor: const Color(0xFF2196F3),
ledColor: Colors.white,
importance:
NotificationImportance.Low, // Lower importance to avoid floating
enableVibration: false, // Disable vibration
playSound: false, // Disable sound
onlyAlertOnce: true, // Prevent multiple alerts for updates
),
],
);
}
// Download YouTube video
Future<void> downloadYoutubeVideo({
required BuildContext context,
required String ytUrl,
required void Function(String e) error,
required void Function(double progress) onProgress,
required void Function(File videoFile, File thumbFile) onComplete,
required void Function(bool isLoading) onLoading,
required Widget Function(
List<VideoOnlyStreamInfo>, void Function(StreamInfo) onSelected)
qualityBuilderSheet,
}) async {
if (_isDownloading) {
error("Another download is already in progress.");
return;
}
_isDownloading = true;
onLoading(true);
try {
// Validate YouTube URL
if (!VideoURLValidator().validateYouTubeVideoURL(url: ytUrl)) {
error("Invalid YouTube URL");
onLoading(false);
return;
}
final videoId = getYoutubeIdFromUrl(ytUrl);
// Fetch video details in a separate isolate
final data = await _fetchVideoDetailsInBackground(videoId!);
final video = data['video'] as Video;
final manifest = data['manifest'] as StreamManifest;
// Check if manifest contains video streams
if (manifest.videoOnly.isEmpty) {
error("No available video streams");
onLoading(false);
return;
}
// Download thumbnail
// final thumbFile = await _downloadThumbnail(video.thumbnails.highResUrl);
// Show video quality selection
// final selectedStream = await
final date = await Future.wait([
_showQualitySelection(
context,
videos: manifest.videoOnly,
qualityBuilderSheet: qualityBuilderSheet,
),
_downloadThumbnail(video.thumbnails.highResUrl),
]);
final selectedStream = date[0] as StreamInfo?;
final thumbFile = date[1] as File;
if (selectedStream == null) {
onLoading(false);
return;
}
final videoUrl = selectedStream.url;
final audioUrl = manifest.audioOnly.first.url;
// Download and merge video & audio
await mergeVideoAndAudio(
videoUrl: videoUrl,
audioUrl: audioUrl,
totalFileDuration: video.duration!.inMilliseconds,
error: (e) {
error(e);
onLoading(false);
},
onProgress: onProgress,
onComplete: (videoFile) {
_isDownloading = false;
onComplete(videoFile, thumbFile);
onLoading(false);
},
);
} catch (e) {
error("Error: $e");
onLoading(false);
} finally {
_isDownloading = false;
}
}
// Function to run in the background isolate
Future<Map<String, dynamic>> _fetchVideoDetailsInBackground(
String videoId) async {
final receivePort =
ReceivePort(); // ReceivePort to get the result from the isolate
// Start a background isolate
await Isolate.spawn(
_fetchVideoDetailsIsolate,
[videoId, receivePort.sendPort],
);
// Listen for the result from the isolate
final result = await receivePort.first;
return result as Map<String, dynamic>;
}
// Isolate function that does the async task and sends the result back
static void _fetchVideoDetailsIsolate(List<dynamic> args) async {
final videoId = args[0] as String;
final sendPort = args[1] as SendPort;
final yt = YoutubeExplode();
final video = await yt.videos.get(videoId);
final manifest = await yt.videos.streamsClient.getManifest(videoId);
yt.close();
// Send back the result to the main isolate
sendPort.send({
'video': video,
'manifest': manifest,
});
}
// Download thumbnail
Future<File> _downloadThumbnail(String thumbUrl) async {
final response = await http.get(Uri.parse(thumbUrl));
final directory = await Directory.systemTemp.createTemp();
final thumbFile = File(
'${directory.path}/thumbnail_${DateTime.now().millisecondsSinceEpoch}.jpg');
await thumbFile.writeAsBytes(response.bodyBytes);
return thumbFile;
}
// Show quality selection bottom sheet
static Future<StreamInfo?> _showQualitySelection(
BuildContext context, {
required Widget Function(
List<VideoOnlyStreamInfo> video,
void Function(StreamInfo) onPick,
) qualityBuilderSheet,
required UnmodifiableListView<VideoOnlyStreamInfo> videos,
}) async {
StreamInfo? streamInfo;
await showModalBottomSheet(
backgroundColor: Colors.transparent,
context: context,
builder: (context) {
List<VideoOnlyStreamInfo> videoStreams = [];
Set<String> seenQualityLabels = {};
for (var element in videos) {
if (element.container.name == 'mp4' &&
!seenQualityLabels.contains(element.qualityLabel)) {
videoStreams.add(element);
seenQualityLabels.add(element.qualityLabel);
}
}
return qualityBuilderSheet(
videoStreams,
(value) {
streamInfo = value;
Navigator.pop(context);
},
);
},
);
return streamInfo;
}
}