index.js 14 KB

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