/
index.js
2395 lines (2154 loc) · 65.5 KB
/
index.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const ytdl = require('ytdl-core');
const ffmpeg = require('fluent-ffmpeg');
const path = require('path');
const fs = require('fs-extra');
const EventEmitter = require('events');
const request = require('request-promise');
const requestNoPromise = require('request');
const _ = require('lodash');
const acoustid = require('acoustid');
const EyeD3 = require('eyed3');
let eyed3 = new EyeD3({ eyed3_path: 'eyeD3' });
eyed3.metaHook = (m) => m;
const levenshtein = require('fast-levenshtein');
const randomstring = require('randomstring');
const cheerio = require('cheerio');
const Promise = require('bluebird');
const sharp = require('sharp');
const smartcrop = require('smartcrop-sharp');
const ytsr = require('ytsr');
const ytpl = require('ytpl');
const lcs = require('longest-common-substring');
// API keys
const API_ACOUSTID = 'lm59lNN597';
const API_SOUNDCLOUD = 'dba290d84e6ca924414c91ac12fc3c8f';
const API_SPOTIFY = 'ODNiZjMzMmQ4MDI1NGNlNzhkNjNkOWM2ZWM2N2M5ZTU6Mzg4OTIxY2M0ZjEyNGEwYWFjM2NiMzIzYTNiZGVlYmU=';
const at3 = {};
// ISO 3166-1 alpha-2 country code of the user (ex: US, FR)
at3.regionCode;
// ISO 639-1 two-letter language code of the user (ex: en, fr)
at3.relevanceLanguage;
// Folder for temporary files
at3.tempFolder = null;
// Fix for renameSync failing on Windows when cropping cover images
// See https://github.com/lovell/sharp/issues/415
sharp.cache(false);
at3.configEyeD3 = (eyeD3Path, eyeD3PathPythonPath, metaHook) => {
process.env.PYTHONPATH = eyeD3PathPythonPath;
eyed3 = new EyeD3({ eyed3_path: eyeD3Path });
if (!metaHook) {
metaHook = (m) => m;
}
eyed3.metaHook = metaHook;
};
at3.FPCALC_PATH = 'fpcalc';
at3.setFpcalcPath = (fpcalcPath) => {
at3.FPCALC_PATH = fpcalcPath;
};
at3.setFfmpegPaths = (ffmpegPath, ffprobePath) => {
if (ffmpegPath) {
at3.FFMPEG_PATH = ffmpegPath;
}
if (ffprobePath) {
at3.FFPROBE_PATH = ffprobePath;
}
};
/**
* Find lyrics for a song
* @param title string
* @param artistName string
* @return Promise
*/
at3.findLyrics = (title, artistName) => {
let promises = [];
const textln = (html) => {
html.find('br').replaceWith('\n');
html.find('script').replaceWith('');
html.find('#video-musictory').replaceWith('');
html.find('strong').replaceWith('');
html = _.trim(html.text());
html = html.replace(/\r\n\n/g, '\n');
html = html.replace(/\t/g, '');
html = html.replace(/\n\r\n/g, '\n');
html = html.replace(/ +/g, ' ');
html = html.replace(/\n /g, '\n');
return html;
};
const lyricsUrl = (title) => {
return _.kebabCase(_.trim(_.toLower(_.deburr(title))));
};
const lyricsManiaUrl = (title) => {
return _.snakeCase(_.trim(_.toLower(_.deburr(title))));
};
const lyricsManiaUrlAlt = (title) => {
title = _.trim(_.toLower(title));
title = title.replace("'", '');
title = title.replace(' ', '_');
title = title.replace(/_+/g, '_');
return title;
};
const reqWikia = request({
uri: 'http://lyrics.wikia.com/wiki/' + encodeURIComponent(artistName) + ':' + encodeURIComponent(title),
transform: (body) => {
return cheerio.load(body);
},
}).then(($) => {
return textln($('.lyricbox'));
});
const reqParolesNet = request({
uri: 'http://www.paroles.net/' + lyricsUrl(artistName) + '/paroles-' + lyricsUrl(title),
transform: (body) => {
return cheerio.load(body);
},
}).then(($) => {
if ($('.song-text').length === 0) {
return Promise.reject();
}
return textln($('.song-text'));
});
const reqLyricsMania1 = request({
uri: 'http://www.lyricsmania.com/' + lyricsManiaUrl(title) + '_lyrics_' + lyricsManiaUrl(artistName) + '.html',
transform: (body) => {
return cheerio.load(body);
},
}).then(($) => {
if ($('.lyrics-body').length === 0) {
return Promise.reject();
}
return textln($('.lyrics-body'));
});
const reqLyricsMania2 = request({
uri: 'http://www.lyricsmania.com/' + lyricsManiaUrl(title) + '_' + lyricsManiaUrl(artistName) + '.html',
transform: (body) => {
return cheerio.load(body);
},
}).then(($) => {
if ($('.lyrics-body').length === 0) {
return Promise.reject();
}
return textln($('.lyrics-body'));
});
const reqLyricsMania3 = request({
uri:
'http://www.lyricsmania.com/' +
lyricsManiaUrlAlt(title) +
'_lyrics_' +
encodeURIComponent(lyricsManiaUrlAlt(artistName)) +
'.html',
transform: (body) => {
return cheerio.load(body);
},
}).then(($) => {
if ($('.lyrics-body').length === 0) {
return Promise.reject();
}
return textln($('.lyrics-body'));
});
const reqSweetLyrics = request({
method: 'POST',
uri: 'http://www.sweetslyrics.com/search.php',
form: {
search: 'title',
searchtext: title,
},
transform: (body) => {
return cheerio.load(body);
},
})
.then(($) => {
let closestLink,
closestScore = -1;
_.forEach($('.search_results_row_color'), (e) => {
let artist = $(e)
.text()
.replace(/ - .+$/, '');
let currentScore = levenshtein.get(artistName, artist);
if (closestScore === -1 || currentScore < closestScore) {
closestScore = currentScore;
closestLink = $(e).find('a').last().attr('href');
}
});
if (!closestLink) {
return Promise.reject();
}
return request({
uri: 'http://www.sweetslyrics.com/' + closestLink,
transform: (body) => {
return cheerio.load(body);
},
});
})
.then(($) => {
return textln($('.lyric_full_text'));
});
if (/\(.*\)/.test(title) || /\[.*\]/.test(title)) {
promises.push(at3.findLyrics(title.replace(/\(.*\)/g, '').replace(/\[.*\]/g, ''), artistName));
}
promises.push(reqWikia);
promises.push(reqParolesNet);
promises.push(reqLyricsMania1);
promises.push(reqLyricsMania2);
promises.push(reqLyricsMania3);
promises.push(reqSweetLyrics);
return Promise.any(promises).then((lyrics) => {
return lyrics;
});
};
/**
* Returns true if the query corresponds
* to an URL, else false
* @param query string
* @return boolean
*/
at3.isURL = (query) => {
return /^http(s?):\/\//.test(query);
};
/**
* Get a fresh access token from Spotify API
* @return {Promise}
*/
at3.spotifyToken = () => {
return request
.post({
uri: 'https://accounts.spotify.com/api/token',
headers: {
Authorization: 'Basic ' + API_SPOTIFY,
},
form: {
grant_type: 'client_credentials',
},
json: true,
})
.then((r) => {
return r.access_token;
});
};
/**
* Perform a GET request to the Spotify API `url` endpoint
* @param {String} url URL of Spotify API endpoint to get
* @return {Promise} The request
*/
at3.requestSpotify = (url) => {
return at3.spotifyToken().then((token) => {
return request({
uri: url,
json: true,
headers: {
Authorization: 'Bearer ' + token,
},
});
});
};
/**
* Download a single video
* @param url
* @param outputFile
* @return Event
*/
at3.downloadWithYoutubeDl = (url, outputFile) => {
const download = ytdl(url, { quality: 'highestaudio' });
download.pipe(fs.createWriteStream(outputFile));
const downloadEmitter = new EventEmitter();
let aborted = false;
const onProgress = (_chunk, nbDownloaded, nbTotal) => {
const percent = ((nbDownloaded / nbTotal) * 100).toFixed(2);
downloadEmitter.emit('download-progress', {
progress: percent,
});
};
download.on('progress', onProgress);
download.once('end', () => {
if (aborted) {
return;
}
download.removeListener('progress', onProgress);
downloadEmitter.emit('download-end');
});
download.once('error', (error) => {
download.removeListener('progress', onProgress);
downloadEmitter.emit('error', new Error(error));
});
const abort = () => {
aborted = true;
download.abort();
if (fs.existsSync(outputFile)) {
fs.unlinkSync(outputFile);
}
};
downloadEmitter.once('abort', abort);
return downloadEmitter;
};
/**
* Convert a outputFile in MP3
* @param inputFile
* @param outputFile
* @param bitrate string
* @return Event
*/
at3.convertInMP3 = (inputFile, outputFile, bitrate) => {
const convertEmitter = new EventEmitter();
let aborted = false;
let started = false;
let convert = ffmpeg(inputFile);
if (at3.FFMPEG_PATH) {
convert.setFfmpegPath(at3.FFMPEG_PATH);
}
if (at3.FFPROBE_PATH) {
convert.setFfprobePath(at3.FFPROBE_PATH);
}
const onProgress = (progress) => {
convertEmitter.emit('convert-progress', {
progress: progress.percent,
});
};
convert
.audioBitrate(bitrate)
.audioCodec('libmp3lame')
.once('codecData', (_data) => {
convertEmitter.emit('convert-start');
})
.on('progress', onProgress)
.once('end', () => {
convert.removeListener('progress', onProgress);
fs.unlinkSync(inputFile);
convertEmitter.emit('convert-end');
})
.once('error', (e) => {
convert.removeListener('progress', onProgress);
if (!aborted) {
convertEmitter.emit('error', e);
} else {
if (fs.existsSync(inputFile)) {
fs.unlink(inputFile, () => {});
}
if (fs.existsSync(outputFile)) {
fs.unlink(outputFile, () => {});
}
}
})
.once('start', () => {
started = true;
if (aborted) {
abort();
}
})
.save(outputFile);
const abort = () => {
aborted = true;
if (started) {
convert.kill();
}
};
convertEmitter.once('abort', abort);
return convertEmitter;
};
/**
* Get infos about an online video
* @param url
* @return Promise
*/
at3.getInfosWithYoutubeDl = (url) => {
return ytdl.getBasicInfo(url).then((infos) => {
const thumbnails = infos.player_response.videoDetails.thumbnail.thumbnails;
return {
title: infos.videoDetails.title,
author: infos.videoDetails.author.name,
picture: thumbnails[thumbnails.length - 1].url,
};
});
// youtubedl.getInfo(url, ['--no-check-certificate'], (err, infos) => {
// if (err || infos === undefined) {
// reject();
// } else {
// resolve({
// title: infos.title,
// author: infos.uploader,
// picture: infos.thumbnail,
// });
// }
// });
// });
};
/**
* Download a single URL in MP3
* @param url
* @param outputFile
* @param bitrate
* @return Event
*/
at3.downloadSingleURL = (url, outputFile, bitrate) => {
const progressEmitter = new EventEmitter();
let tempFile = outputFile + '.video';
let downloadEnded = false;
let convert;
const dl = at3.downloadWithYoutubeDl(url, tempFile);
const onDlProgress = (infos) => {
progressEmitter.emit('download', {
progress: infos.progress,
});
};
dl.once('download-start', () => {
progressEmitter.emit('start');
});
dl.on('download-progress', onDlProgress);
dl.once('download-end', () => {
downloadEnded = true;
dl.removeListener('download-progress', onDlProgress);
progressEmitter.emit('download-end');
convert = at3.convertInMP3(tempFile, outputFile, bitrate);
const onConvertProgress = (infos) => {
progressEmitter.emit('convert', {
progress: infos.progress,
});
};
convert.on('convert-progress', onConvertProgress);
convert.once('convert-end', () => {
convert.removeListener('convert-progress', onConvertProgress);
progressEmitter.emit('end');
});
convert.once('error', (error) => {
progressEmitter.emit('error', error);
});
});
dl.once('error', (error) => {
dl.removeListener('download-progress', onDlProgress);
progressEmitter.emit('error', new Error(error));
});
progressEmitter.once('abort', () => {
if (!downloadEnded) {
dl.emit('abort');
} else {
convert.emit('abort');
}
});
return progressEmitter;
};
/**
* Try to find to title and artist from a string
* (example: a YouTube video title)
* @param query string
* @param exact boolean Can the query be modified or not
* @param last boolean Last call
* @param v boolean Verbose
* @return Promise
*/
at3.guessTrackFromString = (query, exact, last, v) => {
// [TODO] Replace exact by a level of strictness
// 0: no change at all
// 4: remove every thing useless
if (exact === undefined) {
exact = false;
}
if (last === undefined) {
last = false;
}
if (v === undefined) {
v = false;
}
if (v) {
console.log('Query: ', query);
}
let searchq = query;
if (!exact) {
searchq = searchq.replace(/\(.*\)/g, '');
searchq = searchq.replace(/\[.*\]/g, '');
searchq = searchq.replace(/lyric(s?)|parole(s?)/gi, '');
searchq = searchq.replace(/^'/, '');
searchq = searchq.replace(/ '/g, ' ');
searchq = searchq.replace(/' /g, ' ');
searchq = searchq.replace(/Original Motion Picture Soundtrack/i, '');
searchq = searchq.replace(/bande originale/i, '');
}
const requests = [];
const infos = {
title: null,
artistName: null,
};
// We search on Deezer and iTunes
// [TODO] Adding Spotify
// Deezer
const requestDeezer = request({
url: 'https://api.deezer.com/2.0/search?q=' + encodeURIComponent(searchq),
json: true,
}).then((body) => {
let title, artistName, tempTitle;
_.forEach(body.data, (s) => {
if (!title) {
if (vsimpleName(searchq, exact).replace(new RegExp(vsimpleName(s.artist.name), 'ig'))) {
if (
delArtist(s.artist.name, searchq, exact).match(new RegExp(vsimpleName(s.title_short), 'ig')) ||
vsimpleName(s.title_short).match(new RegExp(delArtist(s.artist.name, searchq, exact), 'ig'))
) {
artistName = s.artist.name;
title = s.title;
} else if (!artistName) {
artistName = s.artist.name;
tempTitle = s.title;
}
}
}
});
if (title && artistName) {
infos.title = title;
infos.artistName = artistName;
}
if (v) {
console.log('Deezer answer: ', title, '-', artistName);
}
});
// iTunes
const requestiTunes = request({
url: 'https://itunes.apple.com/search?media=music&term=' + encodeURIComponent(searchq),
json: true,
}).then((body) => {
let title, artistName, tempTitle;
_.forEach(body.results, (s) => {
if (!title) {
if (vsimpleName(searchq, exact).match(new RegExp(vsimpleName(s.artistName), 'gi'))) {
if (delArtist(s.artistName, searchq, exact).match(new RegExp(vsimpleName(s.trackCensoredName), 'gi'))) {
artistName = s.artistName;
title = s.trackCensoredName;
} else if (delArtist(s.artistName, searchq, exact).match(new RegExp(vsimpleName(s.trackName), 'gi'))) {
artistName = s.artistName;
title = s.trackName;
} else if (!artistName) {
artistName = s.artistName;
temp_title = s.trackName;
}
}
}
});
if (title && artistName) {
infos.title = title;
infos.artistName = artistName;
}
if (v) {
console.log('iTunes answer: ', title, '-', artistName);
}
});
requests.push(requestDeezer);
requests.push(requestiTunes);
return Promise.all(requests).then(() => {
if (!last && (!infos.title || !infos.artistName)) {
searchq = searchq.replace(/f(ea)?t(\.)? [^-]+/gi, ' ');
return at3.guessTrackFromString(searchq, false, true, v);
}
return infos;
});
};
/**
* Try to guess title and artist from mp3 file
* @param file
* @return Promise
*/
at3.guessTrackFromFile = (file) => {
return new Promise((resolve, _reject) => {
acoustid(file, { key: API_ACOUSTID, fpcalc: { command: at3.FPCALC_PATH } }, (err, results) => {
if (
err ||
results.length === 0 ||
!results[0].recordings ||
results[0].recordings.length === 0 ||
!results[0].recordings[0].artists ||
results[0].recordings[0].artists.length === 0
) {
resolve({});
return;
}
resolve({
title: results[0].recordings[0].title,
artistName: results[0].recordings[0].artists[0].name,
});
});
});
};
/**
* Retrieve informations about a track from artist and title
* @param title
* @param artistName
* @param exact boolean Exact search or not
* @param v boolean Verbose
* @return Promise
*/
at3.retrieveTrackInformations = (title, artistName, exact, v) => {
if (exact === undefined) {
exact = false;
}
if (v === undefined) {
v = false;
}
if (!exact) {
title = title.replace(/((\[)|(\())?radio edit((\])|(\)))?/gi, '');
}
const infos = {
title: title,
artistName: artistName,
};
const requests = [];
const requestDeezer = request({
url: 'https://api.deezer.com/2.0/search?q=' + encodeURIComponent(artistName + ' ' + title),
json: true,
}).then((body) => {
let deezerInfos;
_.forEach(body.data, (s) => {
if (
!infos.deezerId &&
imatch(vsimpleName(title), vsimpleName(s.title)) &&
imatch(vsimpleName(artistName), vsimpleName(s.artist.name))
) {
infos.deezerId = s.id;
deezerInfos = _.clone(s);
}
});
if (infos.deezerId) {
infos.artistName = deezerInfos.artist.name;
infos.title = deezerInfos.title;
return at3
.getDeezerTrackInfos(infos.deezerId, v)
.then((deezerInfos) => {
infos = deezerInfos;
})
.catch(() => {});
}
});
const requestiTunes = request({
url: 'https://itunes.apple.com/search?media=music&term=' + encodeURIComponent(artistName + ' ' + title),
json: true,
}).then((body) => {
let itunesInfos;
_.forEach(body.results, (s) => {
if (
!infos.itunesId &&
(imatch(vsimpleName(title), vsimpleName(s.trackName)) ||
imatch(vsimpleName(title), vsimpleName(s.trackCensoredName))) &&
imatch(vsimpleName(artistName), vsimpleName(s.artistName))
) {
infos.itunesId = s.trackId;
itunesInfos = _.clone(s);
}
});
if (!infos.deezerId && itunesInfos) {
infos.artistName = itunesInfos.artistName;
if (imatch(vsimpleName(infos.title), vsimpleName(itunesInfos.trackName))) {
infos.title = itunesInfos.trackName;
} else {
infos.title = itunesInfos.trackCensoredName;
}
infos.itunesAlbum = itunesInfos.collectionId;
infos.position = itunesInfos.trackNumber;
infos.nbTracks = itunesInfos.trackCount;
infos.album = itunesInfos.collectionName;
infos.releaseDate = itunesInfos.releaseDate.replace(/T.+/, '');
infos.cover = itunesInfos.artworkUrl100.replace('100x100', '200x200');
infos.genre = itunesInfos.primaryGenreName;
infos.discNumber = itunesInfos.discNumber;
infos.duration = itunesInfos.trackTimeMillis / 1000;
}
if (v) {
console.log('iTunes infos: ', itunesInfos);
}
});
requests.push(requestDeezer);
requests.push(requestiTunes);
return Promise.all(requests).then(() => infos);
};
/**
* Retrieve detailed infos about a Deezer Track
* @param trackId
* @param v boolean Verbosity
* @return Promise(trackInfos)
*/
at3.getDeezerTrackInfos = (trackId, v) => {
const infos = {
deezerId: trackId,
};
return request({
url: 'https://api.deezer.com/2.0/track/' + infos.deezerId,
json: true,
})
.then((trackInfos) => {
if (trackInfos.error) {
return Promise.reject();
}
infos.title = trackInfos.title;
infos.artistName = trackInfos.artist.name;
infos.position = trackInfos.track_position;
infos.duration = trackInfos.duration;
infos.deezerAlbum = trackInfos.album.id;
infos.discNumber = trackInfos.disk_number;
return request({
url: 'https://api.deezer.com/2.0/album/' + infos.deezerAlbum,
json: true,
});
})
.then((albumInfos) => {
infos.album = albumInfos.title;
infos.releaseDate = albumInfos.release_date;
infos.nbTracks = albumInfos.tracks.data.length;
infos.genreId = albumInfos.genre_id;
infos.cover = albumInfos.cover_big;
return request({
url: 'https://api.deezer.com/2.0/genre/' + infos.genreId,
json: true,
});
})
.then((genreInfos) => {
infos.genre = genreInfos.name;
if (v) {
console.log('Deezer infos: ', infos);
}
return infos;
});
};
/**
* Get complete information (title, artist, release date, genre, album name...)
* for a Spotify track
* @param {trackId} string The Spotify track id
* @param {v} boolean The verbosity
* @return Promise
*/
at3.getSpotifyTrackInfos = (trackId, v) => {
const infos = {
spotifyId: trackId,
};
return at3
.requestSpotify('https://api.spotify.com/v1/tracks/' + trackId)
.then((trackInfos) => {
infos.title = trackInfos.name;
infos.artistName = trackInfos.artists[0].name;
infos.duration = Math.ceil(trackInfos.duration_ms / 1000);
infos.position = trackInfos.track_number;
infos.discNumber = trackInfos.disc_number;
infos.spotifyAlbum = trackInfos.album.id;
return at3.requestSpotify('https://api.spotify.com/v1/albums/' + trackInfos.album.id);
})
.then((albumInfos) => {
infos.album = albumInfos.name;
infos.cover = albumInfos.images[0].url;
infos.genre = albumInfos.genres[0] || '';
infos.nbTracks = albumInfos.tracks.total;
infos.releaseDate = albumInfos.release_date;
return infos;
});
};
/**
* Add tags to MP3 file
* @param file
* @param infos
* @return Promise
*/
at3.tagFile = (file, infos) => {
const meta = {
title: infos.title,
artist: infos.artistName,
};
if (infos.album) {
meta.album = infos.album;
}
if (infos.position) {
meta.track = infos.position;
}
if (infos.nbTracks) {
meta.trackTotal = infos.nbTracks;
}
if (infos.discNumber) {
meta.disc = infos.discNumber;
}
if (infos.lyrics) {
meta.lyrics = infos.lyrics;
}
if (infos.releaseDate) {
meta.year = /[0-9]{4}/.exec(infos.releaseDate)[0];
}
if (infos.genre) {
meta.genre = infos.genre.replace(/\/.+/g, '');
}
return new Promise((resolve, reject) => {
eyed3.updateMeta(file, eyed3.metaHook(meta), (err) => {
if (err) {
return reject(err);
}
if (infos.cover) {
let coverPath = file + '.cover.jpg';
requestNoPromise(infos.cover, () => {
// Check that the cover is a square
const coverFile = sharp(coverPath);
coverFile
.metadata()
.then((metadata) => {
if (metadata.width != metadata.height) {
// In that case we will crop the cover to get a square
const tempCoverPath = file + '.cover.resized.jpg';
return smartcrop
.crop(coverPath, { width: 100, height: 100 })
.then((result) => {
let crop = result.topCrop;
return coverFile
.extract({
width: crop.width,
height: crop.height,
left: crop.x,
top: crop.y,
})
.toFile(tempCoverPath);
})
.then(() => {
fs.renameSync(tempCoverPath, coverPath);
});
}
})
.then(() => {
eyed3.updateMeta(file, eyed3.metaHook({ image: coverPath }), (err) => {
fs.unlinkSync(coverPath);
if (err) {
return reject(err);
}
resolve();
});
});
}).pipe(fs.createWriteStream(coverPath));
} else {
resolve();
}
});
});
};
/**
* Search and return complete information about a single video url
* @param url
* @param v boolean Verbosity
* @return Promise(object)
*/
at3.getCompleteInfosFromURL = (url, v) => {
let infosFromString;
// Try to find information based on video title
return at3
.getInfosWithYoutubeDl(url)
.then((videoInfos) => {
infosFromString = {
title: videoInfos.title,
artistName: videoInfos.author,
cover: videoInfos.picture.replace('hqdefault', 'mqdefault'), // [TODO]: getting a better resolution and removing the black borders
originalTitle: videoInfos.title,
};
if (v) {
console.log('Video infos: ', infosFromString);
}
// progressEmitter.emit('infos', _.clone(infosFromString));
return at3.guessTrackFromString(videoInfos.title, false, false, v);
})
.then((guessStringInfos) => {
if (guessStringInfos.title && guessStringInfos.artistName) {
return at3.retrieveTrackInformations(guessStringInfos.title, guessStringInfos.artistName, false, v);
} else {
return Promise.resolve();
}
})
.then((guessStringInfos) => {
if (guessStringInfos) {
guessStringInfos.originalTitle = infosFromString.originalTitle;
infosFromString = guessStringInfos;
// progressEmitter.emit('infos', _.clone(infosFromString));
if (v) {
console.log('guessStringInfos: ', guessStringInfos);
}
} else {
if (v) {
console.log('Cannot retrieve detailed information from video title');
}
}
return infosFromString;
})
.then((guessStringInfos) => {
if (guessStringInfos.deezerId) {
return at3.getDeezerTrackInfos(guessStringInfos.deezerId, v);
} else if (guessStringInfos.spotifyId) {
return at3.getSpotifyTrackInfos(guessStringInfos.spotifyId, v);
} else {
return guessStringInfos;
}
})
.catch((_error) => {
// The download must have failed to, and emit an error
});
};
/**
* Identify the song from a file and then search complete information about it
* @param file string
* @param v boolean Verbosity
* @return Promise(object)
*/
at3.getCompleteInfosFromFile = (file, v) => {
return at3
.guessTrackFromFile(file)
.then((guessFileInfos) => {
if (guessFileInfos.title && guessFileInfos.artistName) {
return at3.retrieveTrackInformations(guessFileInfos.title, guessFileInfos.artistName, false, v);
} else {
return Promise.resolve();
}
})
.then((guessFileInfos) => {
if (guessFileInfos) {
if (v) {
console.log('guessFileInfos: ', guessFileInfos);
}
return guessFileInfos;
} else {
if (v) {
console.log('Cannot retrieve detailed information from MP3 file');
}
}
});
};
/**
* Simplify a string so it works well as a filename
* @param {String} string