-
Notifications
You must be signed in to change notification settings - Fork 4
/
renderer.js
405 lines (336 loc) · 13.2 KB
/
renderer.js
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
'use strict';
const fs = require('fs');
const path = require('path');
const youtubedl = require('youtube-dl');
const {app, dialog} = require('electron').remote;
const ipcRenderer = require('electron').ipcRenderer;
const ISO6391 = require('iso-639-1');
const webvtt = require('node-webvtt-youtube');
let destDownloadFolder = app.getPath("videos");
var downloadFolderDestElement = document.getElementById("downloadFolderDest");
setDownloadFolderDestElement(destDownloadFolder)
// elements
var urlInputElement = document.getElementById("urlInput");
var btnLoadElement = document.getElementById("btnLoad");
var setDownloadDestBtnElement = document.getElementById("setDownloadDestBtn");
var downloadProgressBarEl = document.getElementById("downloadProgressBar")
var infoPanelElemnet = document.getElementById("infoPanel");
var statusElement = document.getElementById("status");
var captionsCheckboxElement = document.getElementById("captionsCheckbox");
var captionsStatusElement = document.getElementById("captionsStatus");
var videoCheckboxElement = document.getElementById("videoCheckbox");
var optionsRadiosHumanCaptionsElement = document.getElementById("optionsRadiosHumanCaptions");
var optionsRadiosAutomatedCaptionsElement = document.getElementById("optionsRadiosAutomatedCaptions");
var languageSelectionElement = document.getElementById("languageSelection");
var captionsToPlainTextCheckboxElement = document.getElementById("captionsToPlainTextCheckbox");
// messages
var downloadingMessage = 'Downloading Video...';
var downloadingPlaylistMessage = 'Downloading Playlist...';
var finishedDownloadingMessage = `Finished downloading Video`;
var subtitlesDownloadedMessage = `Finished downloading subtitle`;
var subtitlesDownloadingMessage = 'Downloading subtitles files ...';
var subtitlesNotAviableMessage = 'Could not retrieve subtitles at this time.';
// set element for select file format.
// getter for file element.
var loadExtraLanguagesOptions = document.getElementById("extraLanguagesBtn");
/**
* helper functions
*/
function requestedVideo() {
return videoCheckboxElement.checked;
}
function getUrlInput() {
return urlInputElement.value;
}
function captionStatus() {
return captionsCheckboxElement.checked;
}
function getCaptionPlainTextOption() {
return captionsToPlainTextCheckboxElement.checked;
}
// set user info in GUI on captions
function setCaptionsStatus(status, done) {
if (status !== "") {
captionsStatusElement.innerHTML = `<div class="alert alert-dismissible ${
isDone(done)
}">${status}</div>`;
}
// TODO: status update for captions temporarily disabled.
}
function setStatusElement(status, done) {
if (status !== "") {
statusElement.innerHTML = `<div class="alert alert-dismissible ${
isDone(done)
}">${status}</div>`;
}
}
function setInfoPanel(info) { // if(info !== ""){
infoPanelElemnet.innerHTML = `<div class="alert alert-dismissible alert-success"><strong>Filename: </strong>${
info.filename
}<br><strong>size: </strong>${
info.size
}<br><strong>Destination: </strong>${
info.path
}</div>`;
// }
}
function isDone(bool) {
if (bool) {
return 'alert-success';
} else {
return 'alert-warning';
}
}
function setDownloadFolderDestElement(text) {
downloadFolderDestElement.innerText = text;
}
function setDownloadProgressBar(percentage){
downloadProgressBarEl.innerHTML = `<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width:${percentage}%;" aria-valuenow="${percentage}" aria-valuemin="0" aria-valuemax="100">${percentage}%</div>
</div>`
}
function resetDownloadFolderDestElement (){
downloadProgressBarEl.innerHTML =""
}
// urlInputElement.oninput = function(){
// setCaptionsStatus("");
// setStatusElement("");
// setInfoPanel("");
// }
/**
* main Download function
*/
// https://youtu.be/pxcI5g2iUCg
function downloadVideo(url) {
if (url.includes("youtube.com/playlist?")) {
setStatusElement(downloadingPlaylistMessage, false);
playlist(url);
} else {
// update user GUI on status of download
// reset captions status
if (requestedVideo()) {
setStatusElement(downloadingMessage, false);
// setup download with youtube-dl
var video = youtubedl(url,
// Optional arguments passed to youtube-dl.
// see here for options https://github.com/rg3/youtube-dl/blob/master/README.md
['--format=best'],
// Additional options can be given for calling `child_process.execFile()`.
{
cwd: destDownloadFolder,
maxBuffer: Infinity
});
// listener for video info, to get file name
video.on('info', function (info) {
var destFilePathName = path.join(destDownloadFolder, info._filename);
// update GUI with info on the file being downloaded
setInfoPanel(`title: ${
info.title
} | filename: ${
info._filename
} | size:${
info.size
} | path:${destFilePathName}`);
// TODO: sanilitse youtube file name so that it can be
// save file locally
var writeStream = fs.createWriteStream(destFilePathName);
video.pipe(writeStream);
});
video.on('end', function () {
console.info("done downloading video file");
// TODO: replace with update Div symbol
setStatusElement(finishedDownloadingMessage, true);
});
}
}
// https://www.npmjs.com/package/youtube-dl#downloading-playlists
function playlist(url) {
const video = youtubedl(url)
video.on('error', function error(err) {
console.log('error 2:', err)
})
let size = 0
let currentFileMessage;
video.on('info', function (info) {
console.log('info', info)
info.playlist
info.playlist_id
info.description
info.title
// currentFileMessage = `playlist: ${info.playlist} |playlist_id: ${info.playlist_id}| title: ${info.title} | filename: ${info._filename} | size:${info.size} | path:${destFilePathName} | description: ${ info.description}`
currentFileMessage = `playlist: ${
info.playlist
} |playlist_id: ${
info.playlist_id
}| title: ${
info.title
} | filename: ${
info._filename
} | size:${
info.size
} | path:${destFilePathName} `
// TODO: save info.description with same name as the file with .descrition
size = info.size
// let output = path.join(__dirname + '/', size + '.mp4')
// video.pipe(fs.createWriteStream(output))
var destFilePathName = path.join(destDownloadFolder, info._filename);
var writeStream = fs.createWriteStream(destFilePathName);
video.pipe(writeStream);
})
let pos = 0
video.on('data', function data(chunk) {
pos += chunk.length
// `size` should not be 0 here.
if (size) {
let percent = (pos / size * 100).toFixed(2)
// process.stdout.cursorTo(0)
// process.stdout.clearLine(1)
// process.stdout.write(percent + '%')
// console.log(percent)
// setStatusElement(`${percent}%`, false);
setStatusElement(`${currentFileMessage}`, false);
setDownloadProgressBar(percent);
}
})
video.on('end', function () {
console.info("done downloading video file");
// TODO: replace with update Div symbol
setStatusElement(finishedDownloadingMessage, true);
resetDownloadFolderDestElement()
});
video.on('next', playlist)
}
}
/**
* function to download
* TODO: provide language/languages as options, eg check boxes(?)
*/
// https://github.com/przemyslawpluta/node-youtube-dl#downloading-subtitles
function downloadCaptions(url, getAutomaticCations, languagesList, cb) {
setCaptionsStatus(subtitlesDownloadingMessage, false);
var options = { // Write automatic subtitle file (youtube only)
auto: getAutomaticCations,
// Downloads all the available subtitles.
all: false,
// Languages of subtitles to download, separated by commas.
lang: languagesList,
// The directory to save the downloaded files in.
cwd: destDownloadFolder
};
youtubedl.getSubs(url, options, function (err, files) {
if (err)
throw err;
if (files.length === 0) {
setCaptionsStatus(subtitlesNotAviableMessage, false);
} else {
setCaptionsStatus(subtitlesDownloadedMessage, true);
console.info('subtitle files downloaded:', files);
if (cb) {
cb(files);
} else {
return files;
}
}
});
}
/**
* kickstart downloafing when user clicks download btn
*/
btnLoadElement.onclick = function () {
var inputValue = getUrlInput();
if (inputValue) {
// TODO: add some checks on validity of (url) url.
// DOWNLOAD CAPTIONS
if (captionStatus()) { // automated vs human captions
var getAutomaticCations;
if (optionsRadiosHumanCaptionsElement.checked) {
getAutomaticCations = false;
} else if (optionsRadiosAutomatedCaptionsElement.checked) {
getAutomaticCations = true;
}
// list of languages
var languagesList = getSelectedValues(languageSelectionElement);
downloadCaptions(inputValue, getAutomaticCations, languagesList, function (files) {
console.info("Downloaded captions", files);
if (getCaptionPlainTextOption()) { // for files in array
console.info('getCaptionPlainTextOption', files);
files.forEach(function (f) {
var parsed = parseYoutubeVtt(openFile(path.join(destDownloadFolder, f)));
parsed = parsed.replace(/\r?\n/g, " ");
// console.log('parsed', parsed);
var destFilePathName = path.join(destDownloadFolder, f + ".txt");
fs.writeFileSync(destFilePathName, parsed);
console.info("writing plain text files", destFilePathName, parsed);
});
// convert vtt to plain text
// write plain text to destination folder.
}
});
}
// DOWNLOAD VIDEO
downloadVideo(inputValue);
}
};
// var filePath ="/Users/pietropassarelli/Desktop/Andrea_Ginzburg_-_L\'attualità_di_un_dissidente._L\'idea_di_sviluppo_in_Albert_O._Hirschman-M7LhBTmJHXg.vtt";
// //////////////////////////// Parsing youtube VTT
// /TODO: move to own module
function parseYoutubeVtt(vtt) {
var vttJSON = webvtt.parse(vtt);
var result = "";
// console.log('vttJSON',vttJSON);
vttJSON.cues.forEach(function (line, index) {
result += parseYoutubeVttTextLine(line.text) + " ";
});
return result;
}
function parseYoutubeVttTextLine(textLine) { // used http://scriptular.com/
return textLine.replace(/<[A-z|.|0-9|:|/]*>/g, "");
}
function openFile(path) { // console.log("inside open file");
var result = fs.readFileSync(path, 'utf8').toString('utf-8');
// console.log("open file result", result);
return result;
}
// /////////////////////////
// helper function
function getSelectedValues(selectionElement) {
var selected = [];
for (var i = 0; i < selectionElement.length; i++) {
if (selectionElement.options[i].selected) {
selected.push(selectionElement.options[i].value);
}
}
return selected;
}
// ////language code options
loadExtraLanguagesOptions.onclick = function () {
populateLanguageCodeOptions();
};
setDownloadDestBtnElement.onclick = function () {
const newDir = ipcRenderer.sendSync('selectDirectory');
destDownloadFolder = newDir;
setDownloadFolderDestElement(newDir)
}
function populateLanguageCodeOptions() {
languageSelectionElement.innerHTML = makeLanguageCodesOptions(ISO6391);
}
function makeLanguageCodesOptions(ISO6391) {
var allLanguageCodes = ISO6391.getAllCodes();
var results = "";
allLanguageCodes.forEach((lc) => {
results += `<option value="${lc}">${
ISO6391.getName(lc)
} \t| ${
ISO6391.getNativeName(lc)
}</option>`;
});
return results;
}
// /////////////
// https://stackoverflow.com/questions/44738314/escape-a-space-in-a-file-path-in-node-js
function escapeSpacesInFileName(fileName) {
return fileName.replace(/(\s+)/g, '\\$1')
}