-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathService.cpp
More file actions
326 lines (254 loc) · 10.6 KB
/
Copy pathService.cpp
File metadata and controls
326 lines (254 loc) · 10.6 KB
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#include "Service.h"
#include "ServiceMaintainer.h"
Service::Service(QObject *parent) : QObject(parent) {
downloadProcess = new QProcess(this);
downloadProcess->setProcessChannelMode(QProcess::MergedChannels);
/* Stall timer */
stallTimer = new QTimer(this);
stallTimer->setInterval(5000); // 5 s
stallTimer->setSingleShot(true);
connect(stallTimer, &QTimer::timeout, this, &Service::onStallTimeout);
killTimer = new QTimer(this);
killTimer->setInterval(20000); // 20 s
killTimer->setSingleShot(true);
connect(killTimer, &QTimer::timeout, this, &Service::onKillTimeout);
/* Connections */
connect(downloadProcess, &QProcess::started, this, &Service::downloadStarted);
connect(downloadProcess, &QProcess::finished, this, &Service::onProcessFinish);
connect(downloadProcess, &QProcess::errorOccurred, this, &Service::downloadFailed);
connect(downloadProcess, &QProcess::readyReadStandardOutput, this, &Service::readOutput);
}
void Service::startDownload(QString link, QString location, int format, QString quality, QString conversion, bool playlist, bool savePlaylistInFolder, bool saveThumbnail, bool saveSubtitles) {
QString executable = ServiceMaintainer::getServiceLocation();
QStringList arguments;
QString outputPath;
playlistStatus = "";
if (playlist) {
arguments << "--yes-playlist";
if (savePlaylistInFolder) {
outputPath = location + "/%(playlist_title)s/%(playlist_index)s - %(title)s.%(ext)s";
} else {
outputPath = location + "/%(title)s.%(ext)s";
}
} else {
arguments << "--no-playlist";
outputPath = location + "/%(title)s.%(ext)s";
}
if (saveThumbnail) {
arguments << "--write-thumbnail";
}
// Print full directory
arguments << "--no-quiet";
arguments << "--print" << "after_move:FINALPATH:%(filepath)s";
arguments << "--no-simulate";
arguments << "--newline" << "--no-colors" << "-o" << outputPath;
// PATH flatpak or .deb
QString ffmpegPath = QStandardPaths::findExecutable("ffmpeg");
// Windows, AppImage, binary
if (ffmpegPath.isEmpty()) {
QString appPath = QCoreApplication::applicationDirPath();
ffmpegPath = QStandardPaths::findExecutable("ffmpeg", QStringList() << appPath + "/bin");
}
if (!ffmpegPath.isEmpty()) {
arguments << "--ffmpeg-location" << ffmpegPath;
}
QString videoFilter = "bv*";
if (quality != "0" && !quality.isEmpty()) {
QString height = quality;
height.remove("p");
videoFilter = "bv*[height<=" + height + "]";
}
switch (format) {
case 0: // both
arguments << "-f" << videoFilter + "+ba/b";
break;
case 1: // video only
arguments << "-f" << videoFilter;
break;
case 2: // audio only
arguments << "-x";
if (conversion != "0" && !conversion.isEmpty()) {
QString targetFormat = conversion;
targetFormat.remove(".");
arguments << "--audio-format" << targetFormat;
}
break;
}
if (conversion != "0" && !conversion.isEmpty() && format != 2) {
QString targetFormat = conversion;
targetFormat.remove(".");
arguments << "--merge-output-format" << targetFormat;
arguments << "--remux-video" << targetFormat;
}
if (saveSubtitles == true) {
arguments << "--write-subs";
}
arguments << link;
partCounter = 0;
savedSizeMiB = 0.0;
currentPartMiB = 0.0;
stallEmitted = false;
killedByTimeout = false;
qDebug() << "Starting yt-dlp download with command: " << arguments;
downloadProcess->start(executable, arguments);
stallTimer->start();
killTimer->start();
}
void Service::readOutput() {
static const QRegularExpression regexDestination("^\\[download\\] Destination:\\s+(.+)$");
static const QRegularExpression regexAlready("^\\[download\\]\\s+(.+)\\s+has already been downloaded");
static const QRegularExpression regexProgress("^\\[download\\]\\s+(\\d+\\.?\\d*)%(?:\\s+of\\s+~?\\s*([0-9.]+)([a-zA-Z]+))?");
static const QRegularExpression regexTitle("^(.+?)(?:\\.f[a-zA-Z0-9]+)?\\.\\w+$");
static const QRegularExpression regexPlaylist("^\\[download\\] Downloading (?:video|item) (\\d+) of (\\d+)");
static const QRegularExpression finalPath("^FINALPATH:(.+)$");
while (downloadProcess->canReadLine()) {
QString line = QString::fromLocal8Bit(downloadProcess->readLine()).trimmed();
resetStallTimer();
if (line.startsWith("ERROR:")) {
qDebug() << "yt-dlp [ERROR]:" << line;
emit processFailed(line);
continue;
}
QRegularExpressionMatch matchAlready = regexAlready.match(line);
if (matchAlready.hasMatch()) {
QString fullPath = matchAlready.captured(1);
QString fileName = QFileInfo(fullPath).fileName();
QRegularExpressionMatch matchTitle = regexTitle.match(fileName);
QString cleanTitle;
if (matchTitle.hasMatch()) {
cleanTitle = matchTitle.captured(1);
} else {
cleanTitle = fileName;
}
cleanTitle.remove(QRegularExpression("^\\d+\\s*-\\s*"));
if (!playlistStatus.isEmpty()) {
cleanTitle = QString("%1 %2").arg(playlistStatus, cleanTitle);
}
emit titleUpdated(cleanTitle);
emit phaseUpdated(tr("Already downloaded"));
continue;
}
// Format (1/50)
QRegularExpressionMatch matchPlaylist = regexPlaylist.match(line);
if (matchPlaylist.hasMatch()) {
QString current = matchPlaylist.captured(1);
QString total = matchPlaylist.captured(2);
playlistStatus = QString("(%1/%2)").arg(current, total);
emit playlistItemUpdated(playlistStatus);
partCounter = 0;
continue;
}
QRegularExpressionMatch matchDestination = regexDestination.match(line);
if (matchDestination.hasMatch()) {
savedSizeMiB += currentPartMiB;
currentPartMiB = 0.0;
partCounter++;
QString fullPath = matchDestination.captured(1);
QString fileName = QFileInfo(fullPath).fileName();
QRegularExpressionMatch matchTitle = regexTitle.match(fileName);
QString cleanTitle;
if (matchTitle.hasMatch()) {
cleanTitle = matchTitle.captured(1);
} else {
cleanTitle = fileName;
}
cleanTitle.remove(QRegularExpression("^\\d+\\s*-\\s*"));
if (!playlistStatus.isEmpty()) {
cleanTitle = QString("%1 %2").arg(playlistStatus, cleanTitle);
}
emit titleUpdated(cleanTitle);
if (partCounter == 1) {
emit phaseUpdated(tr("Downloading..."));
} else if (partCounter > 1) {
emit phaseUpdated(tr("Downloading audio..."));
}
continue;
}
QRegularExpressionMatch matchProgress = regexProgress.match(line);
if (matchProgress.hasMatch()) {
QString textNumber = matchProgress.captured(1);
int percentage = qRound(textNumber.toDouble());
bool isAudioPart = (partCounter > 1);
QString currentPhase = isAudioPart ? tr("Downloading audio...") : tr("Downloading...");
if (!matchProgress.captured(2).isEmpty()) {
double totalSize = matchProgress.captured(2).toDouble();
QString unit = matchProgress.captured(3);
double sizeInMiB = totalSize;
if (unit == "KiB") sizeInMiB /= 1024.0;
else if (unit == "GiB") sizeInMiB *= 1024.0;
currentPartMiB = sizeInMiB;
double downloaded = (textNumber.toDouble() / 100.0) * totalSize;
QString strDownloaded = QString::number(downloaded, 'f', 2);
QString strTotal = matchProgress.captured(2);
QString statsText = QString("(%1 %2 / %3 %2)").arg(strDownloaded, unit, strTotal);
emit phaseUpdated(currentPhase + " " + statsText);
emit sizeUpdated(strDownloaded + " " + unit);
} else {
emit phaseUpdated(currentPhase);
}
emit percentageUpdated(percentage);
if (percentage == 100) {
emit phaseUpdated(tr("Processing..."));
}
continue;
}
QRegularExpressionMatch matchFinalPath = finalPath.match(line);
if (matchFinalPath.hasMatch()) {
QString fullPath = matchFinalPath.captured(1).trimmed();
emit filePath(fullPath);
continue;
}
}
}
void Service::onProcessFinish(int exitCode, QProcess::ExitStatus status) {
stallTimer->stop();
killTimer->stop();
// Drain any remaining buffered output
readOutput();
if (killedByTimeout) {
emit downloadFinished(-2);
return;
}
if (status == QProcess::CrashExit) {
emit downloadFinished(-1);
return;
}
if (exitCode == 0) {
double pesoTotal = savedSizeMiB + currentPartMiB;
emit sizeUpdated(QString::number(pesoTotal, 'f', 2) + " MiB");
emit downloadFinished(0);
} else {
emit downloadFinished(exitCode);
}
}
void Service::downloadFailed(QProcess::ProcessError error) {
if (error == QProcess::FailedToStart) {
emit processFailed(tr("Couldn't find yt-dlp"));
} else {
emit processFailed("");
}
}
void Service::stopDownload() {
stallTimer->stop();
killTimer->stop();
if (downloadProcess->state() == QProcess::Running) {
downloadProcess->terminate();
}
}
void Service::resetStallTimer() {
stallEmitted = false;
stallTimer->start(); // restart
killTimer->start();
}
void Service::onStallTimeout() {
if (!stallEmitted && downloadProcess->state() == QProcess::Running) {
stallEmitted = true;
emit downloadStalled();
}
}
void Service::onKillTimeout() {
if (downloadProcess->state() == QProcess::Running) {
killedByTimeout = true;
downloadProcess->kill();
}
}