Fixed #280
[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.errorLog += `${t.id} | ${t.artist.name} - ${t.title} | ${err}\r\n`
943                                                 downloading.failed++
944                                         }
945                                         io.sockets.emit("updateQueue", {
946                                                 name: downloading.name,
947                                                 artist: downloading.artist,
948                                                 size: downloading.size,
949                                                 downloaded: downloading.downloaded,
950                                                 failed: downloading.failed,
951                                                 queueId: downloading.queueId,
952                                                 id: downloading.id,
953                                                 type: downloading.type,
954                                                 errorLog: downloading.errorLog,
955                                         })
956                                         io.sockets.emit("downloadProgress", {
957                                                 queueId: downloading.queueId,
958                                                 percentage: 100
959                                         })
960                                         resolve()
961                                 })
962                                 try{
963                                         await downloadPromise
964                                 }catch(err){
965                                         if (err) logger.error(`queueDownload:track failed: ${err.stack ? err.stack : err}`)
966                                         logger.info("Downloading Stopped")
967                                 }
968                         break
969                         /*
970                         *  ALBUM DOWNLOAD
971                         */
972                         case "album":
973                                 downloading.settings.albName = downloading.name;
974                                 downloading.settings.artName = downloading.artist;
975                                 downloading.playlistArr = Array(downloading.size);
976                                 filePath = mainFolder;
977                                 downloading.obj.genresString = []
978                                 downloading.obj.genres.data.map((x)=>{
979                                         downloading.obj.genresString.push(x.name)
980                                 })
981                                 if (downloading.settings.createArtistFolder || downloading.settings.createAlbumFolder) {
982                                         if (downloading.settings.createArtistFolder) {
983                                                 filePath += antiDot(fixName(downloading.settings.artName)) + path.sep;
984                                         }
985                                         if (downloading.settings.createAlbumFolder) {
986                                                 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;
987                                         }
988                                 } else if (downloading.settings.artName) {
989                                         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;
990                                 }
991                                 let ajson = {
992                                         artist : downloading.obj.artist,
993                                         nb_tracks : downloading.obj.nb_tracks,
994                                         upc : downloading.obj.upc,
995                                         record_type : downloading.obj.record_type,
996                                         explicit_lyrics : downloading.obj.explicit_lyrics,
997                                         label : downloading.obj.label,
998                                         release_date : downloading.obj.release_date,
999                                         genres : downloading.obj.genres,
1000                                         discTotal: downloading.obj.discTotal ? downloading.obj.discTotal : null
1001                                 }
1002                                 downloading.downloadPromise = new Promise((resolve,reject)=>{
1003                                         downloading.obj.tracks.every(function (t) {
1004                                                 trackQueue.push(async cb=>{
1005                                                         if (!downloadQueue[downloading.queueId]) {
1006                                                                 reject()
1007                                                                 return false
1008                                                         }
1009                                                         t.ajson = ajson
1010                                                         logger.info(`Now downloading: ${t.artist.name} - ${t.title}`)
1011                                                         try{
1012                                                                 await downloadTrackObject(t, downloading.queueId, downloading.settings)
1013                                                                 downloading.downloaded++
1014                                                                 downloading.playlistArr[t.playlistData[0]] = t.playlistData[1].split(filePath)[1]
1015                                                                 if (t.searched) downloading.searchedLog += `${t.artist.name} - ${t.title}\r\n`
1016                                                         }catch(err){
1017                                                                 downloading.failed++
1018                                                                 downloading.errorLog += `${t.id} | ${t.artist.name} - ${t.title} | ${err}\r\n`
1019                                                                 logger.error(`[${t.artist.name} - ${t.title}] ${err}`)
1020                                                         }
1021                                                         io.sockets.emit("downloadProgress", {
1022                                                                 queueId: downloading.queueId,
1023                                                                 percentage: ((downloading.downloaded+downloading.failed) / downloading.size) * 100
1024                                                         });
1025                                                         io.sockets.emit("updateQueue", {
1026                                                                 name: downloading.name,
1027                                                                 artist: downloading.artist,
1028                                                                 size: downloading.size,
1029                                                                 downloaded: downloading.downloaded,
1030                                                                 failed: downloading.failed,
1031                                                                 queueId: downloading.queueId,
1032                                                                 id: downloading.id,
1033                                                                 type: downloading.type,
1034                                                                 errorLog: downloading.errorLog,
1035                                                         })
1036                                                         if (downloading.downloaded + downloading.failed >= downloading.size) resolve()
1037                                                         cb()
1038                                                 })
1039                                                 return true
1040                                         })
1041                                 })
1042                                 try{
1043                                         await downloading.downloadPromise
1044                                         logger.info("Album finished downloading: "+downloading.name);
1045                                         io.sockets.emit("downloadProgress", {
1046                                                 queueId: downloading.queueId,
1047                                                 percentage: 100
1048                                         });
1049                                         if (downloading.settings.logErrors){
1050                                                 if (downloading.errorLog != ""){
1051                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1052                                                         fs.writeFileSync(filePath+"notFound.txt",downloading.errorLog)
1053                                                 }else{
1054                                                         if (fs.existsSync(filePath+"notFound.txt")) fs.unlinkSync(filePath+"notFound.txt");
1055                                                 }
1056                                         }
1057                                         if (downloading.settings.logSearched){
1058                                                 if (downloading.searchedLog != ""){
1059                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1060                                                         fs.writeFileSync(filePath+"alternativeSongs.txt",downloading.searchedLog)
1061                                                 }else{
1062                                                         if (fs.existsSync(filePath+"alternativeSongs.txt")) fs.unlinkSync(filePath+"alternativeSongs.txt");
1063                                                 }
1064                                         }
1065                                         if (downloading.settings.createM3UFile){
1066                                                 fs.writeFileSync(filePath+"playlist.m3u", downloading.playlistArr.join("\r\n"));
1067                                         }
1068                                 }catch(err){
1069                                         if (err) logger.error(`queueDownload:album failed: ${err.stack ? err.stack : err}`)
1070                                         logger.info("Stopping the album queue");
1071                                 }
1072                         break
1073                         /*
1074                         *  PLAYLIST DOWNLOAD
1075                         */
1076                         case "playlist":
1077                                 downloading.settings.plName = downloading.name;
1078                                 downloading.playlistArr = Array(downloading.size);
1079                                 downloading.settings.playlist = {
1080                                         fullSize: downloading.obj.tracks.length
1081                                 };
1082                                 filePath = mainFolder+antiDot(fixName(downloading.settings.plName)) + path.sep
1083                                 downloading.downloadPromise = new Promise((resolve,reject)=>{
1084                                         downloading.obj.tracks.every(function (t, index) {
1085                                                 trackQueue.push(async cb=>{
1086                                                         if (!downloadQueue[downloading.queueId]) {
1087                                                                 reject()
1088                                                                 return false
1089                                                         }
1090                                                         try{
1091                                                                 await downloadTrackObject(t, downloading.queueId, downloading.settings)
1092                                                                 downloading.downloaded++
1093                                                                 downloading.playlistArr[t.playlistData[0]] = t.playlistData[1].split(filePath)[1]
1094                                                                 if (t.searched) downloading.searchedLog += `${t.artist.name} - ${t.title}\r\n`
1095                                                         }catch(err){
1096                                                                 downloading.failed++
1097                                                                 downloading.errorLog += `${t.id} | ${t.artist.name} - ${t.title} | ${err}\r\n`
1098                                                                 logger.error(`[${t.artist.name} - ${t.title}] ${err}`)
1099                                                         }
1100                                                         io.sockets.emit("downloadProgress", {
1101                                                                 queueId: downloading.queueId,
1102                                                                 percentage: ((downloading.downloaded+downloading.failed) / downloading.size) * 100
1103                                                         });
1104                                                         io.sockets.emit("updateQueue", {
1105                                                                 name: downloading.name,
1106                                                                 artist: downloading.artist,
1107                                                                 size: downloading.size,
1108                                                                 downloaded: downloading.downloaded,
1109                                                                 failed: downloading.failed,
1110                                                                 queueId: downloading.queueId,
1111                                                                 id: downloading.id,
1112                                                                 type: downloading.type,
1113                                                                 errorLog: downloading.errorLog,
1114                                                         })
1115                                                         if (downloading.downloaded + downloading.failed >= downloading.size) resolve()
1116                                                         cb()
1117                                                 })
1118                                                 return true
1119                                         })
1120                                 })
1121                                 try{
1122                                         await downloading.downloadPromise
1123                                         logger.info("Playlist finished "+downloading.name);
1124                                         io.sockets.emit("downloadProgress", {
1125                                                 queueId: downloading.queueId,
1126                                                 percentage: 100
1127                                         });
1128                                         if (downloading.settings.logErrors){
1129                                                 if (downloading.errorLog != ""){
1130                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1131                                                         fs.writeFileSync(filePath+"notFound.txt",downloading.errorLog)
1132                                                 }else{
1133                                                         if (fs.existsSync(filePath+"notFound.txt")) fs.unlinkSync(filePath+"notFound.txt");
1134                                                 }
1135                                         }
1136                                         if (downloading.settings.logSearched){
1137                                                 if (downloading.searchedLog != ""){
1138                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1139                                                         fs.writeFileSync(filePath+"alternativeSongs.txt",downloading.searchedLog)
1140                                                 }else{
1141                                                         if (fs.existsSync(filePath+"alternativeSongs.txt")) fs.unlinkSync(filePath+"alternativeSongs.txt");
1142                                                 }
1143                                         }
1144                                         if (downloading.settings.createM3UFile){
1145                                                 fs.writeFileSync(filePath + "playlist.m3u", downloading.playlistArr.join("\r\n"));
1146                                         }
1147                                         if (downloading.settings.saveArtwork){
1148                                                 if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1149                                                 let imgPath = filePath + antiDot(settingsRegexCover(downloading.settings.coverImageTemplate,downloading.artist,downloading.name))+(downloading.settings.PNGcovers ? ".png" : ".jpg");
1150                                                 if (downloading.cover){
1151                                                         downloading.cover = downloading.cover.replace("56x56",`${downloading.settings.artworkSize}x${downloading.settings.artworkSize}`)
1152                                                         request.get(downloading.cover, {strictSSL: false,encoding: 'binary'}, function(error,response,body){
1153                                                                 if(error){
1154                                                                         logger.error(error.stack);
1155                                                                         return;
1156                                                                 }
1157                                                                 fs.outputFile(imgPath,body,'binary',function(err){
1158                                                                         if(err){
1159                                                                                 logger.error(err.stack);
1160                                                                                 return;
1161                                                                         }
1162                                                                         logger.info(`Cover downloaded for: ${downloading.settings.plName}`)
1163                                                                 })
1164                                                         });
1165                                                 }
1166                                         }
1167                                 }catch(err){
1168                                         if (err) logger.error(`queueDownload:playlist failed: ${err.stack ? err.stack : err}`)
1169                                         logger.info("Stopping the playlist queue")
1170                                 }
1171                         break
1172                         /*
1173                         *  SPOTIFY PLAYLIST DOWNLOAD
1174                         */
1175                         case "spotifyplaylist":
1176                                 downloading.settings.plName = downloading.name
1177                                 downloading.playlistArr = Array(downloading.size)
1178                                 downloading.playlistContent = new Array(downloading.size)
1179                                 logger.info("Waiting for all tracks to be converted");
1180                                 const convert = async () =>{
1181                                         await asyncForEach(downloading.obj.tracks, async (t,i)=>{
1182                                                 if (!downloadQueue[downloading.queueId]) return false
1183                                                 try{
1184                                                         downloading.playlistContent[i] = await convertSpotify2Deezer(t)
1185                                                 }catch(err){
1186                                                         logger.error(`queueDownload:spotifyplaylist failed during conversion: ${err.stack ? err.stack : err}`)
1187                                                 }
1188                                         })
1189                                 }
1190                                 await convert()
1191                                 if (!downloadQueue[downloading.queueId]) {
1192                                         logger.info("Stopping the playlist queue")
1193                                         break
1194                                 }
1195                                 downloading.trackList = await s.Deezer.getTracks(downloading.playlistContent)
1196                                 logger.info("All tracks converted, starting download")
1197                                 io.sockets.emit("downloadStarted", {queueId: downloading.queueId})
1198                                 downloading.settings.playlist = {
1199                                         fullSize: downloading.trackList.length
1200                                 }
1201                                 filePath = `${mainFolder}${antiDot(fixName(downloading.settings.plName))}${path.sep}`
1202                                 downloading.downloadPromise = new Promise((resolve,reject)=>{
1203                                         downloading.trackList.every(function (t, index) {
1204                                                 trackQueue.push(async cb=>{
1205                                                         if (!downloadQueue[downloading.queueId]) {
1206                                                                 reject()
1207                                                                 return false
1208                                                         }
1209                                                         t.position = index
1210                                                         if (t.id==0 && downloading.obj.tracks[t.position] != null){
1211                                                                 t.title = downloading.obj.tracks[t.position].name
1212                                               t.album = {id: 0, title: downloading.obj.tracks[t.position].album.name}
1213                                               t.artist = {id: 0, name: downloading.obj.tracks[t.position].artists[0].name}
1214                                                         }
1215                                                         try{
1216                                                                 await downloadTrackObject(t, downloading.queueId, downloading.settings)
1217                                                                 downloading.downloaded++
1218                                                                 downloading.playlistArr[t.playlistData[0]] = t.playlistData[1].split(filePath)[1]
1219                                                                 if (t.searched) downloading.searchedLog += `${t.artist.name} - ${t.title}\r\n`
1220                                                         }catch(err){
1221                                                                 downloading.failed++
1222                                                                 downloading.errorLog += `${t.id} | ${t.artist.name} - ${t.title} | ${err}\r\n`
1223                                                                 logger.error(`[${t.artist.name} - ${t.title}] ${err}`)
1224                                                         }
1225                                                         io.sockets.emit("downloadProgress", {
1226                                                                 queueId: downloading.queueId,
1227                                                                 percentage: ((downloading.downloaded+downloading.failed) / downloading.size) * 100
1228                                                         });
1229                                                         io.sockets.emit("updateQueue", {
1230                                                                 name: downloading.name,
1231                                                                 artist: downloading.artist,
1232                                                                 size: downloading.size,
1233                                                                 downloaded: downloading.downloaded,
1234                                                                 failed: downloading.failed,
1235                                                                 queueId: downloading.queueId,
1236                                                                 id: downloading.id,
1237                                                                 type: downloading.type,
1238                                                                 errorLog: downloading.errorLog,
1239                                                         })
1240                                                         if (downloading.downloaded + downloading.failed >= downloading.size) resolve()
1241                                                         cb()
1242                                                 })
1243                                                 return true
1244                                         })
1245                                 })
1246                                 try{
1247                                         await downloading.downloadPromise
1248                                         logger.info("Playlist finished "+downloading.name);
1249                                         io.sockets.emit("downloadProgress", {
1250                                                 queueId: downloading.queueId,
1251                                                 percentage: 100
1252                                         });
1253                                         if (downloading.settings.logErrors){
1254                                                 if (downloading.errorLog != ""){
1255                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1256                                                         fs.writeFileSync(filePath+"notFound.txt",downloading.errorLog)
1257                                                 }else{
1258                                                         if (fs.existsSync(filePath+"notFound.txt")) fs.unlinkSync(filePath+"notFound.txt");
1259                                                 }
1260                                         }
1261                                         if (downloading.settings.logSearched){
1262                                                 if (downloading.searchedLog != ""){
1263                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1264                                                         fs.writeFileSync(filePath+"alternativeSongs.txt",downloading.searchedLog)
1265                                                 }else{
1266                                                         if (fs.existsSync(filePath+"alternativeSongs.txt")) fs.unlinkSync(filePath+"alternativeSongs.txt");
1267                                                 }
1268                                         }
1269                                         if (downloading.settings.createM3UFile){
1270                                                 fs.writeFileSync(filePath + "playlist.m3u", downloading.playlistArr.join("\r\n"));
1271                                         }
1272                                         if (downloading.settings.saveArtwork){
1273                                                 if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1274                                                 let imgPath = filePath + antiDot(settingsRegexCover(downloading.settings.coverImageTemplate,downloading.artist,downloading.name))+(downloading.settings.PNGcovers ? ".png" : ".jpg");
1275                                                 if (downloading.obj.images){
1276                                                         downloading.cover = downloading.obj.images[0].url.replace("56x56",`${downloading.settings.artworkSize}x${downloading.settings.artworkSize}`)
1277                                                         request.get(downloading.cover, {strictSSL: false,encoding: 'binary'}, function(error,response,body){
1278                                                                 if(error){
1279                                                                         logger.error(error.stack);
1280                                                                         return;
1281                                                                 }
1282                                                                 fs.outputFile(imgPath,body,'binary',function(err){
1283                                                                         if(err){
1284                                                                                 logger.error(err.stack);
1285                                                                                 return;
1286                                                                         }
1287                                                                         logger.info(`Cover downloaded for: ${downloading.settings.plName}`)
1288                                                                 })
1289                                                         });
1290                                                 }
1291                                         }
1292                                 }catch(err){
1293                                         if (err) logger.error(`queueDownload:spotifyplaylist failed: ${err.stack ? err.stack : err}`)
1294                                         logger.info("Stopping the playlist queue")
1295                                 }
1296                         break
1297                 }
1298                 if (downloading && downloadQueue[Object.keys(downloadQueue)[0]] && (Object.keys(downloadQueue)[0] == downloading.queueId)) delete downloadQueue[Object.keys(downloadQueue)[0]]
1299                 if (Object.keys(downloadQueue).length == 0) {
1300                         io.sockets.emit("emptyDownloadQueue", {})
1301                 }
1302         }
1303
1304         // This function takes the track object and does all the stuff to download it
1305         async function downloadTrackObject(track, queueId, settings) {
1306                 if (!downloadQueue[queueId]) {
1307                         logger.error(`[${track.artist.name} - ${track.title}] Failed to download: Not in queue`)
1308                         throw new Error("Not in queue")
1309                         return false
1310                 }
1311                 if (parseInt(track.id) == 0){
1312                         logger.error(`[${track.artist.name} - ${track.title}] Failed to download: Song not Found`)
1313                         throw new Error("Song not Found")
1314                         return false
1315                 }
1316
1317                 /* Album information is necessary for the following tags:
1318                  * album_artist
1319                  * album_artist_picture
1320                  * trackTotal
1321                  * recordType
1322                  * barcode
1323                  * explicit
1324                  * label
1325                  * genres
1326                  * date
1327                 */
1328                 if (parseInt(track.id)>0){
1329                         var ajson
1330                         if (!track.ajson){
1331                                 try{
1332                                         logger.info(`[${track.artist.name} - ${track.title}] Getting album info`)
1333                                         ajson = await s.Deezer.legacyGetAlbum(track.album.id)
1334                                 }catch(err){
1335                                         logger.warn(`[${track.artist.name} - ${track.title}] Album not found, trying to reach deeper`)
1336                                         try{
1337                                                 ajson = await s.Deezer.getAlbum(track.album.id)
1338                                                 ajson.fromNewAPI = true
1339                                         } catch(err){
1340                                                 if(track.fallbackId){
1341                                                         logger.warn(`[${track.artist.name} - ${track.title}] Failed to download track, falling on alternative`)
1342                                                         track = await s.Deezer.getTrack(track.fallbackId)
1343                                                         return downloadTrackObject(track, queueId, settings)
1344                                                 }else if(!track.searched){
1345                                                         logger.warn(`[${track.artist.name} - ${track.title}] Failed to download track, searching for alternative`)
1346                                                         var _trackID = await convertMetadata2Deezer(track.artist.name, track.title, track.album.title)
1347                                                         if (_trackID != "0"){
1348                                                                 track = await s.Deezer.getTrack()
1349                                                                 track.searched = true
1350                                                                 return downloadTrackObject(track, queueId, settings)
1351                                                         }else{
1352                                                                 logger.error(`[${track.artist.name} - ${track.title}] Failed to download: Alternative not found`)
1353                                                                 return
1354                                                         }
1355                                                 }else{
1356                                                         logger.error(`[${track.artist.name} - ${track.title}] Failed to download: ${err}`)
1357                                                         return
1358                                                 }
1359                                         }
1360                                 }
1361                         }else{
1362                                 ajson = track.ajson
1363                         }
1364                         if (!ajson.fromNewAPI){
1365                                 // Aquiring discTotal (only if necessary)
1366                                 if (settings.tags.discTotal || settings.createCDFolder){
1367                                         if (!ajson.discTotal){
1368                                                 logger.info(`[${track.artist.name} - ${track.title}] Getting total disc number`);
1369                                                 var discTotal = await s.Deezer.getAlbum(ajson.id)
1370                                                 track.discTotal = discTotal.discTotal
1371                                         }else{
1372                                                 track.discTotal = ajson.discTotal
1373                                         }
1374                                 }
1375                                 track.album.artist = {
1376                                         id: ajson.artist.id,
1377                                         name: ajson.artist.name,
1378                                         picture: ajson.artist.picture_small.substring(46,ajson.artist.picture_small.length-24),
1379                                 }
1380                                 track.trackTotal = ajson.nb_tracks
1381                                 track.album.barcode = ajson.upc
1382                                 if (ajson.record_type){
1383                                         track.recordType = ajson.record_type
1384                                 }else{
1385                                         track.recordType = switchReleaseType(track.recordType)
1386                                 }
1387                                 if (ajson.explicit_lyrics)
1388                                         track.album.explicit = ajson.explicit_lyrics;
1389                                 if(ajson.label)
1390                                         track.publisher = ajson.label;
1391                                 if (ajson.release_date) {
1392                                         track.date = {
1393                                                 day: ajson.release_date.slice(8,10),
1394                                                 month: ajson.release_date.slice(5,7),
1395                                                 year: ajson.release_date.slice(0, 4),
1396                                                 slicedYear: (settings.dateFormatYear == "2" ? ajson.release_date.slice(2, 4) : ajson.release_date.slice(0, 4))
1397                                         }
1398                                 }else if(!track.date){
1399                                         track.date = {
1400                                                 day: 0,
1401                                                 month: 0,
1402                                                 year: 0,
1403                                                 slicedYear: 0
1404                                         }
1405                                 }
1406                                 if(ajson.genres && ajson.genres.data[0] && ajson.genres.data[0].name){
1407                                         track.genre = []
1408                                         ajson.genres.data.forEach(function(genre){
1409                                                 if (track.genre.indexOf(genre.name) == -1)
1410                                                         track.genre.push(genre.name)
1411                                         })
1412                                 }
1413                         }else{
1414                                 // Missing barcode, genre
1415                                 track.album = ajson
1416                                 track.date = track.album.date
1417                                 track.trackTotal = track.album.trackTotal
1418                                 track.recordType = switchReleaseType(track.recordType)
1419                                 // TODO: Make a loop for each artist
1420                         }
1421
1422                         if (!track.date.slicedYear){
1423                                 track.date.slicedYear = settings.dateFormatYear == "2" ? track.date.year.slice(2, 4) : track.date.year.slice(0, 4)
1424                         }
1425
1426                         // Acquiring bpm (only if necessary)
1427                         if (settings.tags.bpm){
1428                                 logger.info(`[${track.artist.name} - ${track.title}] Getting BPM`);
1429                                 track.legacyTrack = await s.Deezer.legacyGetTrack(track.id)
1430                                 try{
1431                                         track.bpm = track.legacyTrack.bpm
1432                                 }catch(err){
1433                                         track.bpm = 0
1434                                 }
1435                         }else{
1436                                 track.bpm = 0
1437                         }
1438
1439                         // Acquiring ReplayGain value (only if necessary)
1440                         if (settings.tags.replayGain){
1441                                 logger.info(`[${track.artist.name} - ${track.title}] Getting track gain`);
1442                                 if (!track.legacyTrack) track.legacyTrack = await s.Deezer.legacyGetTrack(track.id)
1443                                 try{
1444                                         track.replayGain = track.legacyTrack.gain
1445                                 }catch(err){
1446                                         track.replayGain = 0
1447                                 }
1448                         }else{
1449                                 track.replayGain = 0
1450                         }
1451
1452                         // Acquiring discNumber value (only if necessary)
1453                         if (settings.tags.discNumber && !track.discNumber){
1454                                 logger.info(`[${track.artist.name} - ${track.title}] Getting disc number`);
1455                                 if (!track.legacyTrack) track.legacyTrack = await s.Deezer.legacyGetTrack(track.id)
1456                                 track.discNumber = track.legacyTrack.disk_number
1457                         }
1458
1459                         let separator = settings.multitagSeparator
1460                         if (separator == "null") separator = String.fromCharCode(0)
1461
1462                         // Autoremoves (Album Version) from the title
1463                         if (settings.removeAlbumVersion){
1464                                 if(track.title.indexOf("Album Version")>-1){
1465                                         track.title = track.title.replace(/ ?\(Album Version\)/g,"")
1466                                 }
1467                         }
1468                         if (!track.album.artist.picture && !settings.plName){
1469                                 if (track.artist.name == track.album.artist.name && !track.album.artist.picture){
1470                                         track.album.artist.picture = track.artist.picture
1471                                 }else{
1472                                         let found = false
1473                                         if (track.artists){
1474                                                 track.artists.forEach(x=>{
1475                                                         if(!found && x.name == track.album.artist.name){
1476                                                                 track.album.artist.picture = x.picture
1477                                                                 found = true
1478                                                         }
1479                                                 })
1480                                         }
1481                                         if(settings.saveArtworkArtist && !found){
1482                                                 artist = await s.Deezer.legacyGetArtist(track.album.artist.id)
1483                                                 track.album.artist.picture = artist.picture_small.substring(46,ajson.artist.picture_small.length-24)
1484                                         }
1485                                 }
1486                         }
1487                         if (!track.album.artist.picture) track.album.artist.picture = ""
1488                         track.album.artist.pictureUrl = `${s.Deezer.artistPictureHost}${track.album.artist.picture}/${settings.artworkSize}x${settings.artworkSize}-000000-80-0-0${(settings.PNGcovers ? ".png" : ".jpg")}`
1489                         track.album.pictureUrl = `${s.Deezer.albumPicturesHost}${track.album.picture}/${settings.artworkSize}x${settings.artworkSize}-000000-80-0-0${(settings.PNGcovers ? ".png" : ".jpg")}`
1490
1491                         // Auto detect aviable track format from settings
1492                         switch(downloadQueue[queueId].bitrate.toString()){
1493                                 case "9":
1494                                         track.selectedFormat = 9
1495                                         track.selectedFilesize = track.filesize.flac
1496                                         if (track.filesize.flac>0) break
1497                                         if (!settings.fallbackBitrate) throw new Error("Song not found at desired bitrate.")
1498                                 case "3":
1499                                         track.selectedFormat = 3
1500                                         track.selectedFilesize = track.filesize.mp3_320
1501                                         if (track.filesize.mp3_320>0) break
1502                                         if (!settings.fallbackBitrate) throw new Error("Song not found at desired bitrate.")
1503                                 case "1":
1504                                         track.selectedFormat = 1
1505                                         track.selectedFilesize = track.filesize.mp3_128
1506                                         if (track.filesize.mp3_128>0) break
1507                                         if (!settings.fallbackBitrate) throw new Error("Song not found at desired bitrate.")
1508                                 default:
1509                                         track.selectedFormat = 8
1510                                         track.selectedFilesize = track.filesize.default
1511                         }
1512
1513                         if(track.contributor){
1514                                 if(track.contributor.composer){
1515                                         track.composerString = uniqueArray(track.contributor.composer)
1516                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0))) track.composerString = track.composerString.join(separator)
1517                                 }
1518                                 if(track.contributor.musicpublisher){
1519                                         track.musicpublisherString = uniqueArray(track.contributor.musicpublisher)
1520                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0))) track.musicpublisherString = track.musicpublisherString.join(separator)
1521                                 }
1522                                 if(track.contributor.producer){
1523                                         track.producerString = uniqueArray(track.contributor.producer)
1524                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0))) track.producerString = track.producerString.join(separator)
1525                                 }
1526                                 if(track.contributor.engineer){
1527                                         track.engineerString = uniqueArray(track.contributor.engineer)
1528                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0))) track.engineerString = track.engineerString.join(separator)
1529                                 }
1530                                 if(track.contributor.writer){
1531                                         track.writerString = uniqueArray(track.contributor.writer)
1532                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0))) track.writerString = track.writerString.join(separator)
1533                                 }
1534                                 if(track.contributor.author){
1535                                         track.authorString = uniqueArray(track.contributor.author)
1536                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0))) track.authorString = track.authorString.join(separator)
1537                                 }
1538                                 if(track.contributor.mixer){
1539                                         track.mixerString = uniqueArray(track.contributor.mixer)
1540                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0))) track.mixerString = track.mixerString.join(separator)
1541                                 }
1542                         }
1543
1544                         if(track.artists || track.artistsString){
1545                                 if (!track.artistsString){
1546                                         track.artistsString = []
1547                                         artistArray = []
1548                                         track.artists.forEach(function(artist){
1549                                                 artistArray.push(artist.name)
1550                                         })
1551                                 }else{
1552                                         if (! Array.isArray(track.artistsString)){
1553                                                 track.artistsString = [track.artistsString,]
1554                                         }
1555                                         artistArray = track.artistsString
1556                                 }
1557                                 track.artistsString = uniqueArray(artistArray)
1558                                 let posMainArtist = track.artistsString.indexOf(track.album.artist.name)
1559                                 if (posMainArtist !== -1 && posMainArtist !== 0){
1560                                         let element = track.artistsString[posMainArtist]
1561                                 track.artistsString.splice(posMainArtist, 1)
1562                                 track.artistsString.splice(0, 0, element)
1563                                 }
1564                                 if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0))) track.artistsString = track.artistsString.join(separator)
1565                         }
1566                         if (track.genre){
1567                                 if (!(track.selectedFormat == 9 && separator==String.fromCharCode(0)))
1568                                         track.genreString = track.genre.join(separator)
1569                                 else
1570                                         track.genreString = track.genre
1571                         }
1572
1573                         if (track.date){
1574                                 let date
1575                                 switch (settings.dateFormat){
1576                                         case "0": date = `${track.date.slicedYear}-${track.date.month}-${track.date.day}`; break;
1577                                         case "1": date = `${track.date.day}-${track.date.month}-${track.date.slicedYear}`; break;
1578                                         case "2": date = `${track.date.month}-${track.date.day}-${track.date.slicedYear}`; break;
1579                                         case "3": date = `${track.date.slicedYear}-${track.date.day}-${track.date.month}`; break;
1580                                         case "4": date = `${track.date.day}${track.date.month}`; break;
1581                                         default: date = `${track.date.day}${track.date.month}`; break;
1582                                 }
1583                                 track.dateString = date;
1584                         }
1585                 }else{
1586                         track.date = {year: 0,day: 0,month: 0}
1587                         track.selectedFilesize = track.filesize
1588                         track.selectedFormat = 3
1589                 }
1590
1591                 // TODO: Move to a separate function
1592                 // Generating file name
1593                 if (settings.saveFullArtists && settings.multitagSeparator != null){
1594                         let filename = antiDot(fixName(`${track.artistsString} - ${track.title}`));
1595                 }else{
1596                         let filename = antiDot(fixName(`${track.artist.name} - ${track.title}`));
1597                 }
1598                 if (settings.filename) {
1599                         filename = antiDot(fixName(settingsRegex(track, settings.filename, settings.playlist, settings.saveFullArtists && settings.multitagSeparator != null, settings.paddingSize, settings.plName && !settings.numplaylistbyalbum)))
1600                 }
1601
1602                 filename = antiDot(fixName(filename))
1603
1604                 // TODO: Move to a separate function
1605                 // Generating file path
1606                 let filepath = mainFolder;
1607                 let artistPath;
1608                 if ((settings.createArtistFolder || settings.createAlbumFolder) && !settings.plName) {
1609
1610                         if(settings.plName){
1611                                 filepath += antiDot(fixName(settings.plName)) + path.sep;
1612                         }
1613
1614                         if (settings.createArtistFolder) {
1615                                 if(settings.artName){
1616                                         filepath += antiDot(fixName(settings.artName)) + path.sep;
1617                                 }else{
1618                                         filepath += antiDot(fixName(track.album.artist.name)) + path.sep;
1619                                 }
1620                                 artistPath = filepath;
1621                         }
1622
1623                         if (settings.createAlbumFolder) {
1624                                 if(settings.artName){
1625                                         filepath += antiDot(fixName(settingsRegexAlbum(settings.foldername,settings.artName,settings.albName,track.date.year,track.recordType,track.album.explicit,track.publisher,track.genre))) + path.sep;
1626                                 }else{
1627                                         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;
1628                                 }
1629                         }
1630                 } else if (settings.plName) {
1631                         filepath += antiDot(fixName(settings.plName)) + path.sep;
1632                 } else if (settings.artName) {
1633                         filepath += antiDot(fixName(settingsRegexAlbum(settings.foldername,settings.artName,settings.albName,track.date.year,track.recordType,track.album.explicit,track.publisher,track.genre))) + path.sep;
1634                 }
1635                 let coverpath = filepath;
1636                 if (track.discTotal > 1 && (settings.artName || settings.createAlbumFolder) && settings.createCDFolder){
1637                         filepath += `CD${track.discNumber +  path.sep}`
1638                 }
1639                 let writePath;
1640
1641                 if(track.selectedFormat == 9){
1642                         writePath = filepath + filename + '.flac';
1643                 }else{
1644                         writePath = filepath + filename + '.mp3';
1645                 }
1646
1647                 if ((settings.syncedlyrics || settings.tags.unsynchronisedLyrics) && track.lyricsId>0){
1648                         let lyr = await s.Deezer.getLyrics(track.id)
1649                         track.syncLyrics = lyr.syncLyrics
1650                         track.unsyncLyrics = lyr.unsyncLyrics
1651                 }
1652
1653                 if(track.syncLyrics && settings.syncedlyrics){
1654                         fs.outputFile(writePath.substring(0,writePath.lastIndexOf('.'))+".lrc",track.syncLyrics,function(){});
1655                 }
1656
1657                 track.playlistData = [0,""]
1658                 if (settings.createM3UFile && (settings.plName || settings.albName)) {
1659                         if (track.position){
1660                                 track.playlistData = [parseInt(track.position), writePath];
1661                         }else{
1662                                 track.playlistData = [track.trackNumber-1, writePath];
1663                         }
1664                 }
1665                 if (fs.existsSync(writePath)) {
1666                         logger.info(`[${track.artist.name} - ${track.title}] Already downloaded`);
1667                         return;
1668                 }else{
1669                         logger.info(`[${track.artist.name} - ${track.title}] Downloading file to ${writePath}`);
1670                 }
1671                 // Get cover image
1672                 if (track.album.pictureUrl) {
1673                         let imgPath;
1674                         //If its not from an album but a playlist.
1675                         if(settings.albName || settings.createAlbumFolder){
1676                                 if (settings.saveArtwork && ! settings.plName)
1677                                         imgPath = coverpath + settingsRegexCover(settings.coverImageTemplate,track.album.artist.name,track.album.title)+(settings.PNGcovers ? ".png" : ".jpg")
1678                                 else
1679                                         imgPath = coverArtFolder + fixName(track.album.barcode ? fixName(track.album.barcode) : fixName(`${track.album.artist.name} - ${track.album.title}`))+(settings.PNGcovers ? ".png" : ".jpg")
1680                         }else{
1681                                 imgPath = coverArtFolder + (track.album.barcode ? fixName(track.album.barcode) : fixName(`${track.album.artist.name} - ${track.album.title}`))+(settings.PNGcovers ? ".png" : ".jpg")
1682                         }
1683                         if(fs.existsSync(imgPath)){
1684                                 track.album.picturePath = (imgPath).replace(/\\/g, "/")
1685                                 logger.info(`[${track.artist.name} - ${track.title}] Starting the download process CODE:1`)
1686                         }else{
1687                                 try{
1688                                         var body = await request.get(track.album.pictureUrl, {strictSSL: false,encoding: 'binary'})
1689                                         fs.outputFileSync(imgPath,body,'binary')
1690                                         track.album.picturePath = (imgPath).replace(/\\/g, "/")
1691                                         logger.info(`[${track.artist.name} - ${track.title}] Starting the download process CODE:2`)
1692                                 }catch(error){
1693                                         logger.error(`[${track.artist.name} - ${track.title}] Cannot download Album Image: ${error}`)
1694                                         logger.error(`Album art link: ${track.album.pictureUrl}`)
1695                                         track.album.pictureUrl = undefined
1696                                         track.album.picturePath = undefined
1697                                 }
1698                         }
1699                 }else{
1700                         track.album.pictureUrl = undefined
1701                         logger.info(`[${track.artist.name} - ${track.title}] Starting the download process CODE:3`)
1702                 }
1703
1704                 // Get Artist Image
1705                 if (parseInt(track.id)>0 && track.album.artist.pictureUrl && settings.saveArtworkArtist) {
1706                         let imgPath;
1707                         if(settings.createArtistFolder && artistPath){
1708                                 imgPath = artistPath + antiDot(settingsRegexArtistCover(settings.artistImageTemplate,track.album.artist.name))+(settings.PNGcovers ? ".png" : ".jpg");
1709                                 if(!fs.existsSync(imgPath)){
1710                                         try{
1711                                                 var body = await request.get(track.album.artist.pictureUrl, {strictSSL: false,encoding: 'binary'})
1712                                                 if (body.indexOf("unauthorized")>-1) throw new Error("Unauthorized")
1713                                                 fs.outputFileSync(imgPath,body,'binary')
1714                                                 logger.info(`[${track.artist.name} - ${track.title}] Saved Artist Image`)
1715                                         }catch(err){
1716                                                 logger.error(`[${track.artist.name} - ${track.title}] Cannot download Artist Image: ${err}`)
1717                                         }
1718                                 }
1719                         }
1720                 }
1721
1722                 let tempPath
1723                 if(parseInt(track.id)>0)
1724                         tempPath = `${filepath}${track.id}_${track.selectedFormat}.temp`
1725                 else
1726                         tempPath = writePath
1727
1728                 logger.info(`[${track.artist.name} - ${track.title}] Downloading track`)
1729                 var downloadingPromise = new Promise((resolve, reject)=>{
1730                         let req = requestOld.get({url: track.getDownloadUrl(track.selectedFormat), strictSSL: false, headers: s.Deezer.httpHeaders, encoding: 'binary'}, function (error, response, body) {
1731                                 if (error){
1732                                         logger.error(`[${track.artist.name} - ${track.title}] Downloading error: ${error}`)
1733                                         reject("Downloading error: "+error)
1734                                         return false
1735                                 }
1736                                 if (!downloadQueue[queueId]){
1737                                         fs.remove(tempPath)
1738                                         reject("Not in Queue")
1739                                         return false
1740                                 }
1741                                 if (body.length == 0){
1742                                         fs.remove(tempPath)
1743                                         reject("Track is Empty")
1744                                         return false
1745                                 }
1746                                 logger.info(`[${track.artist.name} - ${track.title}] Decrypting track`)
1747                                 var decryptedSource = s.Deezer.decryptDownload(Buffer.from(body, 'binary'), track.id)
1748                                 try{
1749                                         fs.outputFileSync(tempPath,decryptedSource)
1750                                         resolve()
1751                                 }catch(err){
1752                                         logger.error(`[${track.artist.name} - ${track.title}] Decryption error: ${err}`)
1753                                         reject(err)
1754                                         return false
1755                                 }
1756                         }).on("data", function(data) {
1757                                 if (!downloadQueue[queueId]){
1758                                         reject("Not in Queue")
1759                                         return false
1760                                 }
1761                         })
1762                         if((downloadQueue[queueId]) && downloadQueue[queueId].type == "track"){
1763                                 let chunkLength = 0
1764                                 req.on("data", function(data) {
1765                                         if (!downloadQueue[queueId]){
1766                                                 reject("Not in Queue")
1767                                         }
1768                                         chunkLength += data.length
1769                                         try{
1770                                                 if (!downloadQueue[queueId].percentage) {
1771                                                         downloadQueue[queueId].percentage = 0
1772                                                 }
1773                                                 let complete = track.selectedFilesize
1774                                                 let percentage = (chunkLength / complete) * 100;
1775                                                 if ((percentage - downloadQueue[queueId].percentage > 1) || (chunkLength == complete)) {
1776                                                         downloadQueue[queueId].percentage = percentage
1777                                                         io.sockets.emit("downloadProgress", {
1778                                                                 queueId: queueId,
1779                                                                 percentage: downloadQueue[queueId].percentage-5
1780                                                         })
1781                                                 }
1782                                         }catch(err){}
1783                                 })
1784                         }
1785                 })
1786
1787                 try{
1788                         await downloadingPromise
1789                 }catch(err){
1790                         if (err==="Track is Empty"){
1791                                 if(track.fallbackId && track.fallbackId != "0"){
1792                                         logger.warn(`[${track.artist.name} - ${track.title}] Track is empty, falling on alternative`)
1793                                         var _track = await s.Deezer.getTrack(track.fallbackId)
1794                                         track.id = _track.id
1795                                         track.fallbackId = _track.fallbackId
1796                                         track.filesize = _track.filesize
1797                                         track.duration = _track.duration
1798                                         track.MD5 = _track.MD5
1799                                         track.mediaVersion = _track.mediaVersion
1800                                         return downloadTrackObject(track, queueId, settings)
1801                                 }else if(!track.searched){
1802                                         logger.warn(`[${track.artist.name} - ${track.title}] Track is empty, searching for alternative`)
1803                                         _trackId = await convertMetadata2Deezer(track.artist.name, track.title, track.album.title)
1804                                         if (_trackId != "0"){
1805                                                 _track = await s.Deezer.getTrack(_trackId)
1806                                                 track.id = _track.id
1807                                                 track.fallbackId = _track.fallbackId
1808                                                 track.filesize = _track.filesize
1809                                                 track.duration = _track.duration
1810                                                 track.MD5 = _track.MD5
1811                                                 track.mediaVersion = _track.mediaVersion
1812                                                 track.searched = true
1813                                                 return downloadTrackObject(track, queueId, settings)
1814                                         }else{
1815                                                 logger.error(`[${track.artist.name} - ${track.title}] No alternative found`)
1816                                                 throw new Error("No Alternative Found")
1817                                                 return
1818                                         }
1819                                 }else{
1820                                         logger.error(`[${track.artist.name} - ${track.title}] Downloading error: Track is Empty`)
1821                                         throw new Error("Track is Empty")
1822                                         return
1823                                 }
1824                         }else{
1825                                 throw new Error(err)
1826                                 return
1827                         }
1828                 }
1829
1830                 logger.info(`[${track.artist.name} - ${track.title}] Adding Tags`)
1831                 if (parseInt(track.id)>0){
1832                         if(track.selectedFormat == 9){
1833                                 let flacComments = [];
1834                                 if (settings.tags.title)
1835                                         flacComments.push('TITLE=' + track.title);
1836                                 if (settings.tags.album)
1837                                         flacComments.push('ALBUM=' + track.album.title);
1838                                 if (settings.tags.albumArtist)
1839                                         flacComments.push('ALBUMARTIST=' + track.album.artist.name);
1840                                 if (settings.tags.trackNumber)
1841                                         flacComments.push('TRACKNUMBER=' + track.trackNumber);
1842                                 if (settings.tags.discNumber)
1843                                         flacComments.push('DISCNUMBER=' + track.discNumber);
1844                                 if (settings.tags.trackTotal)
1845                                         flacComments.push('TRACKTOTAL=' + track.trackTotal);
1846                                 if (settings.tags.explicit)
1847                                         flacComments.push('ITUNESADVISORY=' + track.explicit);
1848                                 if (settings.tags.isrc)
1849                                         flacComments.push('ISRC=' + track.ISRC);
1850                                 if (settings.tags.artist && track.artistsString)
1851                                         if (Array.isArray(track.artistsString)){
1852                                                 track.artistsString.forEach(x=>{
1853                                                         flacComments.push('ARTIST=' + x);
1854                                                 });
1855                                         }else{
1856                                                 flacComments.push('ARTIST=' + track.artistsString);
1857                                         }
1858                                 if (settings.tags.discTotal)
1859                                         flacComments.push('DISCTOTAL='+track.discTotal);
1860                                 if (settings.tags.length)
1861                                         flacComments.push('LENGTH=' + track.duration);
1862                                 if (settings.tags.barcode && track.album.barcode)
1863                                         flacComments.push('BARCODE=' + track.album.barcode);
1864                                 if (track.unsyncLyrics && settings.tags.unsynchronisedLyrics)
1865                                         flacComments.push('LYRICS='+track.unsyncLyrics.lyrics);
1866                                 if (track.genreString && settings.tags.genre)
1867                                         if (Array.isArray(track.genreString)){
1868                                                 track.genreString.forEach(x=>{
1869                                                         flacComments.push('GENRE=' + x);
1870                                                 });
1871                                         }else{
1872                                                 flacComments.push('GENRE=' + track.genreString);
1873                                         }
1874                                 if (track.copyright && settings.tags.copyright)
1875                                         flacComments.push('COPYRIGHT=' + track.copyright);
1876                                 if (0 < parseInt(track.date.year)){
1877                                         if (settings.tags.date)
1878                                                 flacComments.push('DATE=' + track.dateString);
1879                                         if (settings.tags.year)
1880                                                 flacComments.push('YEAR=' + track.date.year);
1881                                 }
1882                                 if (0 < parseInt(track.bpm) && settings.tags.bpm)
1883                                         flacComments.push('BPM=' + track.bpm);
1884                                 if(track.publisher && settings.tags.publisher)
1885                                         flacComments.push('PUBLISHER=' + track.publisher);
1886                                 if(track.composerString && settings.tags.composer)
1887                                         if (Array.isArray(track.composerString)){
1888                                                 track.composerString.forEach(x=>{
1889                                                         flacComments.push('COMPOSER=' + x);
1890                                                 });
1891                                         }else{
1892                                                 flacComments.push('COMPOSER=' + track.composerString);
1893                                         }
1894                                 if(track.musicpublisherString && settings.tags.musicpublisher)
1895                                         if (Array.isArray(track.musicpublisherString)){
1896                                                 track.musicpublisherString.forEach(x=>{
1897                                                         flacComments.push('ORGANIZATION=' + x);
1898                                                 });
1899                                         }else{
1900                                                 flacComments.push('ORGANIZATION=' + track.musicpublisherString);
1901                                         }
1902                                 if(track.mixerString && settings.tags.mixer)
1903                                         if (Array.isArray(track.mixerString)){
1904                                                 track.mixerString.forEach(x=>{
1905                                                         flacComments.push('MIXER=' + x);
1906                                                 });
1907                                         }else{
1908                                                 flacComments.push('MIXER=' + track.mixerString);
1909                                         }
1910                                 if(track.authorString && settings.tags.author)
1911                                         if (Array.isArray(track.authorString)){
1912                                                 track.authorString.forEach(x=>{
1913                                                         flacComments.push('AUTHOR=' + x);
1914                                                 });
1915                                         }else{
1916                                                 flacComments.push('AUTHOR=' + track.authorString);
1917                                         }
1918                                 if(track.writerString && settings.tags.writer)
1919                                         if (Array.isArray(track.writerString)){
1920                                                 track.writerString.forEach(x=>{
1921                                                         flacComments.push('WRITER=' + x);
1922                                                 });
1923                                         }else{
1924                                                 flacComments.push('WRITER=' + track.writerString);
1925                                         }
1926                                 if(track.engineerString && settings.tags.engineer)
1927                                         if (Array.isArray(track.engineerString)){
1928                                                 track.engineerString.forEach(x=>{
1929                                                         flacComments.push('ENGINEER=' + x);
1930                                                 });
1931                                         }else{
1932                                                 flacComments.push('ENGINEER=' + track.engineerString);
1933                                         }
1934                                 if(track.producerString && settings.tags.producer)
1935                                         if (Array.isArray(track.producerString)){
1936                                                 track.producerString.forEach(x=>{
1937                                                         flacComments.push('PRODUCER=' + x);
1938                                                 });
1939                                         }else{
1940                                                 flacComments.push('PRODUCER=' + track.producerString);
1941                                         }
1942                                 if(track.replayGain && settings.tags.replayGain)
1943                                         flacComments.push('REPLAYGAIN_TRACK_GAIN=' + track.replayGain);
1944
1945                                 const reader = fs.createReadStream(tempPath);
1946                                 const writer = fs.createWriteStream(writePath);
1947                                 let processor = new mflac.Processor({parseMetaDataBlocks: true});
1948                                 let vendor = 'reference libFLAC 1.2.1 20070917';
1949                                 let cover = null;
1950                                 if(track.album.picturePath && settings.tags.cover){
1951                                         cover = fs.readFileSync(track.album.picturePath)
1952                                 }
1953                                 let mdbVorbisPicture
1954                                 let mdbVorbisComment
1955                                 processor.on('preprocess', (mdb) => {
1956                                         // Remove existing VORBIS_COMMENT and PICTURE blocks, if any.
1957                                         if (mflac.Processor.MDB_TYPE_VORBIS_COMMENT === mdb.type) {
1958                                                 mdb.remove();
1959                                         } else if (mflac.Processor.MDB_TYPE_PICTURE === mdb.type) {
1960                                                 mdb.remove();
1961                                         }
1962                                         if (mdb.isLast) {
1963                                                 if(cover){
1964                                                         mdbVorbisPicture = mflac.data.MetaDataBlockPicture.create(true, 3, `image/${(settings.PNGcovers ? "png" : "jpeg")}`, '', settings.artworkSize, settings.artworkSize, 24, 0, cover);
1965                                                 }
1966                                                 mdbVorbisComment = mflac.data.MetaDataBlockVorbisComment.create(!cover, vendor, flacComments);
1967                                                 mdb.isLast = false;
1968                                         }
1969                                 });
1970                                 processor.on('postprocess', (mdb) => {
1971                                         if (mflac.Processor.MDB_TYPE_VORBIS_COMMENT === mdb.type && null !== mdb.vendor) {
1972                                                 vendor = mdb.vendor;
1973                                         }
1974                                         if (mdbVorbisPicture && mdbVorbisComment) {
1975                                                         processor.push(mdbVorbisComment.publish());
1976                                                         processor.push(mdbVorbisPicture.publish());
1977                                                 }else if(mdbVorbisComment){
1978                                                         processor.push(mdbVorbisComment.publish());
1979                                         }
1980                                 });
1981                                 reader.on('end', () => {
1982                                         fs.remove(tempPath);
1983                                 });
1984                                 await reader.pipe(processor).pipe(writer);
1985                         }else{
1986                                 const songBuffer = fs.readFileSync(tempPath);
1987                                 const writer = new ID3Writer(songBuffer);
1988                                 if (settings.tags.title)
1989                                         writer.setFrame('TIT2', track.title)
1990                                 if (settings.tags.artist)
1991                                         writer.setFrame('TPE1', [track.artistsString])
1992                                 if (settings.tags.album)
1993                                         writer.setFrame('TALB', track.album.title)
1994                                 if (settings.tags.albumArtist && track.album.artist)
1995                                         writer.setFrame('TPE2', track.album.artist.name)
1996                                 if (settings.tags.trackNumber)
1997                                         writer.setFrame('TRCK', (settings.tags.trackTotal ? track.trackNumber+"/"+track.trackTotal : track.trackNumber))
1998                                 if (settings.tags.discNumber)
1999                                         writer.setFrame('TPOS', (settings.tags.discTotal ? track.discNumber+"/"+track.discTotal : track.discNumber))
2000                                 if (settings.tags.isrc)
2001                                         writer.setFrame('TSRC', track.ISRC);
2002
2003                                 if (settings.tags.length)
2004                                         writer.setFrame('TLEN', track.duration);
2005                                 if (settings.tags.barcode && track.album.barcode)
2006                                         writer.setFrame('TXXX', {
2007                                                 description: 'BARCODE',
2008                                                 value: track.album.barcode
2009                                         });
2010                                 if(track.album.picturePath && settings.tags.cover){
2011                                         const coverBuffer = fs.readFileSync(track.album.picturePath);
2012                                         writer.setFrame('APIC', {
2013                                                 type: 3,
2014                                                 data: coverBuffer,
2015                                                 description: ''
2016                                         });
2017                                 }
2018                                 if(track.unsyncLyrics && settings.tags.unsynchronisedLyrics)
2019                                         writer.setFrame('USLT', track.unsyncLyrics);
2020                                 if(track.publisher && settings.tags.publisher)
2021                                         writer.setFrame('TPUB', track.publisher);
2022                                 if(track.genreString && settings.tags.genre)
2023                                         writer.setFrame('TCON', [track.genreString]);
2024                                 if(track.copyright && settings.tags.copyright)
2025                                         writer.setFrame('TCOP', track.copyright);
2026                                 if (0 < parseInt(track.date.year)) {
2027                                         if (settings.tags.date)
2028                                                 writer.setFrame('TDAT', track.dateString);
2029                                         if (settings.tags.year)
2030                                                 writer.setFrame('TYER', track.date.year);
2031                                 }
2032                                 if (0 < parseInt(track.bpm) && settings.tags.bpm)
2033                                         writer.setFrame('TBPM', track.bpm);
2034                                 if(track.composerString && settings.tags.composer)
2035                                         writer.setFrame('TCOM', [track.composerString]);
2036                                 if(track.replayGain && settings.tags.replayGain)
2037                                         writer.setFrame('TXXX', {
2038                                                 description: 'REPLAYGAIN_TRACK_GAIN',
2039                                                 value: track.replayGain
2040                                         });
2041                                 writer.addTag();
2042                                 const taggedSongBuffer = Buffer.from(writer.arrayBuffer);
2043                                 fs.writeFileSync(writePath, taggedSongBuffer);
2044                                 fs.remove(tempPath);
2045                         }
2046                 }
2047                 logger.info(`[${track.artist.name} - ${track.title}] Downloaded`)
2048         }
2049 })
2050
2051 // Helper functions
2052
2053 /**
2054  * Updates individual parameters in the settings file
2055  * @param config
2056  * @param value
2057  */
2058 function updateSettingsFile(config, value) {
2059         configFile.userDefined[config] = value;
2060
2061         fs.outputFile(configFileLocation, JSON.stringify(configFile, null, 2), function (err) {
2062                 if (err) return;
2063                 logger.info("Settings updated");
2064
2065                 // FIXME: Endless Loop, due to call from initFolders()...crashes soon after startup
2066                 // initFolders();
2067         });
2068 }
2069
2070 function fixName (txt) {
2071         txt = txt+""
2072   const regEx = /[\0\/\\:*?"<>|]/g;
2073   txt = txt.replace(regEx, '_');
2074   txt = txt.slice(0,200);
2075   return txt;
2076 }
2077
2078 function antiDot(str){
2079         while(str[str.length-1] == "." || str[str.length-1] == " " || str[str.length-1] == "\n"){
2080                 str = str.substring(0,str.length-1);
2081         }
2082         if(str.length < 1){
2083                 str = "dot";
2084         }
2085         return str;
2086 }
2087
2088 /**
2089  * Initialize the temp folder for covers and main folder for downloads
2090  */
2091 function initFolders() {
2092         // Check if main folder exists
2093         if (!fs.existsSync(mainFolder)) {
2094                 mainFolder = defaultDownloadFolder;
2095                 updateSettingsFile('downloadLocation', defaultDownloadFolder);
2096         }
2097         //fs.removeSync(coverArtFolder);
2098         //fs.ensureFolderSync(coverArtFolder);
2099 }
2100
2101 /**
2102  * Creates the name of the tracks replacing wildcards to correct metadata
2103  * @param track
2104  * @param filename
2105  * @param playlist
2106  * @returns {XML|string|*}
2107  */
2108 function settingsRegex(track, filename, playlist, saveFullArtists, paddingSize, playlistNumbering) {
2109         try{
2110                 filename = filename.replace(/%title%/g, fixName(track.title));
2111                 filename = filename.replace(/%album%/g, fixName(track.album.title));
2112                 filename = filename.replace(/%artist%/g, fixName((saveFullArtists ? track.artistsString : track.artist.name)));
2113                 filename = filename.replace(/%year%/g, fixName(track.date.year));
2114                 filename = filename.replace(/%label%/g, fixName(track.publisher));
2115                 let tNumber = playlistNumbering ? track.position+1 : track.trackNumber
2116                 let tTotal = playlistNumbering ? playlist.fullSize : track.trackTotal
2117                 if(typeof tNumber != 'undefined'){
2118                         if(configFile.userDefined.padtrck){
2119                                  filename = filename.replace(/%number%/g, fixName(pad(tNumber, (parseInt(paddingSize)>0 ? parseInt(paddingSize) : tTotal))));
2120                         }else{
2121                                 filename = filename.replace(/%number%/g, fixName(tNumber));
2122                         }
2123                 } else {
2124                         filename = filename.replace(/%number%/g, '');
2125                 }
2126                 filename = filename.replace(/%explicit%/g, fixName((track.explicit==="1" ? (filename.indexOf(/[^%]explicit/g)>-1 ? "" : "(Explicit Version)") : "")));
2127                 filename = filename.replace(/%label%/g, fixName(track.genre ? (Array.isArray(track.genre) ? track.genre[0] : track.genre) : "Unknown"));
2128                 filename = filename.replace(/[/\\]/g, path.sep)
2129                 return filename.trim();
2130         }catch(e){
2131                 logger.error("settingsRegex failed: "+e)
2132         }
2133 }
2134
2135 /**
2136  * Creates the name of the albums folder replacing wildcards to correct metadata
2137  * @param metadata
2138  * @param foldername
2139  * @returns {XML|string|*}
2140  */
2141 function settingsRegexAlbum(foldername, artist, album, year, rtype, explicit, publisher, genres) {
2142         try{
2143                 foldername = foldername.replace(/%album%/g, fixName(album))
2144                 foldername = foldername.replace(/%artist%/g, fixName(artist))
2145                 foldername = foldername.replace(/%year%/g, fixName(year))
2146                 if (rtype){
2147                         foldername = foldername.replace(/%type%/g, fixName(rtype[0].toUpperCase() + rtype.substring(1)))
2148                 }else{
2149                         foldername = foldername.replace(/%type%/g, "")
2150                 }
2151                 foldername = foldername.replace(/%label%/g, fixName(publisher))
2152                 foldername = foldername.replace(/%explicit%/g, fixName((explicit ? (foldername.indexOf(/[^%]explicit/g)>-1 ? "" : "(Explicit) ") : "")))
2153                 foldername = foldername.replace(/%genre%/g, fixName(genres ? (Array.isArray(genres) ? genres[0] : genres) : "Unknown"))
2154                 foldername = foldername.replace(/[/\\]/g, path.sep)
2155                 return foldername.trim();
2156         }catch(e){
2157                 logger.error("settingsRegexAlbum failed: "+e)
2158         }
2159
2160 }
2161
2162 function settingsRegexCover(foldername, artist, name) {
2163         foldername = foldername.replace(/%name%/g, fixName(name));
2164         foldername = foldername.replace(/%artist%/g, fixName(artist));
2165         foldername = foldername.replace(/[/\\]/g, path.sep)
2166         return foldername;
2167 }
2168
2169 function settingsRegexArtistCover(foldername, artist) {
2170         foldername = foldername.replace(/%artist%/g, fixName(artist));
2171         foldername = foldername.replace(/[/\\]/g, path.sep)
2172         return foldername;
2173 }
2174
2175 /**
2176  * Pad number with 0s so max and str have the same nuber of characters
2177  * @param str
2178  * @param max
2179  * @returns {String|string|*}
2180  */
2181 function pad(str, max) {
2182         str = str.toString();
2183         max = max.toString();
2184         return str.length < max.length || str.length == 1 ? pad("0" + str, max) : str;
2185 }
2186
2187 /**
2188  * Splits the %number%
2189  * @param string str
2190  * @return string
2191  */
2192 function splitNumber(str,total){
2193         str = str.toString();
2194         let i = str.indexOf("/");
2195         if(total && i > 0){
2196                 return str.slice(i+1, str.length);
2197         }else if(i > 0){
2198                 return str.slice(0, i);
2199         }else{
2200                 return str;
2201         }
2202         return i > 0 ? str.slice(0, i) : str;
2203 }
2204
2205 function switchReleaseType(id){
2206         switch (id.toString()) {
2207                 case "0":
2208                         return "Album";
2209                 case "1":
2210                         return "Single";
2211                 case "3":
2212                         return "EP";
2213                 default:
2214                         return "Album";
2215         }
2216 }
2217
2218 function uniqueArray(origin, removeDupes=true){
2219         destination = []
2220         Array.from(new Set(origin)).forEach(function(x){
2221                 if(destination.indexOf(x) == -1)
2222                         destination.push(x);
2223         })
2224         if (removeDupes){
2225                 destination.forEach((name,index)=>{
2226                         destination.forEach((name2,index2)=>{
2227                                 if(!(index===index2) && (name.toLowerCase().indexOf(name2.toLowerCase())!== -1)){
2228                                         destination.splice(index, 1);
2229                                 }
2230                         })
2231                 })
2232         }
2233         return destination
2234 }
2235
2236 async function asyncForEach(array, callback) {
2237   for (let index = 0; index < array.length; index++) {
2238     await callback(array[index], index, array);
2239   }
2240 }
2241
2242 // Show crash error in console for debugging
2243 process.on('unhandledRejection', function (err) {
2244         if (err) logger.error(err.stack ? err.stack : err)
2245
2246 })
2247 process.on('uncaughtException', function (err) {
2248         if (err) logger.error(err.stack ? err.stack : err)
2249 })
2250
2251 // Exporting vars
2252 module.exports.mainFolder = mainFolder
2253 module.exports.defaultSettings = defaultSettings
2254 module.exports.defaultDownloadFolder = defaultDownloadFolder