fe3c43b6849a5446a7227dadb7f47e964f6b1e96
[DeezloaderRemix.git] / app / app.js
1 /*
2 *   _____                _                 _             _____                _
3 *  |  __ \              | |               | |           |  __ \              (_)
4 *  | |  | | ___  ___ ___| | ___   __ _  __| | ___ _ __  | |__) |___ _ __ ___  ___  __
5 *  | |  | |/ _ \/ _ \_  / |/ _ \ / _` |/ _` |/ _ \ '__| |  _  // _ \ '_ ` _ \| \ \/ /
6 *  | |__| |  __/  __// /| | (_) | (_| | (_| |  __/ |    | | \ \  __/ | | | | | |>  <
7 *  |_____/ \___|\___/___|_|\___/ \__,_|\__,_|\___|_|    |_|  \_\___|_| |_| |_|_/_/\_\
8 *
9 **/
10
11 // Server stuff
12 const express = require('express')
13 const app = express()
14 const server = require('http').createServer(app)
15 const io = require('socket.io').listen(server, {log: false, wsEngine: 'ws'})
16 // Music tagging stuff
17 const mflac = require('./lib/flac-metadata')
18 const ID3Writer = require('./lib/browser-id3-writer')
19 const deezerApi = require('deezer-api')
20 const spotifyApi = require('spotify-web-api-node')
21 // App stuff
22 const fs = require('fs-extra')
23 const async = require('async')
24 const request = require('request-promise')
25 const requestOld = require('request')
26 const os = require('os')
27 const path = require('path')
28 const logger = require('./utils/logger.js')
29 const queue = require('queue')
30 const localpaths = require('./utils/localpaths.js')
31 const package = require('./package.json')
32 const stq = require('sequential-task-queue')
33
34 // First run, create config file
35 if(!fs.existsSync(localpaths.user+"config.json")){
36         fs.outputFileSync(localpaths.user+"config.json",fs.readFileSync(__dirname+path.sep+"default.json",'utf8'))
37 }
38
39 // Main Constants
40 // Files
41 const configFileLocation = localpaths.user+"config.json"
42 // Folders
43 var coverArtFolder = 'deezloader-imgs' + path.sep
44 var defaultDownloadFolder = path.sep + 'Deezloader Music' + path.sep
45
46 if(process.platform == "android"){
47     coverArtFolder = localpaths.user + coverArtFolder
48     fs.ensureFileSync(coverArtFolder + '.nomedia');
49     defaultDownloadFolder = localpaths.home + path.sep + 'Music' + defaultDownloadFolder
50 }else{
51     coverArtFolder = os.tmpdir() + path.sep + coverArtFolder
52     defaultDownloadFolder = localpaths.home + defaultDownloadFolder
53 }
54
55 // Default settings
56 const defaultSettings = require('./default.json').userDefined
57 // Spotify Files
58 const spotifySupport = fs.existsSync(localpaths.user+"authCredentials.js")
59 if (spotifySupport){
60         var authCredentials = require(localpaths.user+'authCredentials.js')
61         var Spotify = new spotifyApi(authCredentials)
62 }
63
64 // Setup the folders START
65 var mainFolder = defaultDownloadFolder
66
67 // See if all settings are there after update
68 var configFile = require(localpaths.user+path.sep+"config.json");
69 for (let x in defaultSettings){
70         if (typeof configFile.userDefined[x] != typeof defaultSettings[x]){
71                 configFile.userDefined[x] = defaultSettings[x]
72         }
73 }
74 // Set default download folder if not userDefined
75 if (configFile.userDefined.downloadLocation != "") {
76         mainFolder = configFile.userDefined.downloadLocation
77 }
78
79 initFolders();
80
81 // Route and create server
82 app.use('/', express.static(__dirname + '/public/'))
83 server.listen(configFile.serverPort)
84 logger.info('Server is running @ localhost:' + configFile.serverPort)
85
86 var dqueue = new stq.SequentialTaskQueue()
87 var downloadQueue = {}
88 var trackQueue = queue({
89         autostart: true
90 })
91 trackQueue.concurrency = configFile.userDefined.queueConcurrency
92
93 // START sockets clusterfuck
94 io.sockets.on('connection', function (s) {
95         logger.info("Connection received!")
96
97         // Check for updates
98         request({
99                 url: "https://notabug.org/RemixDevs/DeezloaderRemix/raw/master/update.json",
100                 json: true
101         })
102         .then(body=>{
103                 logger.info("Checking for updates")
104                 let [currentVersion_MAJOR, currentVersion_MINOR, currentVersion_PATCH] = package.version.split(".").map(x=>parseInt(x))
105                 let [lastVersion_MAJOR, lastVersion_MINOR, lastVersion_PATCH] = body.version.split(".").map(x=>parseInt(x))
106                 if (
107                         lastVersion_MAJOR>currentVersion_MAJOR ||
108                         lastVersion_MAJOR==currentVersion_MAJOR && lastVersion_MINOR>currentVersion_MINOR ||
109                         lastVersion_MAJOR==currentVersion_MAJOR && lastVersion_MINOR==currentVersion_MINOR && lastVersion_PATCH>currentVersion_PATCH
110                 ){
111                         logger.info("Update Available")
112                         s.emit("messageUpdate", {title: `Version ${lastVersion_MAJOR}.${lastVersion_MINOR}.${lastVersion_PATCH} is available!`, msg: body.changelog, lastVersion: body.version})
113                 }else{
114                         logger.info("Running the latest version!")
115                 }
116         })
117         .catch(error=>{
118                 logger.error(`UpdateCheck failed: ${error.stack ? error.stack : error}`)
119         })
120
121         // Connection dependet variables
122         s.Deezer = new deezerApi()
123
124         s.emit("checkAutologin")
125         s.emit("getDefaultSettings", defaultSettings, defaultDownloadFolder)
126         s.emit("populateDownloadQueue", downloadQueue)
127
128         const captcha = require('./public/js/captcha');
129         captcha.callbackResponse = function (data) {
130                 s.emit("getCaptcha", data)
131         };
132
133         // Function for logging in
134         s.on("login", async function (username, password, captchaResponse) {
135                 try{
136                         logger.info("Logging in");
137                         await s.Deezer.login(username, password, captchaResponse)
138                         s.emit("login", {user: s.Deezer.user})
139                         logger.info("Logged in successfully")
140                         // Save session login so next time login is not needed
141                         // This is the same method used by the official website
142                         s.emit('getCookies', s.Deezer.getCookies())
143                 }catch(err){
144                         s.emit("login", {error: err.message})
145                         logger.error(`Login failed: ${err.message}`)
146                 }
147         })
148
149         // Function for login with userToken
150         s.on("loginViaUserToken", async function (userToken) {
151                 try{
152                         logger.info("Logging in");
153                         await s.Deezer.loginViaArl(userToken)
154                         s.emit("login", {user: s.Deezer.user})
155                         logger.info("Logged in successfully")
156                         s.emit('getCookies', s.Deezer.getCookies())
157                 }catch(err){
158                         s.emit("login", {error: err.message})
159                         logger.error(`Login failed: ${err.message}`)
160                 }
161         });
162
163         // Function for autologin
164         s.on("autologin", async function(jar, email){
165                 try{
166       await s.Deezer.loginViaCookies(jar, email)
167                         s.emit('login', {user: s.Deezer.user})
168     }catch(err){
169       s.emit('login', {error: err.message})
170                         logger.error(`Autologin failed: ${err.message}`)
171       return
172     }
173         })
174
175         // Function for logout
176         s.on("logout", function(){
177                 logger.info("Logged out")
178                 // Creating new object to clear the cookies
179                 s.Deezer = new deezerApi()
180                 return
181         })
182
183         // Returns list of charts available
184         s.on("getChartsCountryList", async function (data) {
185                 try{
186                         let charts = await s.Deezer.legacyGetChartsTopCountry()
187                         charts = charts.data || []
188                         let countries = []
189                         for (let i = 0; i < charts.length; i++) {
190                                 let obj = {
191                                         country: charts[i].title.replace("Top ", ""),
192                                         picture_small: charts[i].picture_small,
193                                         picture_medium: charts[i].picture_medium,
194                                         picture_big: charts[i].picture_big,
195                                         playlistId: charts[i].id
196                                 }
197                                 countries.push(obj)
198                         }
199                         s.emit("getChartsCountryList", {countries: countries, selected: data.selected})
200                 }catch(err){
201                         logger.error(`getChartsCountryList failed: ${err.stack}`)
202                         return
203                 }
204         })
205
206         // Returns chart tracks from Playlist ID
207         async function getChartsTrackListById(playlistId){
208                 if (typeof playlistId === 'undefined') {
209                         s.emit("getChartsTrackListByCountry", {err: "Can't find that playlist"})
210                         return
211                 }
212                 try{
213                         let tracks = await s.Deezer.legacyGetPlaylistTracks(playlistId)
214                         s.emit("getChartsTrackListByCountry", {
215                                 playlistId: playlistId,
216                                 tracks: tracks.data
217                         })
218                 }catch(err){
219                         s.emit("getChartsTrackListByCountry", {err: err})
220                         logger.error(`getChartsTrackListById failed: ${err.stack}`)
221                         return
222                 }
223         }
224
225         // Returns chart tracks from country name
226         async function getChartsTrackListByCountry(country){
227                 if (typeof country === 'undefined') {
228                         s.emit("getChartsTrackListByCountry", {err: "No country passed"})
229                         return
230                 }
231                 try{
232                         let charts = await s.Deezer.legacyGetChartsTopCountry()
233                         charts = charts.data || []
234                         let countries = []
235                         for (let i = 0; i < charts.length; i++) {
236                                 countries.push(charts[i].title.replace("Top ", ""))
237                         }
238                         if (countries.indexOf(country) == -1) {
239                                 s.emit("getChartsTrackListByCountry", {err: "Country not found"})
240                                 return
241                         }
242                         let playlistId = charts[countries.indexOf(country)].id
243                         await getChartsTrackListById(playlistId)
244                 }catch(err){
245                         logger.error(`getChartsTrackListByCountry failed: ${err.stack}`)
246                         return
247                 }
248         }
249         s.on("getChartsTrackListByCountry", function (data) {getChartsTrackListByCountry(data.country)})
250
251         // Returns list of playlists
252         async function getMyPlaylistList(){
253                 try{
254                         logger.info("Loading Personal Playlists")
255                         let data = await s.Deezer.legacyGetUserPlaylists(s.Deezer.user.id)
256                         data = data.data || []
257                         let playlists = []
258                         for (let i = 0; i < data.length; i++) {
259                                 let obj = {
260                                         title: data[i].title,
261                                         image: data[i].picture_small,
262                                         songs: data[i].nb_tracks,
263                                         link: data[i].link
264                                 }
265                                 playlists.push(obj)
266                         }
267                         if (configFile.userDefined.spotifyUser && spotifySupport){
268                                 try{
269                                         let creds = await Spotify.clientCredentialsGrant()
270                                         Spotify.setAccessToken(creds.body['access_token'])
271                                         let first = true
272                                         let offset = 0
273                                         do{
274                                                 let data = await Spotify.getUserPlaylists(configFile.userDefined.spotifyUser, {fields: "items(images,name,owner.id,tracks.total,uri),total", offset: offset*20})
275                                                 if (first){
276                                                         var total = data.body.total
277                                                         var numPages=Math.floor((total-1)/20)
278                                                         var playlistList = new Array(total)
279                                                         first = false
280                                                 }
281                                                 data.body.items.forEach((playlist, i) => {
282                                                         playlistList[(offset*20)+i] = {
283                                                                 title: playlist.name,
284                                                                 image: (playlist.images[0] ? playlist.images[0].url : ""),
285                                                                 songs: playlist.tracks.total,
286                                                                 link: playlist.uri,
287                                                                 spotify: true
288                                                         }
289                                                 })
290                                                 offset++
291                                         }while(offset<=numPages)
292                                         playlists = playlists.concat(playlistList)
293                                 }catch(err){
294                                         logger.error(`Spotify playlist failed loading: ${err}`)
295                                 }
296                         }
297                         logger.info(`Loaded ${playlists.length} Playlist${playlists.length>1 ? "s" : ""}`)
298                         s.emit("getMyPlaylistList", {playlists: playlists})
299                 }catch(err){
300                         logger.error(`getMyPlaylistList failed: ${err}`)
301                         return
302                 }
303         }
304         s.on("getMyPlaylistList", function (d) {getMyPlaylistList()})
305
306         // Returns search results from a query
307         s.on("search", async function (data) {
308                 data.type = data.type || "track"
309                 if (["track", "playlist", "album", "artist"].indexOf(data.type) == -1) data.type = "track"
310
311                 // Remove "feat."  "ft." and "&" (causes only problems)
312                 data.text = data.text
313                         .replace(/ feat[\.]? /g, " ")
314                         .replace(/ ft[\.]? /g, " ")
315                         .replace(/\(feat[\.]? /g, " ")
316                         .replace(/\(ft[\.]? /g, " ")
317                         .replace(/\&/g, "")
318                         .replace(/–/g, "-")
319                         .replace(/—/g, "-")
320
321                 try {
322                         let searchObject = await s.Deezer.legacySearch(encodeURIComponent(data.text), data.type)
323                         s.emit("search", {type: data.type, items: searchObject.data})
324                 } catch (err) {
325                         s.emit("search", {type: data.type, items: []})
326                         logger.error(`search failed: ${err.stack}`)
327                         return
328                 }
329         })
330
331         // Returns list of tracks from an album/playlist or the list of albums from an artist
332         s.on("getTrackList", async function (data) {
333                 if (!data.type || (["playlist", "album", "artist", "spotifyplaylist"].indexOf(data.type) == -1) || !data.id) {
334                         s.emit("getTrackList", {err: -1, response: {}, id: data.id, reqType: data.type})
335                         return
336                 }
337                 if (data.type == 'artist') {
338                         try{
339                                 let response = await s.Deezer.legacyGetArtist(data.id)
340                                 let tracks = await s.Deezer.legacyGetArtistAlbums(data.id)
341                                 response.data = tracks.data
342                                 s.emit("getTrackList", {response: response, id: data.id, reqType: data.type})
343                         }catch(err){
344                                 s.emit("getTrackList", {err: "wrong artist id", response: {}, id: data.id, reqType: data.type})
345                                 logger.error(`getTrackList failed: ${err.stack}`)
346                                 return
347                         }
348                 }else if(data.type == "spotifyplaylist" && spotifySupport){
349                         try{
350                                 let creds = await Spotify.clientCredentialsGrant()
351                                 Spotify.setAccessToken(creds.body.access_token)
352                                 let first = true
353                                 let offset = 0
354                                 var response = {}
355                                 let resp0 = await Spotify.getPlaylist(data.id, {fields: "images,name,owner"})
356                                 response.title = resp0.body.name
357                                 response.image = resp0.body.images[0].url
358                                 response.owner = resp0.body.owner.display_name
359                                 do{
360                                         let resp = await Spotify.getPlaylistTracks(data.id, {fields: "items(track(artists,name,duration_ms,preview_url,explicit)),total", offset: offset*100})
361                                         if (first){
362                                                 var numPages=Math.floor((resp.body.total-1)/100)
363                                                 response.data = new Array(resp.body.total)
364                                                 first = false
365                                         }
366                                         resp.body.items.forEach((t, index) => {
367                                                 response.data[index+offset*100]={
368                                                         explicit_lyrics: t.track.explicit,
369                                                         preview: t.track.preview_url,
370                                                         title: t.track.name,
371                                                         artist: {
372                                                                 name: t.track.artists[0].name
373                                                         },
374                                                         duration: Math.floor(t.track.duration_ms/1000)
375                                                 }
376                                         })
377                                         offset++
378                                 }while(offset<=numPages)
379                                 s.emit("getTrackList", {response: response, id: data.id, reqType: data.type})
380                         }catch(err){
381                                 logger.error(`getTrackList failed: ${err.stack}`)
382                         }
383                 }else{
384                         let reqType = data.type.charAt(0).toUpperCase() + data.type.slice(1)
385                         try{
386                                 let response = await s.Deezer["legacyGet" + reqType](data.id)
387                                 let tracks = await s.Deezer["legacyGet" + reqType + "Tracks"](data.id)
388                                 response.data = tracks.data
389                                 s.emit("getTrackList", {response: response, id: data.id, reqType: data.type})
390                         }catch(err){
391                                 s.emit("getTrackList", {err: "wrong id "+reqType, response: {}, id: data.id, reqType: data.type})
392                                 logger.error(`getTrackList failed: ${err.stack}`)
393                                 return
394                         }
395                 }
396         })
397
398         // Sends settings saved by the user to the frontend
399         s.on("getUserSettings", function () {
400                 let settings = configFile.userDefined
401                 if (!settings.downloadLocation) {
402                         settings.downloadLocation = mainFolder
403                 }
404                 s.emit('getUserSettings', {settings: settings})
405         });
406
407         // Saves locally the settings comming from the frontend
408         s.on("saveSettings", function (settings) {
409                 if (settings.userDefined.downloadLocation == defaultDownloadFolder) {
410                         settings.userDefined.downloadLocation = ""
411                 } else {
412                         settings.userDefined.downloadLocation = path.resolve(settings.userDefined.downloadLocation + path.sep) + path.sep
413                         mainFolder = settings.userDefined.downloadLocation
414                 }
415
416                 if (settings.userDefined.queueConcurrency < 1) settings.userDefined.queueConcurrency = 1
417
418                 if (settings.userDefined.queueConcurrency != trackQueue.concurrency){
419                         trackQueue.concurrency = settings.userDefined.queueConcurrency
420                 }
421
422                 if (settings.userDefined.chartsCountry != configFile.userDefined.chartsCountry){
423                         s.emit("setChartsCountry", {selected: settings.userDefined.chartsCountry})
424                         getChartsTrackListByCountry(settings.userDefined.chartsCountry)
425                 }
426
427                 if (settings.userDefined.spotifyUser != configFile.userDefined.spotifyUser){
428                         getMyPlaylistList(settings.userDefined.spotifyUser)
429                 }
430
431                 configFile.userDefined = settings.userDefined;
432                 fs.outputFile(configFileLocation, JSON.stringify(configFile, null, 2), function (err) {
433                         if (err) return
434                         logger.info("Settings updated")
435                         initFolders()
436                 });
437         });
438
439         /*
440          * Downloading section of the app
441         */
442
443         // Gets data from the frontend and creates the track object
444         async function downloadTrack(data){
445                 logger.info(`Added to Queue ${data.id}`)
446                 try{
447                         var track = await s.Deezer.getTrack(data.id)
448                         data.settings.filename = data.settings.trackNameTemplate
449                         data.settings.foldername = data.settings.albumNameTemplate
450                         let _track = {
451                                 name: track.title,
452                                 artist: track.artist.name,
453                                 size: 1,
454                                 downloaded: 0,
455                                 failed: 0,
456                                 queueId: `id${Math.random().toString(36).substring(2)}`,
457                                 id: `${track.id}:${data.bitrate}`,
458                                 bitrate: data.bitrate+"",
459                                 type: 'track',
460                                 settings: data.settings || {},
461                                 obj: track,
462                         }
463                         addToQueue(_track)
464                 }catch(err){
465                         logger.error(`downloadTrack failed: ${err.stack ? err.stack : err}`)
466                         message = ""
467                         if (err.message){
468                                 switch (err.message){
469                                         case "DataException: no data":
470                                                 message = "Not Found"
471                                         break
472                                         default:
473                                                 message = err.message
474                                         break
475                                 }
476                         }
477                         s.emit("toast", `Track ${data.id} download failed: ${message}`)
478                         s.emit("silentlyCancelDownload", `${data.id}:${data.bitrate}`)
479                         return
480                 }
481         }
482         s.on("downloadtrack", async data=>{await downloadTrack(data)})
483
484         // Gets data from the frontend and creates the album object
485         async function downloadAlbum(data){
486                 logger.info(`Added to Queue ${data.id}`)
487                 try{
488                         var album = await s.Deezer.legacyGetAlbum(data.id)
489                         if (data.settings.tags.discTotal || data.settings.createCDFolder){
490                                 var discTotal = await s.Deezer.getAlbum(data.id)
491                                 album.discTotal = discTotal.discTotal
492                         }
493                         if (album.nb_tracks == 1 && data.settings.downloadSinglesAsTracks){
494                                 var track = await s.Deezer.getTrack(album.tracks.data[0].id)
495                                 data.settings.filename = data.settings.trackNameTemplate
496                                 data.settings.foldername = data.settings.albumNameTemplate
497                                 let _track = {
498                                         name: track.title,
499                                         artist: track.artist.name,
500                                         size: 1,
501                                         downloaded: 0,
502                                         failed: 0,
503                                         queueId: `id${Math.random().toString(36).substring(2)}`,
504                                         id: `${track.id}:${data.bitrate}`,
505                                         urlId: data.id,
506                                         bitrate: data.bitrate+"",
507                                         type: 'track',
508                                         settings: data.settings || {},
509                                         obj: track,
510                                 }
511                                 addToQueue(_track)
512                         }else{
513                                 album.tracks = await s.Deezer.getAlbumTracks(data.id)
514                                 data.settings.filename = data.settings.albumTrackNameTemplate
515                                 data.settings.foldername = data.settings.albumNameTemplate
516                                 let _album = {
517                                         name: album.title,
518                                         artist: album.artist.name,
519                                         size: album.tracks.length,
520                                         downloaded: 0,
521                                         failed: 0,
522                                         queueId: `id${Math.random().toString(36).substring(2)}`,
523                                         id: `${album.id}:${data.bitrate}`,
524                                         bitrate: data.bitrate+"",
525                                         type: 'album',
526                                         settings: data.settings || {},
527                                         obj: album,
528                                 }
529                                 addToQueue(_album)
530                         }
531                         return
532                 }catch(err){
533                         logger.error(`downloadAlbum failed: ${err.stack ? err.stack : err}`)
534                         message = ""
535                         if (err.message){
536                                 switch (err.message){
537                                         case "DataException: no data":
538                                                 message = "Not Found"
539                                         break
540                                         default:
541                                                 message = err.message
542                                         break
543                                 }
544                         }
545                         s.emit("toast", `Album ${data.id} download failed: ${message}`)
546                         s.emit("silentlyCancelDownload", `${data.id}:${data.bitrate}`)
547                         return
548                 }
549         }
550         s.on("downloadalbum", async data=>{await downloadAlbum(data)});
551
552         // Gets data from the frontend and creates for each album an album object
553         async function downloadArtist(data){
554                 logger.info(`Added to Queue ${data.id}`)
555                 try{
556                         var albums = await s.Deezer.legacyGetArtistAlbums(data.id);
557                         (function sendAllAlbums(i) {
558                                 setTimeout(function () {
559                                         data.id = albums.data[albums.data.length-1-i].id
560                                         downloadAlbum(JSON.parse(JSON.stringify(data)))
561                                         if (--i+1) sendAllAlbums(i)
562                                 }, 100)
563                         })(albums.data.length-1)
564                 }catch(err){
565                         logger.error(`downloadArtist failed: ${err.stack ? err.stack : err}`)
566                         message = ""
567                         if (err.message){
568                                 switch (err.message){
569                                         case "DataException: no data":
570                                                 message = "Not Found"
571                                         break
572                                         default:
573                                                 message = err.message
574                                         break
575                                 }
576                         }
577                         s.emit("toast", `Artist ${data.id} download failed: ${message}`)
578                         s.emit("silentlyCancelDownload", `${data.id}:${data.bitrate}`)
579                         return
580                 }
581         }
582         s.on("downloadartist", async data=>{ await downloadArtist(data)});
583
584         // Gets data from the frontend and creates the playlist object
585         async function downloadPlaylist(data){
586                 logger.info(`Added to Queue ${data.id}`)
587                 try{
588                         var playlist = await s.Deezer.legacyGetPlaylist(data.id)
589                         data.settings.filename = data.settings.playlistTrackNameTemplate
590                         data.settings.foldername = data.settings.albumNameTemplate
591                         playlist.tracks = await s.Deezer.getPlaylistTracks(data.id)
592                         let _playlist = {
593                                 name: playlist.title,
594                                 artist: playlist.creator.name,
595                                 size: playlist.tracks.length,
596                                 downloaded: 0,
597                                 failed: 0,
598                                 queueId: `id${Math.random().toString(36).substring(2)}`,
599                                 id: `${playlist.id}:${data.bitrate}`,
600                                 bitrate: data.bitrate+"",
601                                 type: "playlist",
602                                 settings: data.settings || {},
603                                 obj: playlist,
604                         }
605                         addToQueue(_playlist)
606                 }catch(err){
607                         logger.error(`downloadPlaylist failed: ${err.stack ? err.stack : err}`)
608                         message = ""
609                         if (err.message){
610                                 switch (err.message){
611                                         case "DataException: no data":
612                                                 message = "Not Found"
613                                         break
614                                         default:
615                                                 message = err.message
616                                         break
617                                 }
618                         }
619                         s.emit("toast", `Playlist ${data.id} download failed: ${message}`)
620                         s.emit("silentlyCancelDownload", `${data.id}:${data.bitrate}`)
621                         return
622                 }
623         }
624         s.on("downloadplaylist", data=>{downloadPlaylist(data)});
625
626         // Gets data from the frontend and creates the object fot the artist top tracks
627         async function downloadArtistTop(data){
628                 logger.info(`Added to Queue ${data.id}`)
629                 try{
630                         var artist = await s.Deezer.legacyGetArtist(data.id)
631                         data.settings.filename = data.settings.playlistTrackNameTemplate
632                         data.settings.foldername = data.settings.albumNameTemplate
633                         artist.tracks = await s.Deezer.getArtistTopTracks(data.id)
634                         let _playlist = {
635                                 name: artist.name + " Most played tracks",
636                                 artist: artist.name,
637                                 size: artist.tracks.length,
638                                 downloaded: 0,
639                                 failed: 0,
640                                 queueId: `id${Math.random().toString(36).substring(2)}`,
641                                 id: `${artist.id}:${data.bitrate}`,
642                                 bitrate: data.bitrate+"",
643                                 type: "playlist",
644                                 settings: data.settings || {},
645                                 obj: artist,
646                         }
647                         addToQueue(_playlist)
648                 }catch(err){
649                         logger.error(`downloadArtistTop failed: ${err.stack ? err.stack : err}`)
650                         message = ""
651                         if (err.message){
652                                 switch (err.message){
653                                         case "DataException: no data":
654                                                 message = "Not Found"
655                                         break
656                                         default:
657                                                 message = err.message
658                                         break
659                                 }
660                         }
661                         s.emit("toast", `ArtistTop ${data.id} download failed: ${message}`)
662                         s.emit("silentlyCancelDownload", `${data.id}:${data.bitrate}`)
663                         return
664                 }
665         }
666         s.on("downloadartisttop", data=>{downloadArtistTop(data)});
667
668         // Gets data from the frontend and creates the spotify playlist object
669         async function downloadSpotifyPlaylist(data){
670                 logger.info(`Added to Queue ${data.id}`)
671                 if (spotifySupport){
672                         try{
673                                 let creds = await Spotify.clientCredentialsGrant()
674                                 Spotify.setAccessToken(creds.body['access_token'])
675                                 var offset = 0
676                                 data.settings.filename = data.settings.playlistTrackNameTemplate
677                                 data.settings.foldername = data.settings.albumNameTemplate
678                                 var resp = await Spotify.getPlaylist(data.id, {fields: "id,name,owner,images,tracks(total)"})
679                                 var _playlist = {
680                                         name: resp.body.name,
681                                         artist: (resp.body.owner.display_name ? resp.body.owner.display_name : resp.body.owner.id),
682                                         size: resp.body.tracks.total,
683                                         downloaded: 0,
684                                         failed: 0,
685                                         queueId: `id${Math.random().toString(36).substring(2)}`,
686                                         settings: data.settings || {},
687                                         id: `${resp.body.id}:${data.bitrate}`,
688                                         bitrate: data.bitrate+"",
689                                         type: "spotifyplaylist",
690                                         obj: resp.body
691                                 }
692                                 var numPages=Math.floor((_playlist.size-1)/100)
693                                 var trackList = new Array(_playlist.size)
694                                 do{
695                                         var resp = await Spotify.getPlaylistTracks(data.id, {fields: "items(track(artists,name,album,external_ids))", offset: offset*100})
696                                         resp.body.items.forEach((track, i) => {
697                                                 trackList[i+(offset*100)] = track.track
698                                         })
699                                         offset++
700                                 }while(offset<=numPages)
701                                 _playlist.obj.tracks = trackList
702                                 addToQueue(_playlist)
703                         }catch(err){
704                                 logger.error(`downloadSpotifyPlaylist failed: ${err.stack ? err.stack : err}`)
705                                 if (err.message && err.message == "Bad Request"){
706                                         s.emit("message", {title: "You setted it up wrong!", msg: "It seems like you setted the authCredentials.js file wrong...<br>Make sure you keep the ' around the IDs and that the Secret and Client ID are copied correctly<br>After that you should restart the app to make it work.<br><br>If you need the guide again <a href=\"https://notabug.org/RemixDevs/DeezloaderRemix/wiki/Spotify+Features\">Here it is</a>"})
707                                 }else{
708                                         s.emit("toast", `SpotifyPlaylist ${data.id} failed: ${err.message ? err.message : err}`)
709                                 }
710                                 s.emit("silentlyCancelDownload", `${data.id}:${data.bitrate}`)
711                                 return
712                         }
713                 }else{
714                         s.emit("message", {title: "Spotify Support is not enabled", msg: "You should add authCredentials.js in your config files and then restart the app to use this feature<br>You can see how to do that in <a href=\"https://notabug.org/RemixDevs/DeezloaderRemix/wiki/Spotify+Features\">this guide</a>"})
715                 }
716         }
717         s.on("downloadspotifyplaylist", data=>{downloadSpotifyPlaylist(data)})
718
719         // Gets data from the frontend and creates data for the deezer track object
720         async function downloadSpotifyTrack(data){
721                 logger.info(`Added to Queue ${data.id}`)
722                 if (spotifySupport){
723                         try{
724                                 let creds = await Spotify.clientCredentialsGrant()
725                                 Spotify.setAccessToken(creds.body['access_token'])
726                                 var resp = await Spotify.getTrack(data.id, {fields: "external_ids,artists,album,name"})
727                                 deezerId = await convertSpotify2Deezer(resp.body)
728                                 if (deezerId != 0){
729                                         data.id = deezerId
730                                         downloadTrack(data)
731                                 }else{
732                                         s.emit("toast", "Can't find the track on Deezer!")
733                                         s.emit("silentlyCancelDownload", `${data.id}:${data.bitrate}`)
734                                         logger.error(`Can't find the track on Deezer!`)
735                                 }
736                         }catch(err){
737                                 logger.error(`downloadSpotifyTrack failed: ${err.stack ? err.stack : err}`)
738                                 return
739                         }
740                 }else{
741                         s.emit("message", {title: "Spotify Support is not enabled", msg: "You should add authCredentials.js in your config files and then restart the app to use this feature<br>You can see how to do that in <a href=\"https://notabug.org/RemixDevs/DeezloaderRemix/wiki/Spotify+Features\">this guide</a>"})
742                 }
743         }
744         s.on("downloadspotifytrack", data=>{downloadSpotifyTrack(data)})
745
746         // Gets data from the frontend and creates data for the deezer track object
747         async function downloadSpotifyAlbum(data){
748                 logger.info(`Added to Queue ${data.id}`)
749                 if (spotifySupport){
750                         try{
751                                 let creds = await Spotify.clientCredentialsGrant()
752                                 Spotify.setAccessToken(creds.body['access_token'])
753                                 var resp = await Spotify.getAlbum(data.id, {fields: "external_ids,artists,name"})
754                                 deezerId = await convertSpotifyAlbum2Deezer(resp.body)
755                                 if (deezerId != 0){
756                                         data.id = deezerId
757                                         downloadAlbum(data)
758                                 }else{
759                                         s.emit("toast", "Can't find the album on Deezer!")
760                                         s.emit("silentlyCancelDownload", `${data.id}:${data.bitrate}`)
761                                         logger.error(`Can't find the album on Deezer!`)
762                                 }
763                         }catch(err){
764                                 logger.error(`downloadSpotifyAlbum failed: ${err.stack ? err.stack : err}`)
765                                 return
766                         }
767                 }else{
768                         s.emit("message", {title: "Spotify Support is not enabled", msg: "You should add authCredentials.js in your config files and then restart the app to use this feature<br>You can see how to do that in <a href=\"https://notabug.org/RemixDevs/DeezloaderRemix/wiki/Spotify+Features\">this guide</a>"})
769                 }
770         }
771         s.on("downloadspotifyalbum", data=>{downloadSpotifyAlbum(data)})
772
773         // Converts the spotify track to a deezer one
774         // It tries first with the isrc (best way of conversion)
775         // Fallbacks to the old way, using search
776         async function convertSpotify2Deezer(track){
777                 if (!track) return 0
778                 try{
779                         if (track.external_ids.isrc){
780                                 let resp = await s.Deezer.legacyGetTrackByISRC(track.external_ids.isrc)
781                                 if (resp.title)
782                                         return resp.id
783                                 else
784                                         logger.warn("ISRC track is not on Deezer, falling back to old method")
785                         }
786                 }catch(err){
787                         logger.warn("ISRC not found, falling back to old method")
788                 }
789                 return convertMetadata2Deezer(track.artists[0].name, track.name, track.album.name)
790         }
791
792         // Tries to get track id from pure luck
793         async function convertMetadata2Deezer(artist, track, album){
794                 let resp
795                 artist = artist.replace(/–/g,"-").replace(/’/g, "'")
796                 track = track.replace(/–/g,"-").replace(/’/g, "'")
797                 album = album.replace(/–/g,"-").replace(/’/g, "'")
798                 try{
799                         resp = await s.Deezer.legacySearch(`artist:"${artist}" track:"${track}" album:"${album}"`, "track", 1)
800                 }catch(err){logger.err(`ConvertFromMetadata: ${err.stack ? err.stack : err}`)}
801                 if (resp.data[0]) return resp.data[0].id
802                 try{
803                         resp = await s.Deezer.legacySearch(encodeURIComponent(`artist:"${artist}" track:"${track}"`), "track", 1)
804                 }catch(err){logger.err(`ConvertFromMetadata: ${err.stack ? err.stack : err}`)}
805                 if (resp.data[0]) return resp.data[0].id
806                 if (track.indexOf("(") < track.indexOf(")")){
807                         try{
808                                 resp = await s.Deezer.legacySearch(encodeURIComponent(`artist:"${artist}" track:"${track.split("(")[0]}"`), "track", 1)
809                         }catch(err){logger.err(`ConvertFromMetadata: ${err.stack ? err.stack : err}`)}
810                         if (resp.data[0]) return resp.data[0].id
811                 }else if (track.indexOf(" - ")>0){
812                         try{
813                                 resp = await s.Deezer.legacySearch(encodeURIComponent(`artist:"${artist}" track:"${track.split(" - ")[0]}"`), "track", 1)
814                         }catch(err){logger.err(`ConvertFromMetadata: ${err.stack ? err.stack : err}`)}
815                         if (resp.data[0]) return resp.data[0].id
816                 }else{
817                         return 0
818                 }
819                 return 0
820         }
821
822         // Converts the spotify album to a deezer one
823         // It tries first with the upc (best way of conversion)
824         // Fallbacks to the old way, using search
825         async function convertSpotifyAlbum2Deezer(album){
826                 if (!album) return 0
827                 try{
828                         if (album.external_ids.upc){
829                                 if (! isNaN(album.external_ids.upc)) album.external_ids.upc = parseInt(album.external_ids.upc)
830                                 let resp = await s.Deezer.legacyGetAlbumByUPC(album.external_ids.upc)
831                                 if (resp.title)
832                                         return resp.id
833                                 else
834                                         logger.warn("UPC album is not on Deezer, falling back to old method")
835                         }
836                 }catch(err){
837                         logger.warn("UPC not found, falling back to old method")
838                 }
839                 return convertAlbumMetadata2Deezer(album.artists[0].name, album.name)
840         }
841
842         // Tries to get album id from pure luck
843         async function convertAlbumMetadata2Deezer(artist, album){
844                 let resp
845                 artist = artist.replace(/–/g,"-").replace(/’/g, "'")
846                 album = album.replace(/–/g,"-").replace(/’/g, "'")
847                 try{
848                         resp = await s.Deezer.legacySearch(`artist:"${artist}" album:"${album}"`, "album", 1)
849                 }catch(err){logger.err(`ConvertAlbumFromMetadata: ${err.stack ? err.stack : err}`)}
850                 if (resp.data[0]) return resp.data[0].id
851                 return 0
852         }
853
854         // All the above functions call this function
855         // It adds the object to an array and adds the promise for the download to the object itself
856         function addToQueue(object) {
857                 downloadQueue[object.queueId] = object
858                 io.sockets.emit('addToQueue', object)
859                 downloadQueue[object.queueId].downloadQueuePromise = dqueue.push(addNextDownload, { args: object })
860         }
861
862         // Wrapper for queue download
863         function addNextDownload(obj, token){
864                 return new Promise(async (resolve, reject) => {
865       await queueDownload(obj)
866                         resolve()
867     }).then(() => new Promise((resolve, reject) => {
868       if (token.cancelled)
869         reject()
870       else
871         resolve()
872     }))
873         }
874
875         // Cancels download
876         // TODO: Might check this one, could be a little buggy
877         function cancelDownload(queueId, cleanAll=false){
878                 if (!queueId) return
879                 let cancel = false
880                 let cancelSuccess
881                 if (downloadQueue[queueId]){
882                         cancel = true;
883                         if (downloadQueue[queueId].downloadQueuePromise) downloadQueue[queueId].downloadQueuePromise.cancel()
884                         if (downloadQueue[Object.keys(downloadQueue)[0]].queueId == queueId) {
885                                 trackQueue = queue({
886                                         autostart: true,
887                                         concurrency: trackQueue.concurrency
888                                 })
889                         }
890                         delete downloadQueue[queueId]
891                 }
892
893                 if (cancel) {
894                         io.sockets.emit("cancelDownload", {queueId: queueId, cleanAll: cleanAll});
895                 }
896         }
897         s.on("cancelDownload", function (data) {cancelDownload(data.queueId)});
898
899         s.on("cancelAllDownloads", function(data){
900                 data.queueList.forEach(x=>{
901                         cancelDownload(x, true);
902                 })
903                 io.sockets.emit("cancelAllDownloads")
904         })
905
906         /*function getNextDownload() {
907                 if (s.currentItem != null || Object.keys(downloadQueue).length == 0) {
908                         if (Object.keys(downloadQueue).length == 0 && s.currentItem == null) {
909                                 s.emit("emptyDownloadQueue", {})
910                         }
911                         return null
912                 }
913                 s.currentItem = downloadQueue[Object.keys(downloadQueue)[0]]
914                 return s.currentItem
915         }*/
916
917         //downloadQueue: the tracks in the queue to be downloaded
918         //queueId: random number generated when user clicks download on something
919         async function queueDownload(downloading) {
920                 if (!downloading) return
921
922                 if (downloading.type != "spotifyplaylist"){
923                         io.sockets.emit("downloadStarted", {queueId: downloading.queueId})
924                 }
925
926                 downloading.errorLog = "";
927                 downloading.searchedLog = "";
928
929                 let filePath;
930                 logger.info(`Registered ${downloading.type}: ${downloading.id} | ${downloading.artist} - ${downloading.name}`);
931                 switch(downloading.type){
932                         /*
933                         *  TRACK DOWNLOAD
934                         */
935                         case "track":
936                                 var downloadPromise = new Promise(async (resolve,reject)=>{
937                                         try{
938                                                 await downloadTrackObject(downloading.obj, downloading.queueId, downloading.settings)
939                                                 downloading.downloaded++
940                                         }catch(err){
941                                                 logger.error(`[${downloading.obj.artist.name} - ${downloading.obj.title}] ${err}`)
942                                                 downloading.failed++
943                                         }
944                                         io.sockets.emit("updateQueue", {
945                                                 name: downloading.name,
946                                                 artist: downloading.artist,
947                                                 size: downloading.size,
948                                                 downloaded: downloading.downloaded,
949                                                 failed: downloading.failed,
950                                                 queueId: downloading.queueId,
951                                                 id: downloading.id,
952                                                 type: downloading.type,
953                                         })
954                                         io.sockets.emit("downloadProgress", {
955                                                 queueId: downloading.queueId,
956                                                 percentage: 100
957                                         })
958                                         resolve()
959                                 })
960                                 try{
961                                         await downloadPromise
962                                 }catch(err){
963                                         if (err) logger.error(`queueDownload:track failed: ${err.stack ? err.stack : err}`)
964                                         logger.info("Downloading Stopped")
965                                 }
966                         break
967                         /*
968                         *  ALBUM DOWNLOAD
969                         */
970                         case "album":
971                                 downloading.settings.albName = downloading.name;
972                                 downloading.settings.artName = downloading.artist;
973                                 downloading.playlistArr = Array(downloading.size);
974                                 filePath = mainFolder;
975                                 downloading.obj.genresString = []
976                                 downloading.obj.genres.data.map((x)=>{
977                                         downloading.obj.genresString.push(x.name)
978                                 })
979                                 if (downloading.settings.createArtistFolder || downloading.settings.createAlbumFolder) {
980                                         if (downloading.settings.createArtistFolder) {
981                                                 filePath += antiDot(fixName(downloading.settings.artName)) + path.sep;
982                                         }
983                                         if (downloading.settings.createAlbumFolder) {
984                                                 filePath += antiDot(settingsRegexAlbum(downloading.settings.foldername,downloading.settings.artName,downloading.settings.albName,downloading.obj.release_date.slice(0, 4),downloading.obj.record_type,downloading.obj.explicit_lyrics,downloading.obj.label, downloading.obj.genresString)) + path.sep;
985                                         }
986                                 } else if (downloading.settings.artName) {
987                                         filePath += antiDot(settingsRegexAlbum(downloading.settings.foldername,downloading.settings.artName,downloading.settings.albName,downloading.obj.release_date.slice(0, 4),downloading.obj.record_type,downloading.obj.explicit_lyrics,downloading.obj.label, downloading.obj.genresString)) + path.sep;
988                                 }
989                                 let ajson = {
990                                         artist : downloading.obj.artist,
991                                         nb_tracks : downloading.obj.nb_tracks,
992                                         upc : downloading.obj.upc,
993                                         record_type : downloading.obj.record_type,
994                                         explicit_lyrics : downloading.obj.explicit_lyrics,
995                                         label : downloading.obj.label,
996                                         release_date : downloading.obj.release_date,
997                                         genres : downloading.obj.genres,
998                                         discTotal: downloading.obj.discTotal ? downloading.obj.discTotal : null
999                                 }
1000                                 downloading.downloadPromise = new Promise((resolve,reject)=>{
1001                                         downloading.obj.tracks.every(function (t) {
1002                                                 trackQueue.push(async cb=>{
1003                                                         if (!downloadQueue[downloading.queueId]) {
1004                                                                 reject()
1005                                                                 return false
1006                                                         }
1007                                                         t.ajson = ajson
1008                                                         logger.info(`Now downloading: ${t.artist.name} - ${t.title}`)
1009                                                         try{
1010                                                                 await downloadTrackObject(t, downloading.queueId, downloading.settings)
1011                                                                 downloading.downloaded++
1012                                                                 downloading.playlistArr[t.playlistData[0]] = t.playlistData[1].split(filePath)[1]
1013                                                                 if (t.searched) downloading.searchedLog += `${t.artist.name} - ${t.title}\r\n`
1014                                                         }catch(err){
1015                                                                 downloading.failed++
1016                                                                 downloading.errorLog += `${t.id} | ${t.artist.name} - ${t.title} | ${err}\r\n`
1017                                                                 logger.error(`[${t.artist.name} - ${t.title}] ${err}`)
1018                                                         }
1019                                                         io.sockets.emit("downloadProgress", {
1020                                                                 queueId: downloading.queueId,
1021                                                                 percentage: ((downloading.downloaded+downloading.failed) / downloading.size) * 100
1022                                                         });
1023                                                         io.sockets.emit("updateQueue", {
1024                                                                 name: downloading.name,
1025                                                                 artist: downloading.artist,
1026                                                                 size: downloading.size,
1027                                                                 downloaded: downloading.downloaded,
1028                                                                 failed: downloading.failed,
1029                                                                 queueId: downloading.queueId,
1030                                                                 id: downloading.id,
1031                                                                 type: downloading.type,
1032                                                         })
1033                                                         if (downloading.downloaded + downloading.failed >= downloading.size) resolve()
1034                                                         cb()
1035                                                 })
1036                                                 return true
1037                                         })
1038                                 })
1039                                 try{
1040                                         await downloading.downloadPromise
1041                                         logger.info("Album finished downloading: "+downloading.name);
1042                                         io.sockets.emit("downloadProgress", {
1043                                                 queueId: downloading.queueId,
1044                                                 percentage: 100
1045                                         });
1046                                         if (downloading.settings.logErrors){
1047                                                 if (downloading.errorLog != ""){
1048                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1049                                                         fs.writeFileSync(filePath+"notFound.txt",downloading.errorLog)
1050                                                 }else{
1051                                                         if (fs.existsSync(filePath+"notFound.txt")) fs.unlinkSync(filePath+"notFound.txt");
1052                                                 }
1053                                         }
1054                                         if (downloading.settings.logSearched){
1055                                                 if (downloading.searchedLog != ""){
1056                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1057                                                         fs.writeFileSync(filePath+"alternativeSongs.txt",downloading.searchedLog)
1058                                                 }else{
1059                                                         if (fs.existsSync(filePath+"alternativeSongs.txt")) fs.unlinkSync(filePath+"alternativeSongs.txt");
1060                                                 }
1061                                         }
1062                                         if (downloading.settings.createM3UFile){
1063                                                 fs.writeFileSync(filePath+"playlist.m3u", downloading.playlistArr.join("\r\n"));
1064                                         }
1065                                 }catch(err){
1066                                         if (err) logger.error(`queueDownload:album failed: ${err.stack ? err.stack : err}`)
1067                                         logger.info("Stopping the album queue");
1068                                 }
1069                         break
1070                         /*
1071                         *  PLAYLIST DOWNLOAD
1072                         */
1073                         case "playlist":
1074                                 downloading.settings.plName = downloading.name;
1075                                 downloading.playlistArr = Array(downloading.size);
1076                                 downloading.settings.playlist = {
1077                                         fullSize: downloading.obj.tracks.length
1078                                 };
1079                                 filePath = mainFolder+antiDot(fixName(downloading.settings.plName)) + path.sep
1080                                 downloading.downloadPromise = new Promise((resolve,reject)=>{
1081                                         downloading.obj.tracks.every(function (t, index) {
1082                                                 trackQueue.push(async cb=>{
1083                                                         if (!downloadQueue[downloading.queueId]) {
1084                                                                 reject()
1085                                                                 return false
1086                                                         }
1087                                                         try{
1088                                                                 await downloadTrackObject(t, downloading.queueId, downloading.settings)
1089                                                                 downloading.downloaded++
1090                                                                 downloading.playlistArr[t.playlistData[0]] = t.playlistData[1].split(filePath)[1]
1091                                                                 if (t.searched) downloading.searchedLog += `${t.artist.name} - ${t.title}\r\n`
1092                                                         }catch(err){
1093                                                                 downloading.failed++
1094                                                                 downloading.errorLog += `${t.id} | ${t.artist.name} - ${t.title} | ${err}\r\n`
1095                                                                 logger.error(`[${t.artist.name} - ${t.title}] ${err}`)
1096                                                         }
1097                                                         io.sockets.emit("downloadProgress", {
1098                                                                 queueId: downloading.queueId,
1099                                                                 percentage: ((downloading.downloaded+downloading.failed) / downloading.size) * 100
1100                                                         });
1101                                                         io.sockets.emit("updateQueue", {
1102                                                                 name: downloading.name,
1103                                                                 artist: downloading.artist,
1104                                                                 size: downloading.size,
1105                                                                 downloaded: downloading.downloaded,
1106                                                                 failed: downloading.failed,
1107                                                                 queueId: downloading.queueId,
1108                                                                 id: downloading.id,
1109                                                                 type: downloading.type,
1110                                                         })
1111                                                         if (downloading.downloaded + downloading.failed >= downloading.size) resolve()
1112                                                         cb()
1113                                                 })
1114                                                 return true
1115                                         })
1116                                 })
1117                                 try{
1118                                         await downloading.downloadPromise
1119                                         logger.info("Playlist finished "+downloading.name);
1120                                         io.sockets.emit("downloadProgress", {
1121                                                 queueId: downloading.queueId,
1122                                                 percentage: 100
1123                                         });
1124                                         if (downloading.settings.logErrors){
1125                                                 if (downloading.errorLog != ""){
1126                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1127                                                         fs.writeFileSync(filePath+"notFound.txt",downloading.errorLog)
1128                                                 }else{
1129                                                         if (fs.existsSync(filePath+"notFound.txt")) fs.unlinkSync(filePath+"notFound.txt");
1130                                                 }
1131                                         }
1132                                         if (downloading.settings.logSearched){
1133                                                 if (downloading.searchedLog != ""){
1134                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1135                                                         fs.writeFileSync(filePath+"alternativeSongs.txt",downloading.searchedLog)
1136                                                 }else{
1137                                                         if (fs.existsSync(filePath+"alternativeSongs.txt")) fs.unlinkSync(filePath+"alternativeSongs.txt");
1138                                                 }
1139                                         }
1140                                         if (downloading.settings.createM3UFile){
1141                                                 fs.writeFileSync(filePath + "playlist.m3u", downloading.playlistArr.join("\r\n"));
1142                                         }
1143                                         if (downloading.settings.saveArtwork){
1144                                                 if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1145                                                 let imgPath = filePath + antiDot(settingsRegexCover(downloading.settings.coverImageTemplate,downloading.artist,downloading.name))+(downloading.settings.PNGcovers ? ".png" : ".jpg");
1146                                                 if (downloading.cover){
1147                                                         downloading.cover = downloading.cover.replace("56x56",`${downloading.settings.artworkSize}x${downloading.settings.artworkSize}`)
1148                                                         request.get(downloading.cover, {strictSSL: false,encoding: 'binary'}, function(error,response,body){
1149                                                                 if(error){
1150                                                                         logger.error(error.stack);
1151                                                                         return;
1152                                                                 }
1153                                                                 fs.outputFile(imgPath,body,'binary',function(err){
1154                                                                         if(err){
1155                                                                                 logger.error(err.stack);
1156                                                                                 return;
1157                                                                         }
1158                                                                         logger.info(`Cover downloaded for: ${downloading.settings.plName}`)
1159                                                                 })
1160                                                         });
1161                                                 }
1162                                         }
1163                                 }catch(err){
1164                                         if (err) logger.error(`queueDownload:playlist failed: ${err.stack ? err.stack : err}`)
1165                                         logger.info("Stopping the playlist queue")
1166                                 }
1167                         break
1168                         /*
1169                         *  SPOTIFY PLAYLIST DOWNLOAD
1170                         */
1171                         case "spotifyplaylist":
1172                                 downloading.settings.plName = downloading.name
1173                                 downloading.playlistArr = Array(downloading.size)
1174                                 downloading.playlistContent = new Array(downloading.size)
1175                                 logger.info("Waiting for all tracks to be converted");
1176                                 const convert = async () =>{
1177                                         await asyncForEach(downloading.obj.tracks, async (t,i)=>{
1178                                                 if (!downloadQueue[downloading.queueId]) return false
1179                                                 try{
1180                                                         downloading.playlistContent[i] = await convertSpotify2Deezer(t)
1181                                                 }catch(err){
1182                                                         logger.error(`queueDownload:spotifyplaylist failed during conversion: ${err.stack ? err.stack : err}`)
1183                                                 }
1184                                         })
1185                                 }
1186                                 await convert()
1187                                 if (!downloadQueue[downloading.queueId]) {
1188                                         logger.info("Stopping the playlist queue")
1189                                         break
1190                                 }
1191                                 downloading.trackList = await s.Deezer.getTracks(downloading.playlistContent)
1192                                 logger.info("All tracks converted, starting download")
1193                                 io.sockets.emit("downloadStarted", {queueId: downloading.queueId})
1194                                 downloading.settings.playlist = {
1195                                         fullSize: downloading.trackList.length
1196                                 }
1197                                 filePath = `${mainFolder}${antiDot(fixName(downloading.settings.plName))}${path.sep}`
1198                                 downloading.downloadPromise = new Promise((resolve,reject)=>{
1199                                         downloading.trackList.every(function (t, index) {
1200                                                 trackQueue.push(async cb=>{
1201                                                         if (!downloadQueue[downloading.queueId]) {
1202                                                                 reject()
1203                                                                 return false
1204                                                         }
1205                                                         t.position = index
1206                                                         if (t.id==0 && downloading.obj.tracks[t.position] != null){
1207                                                                 t.title = downloading.obj.tracks[t.position].name
1208                                               t.album = {id: 0, title: downloading.obj.tracks[t.position].album.name}
1209                                               t.artist = {id: 0, name: downloading.obj.tracks[t.position].artists[0].name}
1210                                                         }
1211                                                         try{
1212                                                                 await downloadTrackObject(t, downloading.queueId, downloading.settings)
1213                                                                 downloading.downloaded++
1214                                                                 downloading.playlistArr[t.playlistData[0]] = t.playlistData[1].split(filePath)[1]
1215                                                                 if (t.searched) downloading.searchedLog += `${t.artist.name} - ${t.title}\r\n`
1216                                                         }catch(err){
1217                                                                 downloading.failed++
1218                                                                 downloading.errorLog += `${t.id} | ${t.artist.name} - ${t.title} | ${err}\r\n`
1219                                                                 logger.error(`[${t.artist.name} - ${t.title}] ${err}`)
1220                                                         }
1221                                                         io.sockets.emit("downloadProgress", {
1222                                                                 queueId: downloading.queueId,
1223                                                                 percentage: ((downloading.downloaded+downloading.failed) / downloading.size) * 100
1224                                                         });
1225                                                         io.sockets.emit("updateQueue", {
1226                                                                 name: downloading.name,
1227                                                                 artist: downloading.artist,
1228                                                                 size: downloading.size,
1229                                                                 downloaded: downloading.downloaded,
1230                                                                 failed: downloading.failed,
1231                                                                 queueId: downloading.queueId,
1232                                                                 id: downloading.id,
1233                                                                 type: downloading.type,
1234                                                         })
1235                                                         if (downloading.downloaded + downloading.failed >= downloading.size) resolve()
1236                                                         cb()
1237                                                 })
1238                                                 return true
1239                                         })
1240                                 })
1241                                 try{
1242                                         await downloading.downloadPromise
1243                                         logger.info("Playlist finished "+downloading.name);
1244                                         io.sockets.emit("downloadProgress", {
1245                                                 queueId: downloading.queueId,
1246                                                 percentage: 100
1247                                         });
1248                                         if (downloading.settings.logErrors){
1249                                                 if (downloading.errorLog != ""){
1250                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1251                                                         fs.writeFileSync(filePath+"notFound.txt",downloading.errorLog)
1252                                                 }else{
1253                                                         if (fs.existsSync(filePath+"notFound.txt")) fs.unlinkSync(filePath+"notFound.txt");
1254                                                 }
1255                                         }
1256                                         if (downloading.settings.logSearched){
1257                                                 if (downloading.searchedLog != ""){
1258                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1259                                                         fs.writeFileSync(filePath+"alternativeSongs.txt",downloading.searchedLog)
1260                                                 }else{
1261                                                         if (fs.existsSync(filePath+"alternativeSongs.txt")) fs.unlinkSync(filePath+"alternativeSongs.txt");
1262                                                 }
1263                                         }
1264                                         if (downloading.settings.createM3UFile){
1265                                                 fs.writeFileSync(filePath + "playlist.m3u", downloading.playlistArr.join("\r\n"));
1266                                         }
1267                                         if (downloading.settings.saveArtwork){
1268                                                 if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1269                                                 let imgPath = filePath + antiDot(settingsRegexCover(downloading.settings.coverImageTemplate,downloading.artist,downloading.name))+(downloading.settings.PNGcovers ? ".png" : ".jpg");
1270                                                 if (downloading.obj.images){
1271                                                         downloading.cover = downloading.obj.images[0].url.replace("56x56",`${downloading.settings.artworkSize}x${downloading.settings.artworkSize}`)
1272                                                         request.get(downloading.cover, {strictSSL: false,encoding: 'binary'}, function(error,response,body){
1273                                                                 if(error){
1274                                                                         logger.error(error.stack);
1275                                                                         return;
1276                                                                 }
1277                                                                 fs.outputFile(imgPath,body,'binary',function(err){
1278                                                                         if(err){
1279                                                                                 logger.error(err.stack);
1280                                                                                 return;
1281                                                                         }
1282                                                                         logger.info(`Cover downloaded for: ${downloading.settings.plName}`)
1283                                                                 })
1284                                                         });
1285                                                 }
1286                                         }
1287                                 }catch(err){
1288                                         if (err) logger.error(`queueDownload:spotifyplaylist failed: ${err.stack ? err.stack : err}`)
1289                                         logger.info("Stopping the playlist queue")
1290                                 }
1291                         break
1292                 }
1293                 if (downloading && downloadQueue[Object.keys(downloadQueue)[0]] && (Object.keys(downloadQueue)[0] == downloading.queueId)) delete downloadQueue[Object.keys(downloadQueue)[0]]
1294                 if (Object.keys(downloadQueue).length == 0) {
1295                         io.sockets.emit("emptyDownloadQueue", {})
1296                 }
1297         }
1298
1299         // This function takes the track object and does all the stuff to download it
1300         async function downloadTrackObject(track, queueId, settings) {
1301                 if (!downloadQueue[queueId]) {
1302                         logger.error(`[${track.artist.name} - ${track.title}] Failed to download: Not in queue`)
1303                         throw new Error("Not in queue")
1304                         return false
1305                 }
1306                 if (parseInt(track.id) == 0){
1307                         logger.error(`[${track.artist.name} - ${track.title}] Failed to download: Song not Found`)
1308                         throw new Error("Song not Found")
1309                         return false
1310                 }
1311
1312                 /* Album information is necessary for the following tags:
1313                  * album_artist
1314                  * album_artist_picture
1315                  * trackTotal
1316                  * recordType
1317                  * barcode
1318                  * explicit
1319                  * label
1320                  * genres
1321                  * date
1322                 */
1323                 if (parseInt(track.id)>0){
1324                         var ajson
1325                         if (!track.ajson){
1326                                 try{
1327                                         logger.info(`[${track.artist.name} - ${track.title}] Getting album info`)
1328                                         ajson = await s.Deezer.legacyGetAlbum(track.album.id)
1329                                 }catch(err){
1330                                         logger.warn(`[${track.artist.name} - ${track.title}] Album not found, trying to reach deeper`)
1331                                         try{
1332                                                 ajson = await s.Deezer.getAlbum(track.album.id)
1333                                                 ajson.fromNewAPI = true
1334                                         } catch(err){
1335                                                 if(track.fallbackId){
1336                                                         logger.warn(`[${track.artist.name} - ${track.title}] Failed to download track, falling on alternative`)
1337                                                         track = await s.Deezer.getTrack(track.fallbackId)
1338                                                         return downloadTrackObject(track, queueId, settings)
1339                                                 }else if(!track.searched){
1340                                                         logger.warn(`[${track.artist.name} - ${track.title}] Failed to download track, searching for alternative`)
1341                                                         var _trackID = await convertMetadata2Deezer(track.artist.name, track.title, track.album.title)
1342                                                         if (_trackID != "0"){
1343                                                                 track = await s.Deezer.getTrack()
1344                                                                 track.searched = true
1345                                                                 return downloadTrackObject(track, queueId, settings)
1346                                                         }else{
1347                                                                 logger.error(`[${track.artist.name} - ${track.title}] Failed to download: Alternative not found`)
1348                                                                 return
1349                                                         }
1350                                                 }else{
1351                                                         logger.error(`[${track.artist.name} - ${track.title}] Failed to download: ${err}`)
1352                                                         return
1353                                                 }
1354                                         }
1355                                 }
1356                         }else{
1357                                 ajson = track.ajson
1358                         }
1359                         if (!ajson.fromNewAPI){
1360                                 // Aquiring discTotal (only if necessary)
1361                                 if (settings.tags.discTotal || settings.createCDFolder){
1362                                         if (!ajson.discTotal){
1363                                                 logger.info(`[${track.artist.name} - ${track.title}] Getting total disc number`);
1364                                                 var discTotal = await s.Deezer.getAlbum(ajson.id)
1365                                                 track.discTotal = discTotal.discTotal
1366                                         }else{
1367                                                 track.discTotal = ajson.discTotal
1368                                         }
1369                                 }
1370                                 track.album.artist = {
1371                                         id: ajson.artist.id,
1372                                         name: ajson.artist.name,
1373                                         picture: ajson.artist.picture_small.substring(46,ajson.artist.picture_small.length-24),
1374                                 }
1375                                 track.trackTotal = ajson.nb_tracks
1376                                 track.album.barcode = ajson.upc
1377                                 if (ajson.record_type){
1378                                         track.recordType = ajson.record_type
1379                                 }else{
1380                                         track.recordType = switchReleaseType(track.recordType)
1381                                 }
1382                                 if (ajson.explicit_lyrics)
1383                                         track.album.explicit = ajson.explicit_lyrics;
1384                                 if(ajson.label)
1385                                         track.publisher = ajson.label;
1386                                 if (ajson.release_date) {
1387                                         track.date = {
1388                                                 day: ajson.release_date.slice(8,10),
1389                                                 month: ajson.release_date.slice(5,7),
1390                                                 year: ajson.release_date.slice(0, 4),
1391                                                 slicedYear: (settings.dateFormatYear == "2" ? ajson.release_date.slice(2, 4) : ajson.release_date.slice(0, 4))
1392                                         }
1393                                 }else if(!track.date){
1394                                         track.date = {
1395                                                 day: 0,
1396                                                 month: 0,
1397                                                 year: 0,
1398                                                 slicedYear: 0
1399                                         }
1400                                 }
1401                                 if(ajson.genres && ajson.genres.data[0] && ajson.genres.data[0].name){
1402                                         track.genre = []
1403                                         ajson.genres.data.forEach(function(genre){
1404                                                 if (track.genre.indexOf(genre.name) == -1)
1405                                                         track.genre.push(genre.name)
1406                                         })
1407                                 }
1408                         }else{
1409                                 // Missing barcode, genre
1410                                 track.album = ajson
1411                                 track.date = track.album.date
1412                                 track.trackTotal = track.album.trackTotal
1413                                 track.recordType = switchReleaseType(track.recordType)
1414                                 // TODO: Make a loop for each artist
1415                         }
1416
1417                         if (!track.date.slicedYear){
1418                                 track.date.slicedYear = settings.dateFormatYear == "2" ? track.date.year.slice(2, 4) : track.date.year.slice(0, 4)
1419                         }
1420
1421                         // Acquiring bpm (only if necessary)
1422                         if (settings.tags.bpm){
1423                                 logger.info(`[${track.artist.name} - ${track.title}] Getting BPM`);
1424                                 track.legacyTrack = await s.Deezer.legacyGetTrack(track.id)
1425                                 try{
1426                                         track.bpm = track.legacyTrack.bpm
1427                                 }catch(err){
1428                                         track.bpm = 0
1429                                 }
1430                         }else{
1431                                 track.bpm = 0
1432                         }
1433
1434                         // Acquiring ReplayGain value (only if necessary)
1435                         if (settings.tags.replayGain){
1436                                 logger.info(`[${track.artist.name} - ${track.title}] Getting track gain`);
1437                                 if (!track.legacyTrack) track.legacyTrack = await s.Deezer.legacyGetTrack(track.id)
1438                                 try{
1439                                         track.replayGain = track.legacyTrack.gain
1440                                 }catch(err){
1441                                         track.replayGain = 0
1442                                 }
1443                         }else{
1444                                 track.replayGain = 0
1445                         }
1446
1447                         // Acquiring discNumber value (only if necessary)
1448                         if (settings.tags.discNumber && !track.discNumber){
1449                                 logger.info(`[${track.artist.name} - ${track.title}] Getting disc number`);
1450                                 if (!track.legacyTrack) track.legacyTrack = await s.Deezer.legacyGetTrack(track.id)
1451                                 track.discNumber = track.legacyTrack.disk_number
1452                         }
1453
1454                         let separator = settings.multitagSeparator
1455                         if (separator == "null") separator = String.fromCharCode(0)
1456
1457                         // Autoremoves (Album Version) from the title
1458                         if (settings.removeAlbumVersion){
1459                                 if(track.title.indexOf("Album Version")>-1){
1460                                         track.title = track.title.replace(/ ?\(Album Version\)/g,"")
1461                                 }
1462                         }
1463                         if (!track.album.artist.picture && !settings.plName){
1464                                 if (track.artist.name == track.album.artist.name && !track.album.artist.picture){
1465                                         track.album.artist.picture = track.artist.picture
1466                                 }else{
1467                                         let found = false
1468                                         if (track.artists){
1469                                                 track.artists.forEach(x=>{
1470                                                         if(!found && x.name == track.album.artist.name){
1471                                                                 track.album.artist.picture = x.picture
1472                                                                 found = true
1473                                                         }
1474                                                 })
1475                                         }
1476                                         if(settings.saveArtworkArtist && !found){
1477                                                 artist = await s.Deezer.legacyGetArtist(track.album.artist.id)
1478                                                 track.album.artist.picture = artist.picture_small.substring(46,ajson.artist.picture_small.length-24)
1479                                         }
1480                                 }
1481                         }
1482                         if (!track.album.artist.picture) track.album.artist.picture = ""
1483                         track.album.artist.pictureUrl = `${s.Deezer.artistPictureHost}${track.album.artist.picture}/${settings.artworkSize}x${settings.artworkSize}-000000-80-0-0${(settings.PNGcovers ? ".png" : ".jpg")}`
1484                         track.album.pictureUrl = `${s.Deezer.albumPicturesHost}${track.album.picture}/${settings.artworkSize}x${settings.artworkSize}-000000-80-0-0${(settings.PNGcovers ? ".png" : ".jpg")}`
1485
1486                         // Auto detect aviable track format from settings
1487                         switch(downloadQueue[queueId].bitrate.toString()){
1488                                 case "9":
1489                                         track.selectedFormat = 9
1490                                         track.selectedFilesize = track.filesize.flac
1491                                         if (track.filesize.flac>0) break
1492                                         if (!settings.fallbackBitrate) throw new Error("Song not found at desired bitrate.")
1493                                 case "3":
1494                                         track.selectedFormat = 3
1495                                         track.selectedFilesize = track.filesize.mp3_320
1496                                         if (track.filesize.mp3_320>0) break
1497                                         if (!settings.fallbackBitrate) throw new Error("Song not found at desired bitrate.")
1498                                 case "1":
1499                                         track.selectedFormat = 1
1500                                         track.selectedFilesize = track.filesize.mp3_128
1501                                         if (track.filesize.mp3_128>0) break
1502                                         if (!settings.fallbackBitrate) throw new Error("Song not found at desired bitrate.")
1503                                 default:
1504                                         track.selectedFormat = 8
1505                                         track.selectedFilesize = track.filesize.default
1506                         }
1507
1508                         if(track.contributor){
1509                                 if(track.contributor.composer){
1510                                         track.composerString = uniqueArray(track.contributor.composer)
1511                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0))) track.composerString = track.composerString.join(separator)
1512                                 }
1513                                 if(track.contributor.musicpublisher){
1514                                         track.musicpublisherString = uniqueArray(track.contributor.musicpublisher)
1515                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0))) track.musicpublisherString = track.musicpublisherString.join(separator)
1516                                 }
1517                                 if(track.contributor.producer){
1518                                         track.producerString = uniqueArray(track.contributor.producer)
1519                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0))) track.producerString = track.producerString.join(separator)
1520                                 }
1521                                 if(track.contributor.engineer){
1522                                         track.engineerString = uniqueArray(track.contributor.engineer)
1523                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0))) track.engineerString = track.engineerString.join(separator)
1524                                 }
1525                                 if(track.contributor.writer){
1526                                         track.writerString = uniqueArray(track.contributor.writer)
1527                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0))) track.writerString = track.writerString.join(separator)
1528                                 }
1529                                 if(track.contributor.author){
1530                                         track.authorString = uniqueArray(track.contributor.author)
1531                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0))) track.authorString = track.authorString.join(separator)
1532                                 }
1533                                 if(track.contributor.mixer){
1534                                         track.mixerString = uniqueArray(track.contributor.mixer)
1535                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0))) track.mixerString = track.mixerString.join(separator)
1536                                 }
1537                         }
1538
1539                         if(track.artists || track.artistsString){
1540                                 if (!track.artistsString){
1541                                         track.artistsString = []
1542                                         artistArray = []
1543                                         track.artists.forEach(function(artist){
1544                                                 artistArray.push(artist.name)
1545                                         })
1546                                 }else{
1547                                         if (! Array.isArray(track.artistsString)){
1548                                                 track.artistsString = [track.artistsString,]
1549                                         }
1550                                         artistArray = track.artistsString
1551                                 }
1552                                 track.artistsString = uniqueArray(artistArray)
1553                                 let posMainArtist = track.artistsString.indexOf(track.album.artist.name)
1554                                 if (posMainArtist !== -1 && posMainArtist !== 0){
1555                                         let element = track.artistsString[posMainArtist]
1556                                 track.artistsString.splice(posMainArtist, 1)
1557                                 track.artistsString.splice(0, 0, element)
1558                                 }
1559                                 if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0))) track.artistsString = track.artistsString.join(separator)
1560                         }
1561                         if (track.genre){
1562                                 if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0)))
1563                                         track.genreString = track.genre.join(separator)
1564                                 else
1565                                         track.genreString = track.genre
1566                         }
1567
1568                         if (track.date){
1569                                 let date
1570                                 switch (settings.dateFormat){
1571                                         case "0": date = `${track.date.slicedYear}-${track.date.month}-${track.date.day}`; break;
1572                                         case "1": date = `${track.date.day}-${track.date.month}-${track.date.slicedYear}`; break;
1573                                         case "2": date = `${track.date.month}-${track.date.day}-${track.date.slicedYear}`; break;
1574                                         case "3": date = `${track.date.slicedYear}-${track.date.day}-${track.date.month}`; break;
1575                                         case "4": date = `${track.date.day}${track.date.month}`; break;
1576                                         default: date = `${track.date.day}${track.date.month}`; break;
1577                                 }
1578                                 track.dateString = date;
1579                         }
1580                 }else{
1581                         track.date = {year: 0,day: 0,month: 0}
1582                         track.selectedFilesize = track.filesize
1583                         track.selectedFormat = 3
1584                 }
1585
1586                 // TODO: Move to a separate function
1587                 // Generating file name
1588                 if (settings.saveFullArtists && settings.multitagSeparator != null){
1589                         let filename = antiDot(fixName(`${track.artistsString} - ${track.title}`));
1590                 }else{
1591                         let filename = antiDot(fixName(`${track.artist.name} - ${track.title}`));
1592                 }
1593                 if (settings.filename) {
1594                         filename = antiDot(fixName(settingsRegex(track, settings.filename, settings.playlist, settings.saveFullArtists && settings.multitagSeparator != null, settings.paddingSize, settings.plName && !settings.numplaylistbyalbum)))
1595                 }
1596
1597                 filename = antiDot(fixName(filename))
1598
1599                 // TODO: Move to a separate function
1600                 // Generating file path
1601                 let filepath = mainFolder;
1602                 let artistPath;
1603                 if ((settings.createArtistFolder || settings.createAlbumFolder) && !settings.plName) {
1604
1605                         if(settings.plName){
1606                                 filepath += antiDot(fixName(settings.plName)) + path.sep;
1607                         }
1608
1609                         if (settings.createArtistFolder) {
1610                                 if(settings.artName){
1611                                         filepath += antiDot(fixName(settings.artName)) + path.sep;
1612                                 }else{
1613                                         filepath += antiDot(fixName(track.album.artist.name)) + path.sep;
1614                                 }
1615                                 artistPath = filepath;
1616                         }
1617
1618                         if (settings.createAlbumFolder) {
1619                                 if(settings.artName){
1620                                         filepath += antiDot(fixName(settingsRegexAlbum(settings.foldername,settings.artName,settings.albName,track.date.year,track.recordType,track.album.explicit,track.publisher,track.genre))) + path.sep;
1621                                 }else{
1622                                         filepath += antiDot(fixName(settingsRegexAlbum(settings.foldername,track.album.artist.name,track.album.title,track.date.year,track.recordType,track.album.explicit,track.publisher,track.genre))) + path.sep;
1623                                 }
1624                         }
1625                 } else if (settings.plName) {
1626                         filepath += antiDot(fixName(settings.plName)) + path.sep;
1627                 } else if (settings.artName) {
1628                         filepath += antiDot(fixName(settingsRegexAlbum(settings.foldername,settings.artName,settings.albName,track.date.year,track.recordType,track.album.explicit,track.publisher,track.genre))) + path.sep;
1629                 }
1630                 let coverpath = filepath;
1631                 if (track.discTotal > 1 && (settings.artName || settings.createAlbumFolder) && settings.createCDFolder){
1632                         filepath += `CD${track.discNumber +  path.sep}`
1633                 }
1634                 let writePath;
1635
1636                 if(track.selectedFormat == 9){
1637                         writePath = filepath + filename + '.flac';
1638                 }else{
1639                         writePath = filepath + filename + '.mp3';
1640                 }
1641
1642                 if ((settings.syncedlyrics || settings.tags.unsynchronisedLyrics) && track.lyricsId>0){
1643                         let lyr = await s.Deezer.getLyrics(track.id)
1644                         track.syncLyrics = lyr.syncLyrics
1645                         track.unsyncLyrics = lyr.unsyncLyrics
1646                 }
1647
1648                 if(track.syncLyrics && settings.syncedlyrics){
1649                         fs.outputFile(writePath.substring(0,writePath.lastIndexOf('.'))+".lrc",track.syncLyrics,function(){});
1650                 }
1651
1652                 track.playlistData = [0,""]
1653                 if (settings.createM3UFile && (settings.plName || settings.albName)) {
1654                         if (track.position){
1655                                 track.playlistData = [parseInt(track.position), writePath];
1656                         }else{
1657                                 track.playlistData = [track.trackNumber-1, writePath];
1658                         }
1659                 }
1660                 if (fs.existsSync(writePath)) {
1661                         logger.info(`[${track.artist.name} - ${track.title}] Already downloaded`);
1662                         return;
1663                 }else{
1664                         logger.info(`[${track.artist.name} - ${track.title}] Downloading file to ${writePath}`);
1665                 }
1666                 // Get cover image
1667                 if (track.album.pictureUrl) {
1668                         let imgPath;
1669                         //If its not from an album but a playlist.
1670                         if(settings.albName || settings.createAlbumFolder){
1671                                 if (settings.saveArtwork && ! settings.plName)
1672                                         imgPath = coverpath + settingsRegexCover(settings.coverImageTemplate,track.album.artist.name,track.album.title)+(settings.PNGcovers ? ".png" : ".jpg")
1673                                 else
1674                                         imgPath = coverArtFolder + fixName(track.album.barcode ? fixName(track.album.barcode) : fixName(`${track.album.artist.name} - ${track.album.title}`))+(settings.PNGcovers ? ".png" : ".jpg")
1675                         }else{
1676                                 imgPath = coverArtFolder + (track.album.barcode ? fixName(track.album.barcode) : fixName(`${track.album.artist.name} - ${track.album.title}`))+(settings.PNGcovers ? ".png" : ".jpg")
1677                         }
1678                         if(fs.existsSync(imgPath)){
1679                                 track.album.picturePath = (imgPath).replace(/\\/g, "/")
1680                                 logger.info(`[${track.artist.name} - ${track.title}] Starting the download process CODE:1`)
1681                         }else{
1682                                 try{
1683                                         var body = await request.get(track.album.pictureUrl, {strictSSL: false,encoding: 'binary'})
1684                                         fs.outputFileSync(imgPath,body,'binary')
1685                                         track.album.picturePath = (imgPath).replace(/\\/g, "/")
1686                                         logger.info(`[${track.artist.name} - ${track.title}] Starting the download process CODE:2`)
1687                                 }catch(error){
1688                                         logger.error(`[${track.artist.name} - ${track.title}] Cannot download Album Image: ${error}`)
1689                                         logger.error(`Album art link: ${track.album.pictureUrl}`)
1690                                         track.album.pictureUrl = undefined
1691                                         track.album.picturePath = undefined
1692                                 }
1693                         }
1694                 }else{
1695                         track.album.pictureUrl = undefined
1696                         logger.info(`[${track.artist.name} - ${track.title}] Starting the download process CODE:3`)
1697                 }
1698
1699                 // Get Artist Image
1700                 if (parseInt(track.id)>0 && track.album.artist.pictureUrl && settings.saveArtworkArtist) {
1701                         let imgPath;
1702                         if(settings.createArtistFolder && artistPath){
1703                                 imgPath = artistPath + antiDot(settingsRegexArtistCover(settings.artistImageTemplate,track.album.artist.name))+(settings.PNGcovers ? ".png" : ".jpg");
1704                                 if(!fs.existsSync(imgPath)){
1705                                         try{
1706                                                 var body = await request.get(track.album.artist.pictureUrl, {strictSSL: false,encoding: 'binary'})
1707                                                 if (body.indexOf("unauthorized")>-1) throw new Error("Unauthorized")
1708                                                 fs.outputFileSync(imgPath,body,'binary')
1709                                                 logger.info(`[${track.artist.name} - ${track.title}] Saved Artist Image`)
1710                                         }catch(err){
1711                                                 logger.error(`[${track.artist.name} - ${track.title}] Cannot download Artist Image: ${err}`)
1712                                         }
1713                                 }
1714                         }
1715                 }
1716
1717                 let tempPath
1718                 if(parseInt(track.id)>0)
1719                         tempPath = `${filepath}${track.id}_${track.selectedFormat}.temp`
1720                 else
1721                         tempPath = writePath
1722
1723                 logger.info(`[${track.artist.name} - ${track.title}] Downloading track`)
1724                 var downloadingPromise = new Promise((resolve, reject)=>{
1725                         let req = requestOld.get({url: track.getDownloadUrl(track.selectedFormat), strictSSL: false, headers: s.Deezer.httpHeaders, encoding: 'binary'}, function (error, response, body) {
1726                                 if (error){
1727                                         logger.error(`[${track.artist.name} - ${track.title}] Downloading error: ${error}`)
1728                                         reject("Downloading error: "+error)
1729                                         return false
1730                                 }
1731                                 if (!downloadQueue[queueId]){
1732                                         fs.remove(tempPath)
1733                                         reject("Not in Queue")
1734                                         return false
1735                                 }
1736                                 if (body.length == 0){
1737                                         fs.remove(tempPath)
1738                                         reject("Track is Empty")
1739                                         return false
1740                                 }
1741                                 logger.info(`[${track.artist.name} - ${track.title}] Decrypting track`)
1742                                 var decryptedSource = s.Deezer.decryptDownload(Buffer.from(body, 'binary'), track.id)
1743                                 try{
1744                                         fs.outputFileSync(tempPath,decryptedSource)
1745                                         resolve()
1746                                 }catch(err){
1747                                         logger.error(`[${track.artist.name} - ${track.title}] Decryption error: ${err}`)
1748                                         reject(err)
1749                                         return false
1750                                 }
1751                         }).on("data", function(data) {
1752                                 if (!downloadQueue[queueId]){
1753                                         reject("Not in Queue")
1754                                         return false
1755                                 }
1756                         })
1757                         if((downloadQueue[queueId]) && downloadQueue[queueId].type == "track"){
1758                                 let chunkLength = 0
1759                                 req.on("data", function(data) {
1760                                         if (!downloadQueue[queueId]){
1761                                                 reject("Not in Queue")
1762                                         }
1763                                         chunkLength += data.length
1764                                         try{
1765                                                 if (!downloadQueue[queueId].percentage) {
1766                                                         downloadQueue[queueId].percentage = 0
1767                                                 }
1768                                                 let complete = track.selectedFilesize
1769                                                 let percentage = (chunkLength / complete) * 100;
1770                                                 if ((percentage - downloadQueue[queueId].percentage > 1) || (chunkLength == complete)) {
1771                                                         downloadQueue[queueId].percentage = percentage
1772                                                         io.sockets.emit("downloadProgress", {
1773                                                                 queueId: queueId,
1774                                                                 percentage: downloadQueue[queueId].percentage-5
1775                                                         })
1776                                                 }
1777                                         }catch(err){}
1778                                 })
1779                         }
1780                 })
1781
1782                 try{
1783                         await downloadingPromise
1784                 }catch(err){
1785                         if (err==="Track is Empty"){
1786                                 if(track.fallbackId && track.fallbackId != "0"){
1787                                         logger.warn(`[${track.artist.name} - ${track.title}] Track is empty, falling on alternative`)
1788                                         var _track = await s.Deezer.getTrack(track.fallbackId)
1789                                         track.id = _track.id
1790                                         track.fallbackId = _track.fallbackId
1791                                         track.filesize = _track.filesize
1792                                         track.duration = _track.duration
1793                                         track.MD5 = _track.MD5
1794                                         track.mediaVersion = _track.mediaVersion
1795                                         return downloadTrackObject(track, queueId, settings)
1796                                 }else if(!track.searched){
1797                                         logger.warn(`[${track.artist.name} - ${track.title}] Track is empty, searching for alternative`)
1798                                         _trackId = await convertMetadata2Deezer(track.artist.name, track.title, track.album.title)
1799                                         if (_trackId != "0"){
1800                                                 _track = await s.Deezer.getTrack(_trackId)
1801                                                 track.id = _track.id
1802                                                 track.fallbackId = _track.fallbackId
1803                                                 track.filesize = _track.filesize
1804                                                 track.duration = _track.duration
1805                                                 track.MD5 = _track.MD5
1806                                                 track.mediaVersion = _track.mediaVersion
1807                                                 track.searched = true
1808                                                 return downloadTrackObject(track, queueId, settings)
1809                                         }else{
1810                                                 logger.error(`[${track.artist.name} - ${track.title}] No alternative found`)
1811                                                 throw new Error("No Alternative Found")
1812                                                 return
1813                                         }
1814                                 }else{
1815                                         logger.error(`[${track.artist.name} - ${track.title}] Downloading error: Track is Empty`)
1816                                         throw new Error("Track is Empty")
1817                                         return
1818                                 }
1819                         }else{
1820                                 throw new Error(err)
1821                                 return
1822                         }
1823                 }
1824
1825                 logger.info(`[${track.artist.name} - ${track.title}] Adding Tags`)
1826                 if (parseInt(track.id)>0){
1827                         if(track.selectedFormat == 9){
1828                                 let flacComments = [];
1829                                 if (settings.tags.title)
1830                                         flacComments.push('TITLE=' + track.title);
1831                                 if (settings.tags.album)
1832                                         flacComments.push('ALBUM=' + track.album.title);
1833                                 if (settings.tags.albumArtist)
1834                                         flacComments.push('ALBUMARTIST=' + track.album.artist.name);
1835                                 if (settings.tags.trackNumber)
1836                                         flacComments.push('TRACKNUMBER=' + track.trackNumber);
1837                                 if (settings.tags.discNumber)
1838                                         flacComments.push('DISCNUMBER=' + track.discNumber);
1839                                 if (settings.tags.trackTotal)
1840                                         flacComments.push('TRACKTOTAL=' + track.trackTotal);
1841                                 if (settings.tags.explicit)
1842                                         flacComments.push('ITUNESADVISORY=' + track.explicit);
1843                                 if (settings.tags.isrc)
1844                                         flacComments.push('ISRC=' + track.ISRC);
1845                                 if (settings.tags.artist && track.artistsString)
1846                                         if (Array.isArray(track.artistsString)){
1847                                                 track.artistsString.forEach(x=>{
1848                                                         flacComments.push('ARTIST=' + x);
1849                                                 });
1850                                         }else{
1851                                                 flacComments.push('ARTIST=' + track.artistsString);
1852                                         }
1853                                 if (settings.tags.discTotal)
1854                                         flacComments.push('DISCTOTAL='+track.discTotal);
1855                                 if (settings.tags.length)
1856                                         flacComments.push('LENGTH=' + track.duration);
1857                                 if (settings.tags.barcode && track.album.barcode)
1858                                         flacComments.push('BARCODE=' + track.album.barcode);
1859                                 if (track.unsyncLyrics && settings.tags.unsynchronisedLyrics)
1860                                         flacComments.push('LYRICS='+track.unsyncLyrics.lyrics);
1861                                 if (track.genreString && settings.tags.genre)
1862                                         if (Array.isArray(track.genreString)){
1863                                                 track.genreString.forEach(x=>{
1864                                                         flacComments.push('GENRE=' + x);
1865                                                 });
1866                                         }else{
1867                                                 flacComments.push('GENRE=' + track.genreString);
1868                                         }
1869                                 if (track.copyright && settings.tags.copyright)
1870                                         flacComments.push('COPYRIGHT=' + track.copyright);
1871                                 if (0 < parseInt(track.date.year)){
1872                                         if (settings.tags.date)
1873                                                 flacComments.push('DATE=' + track.dateString);
1874                                         if (settings.tags.year)
1875                                                 flacComments.push('YEAR=' + track.date.year);
1876                                 }
1877                                 if (0 < parseInt(track.bpm) && settings.tags.bpm)
1878                                         flacComments.push('BPM=' + track.bpm);
1879                                 if(track.publisher && settings.tags.publisher)
1880                                         flacComments.push('PUBLISHER=' + track.publisher);
1881                                 if(track.composerString && settings.tags.composer)
1882                                         if (Array.isArray(track.composerString)){
1883                                                 track.composerString.forEach(x=>{
1884                                                         flacComments.push('COMPOSER=' + x);
1885                                                 });
1886                                         }else{
1887                                                 flacComments.push('COMPOSER=' + track.composerString);
1888                                         }
1889                                 if(track.musicpublisherString && settings.tags.musicpublisher)
1890                                         if (Array.isArray(track.musicpublisherString)){
1891                                                 track.musicpublisherString.forEach(x=>{
1892                                                         flacComments.push('ORGANIZATION=' + x);
1893                                                 });
1894                                         }else{
1895                                                 flacComments.push('ORGANIZATION=' + track.musicpublisherString);
1896                                         }
1897                                 if(track.mixerString && settings.tags.mixer)
1898                                         if (Array.isArray(track.mixerString)){
1899                                                 track.mixerString.forEach(x=>{
1900                                                         flacComments.push('MIXER=' + x);
1901                                                 });
1902                                         }else{
1903                                                 flacComments.push('MIXER=' + track.mixerString);
1904                                         }
1905                                 if(track.authorString && settings.tags.author)
1906                                         if (Array.isArray(track.authorString)){
1907                                                 track.authorString.forEach(x=>{
1908                                                         flacComments.push('AUTHOR=' + x);
1909                                                 });
1910                                         }else{
1911                                                 flacComments.push('AUTHOR=' + track.authorString);
1912                                         }
1913                                 if(track.writerString && settings.tags.writer)
1914                                         if (Array.isArray(track.writerString)){
1915                                                 track.writerString.forEach(x=>{
1916                                                         flacComments.push('WRITER=' + x);
1917                                                 });
1918                                         }else{
1919                                                 flacComments.push('WRITER=' + track.writerString);
1920                                         }
1921                                 if(track.engineerString && settings.tags.engineer)
1922                                         if (Array.isArray(track.engineerString)){
1923                                                 track.engineerString.forEach(x=>{
1924                                                         flacComments.push('ENGINEER=' + x);
1925                                                 });
1926                                         }else{
1927                                                 flacComments.push('ENGINEER=' + track.engineerString);
1928                                         }
1929                                 if(track.producerString && settings.tags.producer)
1930                                         if (Array.isArray(track.producerString)){
1931                                                 track.producerString.forEach(x=>{
1932                                                         flacComments.push('PRODUCER=' + x);
1933                                                 });
1934                                         }else{
1935                                                 flacComments.push('PRODUCER=' + track.producerString);
1936                                         }
1937                                 if(track.replayGain && settings.tags.replayGain)
1938                                         flacComments.push('REPLAYGAIN_TRACK_GAIN=' + track.replayGain);
1939
1940                                 const reader = fs.createReadStream(tempPath);
1941                                 const writer = fs.createWriteStream(writePath);
1942                                 let processor = new mflac.Processor({parseMetaDataBlocks: true});
1943                                 let vendor = 'reference libFLAC 1.2.1 20070917';
1944                                 let cover = null;
1945                                 if(track.album.picturePath && settings.tags.cover){
1946                                         cover = fs.readFileSync(track.album.picturePath)
1947                                 }
1948                                 let mdbVorbisPicture
1949                                 let mdbVorbisComment
1950                                 processor.on('preprocess', (mdb) => {
1951                                         // Remove existing VORBIS_COMMENT and PICTURE blocks, if any.
1952                                         if (mflac.Processor.MDB_TYPE_VORBIS_COMMENT === mdb.type) {
1953                                                 mdb.remove();
1954                                         } else if (mflac.Processor.MDB_TYPE_PICTURE === mdb.type) {
1955                                                 mdb.remove();
1956                                         }
1957                                         if (mdb.isLast) {
1958                                                 if(cover){
1959                                                         mdbVorbisPicture = mflac.data.MetaDataBlockPicture.create(true, 3, `image/${(settings.PNGcovers ? "png" : "jpeg")}`, '', settings.artworkSize, settings.artworkSize, 24, 0, cover);
1960                                                 }
1961                                                 mdbVorbisComment = mflac.data.MetaDataBlockVorbisComment.create(!cover, vendor, flacComments);
1962                                                 mdb.isLast = false;
1963                                         }
1964                                 });
1965                                 processor.on('postprocess', (mdb) => {
1966                                         if (mflac.Processor.MDB_TYPE_VORBIS_COMMENT === mdb.type && null !== mdb.vendor) {
1967                                                 vendor = mdb.vendor;
1968                                         }
1969                                         if (mdbVorbisPicture && mdbVorbisComment) {
1970                                                         processor.push(mdbVorbisComment.publish());
1971                                                         processor.push(mdbVorbisPicture.publish());
1972                                                 }else if(mdbVorbisComment){
1973                                                         processor.push(mdbVorbisComment.publish());
1974                                         }
1975                                 });
1976                                 reader.on('end', () => {
1977                                         fs.remove(tempPath);
1978                                 });
1979                                 await reader.pipe(processor).pipe(writer);
1980                         }else{
1981                                 const songBuffer = fs.readFileSync(tempPath);
1982                                 const writer = new ID3Writer(songBuffer);
1983                                 if (settings.tags.title)
1984                                         writer.setFrame('TIT2', track.title)
1985                                 if (settings.tags.artist)
1986                                         writer.setFrame('TPE1', [track.artistsString])
1987                                 if (settings.tags.album)
1988                                         writer.setFrame('TALB', track.album.title)
1989                                 if (settings.tags.albumArtist && track.album.artist)
1990                                         writer.setFrame('TPE2', track.album.artist.name)
1991                                 if (settings.tags.trackNumber)
1992                                         writer.setFrame('TRCK', (settings.tags.trackTotal ? track.trackNumber+"/"+track.trackTotal : track.trackNumber))
1993                                 if (settings.tags.discNumber)
1994                                         writer.setFrame('TPOS', (settings.tags.discTotal ? track.discNumber+"/"+track.discTotal : track.discNumber))
1995                                 if (settings.tags.isrc)
1996                                         writer.setFrame('TSRC', track.ISRC);
1997
1998                                 if (settings.tags.length)
1999                                         writer.setFrame('TLEN', track.duration);
2000                                 if (settings.tags.barcode && track.album.barcode)
2001                                         writer.setFrame('TXXX', {
2002                                                 description: 'BARCODE',
2003                                                 value: track.album.barcode
2004                                         });
2005                                 if(track.album.picturePath && settings.tags.cover){
2006                                         const coverBuffer = fs.readFileSync(track.album.picturePath);
2007                                         writer.setFrame('APIC', {
2008                                                 type: 3,
2009                                                 data: coverBuffer,
2010                                                 description: ''
2011                                         });
2012                                 }
2013                                 if(track.unsyncLyrics && settings.tags.unsynchronisedLyrics)
2014                                         writer.setFrame('USLT', track.unsyncLyrics);
2015                                 if(track.publisher && settings.tags.publisher)
2016                                         writer.setFrame('TPUB', track.publisher);
2017                                 if(track.genreString && settings.tags.genre)
2018                                         writer.setFrame('TCON', [track.genreString]);
2019                                 if(track.copyright && settings.tags.copyright)
2020                                         writer.setFrame('TCOP', track.copyright);
2021                                 if (0 < parseInt(track.date.year)) {
2022                                         if (settings.tags.date)
2023                                                 writer.setFrame('TDAT', track.dateString);
2024                                         if (settings.tags.year)
2025                                                 writer.setFrame('TYER', track.date.year);
2026                                 }
2027                                 if (0 < parseInt(track.bpm) && settings.tags.bpm)
2028                                         writer.setFrame('TBPM', track.bpm);
2029                                 if(track.composerString && settings.tags.composer)
2030                                         writer.setFrame('TCOM', [track.composerString]);
2031                                 if(track.replayGain && settings.tags.replayGain)
2032                                         writer.setFrame('TXXX', {
2033                                                 description: 'REPLAYGAIN_TRACK_GAIN',
2034                                                 value: track.replayGain
2035                                         });
2036                                 writer.addTag();
2037                                 const taggedSongBuffer = Buffer.from(writer.arrayBuffer);
2038                                 fs.writeFileSync(writePath, taggedSongBuffer);
2039                                 fs.remove(tempPath);
2040                         }
2041                 }
2042                 logger.info(`[${track.artist.name} - ${track.title}] Downloaded`)
2043         }
2044 })
2045
2046 // Helper functions
2047
2048 /**
2049  * Updates individual parameters in the settings file
2050  * @param config
2051  * @param value
2052  */
2053 function updateSettingsFile(config, value) {
2054         configFile.userDefined[config] = value;
2055
2056         fs.outputFile(configFileLocation, JSON.stringify(configFile, null, 2), function (err) {
2057                 if (err) return;
2058                 logger.info("Settings updated");
2059
2060                 // FIXME: Endless Loop, due to call from initFolders()...crashes soon after startup
2061                 // initFolders();
2062         });
2063 }
2064
2065 function fixName (txt) {
2066         txt = txt+""
2067   const regEx = /[\0\/\\:*?"<>|]/g;
2068   txt = txt.replace(regEx, '_');
2069   txt = txt.slice(0,200);
2070   return txt;
2071 }
2072
2073 function antiDot(str){
2074         while(str[str.length-1] == "." || str[str.length-1] == " " || str[str.length-1] == "\n"){
2075                 str = str.substring(0,str.length-1);
2076         }
2077         if(str.length < 1){
2078                 str = "dot";
2079         }
2080         return str;
2081 }
2082
2083 /**
2084  * Initialize the temp folder for covers and main folder for downloads
2085  */
2086 function initFolders() {
2087         // Check if main folder exists
2088         if (!fs.existsSync(mainFolder)) {
2089                 mainFolder = defaultDownloadFolder;
2090                 updateSettingsFile('downloadLocation', defaultDownloadFolder);
2091         }
2092         //fs.removeSync(coverArtFolder);
2093         //fs.ensureFolderSync(coverArtFolder);
2094 }
2095
2096 /**
2097  * Creates the name of the tracks replacing wildcards to correct metadata
2098  * @param track
2099  * @param filename
2100  * @param playlist
2101  * @returns {XML|string|*}
2102  */
2103 function settingsRegex(track, filename, playlist, saveFullArtists, paddingSize, playlistNumbering) {
2104         try{
2105                 filename = filename.replace(/%title%/g, fixName(track.title));
2106                 filename = filename.replace(/%album%/g, fixName(track.album.title));
2107                 filename = filename.replace(/%artist%/g, fixName((saveFullArtists ? track.artistsString : track.artist.name)));
2108                 filename = filename.replace(/%year%/g, fixName(track.date.year));
2109                 filename = filename.replace(/%label%/g, fixName(track.publisher));
2110                 let tNumber = playlistNumbering ? track.position+1 : track.trackNumber
2111                 let tTotal = playlistNumbering ? playlist.fullSize : track.trackTotal
2112                 if(typeof tNumber != 'undefined'){
2113                         if(configFile.userDefined.padtrck){
2114                                  filename = filename.replace(/%number%/g, fixName(pad(tNumber, (parseInt(paddingSize)>0 ? parseInt(paddingSize) : tTotal))));
2115                         }else{
2116                                 filename = filename.replace(/%number%/g, fixName(tNumber));
2117                         }
2118                 } else {
2119                         filename = filename.replace(/%number%/g, '');
2120                 }
2121                 filename = filename.replace(/%explicit%/g, fixName((track.explicit==="1" ? (filename.indexOf(/[^%]explicit/g)>-1 ? "" : "(Explicit Version)") : "")));
2122                 filename = filename.replace(/%label%/g, fixName(track.genre ? (Array.isArray(track.genre) ? track.genre[0] : track.genre) : "Unknown"));
2123                 filename = filename.replace(/[/\\]/g, path.sep)
2124                 return filename.trim();
2125         }catch(e){
2126                 logger.error("settingsRegex failed: "+e)
2127         }
2128 }
2129
2130 /**
2131  * Creates the name of the albums folder replacing wildcards to correct metadata
2132  * @param metadata
2133  * @param foldername
2134  * @returns {XML|string|*}
2135  */
2136 function settingsRegexAlbum(foldername, artist, album, year, rtype, explicit, publisher, genres) {
2137         try{
2138                 foldername = foldername.replace(/%album%/g, fixName(album))
2139                 foldername = foldername.replace(/%artist%/g, fixName(artist))
2140                 foldername = foldername.replace(/%year%/g, fixName(year))
2141                 if (rtype){
2142                         foldername = foldername.replace(/%type%/g, fixName(rtype[0].toUpperCase() + rtype.substring(1)))
2143                 }else{
2144                         foldername = foldername.replace(/%type%/g, "")
2145                 }
2146                 foldername = foldername.replace(/%label%/g, fixName(publisher))
2147                 foldername = foldername.replace(/%explicit%/g, fixName((explicit ? (foldername.indexOf(/[^%]explicit/g)>-1 ? "" : "(Explicit) ") : "")))
2148                 foldername = foldername.replace(/%genre%/g, fixName(genres ? (Array.isArray(genres) ? genres[0] : genres) : "Unknown"))
2149                 foldername = foldername.replace(/[/\\]/g, path.sep)
2150                 return foldername.trim();
2151         }catch(e){
2152                 logger.error("settingsRegexAlbum failed: "+e)
2153         }
2154
2155 }
2156
2157 function settingsRegexCover(foldername, artist, name) {
2158         foldername = foldername.replace(/%name%/g, fixName(name));
2159         foldername = foldername.replace(/%artist%/g, fixName(artist));
2160         foldername = foldername.replace(/[/\\]/g, path.sep)
2161         return foldername;
2162 }
2163
2164 function settingsRegexArtistCover(foldername, artist) {
2165         foldername = foldername.replace(/%artist%/g, fixName(artist));
2166         foldername = foldername.replace(/[/\\]/g, path.sep)
2167         return foldername;
2168 }
2169
2170 /**
2171  * Pad number with 0s so max and str have the same nuber of characters
2172  * @param str
2173  * @param max
2174  * @returns {String|string|*}
2175  */
2176 function pad(str, max) {
2177         str = str.toString();
2178         max = max.toString();
2179         return str.length < max.length || str.length == 1 ? pad("0" + str, max) : str;
2180 }
2181
2182 /**
2183  * Splits the %number%
2184  * @param string str
2185  * @return string
2186  */
2187 function splitNumber(str,total){
2188         str = str.toString();
2189         let i = str.indexOf("/");
2190         if(total && i > 0){
2191                 return str.slice(i+1, str.length);
2192         }else if(i > 0){
2193                 return str.slice(0, i);
2194         }else{
2195                 return str;
2196         }
2197         return i > 0 ? str.slice(0, i) : str;
2198 }
2199
2200 function switchReleaseType(id){
2201         switch (id.toString()) {
2202                 case "0":
2203                         return "Album";
2204                 case "1":
2205                         return "Single";
2206                 case "3":
2207                         return "EP";
2208                 default:
2209                         return "Album";
2210         }
2211 }
2212
2213 function uniqueArray(origin, removeDupes=true){
2214         destination = []
2215         Array.from(new Set(origin)).forEach(function(x){
2216                 if(destination.indexOf(x) == -1)
2217                         destination.push(x);
2218         })
2219         if (removeDupes){
2220                 destination.forEach((name,index)=>{
2221                         destination.forEach((name2,index2)=>{
2222                                 if(!(index===index2) && (name.toLowerCase().indexOf(name2.toLowerCase())!== -1)){
2223                                         destination.splice(index, 1);
2224                                 }
2225                         })
2226                 })
2227         }
2228         return destination
2229 }
2230
2231 async function asyncForEach(array, callback) {
2232   for (let index = 0; index < array.length; index++) {
2233     await callback(array[index], index, array);
2234   }
2235 }
2236
2237 // Show crash error in console for debugging
2238 process.on('unhandledRejection', function (err) {
2239         if (err) logger.error(err.stack ? err.stack : err)
2240
2241 })
2242 process.on('uncaughtException', function (err) {
2243         if (err) logger.error(err.stack ? err.stack : err)
2244 })
2245
2246 // Exporting vars
2247 module.exports.mainFolder = mainFolder
2248 module.exports.defaultSettings = defaultSettings
2249 module.exports.defaultDownloadFolder = defaultDownloadFolder