index.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. "use strict";
  2. const inquirer = require('inquirer');
  3. const bent = require('bent');
  4. const fs = require('fs');
  5. const util = require('util');
  6. const stream = require('stream');
  7. const pipeline = util.promisify(stream.pipeline);
  8. const path = require('path');
  9. const async = require('async');
  10. const chalk = require('chalk');
  11. const ora = require('ora');
  12. const spinner = ora({spinner: { interval: 100, frames: ['.', 'o', 'O', '@', '*'] }}); // global spinner
  13. const MAX_RETRY = 10;
  14. const RETRY_INTERVAL = 2000;
  15. const NETWORK_ERRORS = ['ENOTFOUND', 'ECONNRESET', 'ETIMEDOUT', 'ISC503', 'MAXQUERIES'] // ISC503 = Incorrect status code 503
  16. /*******************************************
  17. ************* Requests *******************
  18. *******************************************/
  19. const retryRequest = async (retryCount, func, params=[]) => {
  20. if (retryCount==MAX_RETRY && spinner.text.indexOf('Error')==-1)
  21. spinner.warn('Aaaah! Network probleeems!');
  22. return await new Promise(resolve => {
  23. setTimeout(() => resolve(func(...params, retryCount-1)), RETRY_INTERVAL);
  24. });
  25. }
  26. const getSpotifyToken = async (retry=MAX_RETRY) => {
  27. // The user-agent header is required. Otherwise, the request returns a 400 status code
  28. const getJson = bent('GET', 'json', { 'User-Agent': 'Mozilla/5.0', }, 200);
  29. let json = null;
  30. try{
  31. json = await getJson('https://open.spotify.com/get_access_token');
  32. }
  33. catch(err){
  34. if (NETWORK_ERRORS.includes(err.code) && retry) return await retryRequest(retry, getSpotifyToken);
  35. else throw err;
  36. }
  37. return json['accessToken'];
  38. }
  39. const getPlaylistFromURL = async (url, retry=MAX_RETRY) => {
  40. // Retrieve information necessary to make the request
  41. let token = await getSpotifyToken();
  42. let [_, type, id] = url.match(/((?:album)|(?:playlist))\/((?:\d|[a-z]|[A-Z])+)(?:\?si=)?/);
  43. let isAlbum = type==="album";
  44. // Make request to spotify API
  45. const requestSpotify = bent('GET', 'json', 200, { 'Authorization': `Bearer ${token}` });
  46. let response = null;
  47. try{
  48. response = await requestSpotify(`https://api.spotify.com/v1/${type}s/${id}`); // to /albums or /playlists
  49. }
  50. catch(err){
  51. if (NETWORK_ERRORS.includes(err.code) && retry) return await retryRequest(retry, getPlaylistFromURL, [plUrl]);
  52. else throw err;
  53. }
  54. let playlist = {};
  55. // Parse response
  56. playlist['name'] = response['name'];
  57. playlist['totalSongs'] = response['tracks']['total'];
  58. playlist['owner'] = (isAlbum?
  59. response['artists'][0]['name'] :
  60. response['owner']['display_name']
  61. );
  62. response = response['tracks'];
  63. playlist['songs'] = response['items'].map(song => ({
  64. 'artist': (isAlbum?
  65. song['artists'][0]['name'] :
  66. song['track']['artists'][0]['name']
  67. ),
  68. 'title': (isAlbum?
  69. song['name'] :
  70. song['track']['name']
  71. )
  72. }));
  73. // The Spotify API has a limit for 100 tracks per request
  74. // if the playlist has more than 100 tracks, the response
  75. // contains a 'next' url for the next 100 tracks.
  76. // Albums have a 50 limit instead of 100.
  77. let counter = 0;
  78. let nullSongs = [];
  79. while (response['next']){
  80. counter += isAlbum? 50 : 100;
  81. spinner.text = `Loading playlist details. ${counter} songs processed`;
  82. let nextPage = response['next'];
  83. try {
  84. response = await requestSpotify(nextPage)
  85. }
  86. catch(err){
  87. if (NETWORK_ERRORS.includes(err.code) && retry) return await retryRequest(retry, getPlaylistFromURL, [plUrl]);
  88. else throw err;
  89. }
  90. // Parse response
  91. playlist['songs'] = playlist['songs'].concat(response['items'].map(song => {
  92. if (!isAlbum) {
  93. if (!song['track']) return null; // empty song in playlist
  94. song = song['track']; // playlist tracks contain artist/title in song['track']
  95. // album tracks don't have a 'track' key
  96. }
  97. return {
  98. 'artist': song['artists'][0]['name'],
  99. 'title': song['name']
  100. }
  101. }));
  102. }
  103. playlist["songs"] = playlist["songs"].filter(song => {
  104. return song!=null;
  105. });
  106. playlist["totalSongs"] = playlist["songs"].length;
  107. return playlist;
  108. }
  109. const getDeezerSongUrl = async (song, retry=MAX_RETRY) => {
  110. /*
  111. @return {String} URL of song in Deezer
  112. {null} If song couldn't be found
  113. */
  114. const deezerSearch = bent('https://api.deezer.com/search?q=', 'GET', 'json', 200);
  115. let bestTitle = song.title.replace(/(feat\.? )|(ft\.? )|(with )|(con )/, '');
  116. let encodedSong = encodeURIComponent(`${song.artist} ${bestTitle}`);
  117. let results = null;
  118. try {
  119. results = await deezerSearch(encodedSong);
  120. if ('error' in results) throw {...results['error'], code:'DZERROR'};
  121. }
  122. catch(err){
  123. if (err.statusCode) err['code'] = `ISC${err.statusCode}`;
  124. if (NETWORK_ERRORS.includes(err.code) && retry) return await retryRequest(retry, getDeezerSongUrl, [song]);
  125. else throw err;
  126. }
  127. // Parse response
  128. results = results['data'];
  129. if (!results.length)
  130. return null;
  131. return results[0]['link'];
  132. }
  133. const downloadDeezerSong = async (song, directory, quality, retry=MAX_RETRY) => {
  134. /*
  135. @return {String} Path to downloaded song
  136. */
  137. // Get redirected URL
  138. // The dzloader API receives the deezer URL and redirects to the file URL
  139. const requestDzloader = bent('https://dz.loaderapp.info', 'GET', 200, 302);
  140. let redirectedRes = null;
  141. try{
  142. redirectedRes = await requestDzloader(`/deezer/${quality}/${song.deezerUrl}`);
  143. }
  144. catch(err){
  145. if (err.statusCode) err['code'] = `ISC${err.statusCode}`;
  146. if (NETWORK_ERRORS.includes(err.code) && retry)
  147. return await retryRequest(retry, downloadDeezerSong, [song, directory, quality]);
  148. else throw err;
  149. }
  150. let downloadEndpoint = redirectedRes.headers['location'];
  151. // Download file
  152. let bytes = null;
  153. try{
  154. bytes = await requestDzloader(downloadEndpoint);
  155. }
  156. catch(err){
  157. if (err.statusCode) err['code'] = `ISC${err.statusCode}`;
  158. if (NETWORK_ERRORS.includes(err.code) && retry)
  159. return await retryRequest(retry, downloadDeezerSong, [song, directory, quality]);
  160. else throw err;
  161. }
  162. // Create file
  163. let extension = quality==1411? '.flac' : '.mp3';
  164. let filepath = path.join(directory, song.displayName.replace(/[/\\?%*:|"<>]/, '') + extension);
  165. const file = fs.createWriteStream(filepath);
  166. await pipeline(bytes, file).catch(err => { throw err; });
  167. return file.path;
  168. }
  169. const downloadSpotifySong = async (song, directory, quality) => {
  170. /*
  171. @return {String} Path to downloaded song
  172. */
  173. let deezerUrl = await getDeezerSongUrl(song).catch(async err => { throw err; });
  174. if (!deezerUrl) throw {'code': 'NFDEEZER'};
  175. song['deezerUrl'] = deezerUrl;
  176. return await downloadDeezerSong(song, directory, quality).catch(async err => {throw err;});
  177. }
  178. /*******************************************
  179. ************* Interface *******************
  180. *******************************************/
  181. const displaySptDl = () => {
  182. process.stdout.write(chalk.green(' ██████  ██  ███████ ██████  ████████\n'));
  183. process.stdout.write(chalk.green(' ██   ██ ██  ██      ██   ██    ██   \n'));
  184. process.stdout.write(chalk.green(' ██  ██ ██ █████ ███████ ██████   ██  \n'));
  185. process.stdout.write(chalk.green(' ██  ██ ██            ██ ██      ██  \n'));
  186. process.stdout.write(chalk.green(' ██████  ███████  ███████ ██  ██ v1.3\n\n'));
  187.                                 
  188. }
  189. const formatTitle = (title) => {
  190. return chalk.bold(title.toUpperCase());
  191. }
  192. const fillStringTemplate = (template, values) => template.replace(/%(.*?)%/g, (x,g)=> values[g]);
  193. const songToString = (song, firstArtist=true) => {
  194. if (firstArtist) return (song.artist + ' - ' + song.title);
  195. return (song.title + ' - ' + song.artist);
  196. }
  197. const displayQuestions = async () => {
  198. let questions = [
  199. {
  200. name: 'playlistUrl',
  201. prefix: '♪',
  202. message: 'Spotify playlist or album url: ',
  203. validate: (input) => {
  204. let regExVal = /^(https:\/\/)?open\.spotify\.com\/((playlist)|(album))\/(\d|[a-z]|[A-Z])+(\?si=.*)?$/;
  205. if (!regExVal.test(input))
  206. return 'You sure this is a Spotify URL?';
  207. return true;
  208. }
  209. },
  210. {
  211. type: 'list',
  212. name: 'quality',
  213. prefix: '♪',
  214. message: 'Select mp3 quality',
  215. choices: [
  216. {'name': '128 kpps (mp3)', 'value': 128},
  217. {'name': '320 kpps (mp3)', 'value' : 320},
  218. {'name': '1411 kpps (flac)', 'value' : 1411}
  219. ]
  220. },
  221. {
  222. name: 'directory',
  223. prefix: '♪',
  224. message: 'Where do you want to download your songs?',
  225. validate: input => {
  226. if (!fs.existsSync(input))
  227. return 'Eeeh... this path doesn\'t exist';
  228. return true;
  229. }
  230. },
  231. {
  232. type: 'list',
  233. prefix: '♪',
  234. name: 'displayNameTemplate',
  235. message: `How do you prefer to name your songs?
  236. For example: The Beatles - Hey Jude (%artist% - %title%)
  237. Hey Jude - The Beatles (%title% - %artist%)\n`,
  238. choices: [
  239. '%artist% - %title%',
  240. '%title% - %artist%'
  241. ]
  242. },
  243. {
  244. prefix: '⚡',
  245. name: 'parallelDownloads',
  246. message: 'Number of parallel downloads (Leave empty if you don\'t know what\'s this): ',
  247. validate: input => {
  248. return /^[1-9]|10$/.test(input)? true : 'Noo! Just enter a value between 1 and 10';
  249. },
  250. default: 6
  251. }
  252. ];
  253. let answers = await inquirer.prompt(questions);
  254. // Add 'https:// to spotify url if missing'
  255. if (!/^https:\/\//.test(answers.playlistUrl))
  256. answers.playlistUrl = 'https://'+answers.playlistUrl;
  257. return answers;
  258. }
  259. const displayPlaylistInfo = async playlist => {
  260. /* @param playlist {Object}
  261. * .name {String} Playlist/Album name
  262. * .owner {String} Owner name
  263. * .totalSongs {Number} Number of songs in playlist
  264. * .songs {Object}
  265. * .artist {String} Name of song artist
  266. * .title {String} Song title
  267. * .displayName {String} Song name to display
  268. */
  269. process.stdout.write(formatTitle('Album/Playlist Details\n'));
  270. process.stdout.write(chalk.bold('Name: ') + playlist.name + '\n');
  271. process.stdout.write(chalk.bold('Owner: ') + playlist.owner + '\n');
  272. process.stdout.write(chalk.bold('Total valid songs: ') + playlist.totalSongs + '\n');
  273. let answers = await inquirer.prompt([
  274. {
  275. type: 'checkbox',
  276. prefix: '♪',
  277. name: 'songsToDl',
  278. message: 'Uncheck any song you DON\'T want to download',
  279. pageSize: process.stdout.rows - 7, // 5 = 3 process.stdout.write before + inquire logs + 2 extra space
  280. choices: playlist.songs.map(song => (
  281. {
  282. 'name': song.displayName,
  283. 'value': song,
  284. 'checked': true
  285. })
  286. )
  287. }
  288. ]);
  289. return answers['songsToDl'];
  290. }
  291. const displayFinalReport = (failedDownloads, totalSongs, directory) => {
  292. clearConsole();
  293. console.log('All done!\n');
  294. let nfailed = failedDownloads.length;
  295. let nsuccessful = totalSongs-failedDownloads.length;
  296. process.stdout.write(formatTitle('Final report\n'));
  297. process.stdout.write(`${nsuccessful} successful downloads.\nCouldn't download ${nfailed} songs\n`);
  298. if (!failedDownloads.length) return;
  299. let buff = '';
  300. for (let fail of failedDownloads){
  301. let line = `[${fail.error}] ${fail.song}\n`;
  302. buff += line;
  303. process.stdout.write(line);
  304. }
  305. // Display error summary
  306. let errors = failedDownloads.map(fail => fail.error);
  307. errors = errors.reduce((acum,cur) => Object.assign(acum,{[cur]: (acum[cur] | 0)+1}),{});
  308. buff += '\n';
  309. process.stdout.write(chalk.bold('\nError summary\n'));
  310. if ('NFDEEZER' in errors)
  311. process.stdout.write(`[NFDEEZER] Songs not found in Deezer: ${errors['NFDEEZER']}\n`);
  312. for (let error in errors){
  313. let line = '';
  314. if (error!=='NFDEEZER')
  315. line = `[${error}]: ${errors[error]}\n`;
  316. else
  317. buff += `[NFDEEZER]: ${errors['NFDEEZER']}\n`;
  318. buff+=line;
  319. process.stdout.write(line);
  320. }
  321. fs.writeFileSync(path.join(directory, 'failed-songs.txt'), buff);
  322. process.stdout.write(chalk.bold(`This report has been save in failed-songs.txt in ${directory}\n`))
  323. }
  324. const clearConsole = () => { console.clear(); }
  325. /*******************************************
  326. *********** Control App Flow **************
  327. *******************************************/
  328. (async () => {
  329. clearConsole();
  330. displaySptDl();
  331. /* Get input from user */
  332. let {playlistUrl, quality, directory, displayNameTemplate, parallelDownloads} = await displayQuestions();
  333. clearConsole();
  334. /* Get information about the Spotify playlist with the Spotify API.
  335. This might take a few seconds */
  336. spinner.start('Loading playlist details');
  337. let playlist = await getPlaylistFromURL(playlistUrl);
  338. spinner.stop();
  339. /* Add display name attribute to songs */
  340. playlist.songs.forEach(song => {
  341. song['displayName'] = fillStringTemplate(displayNameTemplate, song);
  342. });
  343. /* Show playlist information and select sorted songs to download */
  344. playlist.songs.sort( (a,b) => {
  345. return a.displayName.toLowerCase() < b.displayName.toLowerCase()? -1 : a.displayName > b.displayName? 1 : 0;
  346. })
  347. let songsToDownload = await displayPlaylistInfo(playlist);
  348. clearConsole();
  349. /* Download songs */
  350. process.stdout.write(formatTitle('Downloading songs\n'));
  351. directory = path.join(directory, 'downloaded-songs');
  352. if (!fs.existsSync(directory)){
  353. fs.mkdirSync(directory);
  354. }
  355. // Download songs
  356. let finished = 0;
  357. let failedDownloads = [];
  358. await async.eachOfLimit(songsToDownload, parallelDownloads, async (song, songIndex) => {
  359. let errorCode = null;
  360. let filename = await downloadSpotifySong(song, directory, quality)
  361. .catch(async err => {
  362. errorCode = err.code? err.code : err.message;
  363. });
  364. finished+=1;
  365. if (!errorCode)
  366. process.stdout.write(`${chalk.green('√')} Finished ${song.displayName}`);
  367. else{
  368. process.stdout.write(chalk.red(`× Error [${errorCode}] Couldn\'t download ${song.displayName}`));
  369. failedDownloads.push({ 'song': song.displayName, 'error': errorCode });
  370. }
  371. process.stdout.write('');
  372. process.stdout.write(chalk.blue(` [${finished}/${playlist.totalSongs}` +
  373. ` | ${parseInt(finished/playlist.totalSongs*100)}%` +
  374. ` | ${failedDownloads.length} errors]\n`));
  375. })
  376. .catch(err => { if (err) throw err; });
  377. displayFinalReport(failedDownloads, playlist.totalSongs, directory);
  378. process.stdout.write('You can close this now. Press any key to exit.\n');
  379. process.stdin.setRawMode(true);
  380. process.stdin.resume();
  381. process.stdin.on('data', process.exit.bind(process, 0));
  382. })();