Maybe fixed the queue problem
[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('./lib/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 const coverArtFolder = os.tmpdir() + path.sep + 'deezloader-imgs' + path.sep
44 const defaultDownloadFolder = localpaths.user + 'Deezloader Music' + path.sep
45 // Default settings
46 const defaultSettings = require('./default.json').userDefined
47 // Spotify Files
48 const spotifySupport = fs.existsSync(localpaths.user+"authCredentials.js")
49 if (spotifySupport){
50         var authCredentials = require(localpaths.user+'authCredentials.js')
51         var Spotify = new spotifyApi(authCredentials)
52 }
53
54 // Setup the folders START
55 var mainFolder = defaultDownloadFolder
56
57 // See if all settings are there after update
58 var configFile = require(localpaths.user+path.sep+"config.json");
59 for (let x in defaultSettings){
60         if (typeof configFile.userDefined[x] != typeof defaultSettings[x]){
61                 configFile.userDefined[x] = defaultSettings[x]
62         }
63 }
64 // Set default download folder if not userDefined
65 if (configFile.userDefined.downloadLocation != "") {
66         mainFolder = configFile.userDefined.downloadLocation
67 }
68
69 initFolders();
70
71 // Route and create server
72 app.use('/', express.static(__dirname + '/public/'))
73 server.listen(configFile.serverPort)
74 logger.info('Server is running @ localhost:' + configFile.serverPort)
75
76 // START sockets clusterfuck
77 io.sockets.on('connection', function (s) {
78         logger.info("Connection recived!")
79
80         // Check for updates
81         request({
82                 url: "https://notabug.org/RemixDevs/DeezloaderRemix/raw/master/update.json",
83                 json: true
84         })
85         .then(body=>{
86                 logger.info("Checking for updates")
87                 let [currentVersion_MAJOR, currentVersion_MINOR, currentVersion_PATCH] = package.version.split(".")
88                 let [lastVersion_MAJOR, lastVersion_MINOR, lastVersion_PATCH] = body.version.split(".")
89                 if (
90                         parseInt(lastVersion_MAJOR) > parseInt(currentVersion_MAJOR) ||
91                         parseInt(lastVersion_MINOR) > parseInt(currentVersion_MINOR) ||
92                         parseInt(lastVersion_PATCH) > parseInt(currentVersion_PATCH))
93                 {
94                         logger.info("Update Available")
95                         s.emit("message", {title: `Version ${lastVersion_MAJOR}.${lastVersion_MINOR}.${lastVersion_PATCH} is available!`, msg: body.changelog})
96                 }
97         })
98         .catch(error=>{
99                 logger.error(`UpdateCheck failed: ${error.stack ? error.stack : error}`)
100         })
101
102         // Connection dependet variables
103         s.Deezer = new deezerApi()
104         s.dqueue = new stq.SequentialTaskQueue()
105         s.downloadQueue = {}
106         s.trackQueue = queue({
107                 autostart: true
108         })
109         s.trackQueue.concurrency = configFile.userDefined.queueConcurrency
110
111         // Function for logging in
112         s.on("login", async function (username, password, autologin) {
113                 try{
114                         logger.info("Logging in");
115                         await s.Deezer.login(username, password)
116                         s.emit("login", {user: s.Deezer.user})
117                         logger.info("Logged in successfully")
118                         if (autologin){
119                                 // Save session login so next time login is not needed
120                                 // This is the same method used by the official website
121                                 s.emit('getCookies', s.Deezer.getCookies())
122                         }
123                 }catch(err){
124                         s.emit("login", {error: err.message})
125                         logger.error(`Login failed: ${err.message}`)
126                 }
127         });
128
129         // Function for autologin
130         s.on("autologin", async function(jar, email){
131                 try{
132       await s.Deezer.loginViaCookies(jar, email)
133                         s.emit('login', {user: s.Deezer.user})
134     }catch(err){
135       s.emit('login', {error: err.message})
136                         logger.error(`Autologin failed: ${err.message}`)
137       return
138     }
139         })
140
141         // Function for logout
142         s.on("logout", function(){
143                 logger.info("Logged out")
144                 // Creating new object to clear the cookies
145                 s.Deezer = new deezerApi()
146                 return
147         })
148
149         // Returns list of charts available
150         s.on("getChartsCountryList", async function (data) {
151                 try{
152                         let charts = await s.Deezer.legacyGetChartsTopCountry()
153                         charts = charts.data || []
154                         let countries = []
155                         for (let i = 0; i < charts.length; i++) {
156                                 let obj = {
157                                         country: charts[i].title.replace("Top ", ""),
158                                         picture_small: charts[i].picture_small,
159                                         picture_medium: charts[i].picture_medium,
160                                         picture_big: charts[i].picture_big,
161                                         playlistId: charts[i].id
162                                 }
163                                 countries.push(obj)
164                         }
165                         s.emit("getChartsCountryList", {countries: countries, selected: data.selected})
166                 }catch(err){
167                         logger.error(`getChartsCountryList failed: ${err.stack}`)
168                         return
169                 }
170         })
171
172         // Returns chart tracks from Playlist ID
173         async function getChartsTrackListById(playlistId){
174                 if (typeof playlistId === 'undefined') {
175                         s.emit("getChartsTrackListByCountry", {err: "Can't find that playlist"})
176                         return
177                 }
178                 try{
179                         let tracks = await s.Deezer.legacyGetPlaylistTracks(playlistId)
180                         s.emit("getChartsTrackListByCountry", {
181                                 playlistId: playlistId,
182                                 tracks: tracks.data
183                         })
184                 }catch(err){
185                         s.emit("getChartsTrackListByCountry", {err: err})
186                         logger.error(`getChartsTrackListById failed: ${err.stack}`)
187                         return
188                 }
189         }
190
191         // Returns chart tracks from country name
192         async function getChartsTrackListByCountry(country){
193                 if (typeof country === 'undefined') {
194                         s.emit("getChartsTrackListByCountry", {err: "No country passed"})
195                         return
196                 }
197                 try{
198                         let charts = await s.Deezer.legacyGetChartsTopCountry()
199                         charts = charts.data || []
200                         let countries = []
201                         for (let i = 0; i < charts.length; i++) {
202                                 countries.push(charts[i].title.replace("Top ", ""))
203                         }
204                         if (countries.indexOf(country) == -1) {
205                                 s.emit("getChartsTrackListByCountry", {err: "Country not found"})
206                                 return
207                         }
208                         let playlistId = charts[countries.indexOf(country)].id
209                         await getChartsTrackListById(playlistId)
210                 }catch(err){
211                         logger.error(`getChartsTrackListByCountry failed: ${err.stack}`)
212                         return
213                 }
214         }
215         s.on("getChartsTrackListByCountry", function (data) {getChartsTrackListByCountry(data.country)})
216
217         // Returns list of playlists
218         async function getMyPlaylistList(){
219                 try{
220                         logger.info("Loading Personal Playlists")
221                         let data = await s.Deezer.legacyGetUserPlaylists(s.Deezer.user.id)
222                         data = data.data || []
223                         let playlists = []
224                         for (let i = 0; i < data.length; i++) {
225                                 let obj = {
226                                         title: data[i].title,
227                                         image: data[i].picture_small,
228                                         songs: data[i].nb_tracks,
229                                         link: data[i].link
230                                 }
231                                 playlists.push(obj)
232                         }
233                         if (configFile.userDefined.spotifyUser && spotifySupport){
234                                 try{
235                                         let creds = await Spotify.clientCredentialsGrant()
236                                         Spotify.setAccessToken(creds.body['access_token'])
237                                         let first = true
238                                         let offset = 0
239                                         do{
240                                                 let data = await Spotify.getUserPlaylists(configFile.userDefined.spotifyUser, {fields: "items(images,name,owner.id,tracks.total,uri),total", offset: offset*20})
241                                                 if (first){
242                                                         var total = data.body.total
243                                                         var numPages=Math.floor((total-1)/20)
244                                                         var playlistList = new Array(total)
245                                                         first = false
246                                                 }
247                                                 data.body.items.forEach((playlist, i) => {
248                                                         playlistList[(offset*20)+i] = {
249                                                                 title: playlist.name,
250                                                                 image: (playlist.images[0] ? playlist.images[0].url : ""),
251                                                                 songs: playlist.tracks.total,
252                                                                 link: playlist.uri,
253                                                                 spotify: true
254                                                         }
255                                                 })
256                                                 offset++
257                                         }while(offset<=numPages)
258                                         playlists = playlists.concat(playlistList)
259                                 }catch(err){
260                                         logger.error(`Spotify playlist failed loading: ${err}`)
261                                 }
262                         }
263                         logger.info(`Loaded ${playlists.length} Playlist${playlists.length>1 ? "s" : ""}`)
264                         s.emit("getMyPlaylistList", {playlists: playlists})
265                 }catch(err){
266                         logger.error(`getMyPlaylistList failed: ${err}`)
267                         return
268                 }
269         }
270         s.on("getMyPlaylistList", function (d) {getMyPlaylistList()})
271
272         // Returns search results from a query
273         s.on("search", async function (data) {
274                 data.type = data.type || "track"
275                 if (["track", "playlist", "album", "artist"].indexOf(data.type) == -1) data.type = "track"
276
277                 // Remove "feat."  "ft." and "&" (causes only problems)
278                 data.text = data.text
279                         .replace(/ feat[\.]? /g, " ")
280                         .replace(/ ft[\.]? /g, " ")
281                         .replace(/\(feat[\.]? /g, " ")
282                         .replace(/\(ft[\.]? /g, " ")
283                         .replace(/\&/g, "")
284                         .replace(/–/g, "-")
285                         .replace(/—/g, "-")
286
287                 try {
288                         let searchObject = await s.Deezer.legacySearch(encodeURIComponent(data.text), data.type)
289                         s.emit("search", {type: data.type, items: searchObject.data})
290                 } catch (err) {
291                         s.emit("search", {type: data.type, items: []})
292                         logger.error(`search failed: ${err.stack}`)
293                         return
294                 }
295         })
296
297         // Returns list of tracks from an album/playlist or the list of albums from an artist
298         s.on("getTrackList", async function (data) {
299                 if (!data.type || (["playlist", "album", "artist", "spotifyplaylist"].indexOf(data.type) == -1) || !data.id) {
300                         s.emit("getTrackList", {err: -1, response: {}, id: data.id, reqType: data.type})
301                         return
302                 }
303                 if (data.type == 'artist') {
304                         try{
305                                 let response = await s.Deezer.legacyGetArtistAlbums(data.id)
306                                 s.emit("getTrackList", {response: response, id: data.id, reqType: data.type})
307                         }catch(err){
308                                 s.emit("getTrackList", {err: "wrong artist id", response: {}, id: data.id, reqType: data.type})
309                                 logger.error(`getTrackList failed: ${err.stack}`)
310                                 return
311                         }
312                 }else if(data.type == "spotifyplaylist" && spotifySupport){
313                         try{
314                                 let creds = await Spotify.clientCredentialsGrant()
315                                 Spotify.setAccessToken(creds.body.access_token)
316                                 let first = true
317                                 let offset = 0
318                                 do{
319                                         let resp = await Spotify.getPlaylistTracks(data.id, {fields: "items(track(artists,name,duration_ms,preview_url,explicit)),total", offset: offset*100})
320                                         if (first){
321                                                 var numPages=Math.floor((resp.body.total-1)/100)
322                                                 var response = new Array(resp.body.total)
323                                                 first = false
324                                         }
325                                         resp.body.items.forEach((t, index) => {
326                                                 response[index+offset*100]={
327                                                         explicit_lyrics: t.track.explicit,
328                                                         preview: t.track.preview_url,
329                                                         title: t.track.name,
330                                                         artist: {
331                                                                 name: t.track.artists[0].name
332                                                         },
333                                                         duration: Math.floor(t.track.duration_ms/1000)
334                                                 }
335                                         })
336                                         offset++
337                                 }while(offset<=numPages)
338                                 s.emit("getTrackList", {response: {'data': response}, id: data.id, reqType: data.type})
339                         }catch(err){
340                                 logger.error(`getTrackList failed: ${err.stack}`)
341                         }
342                 }else{
343                         let reqType = data.type.charAt(0).toUpperCase() + data.type.slice(1)
344                         try{
345                                 let response = await s.Deezer["legacyGet" + reqType + "Tracks"](data.id)
346                                 s.emit("getTrackList", {response: response, id: data.id, reqType: data.type})
347                         }catch(err){
348                                 s.emit("getTrackList", {err: "wrong id "+reqType, response: {}, id: data.id, reqType: data.type})
349                                 logger.error(`getTrackList failed: ${err.stack}`)
350                                 return
351                         }
352                 }
353         })
354
355         // Sends settings saved by the user to the frontend
356         s.on("getUserSettings", function () {
357                 let settings = configFile.userDefined
358                 if (!settings.downloadLocation) {
359                         settings.downloadLocation = mainFolder
360                 }
361                 s.emit('getUserSettings', {settings: settings})
362         });
363
364         // Saves locally the settings comming from the frontend
365         s.on("saveSettings", function (settings) {
366                 if (settings.userDefined.downloadLocation == defaultDownloadFolder) {
367                         settings.userDefined.downloadLocation = ""
368                 } else {
369                         settings.userDefined.downloadLocation = path.resolve(settings.userDefined.downloadLocation + path.sep) + path.sep
370                         mainFolder = settings.userDefined.downloadLocation
371                 }
372
373                 if (settings.userDefined.queueConcurrency < 1) settings.userDefined.queueConcurrency = 1
374
375                 if (settings.userDefined.queueConcurrency != s.trackQueue.concurrency){
376                         s.trackQueue.concurrency = settings.userDefined.queueConcurrency
377                 }
378
379                 if (settings.userDefined.chartsCountry != configFile.userDefined.chartsCountry){
380                         s.emit("setChartsCountry", {selected: settings.userDefined.chartsCountry})
381                         getChartsTrackListByCountry(settings.userDefined.chartsCountry)
382                 }
383
384                 if (settings.userDefined.spotifyUser != configFile.userDefined.spotifyUser){
385                         getMyPlaylistList(settings.userDefined.spotifyUser)
386                 }
387
388                 configFile.userDefined = settings.userDefined;
389                 fs.outputFile(configFileLocation, JSON.stringify(configFile, null, 2), function (err) {
390                         if (err) return
391                         logger.info("Settings updated")
392                         initFolders()
393                 });
394         });
395
396         async function downloadTrack(data){
397                 try{
398                         var track = await s.Deezer.getTrack(data.id)
399                         let _track = {
400                                 name: track.title,
401                                 artist: track.artist.name,
402                                 size: 1,
403                                 downloaded: 0,
404                                 failed: 0,
405                                 queueId: `id${Math.random().toString(36).substring(2)}`,
406                                 id: `${track.id}:${data.settings.maxBitrate}`,
407                                 type: 'track',
408                                 settings: data.settings || {},
409                                 obj: track,
410                         }
411                         addToQueue(_track)
412                 }catch(err){
413                         logger.error(`downloadTrack failed: ${err.stack ? err.stack : err}`)
414                         return
415                 }
416         }
417         s.on("downloadtrack", async data=>{await downloadTrack(data)})
418
419         async function downloadAlbum(data){
420                 try{
421                         var album = await s.Deezer.legacyGetAlbum(data.id)
422                         if (data.settings.tags.discTotal || data.settings.createCDFolder){
423                                 var discTotal = await s.Deezer.getAlbum(data.id)
424                                 album.discTotal = discTotal.discTotal
425                         }
426                         album.tracks = await s.Deezer.getAlbumTracks(data.id)
427                         let _album = {
428                                 name: album.title,
429                                 artist: album.artist.name,
430                                 size: album.tracks.length,
431                                 downloaded: 0,
432                                 failed: 0,
433                                 queueId: `id${Math.random().toString(36).substring(2)}`,
434                                 id: `${album.id}:${data.settings.maxBitrate}`,
435                                 type: 'album',
436                                 settings: data.settings || {},
437                                 obj: album,
438                         }
439                         addToQueue(_album)
440                         return
441                 }catch(err){
442                         logger.error(`downloadAlbum failed: ${err.stack ? err.stack : err}`)
443                         return
444                 }
445         }
446         s.on("downloadalbum", async data=>{await downloadAlbum(data)});
447
448         async function downloadArtist(data){
449                 try{
450                         var albums = await s.Deezer.legacyGetArtistAlbums(data.id);
451                         (function sendAllAlbums(i) {
452                                 setTimeout(function () {
453                                         data.id = albums.data[albums.data.length-1-i].id
454                                         downloadAlbum(JSON.parse(JSON.stringify(data)))
455                                         if (--i+1) sendAllAlbums(i)
456                                 }, 100)
457                         })(albums.data.length-1)
458                 }catch(err){
459                         logger.error(`downloadArtist failed: ${err.stack ? err.stack : err}`)
460                         return
461                 }
462         }
463         s.on("downloadartist", async data=>{ await downloadArtist(data)});
464
465         async function downloadPlaylist(data){
466                 try{
467                         var playlist = await s.Deezer.legacyGetPlaylist(data.id)
468                         playlist.tracks = await s.Deezer.getPlaylistTracks(data.id)
469                         let _playlist = {
470                                 name: playlist.title,
471                                 artist: playlist.creator.name,
472                                 size: playlist.tracks.length,
473                                 downloaded: 0,
474                                 failed: 0,
475                                 queueId: `id${Math.random().toString(36).substring(2)}`,
476                                 id: `${playlist.id}:${data.settings.maxBitrate}`,
477                                 type: "playlist",
478                                 settings: data.settings || {},
479                                 obj: playlist,
480                         }
481                         addToQueue(_playlist)
482                 }catch(err){
483                         logger.error(`downloadPlaylist failed: ${err.stack ? err.stack : err}`)
484                         return
485                 }
486         }
487         s.on("downloadplaylist", data=>{downloadPlaylist(data)});
488
489         async function downloadSpotifyPlaylist(data){
490                 if (spotifySupport){
491                         try{
492                                 let creds = await Spotify.clientCredentialsGrant()
493                                 Spotify.setAccessToken(creds.body['access_token'])
494                                 let first = true
495                                 let offset = 0
496                                 do{
497                                         var resp = await Spotify.getPlaylist(data.id, {fields: "id,name,owner,images,tracks(total,items(track(artists,name,album,external_ids)))", offset: offset*100})
498                                         if (first){
499                                                 var _playlist = {
500                                                         name: resp.body.name,
501                                                         artist: (resp.body.owner.display_name ? resp.body.owner.display_name : resp.body.owner.id),
502                                                         size: resp.body.tracks.total,
503                                                         downloaded: 0,
504                                                         failed: 0,
505                                                         queueId: `id${Math.random().toString(36).substring(2)}`,
506                                                         settings: data.settings || {},
507                                                         id: `${resp.body.id}:${data.settings.maxBitrate}`,
508                                                         type: "spotifyplaylist",
509                                                         obj: resp.body
510                                                 }
511                                                 var numPages=Math.floor((_playlist.size-1)/100)
512                                                 var trackList = new Array(_playlist.size)
513                                                 first = false
514                                         }
515                                         resp.body.tracks.items.forEach((track, i) => {
516                                                 trackList[(offset*20)+i] = track.track
517                                         })
518                                         offset++
519                                 }while(offset<=numPages)
520                                 _playlist.obj.tracks = trackList
521                                 addToQueue(_playlist)
522                         }catch(err){
523                                 logger.error(`downloadSpotifyPlaylist failed: ${err.stack ? err.stack : err}`)
524                                 return
525                         }
526                 }else{
527                         s.emit("message", {title: "Spotify Support is not enabled", msg: "You should add authCredentials.js in your config files 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>"})
528                 }
529         }
530         s.on("downloadspotifyplaylist", data=>{downloadSpotifyPlaylist(data)})
531
532         async function convertSpotify2Deezer(track){
533                 if (track.external_ids.isrc){
534                         let resp = await s.Deezer.legacyGetTrackByISRC(track.external_ids.isrc)
535                         return resp.id
536                 }else{
537                         let resp
538                         track.artists[0].name = track.artists[0].name.replace(/–/g,"-").replace(/’/g, "'")
539                         track.name = track.name.replace(/–/g,"-").replace(/’/g, "'")
540                         track.album.name = track.album.name.replace(/–/g,"-").replace(/’/g, "'")
541                         try{
542                                 resp = await s.Deezer.legacySearch(`artist:"${track.artists[0].name}" track:"${track.name}" album:"${track.album.name}"`, "track", 1)
543                         }catch(err){logger.err(`Convert2Spotify: ${err.stack ? err.stack : err}`)}
544                         if (resp.data) return resp.data[0].id
545                         try{
546                                 resp = await s.Deezer.legacySearch(`artist:"${track.artists[0].name}" track:"${track.name}"`, "track", 1)
547                         }catch(err){logger.err(`Convert2Spotify: ${err.stack ? err.stack : err}`)}
548                         if (resp.data) return resp.data[0].id
549                         if (track.name.indexOf("(") < track.name.indexOf(")")){
550                                 try{
551                                         resp = await s.Deezer.legacySearch(`artist:"${track.artists[0].name}" track:"${track.name.split("(")[0]}"`, "track", 1)
552                                 }catch(err){logger.err(`Convert2Spotify: ${err.stack ? err.stack : err}`)}
553                                 if (resp.data) return resp.data[0].id
554                         }else if (track.indexOf(" - ")>0){
555                                 try{
556                                         resp = await s.Deezer.legacySearch(`artist:"${track.artists[0].name}" track:"${track.name.split(" - ")[0]}"`, "track", 1)
557                                 }catch(err){logger.err(`Convert2Spotify: ${err.stack ? err.stack : err}`)}
558                                 if (resp.data) return resp.data[0].id
559                         }else{
560                                 return 0
561                         }
562                         return 0
563                 }
564         }
565
566         function addToQueue(object) {
567                 s.downloadQueue[object.queueId] = object
568                 s.emit('addToQueue', object)
569                 s.downloadQueue[object.queueId].downloadQueuePromise = s.dqueue.push(addNextDownload, { args: object })
570         }
571
572         function addNextDownload(obj, token){
573                 return new Promise(async (resolve, reject) => {
574       await queueDownload(obj)
575                         resolve()
576     }).then(() => new Promise((resolve, reject) => {
577       if (token.cancelled)
578         reject()
579       else
580         resolve()
581     }))
582         }
583
584         function cancelDownload(queueId, cleanAll=false){
585                 if (!queueId) return
586                 let cancel = false
587                 let cancelSuccess
588                 if (s.downloadQueue[queueId]){
589                         cancel = true;
590                         if (s.downloadQueue[queueId].downloadQueuePromise) s.downloadQueue[queueId].downloadQueuePromise.cancel()
591                         if (s.downloadQueue[Object.keys(s.downloadQueue)[0]].queueId == queueId) {
592                                 s.trackQueue = queue({
593                                         autostart: true,
594                                         concurrency: s.trackQueue.concurrency
595                                 })
596                         }
597                         delete s.downloadQueue[queueId]
598                 }
599
600                 if (cancel) {
601                         s.emit("cancelDownload", {queueId: queueId, cleanAll: cleanAll});
602                 }
603         }
604         s.on("cancelDownload", function (data) {cancelDownload(data.queueId)});
605
606         s.on("cancelAllDownloads", function(data){
607                 data.queueList.forEach(x=>{
608                         cancelDownload(x, true);
609                 })
610                 s.emit("cancelAllDownloads")
611         })
612
613         /*function getNextDownload() {
614                 if (s.currentItem != null || Object.keys(s.downloadQueue).length == 0) {
615                         if (Object.keys(s.downloadQueue).length == 0 && s.currentItem == null) {
616                                 s.emit("emptyDownloadQueue", {})
617                         }
618                         return null
619                 }
620                 s.currentItem = s.downloadQueue[Object.keys(s.downloadQueue)[0]]
621                 return s.currentItem
622         }*/
623
624         //downloadQueue: the tracks in the queue to be downloaded
625         //lastQueueId: the most recent queueId
626         //queueId: random number generated when user clicks download on something
627         async function queueDownload(downloading) {
628                 if (!downloading) return
629
630                 if (downloading.type != "spotifyplaylist"){
631                         s.emit("downloadStarted", {queueId: downloading.queueId})
632                 }
633
634                 downloading.errorLog = "";
635                 downloading.searchedLog = "";
636
637                 let filePath;
638                 logger.info(`Registered ${downloading.type}: ${downloading.id} | ${downloading.artist} - ${downloading.name}`);
639                 switch(downloading.type){
640                         /*
641                         *  TRACK DOWNLOAD
642                         */
643                         case "track":
644                                 var downloadPromise = new Promise(async (resolve,reject)=>{
645                                         try{
646                                                 await downloadTrackObject(downloading.obj, downloading.queueId, downloading.settings)
647                                                 downloading.downloaded++
648                                         }catch(err){
649                                                 logger.error(`queueDownload:track failed: ${err.stack ? err.stack : err}`)
650                                                 downloading.failed++
651                                         }
652                                         s.emit("updateQueue", {
653                                                 name: downloading.name,
654                                                 artist: downloading.artist,
655                                                 size: downloading.size,
656                                                 downloaded: downloading.downloaded,
657                                                 failed: downloading.failed,
658                                                 queueId: downloading.queueId,
659                                                 id: downloading.id,
660                                                 type: downloading.type,
661                                         })
662                                         s.emit("downloadProgress", {
663                                                 queueId: downloading.queueId,
664                                                 percentage: 100
665                                         })
666                                         resolve()
667                                 })
668                                 try{
669                                         await downloadPromise
670                                 }catch(err){
671                                         if (err) logger.error(`queueDownload:track failed: ${err.stack ? err.stack : err}`)
672                                         logger.info("Downloading Stopped")
673                                 }
674                         break
675                         /*
676                         *  ALBUM DOWNLOAD
677                         */
678                         case "album":
679                                 downloading.settings.albName = downloading.name;
680                                 downloading.settings.artName = downloading.artist;
681                                 downloading.playlistArr = Array(downloading.size);
682                                 filePath = mainFolder;
683                                 if (downloading.settings.createArtistFolder || downloading.settings.createAlbumFolder) {
684                                         if (downloading.settings.createArtistFolder) {
685                                                 filePath += antiDot(fixName(downloading.settings.artName)) + path.sep;
686                                         }
687                                         if (downloading.settings.createAlbumFolder) {
688                                                 filePath += antiDot(fixName(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))) + path.sep;
689                                         }
690                                 } else if (downloading.settings.artName) {
691                                         filePath += antiDot(fixName(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))) + path.sep;
692                                 }
693                                 let ajson = {
694                                         artist : downloading.obj.artist,
695                                         nb_tracks : downloading.obj.nb_tracks,
696                                         upc : downloading.obj.upc,
697                                         record_type : downloading.obj.record_type,
698                                         explicit_lyrics : downloading.obj.explicit_lyrics,
699                                         label : downloading.obj.label,
700                                         release_date : downloading.obj.release_date,
701                                         genres : downloading.obj.genres,
702                                 }
703                                 downloading.downloadPromise = new Promise((resolve,reject)=>{
704                                         downloading.obj.tracks.every(function (t) {
705                                                 s.trackQueue.push(async cb=>{
706                                                         if (!s.downloadQueue[downloading.queueId]) {
707                                                                 reject()
708                                                                 return false
709                                                         }
710                                                         t.ajson = ajson
711                                                         logger.info(`Now downloading: ${t.artist.name} - ${t.title}`)
712                                                         try{
713                                                                 await downloadTrackObject(t, downloading.queueId, downloading.settings)
714                                                                 downloading.downloaded++
715                                                                 downloading.playlistArr[t.playlistData[0]] = t.playlistData[1].split(filePath)[1]
716                                                                 if (t.searched) downloading.searchedLog += `${t.artist.name} - ${t.name}\r\n`
717                                                         }catch(err){
718                                                                 logger.error(`queueDownload:album failed: ${err.stack ? err.stack : err}`)
719                                                                 downloading.failed++
720                                                                 downloading.errorLog += `${t.id} | ${t.artist.name} - ${t.title} | ${err}\r\n`
721                                                         }
722                                                         s.emit("downloadProgress", {
723                                                                 queueId: downloading.queueId,
724                                                                 percentage: ((downloading.downloaded+downloading.failed) / downloading.size) * 100
725                                                         });
726                                                         s.emit("updateQueue", {
727                                                                 name: downloading.name,
728                                                                 artist: downloading.artist,
729                                                                 size: downloading.size,
730                                                                 downloaded: downloading.downloaded,
731                                                                 failed: downloading.failed,
732                                                                 queueId: downloading.queueId,
733                                                                 id: downloading.id,
734                                                                 type: downloading.type,
735                                                         })
736                                                         if (downloading.downloaded + downloading.failed >= downloading.size) resolve()
737                                                         cb()
738                                                 })
739                                                 return true
740                                         })
741                                 })
742                                 try{
743                                         await downloading.downloadPromise
744                                         logger.info("Album finished downloading: "+downloading.name);
745                                         s.emit("downloadProgress", {
746                                                 queueId: downloading.queueId,
747                                                 percentage: 100
748                                         });
749                                         if (downloading.settings.logErrors){
750                                                 if (downloading.errorLog != ""){
751                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
752                                                         fs.writeFileSync(filePath+"notFound.txt",downloading.errorLog)
753                                                 }else{
754                                                         if (fs.existsSync(filePath+"notFound.txt")) fs.unlinkSync(filePath+"notFound.txt");
755                                                 }
756                                         }
757                                         if (downloading.settings.logSearched){
758                                                 if (downloading.searchedLog != ""){
759                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
760                                                         fs.writeFileSync(filePath+"alternativeSongs.txt",downloading.searchedLog)
761                                                 }else{
762                                                         if (fs.existsSync(filePath+"alternativeSongs.txt")) fs.unlinkSync(filePath+"alternativeSongs.txt");
763                                                 }
764                                         }
765                                         if (downloading.settings.createM3UFile){
766                                                 fs.writeFileSync(filePath+"playlist.m3u", downloading.playlistArr.join("\r\n"));
767                                         }
768                                 }catch(err){
769                                         if (err) logger.error(`queueDownload:album failed: ${err.stack ? err.stack : err}`)
770                                         logger.info("Stopping the album queue");
771                                 }
772                         break
773                         /*
774                         *  PLAYLIST DOWNLOAD
775                         */
776                         case "playlist":
777                                 downloading.settings.plName = downloading.name;
778                                 downloading.playlistArr = Array(downloading.size);
779                                 downloading.settings.playlist = {
780                                         fullSize: downloading.obj.tracks.length
781                                 };
782                                 filePath = mainFolder+antiDot(fixName(downloading.settings.plName)) + path.sep
783                                 downloading.downloadPromise = new Promise((resolve,reject)=>{
784                                         downloading.obj.tracks.every(function (t, index) {
785                                                 s.trackQueue.push(async cb=>{
786                                                         if (!s.downloadQueue[downloading.queueId]) {
787                                                                 reject()
788                                                                 return false
789                                                         }
790                                                         try{
791                                                                 await downloadTrackObject(t, downloading.queueId, downloading.settings)
792                                                                 downloading.downloaded++
793                                                                 downloading.playlistArr[t.playlistData[0]] = t.playlistData[1].split(filePath)[1]
794                                                                 if (t.searched) downloading.searchedLog += `${t.artist.name} - ${t.name}\r\n`
795                                                         }catch(err){
796                                                                 logger.error(`queueDownload:playlist failed: ${err.stack ? err.stack : err}`)
797                                                                 downloading.failed++
798                                                                 downloading.errorLog += `${t.id} | ${t.artist.name} - ${t.title} | ${err}\r\n`
799                                                         }
800                                                         s.emit("downloadProgress", {
801                                                                 queueId: downloading.queueId,
802                                                                 percentage: ((downloading.downloaded+downloading.failed) / downloading.size) * 100
803                                                         });
804                                                         s.emit("updateQueue", {
805                                                                 name: downloading.name,
806                                                                 artist: downloading.artist,
807                                                                 size: downloading.size,
808                                                                 downloaded: downloading.downloaded,
809                                                                 failed: downloading.failed,
810                                                                 queueId: downloading.queueId,
811                                                                 id: downloading.id,
812                                                                 type: downloading.type,
813                                                         })
814                                                         if (downloading.downloaded + downloading.failed >= downloading.size) resolve()
815                                                         cb()
816                                                 })
817                                                 return true
818                                         })
819                                 })
820                                 try{
821                                         await downloading.downloadPromise
822                                         logger.info("Playlist finished "+downloading.name);
823                                         s.emit("downloadProgress", {
824                                                 queueId: downloading.queueId,
825                                                 percentage: 100
826                                         });
827                                         if (downloading.settings.logErrors){
828                                                 if (downloading.errorLog != ""){
829                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
830                                                         fs.writeFileSync(filePath+"notFound.txt",downloading.errorLog)
831                                                 }else{
832                                                         if (fs.existsSync(filePath+"notFound.txt")) fs.unlinkSync(filePath+"notFound.txt");
833                                                 }
834                                         }
835                                         if (downloading.settings.logSearched){
836                                                 if (downloading.searchedLog != ""){
837                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
838                                                         fs.writeFileSync(filePath+"alternativeSongs.txt",downloading.searchedLog)
839                                                 }else{
840                                                         if (fs.existsSync(filePath+"alternativeSongs.txt")) fs.unlinkSync(filePath+"alternativeSongs.txt");
841                                                 }
842                                         }
843                                         if (downloading.settings.createM3UFile){
844                                                 fs.writeFileSync(filePath + "playlist.m3u", downloading.playlistArr.join("\r\n"));
845                                         }
846                                         if (downloading.settings.saveArtwork){
847                                                 if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
848                                                 let imgPath = filePath + antiDot(fixName(settingsRegexCover(downloading.settings.coverImageTemplate,downloading.artist,downloading.name)))+(downloading.settings.PNGcovers ? ".png" : ".jpg");
849                                                 if (downloading.cover){
850                                                         downloading.cover = downloading.cover.replace("56x56",`${downloading.settings.artworkSize}x${downloading.settings.artworkSize}`)
851                                                         request.get(downloading.cover, {strictSSL: false,encoding: 'binary'}, function(error,response,body){
852                                                                 if(error){
853                                                                         logger.error(error.stack);
854                                                                         return;
855                                                                 }
856                                                                 fs.outputFile(imgPath,body,'binary',function(err){
857                                                                         if(err){
858                                                                                 logger.error(err.stack);
859                                                                                 return;
860                                                                         }
861                                                                         logger.info(`Cover downloaded for: ${downloading.settings.plName}`)
862                                                                 })
863                                                         });
864                                                 }
865                                         }
866                                 }catch(err){
867                                         if (err) logger.error(`queueDownload:playlist failed: ${err.stack ? err.stack : err}`)
868                                         logger.info("Stopping the playlist queue")
869                                 }
870                         break
871                         /*
872                         *  SPOTIFY PLAYLIST DOWNLOAD
873                         */
874                         case "spotifyplaylist":
875                                 downloading.settings.plName = downloading.name
876                                 downloading.playlistArr = Array(downloading.size)
877                                 downloading.playlistContent = new Array(downloading.size);
878                                 logger.info("Waiting for all tracks to be converted");
879                                 downloading.obj.tracks.map(async (t,i)=>{
880                                         try{
881                                                 downloading.playlistContent[i] = await convertSpotify2Deezer(t)
882                                         }catch(err){
883                                                 logger.error(`queueDownload:spotifyplaylist failed during conversion: ${err.stack ? err.stack : err}`)
884                                         }
885                                 })
886                                 if (!s.downloadQueue[downloading.queueId]) {
887                                         logger.info("Stopping the playlist queue")
888                                         break
889                                 }
890                                 downloading.trackList = await s.Deezer.getTracks(downloading.playlistContent)
891                                 logger.info("All tracks converted, starting download")
892                                 s.emit("downloadStarted", {queueId: downloading.queueId})
893                                 downloading.settings.playlist = {
894                                         fullSize: downloading.trackList.length
895                                 }
896                                 filePath = `${mainFolder}${antiDot(fixName(downloading.settings.plName))}${path.sep}`
897                                 downloading.downloadPromise = new Promise((resolve,reject)=>{
898                                         downloading.trackList.every(function (t, index) {
899                                                 s.trackQueue.push(async cb=>{
900                                                         if (!s.downloadQueue[downloading.queueId]) {
901                                                                 reject()
902                                                                 return false
903                                                         }
904                                                         t.position = index
905                                                         try{
906                                                                 await downloadTrackObject(t, downloading.queueId, downloading.settings)
907                                                                 downloading.downloaded++
908                                                                 downloading.playlistArr[t.playlistData[0]] = t.playlistData[1].split(filePath)[1]
909                                                                 if (t.searched) downloading.searchedLog += `${t.artist.name} - ${t.name}\r\n`
910                                                         }catch(err){
911                                                                 logger.error(`queueDownload:spotifyplaylist failed: ${err.stack ? err.stack : err}`)
912                                                                 downloading.failed++
913                                                                 downloading.errorLog += `${t.id} | ${t.artist.name} - ${t.title} | ${err}\r\n`
914                                                         }
915                                                         s.emit("downloadProgress", {
916                                                                 queueId: downloading.queueId,
917                                                                 percentage: ((downloading.downloaded+downloading.failed) / downloading.size) * 100
918                                                         });
919                                                         s.emit("updateQueue", {
920                                                                 name: downloading.name,
921                                                                 artist: downloading.artist,
922                                                                 size: downloading.size,
923                                                                 downloaded: downloading.downloaded,
924                                                                 failed: downloading.failed,
925                                                                 queueId: downloading.queueId,
926                                                                 id: downloading.id,
927                                                                 type: downloading.type,
928                                                         })
929                                                         if (downloading.downloaded + downloading.failed >= downloading.size) resolve()
930                                                         cb()
931                                                 })
932                                                 return true
933                                         })
934                                 })
935                                 try{
936                                         await downloading.downloadPromise
937                                         logger.info("Playlist finished "+downloading.name);
938                                         s.emit("downloadProgress", {
939                                                 queueId: downloading.queueId,
940                                                 percentage: 100
941                                         });
942                                         if (downloading.settings.logErrors){
943                                                 if (downloading.errorLog != ""){
944                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
945                                                         fs.writeFileSync(filePath+"notFound.txt",downloading.errorLog)
946                                                 }else{
947                                                         if (fs.existsSync(filePath+"notFound.txt")) fs.unlinkSync(filePath+"notFound.txt");
948                                                 }
949                                         }
950                                         if (downloading.settings.logSearched){
951                                                 if (downloading.searchedLog != ""){
952                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
953                                                         fs.writeFileSync(filePath+"alternativeSongs.txt",downloading.searchedLog)
954                                                 }else{
955                                                         if (fs.existsSync(filePath+"alternativeSongs.txt")) fs.unlinkSync(filePath+"alternativeSongs.txt");
956                                                 }
957                                         }
958                                         if (downloading.settings.createM3UFile){
959                                                 fs.writeFileSync(filePath + "playlist.m3u", downloading.playlistArr.join("\r\n"));
960                                         }
961                                         if (downloading.settings.saveArtwork){
962                                                 if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
963                                                 let imgPath = filePath + antiDot(fixName(settingsRegexCover(downloading.settings.coverImageTemplate,downloading.artist,downloading.name)))+(downloading.settings.PNGcovers ? ".png" : ".jpg");
964                                                 if (downloading.obj.images){
965                                                         downloading.cover = downloading.obj.images[0].url.replace("56x56",`${downloading.settings.artworkSize}x${downloading.settings.artworkSize}`)
966                                                         request.get(downloading.cover, {strictSSL: false,encoding: 'binary'}, function(error,response,body){
967                                                                 if(error){
968                                                                         logger.error(error.stack);
969                                                                         return;
970                                                                 }
971                                                                 fs.outputFile(imgPath,body,'binary',function(err){
972                                                                         if(err){
973                                                                                 logger.error(err.stack);
974                                                                                 return;
975                                                                         }
976                                                                         logger.info(`Cover downloaded for: ${downloading.settings.plName}`)
977                                                                 })
978                                                         });
979                                                 }
980                                         }
981                                 }catch(err){
982                                         if (err) logger.error(`queueDownload:spotifyplaylist failed: ${err.stack ? err.stack : err}`)
983                                         logger.info("Stopping the playlist queue")
984                                 }
985                         break
986                 }
987                 if (downloading && s.downloadQueue[Object.keys(s.downloadQueue)[0]] && (Object.keys(s.downloadQueue)[0] == downloading.queueId)) delete s.downloadQueue[Object.keys(s.downloadQueue)[0]]
988                 if (Object.keys(s.downloadQueue).length == 0) {
989                         s.emit("emptyDownloadQueue", {})
990                 }
991         }
992
993         async function downloadTrackObject(track, queueId, settings) {
994                 if (!s.downloadQueue[queueId]) {
995                         logger.error(`[${track.artist.name} - ${track.title}] Failed to download: Not in queue`)
996                         throw new Error(`Failed to download: Not in queue`)
997                         return
998                 }
999                 if (track.id == 0){
1000                         logger.error(`[${track.artist.name} - ${track.title}] Failed to download: Wrong ID`)
1001                         throw new Error(`Failed to download: Wrong ID`)
1002                         return
1003                 }
1004
1005                 /* Album information is necessary for the following tags:
1006                  * album_artist
1007                  * album_artist_picture
1008                  * trackTotal
1009                  * recordType
1010                  * barcode
1011                  * explicit
1012                  * label
1013                  * genres
1014                  * date
1015                 */
1016                 if (parseInt(track.id)>0){
1017                         var ajson
1018                         if (!track.ajson){
1019                                 try{
1020                                         logger.info(`[${track.artist.name} - ${track.title}] Getting album info`)
1021                                         ajson = await s.Deezer.legacyGetAlbum(track.album.id)
1022                                 }catch(err){
1023                                         logger.warn(`[${track.artist.name} - ${track.title}] Album not found, trying to reach deeper`)
1024                                         try{
1025                                                 ajson = await s.Deezer.getAlbum(track.album.id)
1026                                                 ajson.fromNewAPI = true
1027                                         } catch(err){
1028                                                 if(track.fallbackId){
1029                                                         logger.warn(`[${track.artist.name} - ${track.title}] Failed to download track, falling on alternative`)
1030                                                         track = await s.Deezer.getTrack(track.fallbackId)
1031                                                         return downloadTrackObject(track, queueId, settings)
1032                                                 }else{
1033                                                         logger.error(`[${track.artist.name} - ${track.title}] Failed to download: ${err}`)
1034                                                         return
1035                                                 }
1036                                         }
1037                                 }
1038                         }else{
1039                                 ajson = track.ajson
1040                         }
1041                         if (!ajson.fromNewAPI){
1042                                 // Aquiring discTotal (only if necessary)
1043                                 if ((settings.tags.discTotal || settings.createCDFolder) && parseInt(track.id)>0){
1044                                         if (ajson.discTotal){
1045                                                 logger.info(`[${track.artist.name} - ${track.title}] Getting total disc number`);
1046                                                 var discTotal = await s.Deezer.getAlbum(ajson.id)
1047                                                 track.discTotal = discTotal.discTotal
1048                                         }else{
1049                                                 track.discTotal = ajson.discTotal
1050                                         }
1051                                 }
1052                                 track.album.artist = {
1053                                         id: ajson.artist.id,
1054                                         name: ajson.artist.name,
1055                                         picture: ajson.artist.picture_small.split("/56x56-000000-80-0-0.jpg")[0].split(s.Deezer.artistPicturesHost)[1],
1056                                 }
1057                                 track.trackTotal = ajson.nb_tracks
1058                                 track.album.barcode = ajson.upc
1059                                 if (!ajson.record_type){
1060                                         track.recordType = swichReleaseType(track.recordType)
1061                                 }else{
1062                                         track.recordType = ajson.record_type
1063                                 }
1064                                 if (ajson.explicit_lyrics){
1065                                         track.album.explicit = ajson.explicit_lyrics;
1066                                 }
1067                                 if(ajson.label){
1068                                         track.publisher = ajson.label;
1069                                 }
1070                                 if (ajson.release_date) {
1071                                         track.date = {
1072                                                 day: ajson.release_date.slice(8,10),
1073                                                 month: ajson.release_date.slice(5,7),
1074                                                 year: ajson.release_date.slice(0, 4),
1075                                                 slicedYear: (settings.dateFormatYear == "2" ? ajson.release_date.slice(2, 4) : ajson.release_date.slice(0, 4))
1076                                         }
1077                                 }else if(!track.date){
1078                                         track.date = {
1079                                                 day: 0,
1080                                                 month: 0,
1081                                                 year: 0,
1082                                                 slicedYear: 0
1083                                         }
1084                                 }
1085                                 if(ajson.genres && ajson.genres.data[0] && ajson.genres.data[0].name){
1086                                         track.genre = [];
1087                                         genreArray = [];
1088                                         ajson.genres.data.forEach(function(genre){
1089                                                 genreArray.push(genre.name);
1090                                         });
1091                                         uniqueArray(genreArray, track.genre, false)
1092                                 }
1093                         }else{
1094                                 // Missing barcode, genre, recordType
1095                                 track.album = ajson
1096                                 track.date = track.album.date
1097                                 // TODO: Make a loop for each artist
1098
1099                         }
1100
1101                         // Aquiring bpm (only if necessary)
1102                         if (settings.tags.bpm){
1103                                 logger.info(`[${track.artist.name} - ${track.title}] Getting BPM`);
1104                                 try{
1105                                         var bpm = await s.Deezer.legacyGetTrack(track.id)
1106                                         track.bpm = bpm.bpm
1107                                 }catch(err){
1108                                         track.bpm = 0
1109                                 }
1110                         }else{
1111                                 track.bpm = 0
1112                         }
1113
1114                         let separator = settings.multitagSeparator
1115                         if (separator == "null") separator = String.fromCharCode(parseInt("\u0000",16))
1116
1117                         // Autoremoves (Album Version) from the title
1118                         if (settings.removeAlbumVersion){
1119                                 if(track.title.indexOf("Album Version")>-1){
1120                                         track.title = track.title.replace(/\(Album Version\)/g,"")
1121                                         track.title.trim()
1122                                 }
1123                         }
1124
1125                         track.album.artist.pictureUrl = `${s.Deezer.artistPicturesHost}${track.album.artist.picture}/${settings.artworkSize}x${settings.artworkSize}-000000-80-0-0${(settings.PNGcovers ? ".png" : ".jpg")}`
1126                         track.album.pictureUrl = `${s.Deezer.albumPicturesHost}${track.album.picture}/${settings.artworkSize}x${settings.artworkSize}-000000-80-0-0${(settings.PNGcovers ? ".png" : ".jpg")}`
1127                         if(track.contributor){
1128                                 if(track.contributor.composer){
1129                                         track.composerString = []
1130                                         uniqueArray(track.contributor.composer, track.composerString, settings.removeDupedTags)
1131                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.composerString = track.composerString.join(separator)
1132                                 }
1133                                 if(track.contributor.musicpublisher){
1134                                         track.musicpublisherString = []
1135                                         uniqueArray(track.contributor.musicpublisher, track.musicpublisherString, settings.removeDupedTags)
1136                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.musicpublisherString = track.musicpublisherString.join(separator)
1137                                 }
1138                                 if(track.contributor.producer){
1139                                         track.producerString = []
1140                                         uniqueArray(track.contributor.producer, track.producerString, settings.removeDupedTags)
1141                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.producerString = track.producerString.join(separator)
1142                                 }
1143                                 if(track.contributor.engineer){
1144                                         track.engineerString = []
1145                                         uniqueArray(track.contributor.engineer, track.engineerString, settings.removeDupedTags)
1146                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.engineerString = track.engineerString.join(separator)
1147                                 }
1148                                 if(track.contributor.writer){
1149                                         track.writerString = []
1150                                         uniqueArray(track.contributor.writer, track.writerString, settings.removeDupedTags)
1151                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.writerString = track.writerString.join(separator)
1152                                 }
1153                                 if(track.contributor.author){
1154                                         track.authorString = []
1155                                         uniqueArray(track.contributor.author, track.authorString, settings.removeDupedTags)
1156                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.authorString = track.authorString.join(separator)
1157                                 }
1158                                 if(track.contributor.mixer){
1159                                         track.mixerString = [];
1160                                         uniqueArray(track.contributor.mixer, track.mixerString, settings.removeDupedTags)
1161                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.mixerString = track.mixerString.join(separator)
1162                                 }
1163                         }
1164
1165                         if(track.artists || track.artistsString){
1166                                 if (!track.artistsString){
1167                                         track.artistsString = []
1168                                         artistArray = []
1169                                         track.artists.forEach(function(artist){
1170                                                 artistArray.push(artist.name)
1171                                         })
1172                                 }else{
1173                                         artistArray = track.artistsString
1174                                 }
1175                                 uniqueArray(artistArray, track.artistsString, settings.removeDupedTags)
1176                                 let posMainArtist = track.artistsString.indexOf(track.album.artist.name)
1177                                 if (posMainArtist !== -1 && posMainArtist !== 0 && settings.removeDupedTags){
1178                                         let element = track.artistsString[posMainArtist]
1179                                 track.artistsString.splice(posMainArtist, 1)
1180                                 track.artistsString.splice(0, 0, element)
1181                                 }
1182                                 if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.artistsString = track.artistsString.join(separator)
1183                         }
1184                         if (track.genre){
1185                                 if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.genreString = track.genre.join(separator)
1186                         }
1187
1188                         if (track.date){
1189                                 let date
1190                                 switch (settings.dateFormat){
1191                                         case "0": date = `${track.date.slicedYear}-${track.date.month}-${track.date.day}`; break;
1192                                         case "1": date = `${track.date.day}-${track.date.month}-${track.date.slicedYear}`; break;
1193                                         case "2": date = `${track.date.month}-${track.date.day}-${track.date.slicedYear}`; break;
1194                                         case "3": date = `${track.date.slicedYear}-${track.date.day}-${track.date.month}`; break;
1195                                         case "4": date = `${track.date.day}${track.date.month}`; break;
1196                                         default: date = `${track.date.day}${track.date.month}`; break;
1197                                 }
1198                                 track.dateString = date;
1199                         }
1200                 }else{
1201                         track.date = {year: 0,day: 0,month: 0}
1202                 }
1203
1204                 if(settings.plName && !(settings.createArtistFolder || settings.createAlbumFolder) && !settings.numplaylistbyalbum){
1205                         track.trackNumber = (track.position+1).toString();
1206                         track.trackTotal = settings.playlist.fullSize;
1207                         track.discNumber = "1";
1208                         track.discTotal = "1";
1209                 }
1210
1211                 // Auto detect aviable track format from settings
1212                 if (parseInt(track.id)>0){
1213                         switch(settings.maxBitrate){
1214                                 case "9":
1215                                         track.selectedFormat = 9
1216                                         track.selectedFilesize = track.filesize.flac
1217                                         if (track.filesize.flac>0) break
1218                                         if (!settings.fallbackBitrate) throw new Error("Song not found at desired bitrate.")
1219                                 case "3":
1220                                         track.selectedFormat = 3
1221                                         track.selectedFilesize = track.filesize.mp3_320
1222                                         if (track.filesize.mp3_320>0) break
1223                                         if (!settings.fallbackBitrate) throw new Error("Song not found at desired bitrate.")
1224                                 case "1":
1225                                         track.selectedFormat = 1
1226                                         track.selectedFilesize = track.filesize.mp3_128
1227                                         if (track.filesize.mp3_128>0) break
1228                                         if (!settings.fallbackBitrate) throw new Error("Song not found at desired bitrate.")
1229                                 default:
1230                                         track.selectedFormat = 8
1231                                         track.selectedFilesize = track.filesize.default
1232                         }
1233                 }else{
1234                         track.selectedFilesize = track.filesize
1235                         track.selectedFormat = 3
1236                 }
1237
1238                 // TODO: Move to a separate function
1239                 // Generating file name
1240                 if (settings.saveFullArtists && settings.multitagSeparator != null){
1241                         let filename = fixName(`${track.artistsString} - ${track.title}`);
1242                 }else{
1243                         let filename = fixName(`${track.artist.name} - ${track.title}`);
1244                 }
1245                 if (settings.filename) {
1246                         filename = fixName(settingsRegex(track, settings.filename, settings.playlist, settings.saveFullArtists && settings.multitagSeparator != null, settings.paddingSize));
1247                 }
1248
1249                 // TODO: Move to a separate function
1250                 // Generating file path
1251                 let filepath = mainFolder;
1252                 let artistPath;
1253                 if (settings.createArtistFolder || settings.createAlbumFolder) {
1254                         if(settings.plName){
1255                                 filepath += antiDot(fixName(settings.plName)) + path.sep;
1256                         }
1257                         if (settings.createArtistFolder) {
1258                                 if(settings.artName){
1259                                         filepath += antiDot(fixName(settings.artName)) + path.sep;
1260                                 }else{
1261                                         filepath += antiDot(fixName(track.album.artist.name)) + path.sep;
1262                                 }
1263                                 artistPath = filepath;
1264                         }
1265
1266                         if (settings.createAlbumFolder) {
1267                                 if(settings.artName){
1268                                         filepath += antiDot(fixName(settingsRegexAlbum(settings.foldername,settings.artName,settings.albName,track.date.year,track.recordType,track.album.explicit,track.publisher))) + path.sep;
1269                                 }else{
1270                                         filepath += antiDot(fixName(settingsRegexAlbum(settings.foldername,track.album.artist.name,track.album.title,track.date.year,track.recordType,track.album.explicit,track.publisher))) + path.sep;
1271                                 }
1272                         }
1273                 } else if (settings.plName) {
1274                         filepath += antiDot(fixName(settings.plName)) + path.sep;
1275                 } else if (settings.artName) {
1276                         filepath += antiDot(fixName(settingsRegexAlbum(settings.foldername,settings.artName,settings.albName,track.date.year,track.recordType,track.album.explicit,track.publisher))) + path.sep;
1277                 }
1278                 let coverpath = filepath;
1279                 if (track.discTotal > 1 && (settings.artName || settings.createAlbumFolder) && settings.createCDFolder){
1280                         filepath += `CD${track.discNumber +  path.sep}`
1281                 }
1282                 let writePath;
1283
1284                 if(track.selectedFormat == 9){
1285                         writePath = filepath + filename + '.flac';
1286                 }else{
1287                         writePath = filepath + filename + '.mp3';
1288                 }
1289
1290                 if ((settings.syncedlyrics || settings.tags.unsynchronisedLyrics) && track.lyricsId>0){
1291                         let lyr = await s.Deezer.getLyrics(track.id)
1292                         track.syncLyrics = lyr.syncLyrics
1293                         track.unsyncLyrics = lyr.unsyncLyrics
1294                 }
1295
1296                 if(track.syncLyrics && settings.syncedlyrics){
1297                         fs.outputFile(writePath.substring(0,writePath.lastIndexOf('.'))+".lrc",track.syncLyrics,function(){});
1298                 }
1299
1300                 track.playlistData = [0,""]
1301                 if (settings.createM3UFile && (settings.plName || settings.albName)) {
1302                         if (track.position){
1303                                 track.playlistData = [parseInt(track.position), writePath];
1304                         }else{
1305                                 track.playlistData = [track.trackNumber-1, writePath];
1306                         }
1307                 }
1308                 if (fs.existsSync(writePath)) {
1309                         logger.info(`[${track.artist.name} - ${track.title}] Already downloaded`);
1310                         return;
1311                 }else{
1312                         logger.info(`[${track.artist.name} - ${track.title}] Downloading file to ${writePath}`);
1313                 }
1314                 // Get cover image
1315                 if (track.album.pictureUrl) {
1316                         let imgPath;
1317                         //If its not from an album but a playlist.
1318                         if(!(settings.albName || settings.createAlbumFolder)){
1319                                 imgPath = coverArtFolder + (track.album.barcode ? fixName(track.album.barcode) : fixName(`${track.album.artist.name} - ${track.album.title}`))+(settings.PNGcovers ? ".png" : ".jpg");
1320                         }else{
1321                                 if (settings.saveArtwork)
1322                                         imgPath = coverpath + fixName(settingsRegexCover(settings.coverImageTemplate,settings.artName,settings.albName))+(settings.PNGcovers ? ".png" : ".jpg");
1323                                 else
1324                                         imgPath = coverArtFolder + fixName(track.album.barcode ? fixName(track.album.barcode) : fixName(`${track.album.artist.name} - ${track.album.title}`))+(settings.PNGcovers ? ".png" : ".jpg");
1325                         }
1326                         if(fs.existsSync(imgPath)){
1327                                 track.album.picturePath = (imgPath).replace(/\\/g, "/")
1328                                 logger.info(`[${track.artist.name} - ${track.title}] Starting the download process CODE:1`)
1329                         }else{
1330                                 try{
1331                                         var body = await request.get(track.album.pictureUrl, {strictSSL: false,encoding: 'binary'})
1332                                         fs.outputFileSync(imgPath,body,'binary')
1333                                         track.album.picturePath = (imgPath).replace(/\\/g, "/")
1334                                         logger.info(`[${track.artist.name} - ${track.title}] Starting the download process CODE:2`)
1335                                 }catch(error){
1336                                         logger.error(`[${track.artist.name} - ${track.title}] Cannot download Album Image: ${error.stack}`)
1337                                         track.album.pictureUrl = undefined
1338                                         track.album.picturePath = undefined
1339                                 }
1340                         }
1341                 }else{
1342                         track.album.pictureUrl = undefined
1343                         logger.info(`[${track.artist.name} - ${track.title}] Starting the download process CODE:3`)
1344                 }
1345
1346                 // Get Artist Image
1347                 if (parseInt(this.id)>0 && track.album.artist.picture && settings.saveArtworkArtist) {
1348                         let imgPath;
1349                         if(settings.createArtistFolder){
1350                                 imgPath = artistPath + antiDot(fixName(settingsRegexArtistCover(settings.artistImageTemplate,track.album.artist.name)))+(settings.PNGcovers ? ".png" : ".jpg");
1351                                 if(!fs.existsSync(imgPath)){
1352                                         try{
1353                                                 var body = await request.get(track.album.artist.pictureUrl, {strictSSL: false,encoding: 'binary'})
1354                                                 if (body.indexOf("unauthorized")>-1) throw new Error("Unauthorized")
1355                                                 fs.outputFileSync(imgPath,body,'binary')
1356                                                 logger.info(`[${track.artist.name} - ${track.title}] Saved Artist Image`)
1357                                         }catch(err){
1358                                                 logger.error(`[${track.artist.name} - ${track.title}] Cannot download Artist Image: ${err.stack}`)
1359                                         }
1360                                 }
1361                         }
1362                 }
1363
1364                 let tempPath
1365                 if(parseInt(track.id)>0)
1366                         tempPath = `${filepath}${track.id}_${track.selectedFormat}.temp`
1367                 else
1368                         tempPath = writePath
1369
1370                 logger.info(`[${track.artist.name} - ${track.title}] Downloading track`)
1371                 var downloadingPromise = new Promise((resolve, reject)=>{
1372                         let req = requestOld.get({url: track.getDownloadUrl(track.selectedFormat), strictSSL: false, headers: s.Deezer.httpHeaders, encoding: 'binary'}, function (error, response, body) {
1373                                 if (error){
1374                                         logger.error(`[${track.artist.name} - ${track.title}] Downloading error: ${error}`)
1375                                         reject("Downloading error: "+error)
1376                                 }
1377                                 if (!s.downloadQueue[queueId]){
1378                                         fs.remove(tempPath)
1379                                         return reject()
1380                                 }
1381                                 logger.info(`[${track.artist.name} - ${track.title}] Decrypting track`)
1382                                 var decryptedSource = s.Deezer.decryptDownload(Buffer.from(body, 'binary'), track.id)
1383                                 try{
1384                                         fs.outputFileSync(tempPath,decryptedSource)
1385                                         resolve()
1386                                 }catch(err){
1387                                         return logger.error(`[${track.artist.name} - ${track.title}] Decryption error: ${err.stack}`)
1388                                 }
1389                         }).on("data", function(data) {
1390                                 if (!s.downloadQueue[queueId]) reject()
1391                         })
1392                         if((s.downloadQueue[queueId]) && s.downloadQueue[queueId].type == "track"){
1393                                 let chunkLength = 0
1394                                 req.on("data", function(data) {
1395                                         if (!s.downloadQueue[queueId]) reject()
1396                                         chunkLength += data.length
1397                                         try{
1398                                                 if (!s.downloadQueue[queueId].percentage) {
1399                                                         s.downloadQueue[queueId].percentage = 0
1400                                                 }
1401                                                 let complete = track.selectedFilesize
1402                                                 let percentage = (chunkLength / complete) * 100;
1403                                                 if ((percentage - s.downloadQueue[queueId].percentage > 1) || (chunkLength == complete)) {
1404                                                         s.downloadQueue[queueId].percentage = percentage
1405                                                         s.emit("downloadProgress", {
1406                                                                 queueId: queueId,
1407                                                                 percentage: s.downloadQueue[queueId].percentage-5
1408                                                         })
1409                                                 }
1410                                         }catch(err){}
1411                                 })
1412                         }
1413                 })
1414                 try{
1415                         await downloadingPromise
1416                 }catch(err){
1417                         if (err) logger.error(`downloadTrackObject failed: ${err.stack ? err.stack : err}`)
1418                         return
1419                 }
1420
1421                 logger.info(`[${track.artist.name} - ${track.title}] Adding Tags`)
1422                 if (parseInt(track.id)>0){
1423                         if(track.selectedFormat == 9){
1424                                 let flacComments = [];
1425                                 if (settings.tags.title)
1426                                         flacComments.push('TITLE=' + track.title);
1427                                 if (settings.tags.album)
1428                                         flacComments.push('ALBUM=' + track.album.title);
1429                                 if (settings.tags.albumArtist)
1430                                         flacComments.push('ALBUMARTIST=' + track.album.artist.name);
1431                                 if (settings.tags.trackNumber)
1432                                         flacComments.push('TRACKNUMBER=' + track.trackNumber);
1433                                 if (settings.tags.discNumber)
1434                                         flacComments.push('DISCNUMBER=' + track.discNumber);
1435                                 if (settings.tags.trackTotal)
1436                                         flacComments.push('TRACKTOTAL=' + track.trackTotal);
1437                                 if (settings.tags.explicit)
1438                                         flacComments.push('ITUNESADVISORY=' + track.explicit);
1439                                 if (settings.tags.isrc)
1440                                         flacComments.push('ISRC=' + track.ISRC);
1441                                 if (settings.tags.artist && track.artistsString)
1442                                         if (Array.isArray(track.artistsString)){
1443                                                 track.artistsString.forEach(x=>{
1444                                                         flacComments.push('ARTIST=' + x);
1445                                                 });
1446                                         }else{
1447                                                 flacComments.push('ARTIST=' + track.artistsString);
1448                                         }
1449                                 if (settings.tags.discTotal)
1450                                         flacComments.push('DISCTOTAL='+splitNumber(track.discTotal,true));
1451                                 if (settings.tags.length)
1452                                         flacComments.push('LENGTH=' + track.length);
1453                                 if (settings.tags.barcode && track.album.barcode)
1454                                         flacComments.push('BARCODE=' + track.album.barcode);
1455                                 if (track.unsyncLyrics && settings.tags.unsynchronisedLyrics)
1456                                         flacComments.push('LYRICS='+track.unsyncLyrics.lyrics);
1457                                 if (track.genreString && settings.tags.genre)
1458                                         if (Array.isArray(track.genreString)){
1459                                                 track.genreString.forEach(x=>{
1460                                                         flacComments.push('GENRE=' + x);
1461                                                 });
1462                                         }else{
1463                                                 flacComments.push('GENRE=' + track.genreString);
1464                                         }
1465                                 if (track.copyright && settings.tags.copyright)
1466                                         flacComments.push('COPYRIGHT=' + track.copyright);
1467                                 if (0 < parseInt(track.date.year)){
1468                                         if (settings.tags.year)
1469                                                 flacComments.push('YEAR=' + track.date.year);
1470                                         if (settings.tags.date)
1471                                         flacComments.push('DATE=' + track.dateString);
1472                                 }
1473                                 if (0 < parseInt(track.bpm) && settings.tags.bpm)
1474                                         flacComments.push('BPM=' + track.bpm);
1475                                 if(track.publisher && settings.tags.publisher)
1476                                         flacComments.push('PUBLISHER=' + track.publisher);
1477                                 if(track.composerString && settings.tags.composer)
1478                                         if (Array.isArray(track.composerString)){
1479                                                 track.composerString.forEach(x=>{
1480                                                         flacComments.push('COMPOSER=' + x);
1481                                                 });
1482                                         }else{
1483                                                 flacComments.push('COMPOSER=' + track.composerString);
1484                                         }
1485                                 if(track.musicpublisherString && settings.tags.musicpublisher)
1486                                         if (Array.isArray(track.musicpublisherString)){
1487                                                 track.musicpublisherString.forEach(x=>{
1488                                                         flacComments.push('ORGANIZATION=' + x);
1489                                                 });
1490                                         }else{
1491                                                 flacComments.push('ORGANIZATION=' + track.musicpublisherString);
1492                                         }
1493                                 if(track.mixerString && settings.tags.mixer)
1494                                         if (Array.isArray(track.mixerString)){
1495                                                 track.mixerString.forEach(x=>{
1496                                                         flacComments.push('MIXER=' + x);
1497                                                 });
1498                                         }else{
1499                                                 flacComments.push('MIXER=' + track.mixerString);
1500                                         }
1501                                 if(track.authorString && settings.tags.author)
1502                                         if (Array.isArray(track.authorString)){
1503                                                 track.authorString.forEach(x=>{
1504                                                         flacComments.push('AUTHOR=' + x);
1505                                                 });
1506                                         }else{
1507                                                 flacComments.push('AUTHOR=' + track.authorString);
1508                                         }
1509                                 if(track.writerString && settings.tags.writer)
1510                                         if (Array.isArray(track.writerString)){
1511                                                 track.writerString.forEach(x=>{
1512                                                         flacComments.push('WRITER=' + x);
1513                                                 });
1514                                         }else{
1515                                                 flacComments.push('WRITER=' + track.writerString);
1516                                         }
1517                                 if(track.engineerString && settings.tags.engineer)
1518                                         if (Array.isArray(track.engineerString)){
1519                                                 track.engineerString.forEach(x=>{
1520                                                         flacComments.push('ENGINEER=' + x);
1521                                                 });
1522                                         }else{
1523                                                 flacComments.push('ENGINEER=' + track.engineerString);
1524                                         }
1525                                 if(track.producerString && settings.tags.producer)
1526                                         if (Array.isArray(track.producerString)){
1527                                                 track.producerString.forEach(x=>{
1528                                                         flacComments.push('PRODUCER=' + x);
1529                                                 });
1530                                         }else{
1531                                                 flacComments.push('PRODUCER=' + track.producerString);
1532                                         }
1533                                 if(track.replayGain && settings.tags.replayGain)
1534                                         flacComments.push('REPLAYGAIN_TRACK_GAIN=' + track.replayGain);
1535
1536                                 const reader = fs.createReadStream(tempPath);
1537                                 const writer = fs.createWriteStream(writePath);
1538                                 let processor = new mflac.Processor({parseMetaDataBlocks: true});
1539                                 let vendor = 'reference libFLAC 1.2.1 20070917';
1540                                 let cover = null;
1541                                 if(track.album.picturePath && settings.tags.cover){
1542                                         cover = fs.readFileSync(track.album.picturePath)
1543                                 }
1544                                 let mdbVorbisPicture
1545                                 let mdbVorbisComment
1546                                 processor.on('preprocess', (mdb) => {
1547                                         // Remove existing VORBIS_COMMENT and PICTURE blocks, if any.
1548                                         if (mflac.Processor.MDB_TYPE_VORBIS_COMMENT === mdb.type) {
1549                                                 mdb.remove();
1550                                         } else if (mflac.Processor.MDB_TYPE_PICTURE === mdb.type) {
1551                                                 mdb.remove();
1552                                         }
1553                                         if (mdb.isLast) {
1554                                                 if(cover){
1555                                                         mdbVorbisPicture = mflac.data.MetaDataBlockPicture.create(true, 3, `image/${(settings.PNGcovers ? "png" : "jpeg")}`, '', settings.artworkSize, settings.artworkSize, 24, 0, cover);
1556                                                 }
1557                                                 mdbVorbisComment = mflac.data.MetaDataBlockVorbisComment.create(!cover, vendor, flacComments);
1558                                                 mdb.isLast = false;
1559                                         }
1560                                 });
1561                                 processor.on('postprocess', (mdb) => {
1562                                         if (mflac.Processor.MDB_TYPE_VORBIS_COMMENT === mdb.type && null !== mdb.vendor) {
1563                                                 vendor = mdb.vendor;
1564                                         }
1565                                         if (mdbVorbisPicture && mdbVorbisComment) {
1566                                                         processor.push(mdbVorbisComment.publish());
1567                                                         processor.push(mdbVorbisPicture.publish());
1568                                                 }else if(mdbVorbisComment){
1569                                                         processor.push(mdbVorbisComment.publish());
1570                                         }
1571                                 });
1572                                 reader.on('end', () => {
1573                                         fs.remove(tempPath);
1574                                 });
1575                                 await reader.pipe(processor).pipe(writer);
1576                         }else{
1577                                 const songBuffer = fs.readFileSync(tempPath);
1578                                 const writer = new ID3Writer(songBuffer);
1579                                 if (settings.tags.title)
1580                                         writer.setFrame('TIT2', track.title)
1581                                 if (settings.tags.artist)
1582                                         writer.setFrame('TPE1', [track.artistsString])
1583                                 if (settings.tags.album)
1584                                         writer.setFrame('TALB', track.album.title)
1585                                 if (settings.tags.albumArtist && track.album.artist)
1586                                         writer.setFrame('TPE2', track.album.artist.name)
1587                                 if (settings.tags.trackNumber)
1588                                         writer.setFrame('TRCK', (settings.tags.trackTotal ? track.trackNumber+"/"+track.trackTotal : track.trackNumber))
1589                                 if (settings.tags.discNumber)
1590                                         writer.setFrame('TPOS', (settings.tags.discTotal ? track.discNumber+"/"+track.discTotal : track.discNumber))
1591                                 if (settings.tags.isrc)
1592                                         writer.setFrame('TSRC', track.ISRC);
1593
1594                                 if (settings.tags.length)
1595                                         writer.setFrame('TLEN', track.length);
1596                                 if (settings.tags.barcode && track.album.barcode)
1597                                         writer.setFrame('TXXX', {
1598                                                 description: 'BARCODE',
1599                                                 value: track.album.barcode
1600                                         });
1601                                 if(track.album.picturePath && settings.tags.cover){
1602                                         const coverBuffer = fs.readFileSync(track.album.picturePath);
1603                                         writer.setFrame('APIC', {
1604                                                 type: 3,
1605                                                 data: coverBuffer,
1606                                                 description: ''
1607                                         });
1608                                 }
1609                                 if(track.unsyncLyrics && settings.tags.unsynchronisedLyrics)
1610                                         writer.setFrame('USLT', track.unsyncLyrics);
1611                                 if(track.publisher && settings.tags.publisher)
1612                                         writer.setFrame('TPUB', track.publisher);
1613                                 if(track.genreString && settings.tags.genre)
1614                                         writer.setFrame('TCON', [track.genreString]);
1615                                 if(track.copyright && settings.tags.copyright)
1616                                         writer.setFrame('TCOP', track.copyright);
1617                                 if (0 < parseInt(track.date.year)) {
1618                                         if (settings.tags.date)
1619                                                 writer.setFrame('TDAT', track.dateString);
1620                                         if (settings.tags.year)
1621                                                 writer.setFrame('TYER', track.date.year);
1622                                 }
1623                                 if (0 < parseInt(track.bpm) && settings.tags.bpm)
1624                                         writer.setFrame('TBPM', track.bpm);
1625                                 if(track.composerString && settings.tags.composer)
1626                                         writer.setFrame('TCOM', [track.composerString]);
1627                                 if(track.replayGain && settings.tags.replayGain)
1628                                         writer.setFrame('TXXX', {
1629                                                 description: 'REPLAYGAIN_TRACK_GAIN',
1630                                                 value: track.replayGain
1631                                         });
1632                                 writer.addTag();
1633                                 const taggedSongBuffer = Buffer.from(writer.arrayBuffer);
1634                                 fs.writeFileSync(writePath, taggedSongBuffer);
1635                                 fs.remove(tempPath);
1636                         }
1637                 }
1638                 logger.info(`[${track.artist.name} - ${track.title}] Downloaded`)
1639         }
1640 })
1641
1642 // Helper functions
1643
1644 /**
1645  * Updates individual parameters in the settings file
1646  * @param config
1647  * @param value
1648  */
1649 function updateSettingsFile(config, value) {
1650         configFile.userDefined[config] = value;
1651
1652         fs.outputFile(configFileLocation, JSON.stringify(configFile, null, 2), function (err) {
1653                 if (err) return;
1654                 logger.info("Settings updated");
1655
1656                 // FIXME: Endless Loop, due to call from initFolders()...crashes soon after startup
1657                 // initFolders();
1658         });
1659 }
1660
1661 function fixName (txt) {
1662   const regEx = /[\0\/\\:*?"<>|]/g;
1663   return txt.replace(regEx, '_');
1664 }
1665
1666 function antiDot(str){
1667         while(str[str.length-1] == "." || str[str.length-1] == " " || str[str.length-1] == "\n"){
1668                 str = str.substring(0,str.length-1);
1669         }
1670         if(str.length < 1){
1671                 str = "dot";
1672         }
1673         return fixName(str);
1674 }
1675
1676 /**
1677  * Initialize the temp folder for covers and main folder for downloads
1678  */
1679 function initFolders() {
1680         // Check if main folder exists
1681         if (!fs.existsSync(mainFolder)) {
1682                 mainFolder = defaultDownloadFolder;
1683                 updateSettingsFile('downloadLocation', defaultDownloadFolder);
1684         }
1685         //fs.removeSync(coverArtFolder);
1686         //fs.ensureFolderSync(coverArtFolder);
1687 }
1688
1689 /**
1690  * Creates the name of the tracks replacing wildcards to correct metadata
1691  * @param track
1692  * @param filename
1693  * @param playlist
1694  * @returns {XML|string|*}
1695  */
1696 function settingsRegex(track, filename, playlist, saveFullArtists, paddingSize) {
1697         try{
1698                 filename = filename.replace(/%title%/g, track.title);
1699                 filename = filename.replace(/%album%/g, track.album);
1700                 filename = filename.replace(/%artist%/g, (saveFullArtists ? track.artistsString : track.artist.name));
1701                 filename = filename.replace(/%year%/g, track.date.year);
1702                 filename = filename.replace(/%label%/g, track.publisher);
1703                 if(typeof track.trackNumber != 'undefined'){
1704                         if(configFile.userDefined.padtrck){
1705                                  filename = filename.replace(/%number%/g, pad(track.trackNumber, (parseInt(paddingSize)>0 ? parseInt(paddingSize) : track.trackTotal)));
1706                         }else{
1707                                 filename = filename.replace(/%number%/g, track.trackNumber);
1708                         }
1709                 } else {
1710                         filename = filename.replace(/%number%/g, '');
1711                 }
1712                 filename = filename.replace(/%explicit%/g, (track.explicit==="1" ? (filename.indexOf(/[^%]explicit/g)>-1 ? "" : "(Explicit Version)") : ""));
1713                 return filename.trim();
1714         }catch(e){
1715                 if (typeof e == "Error") throw e; else throw new Error(e)
1716         }
1717 }
1718
1719 /**
1720  * Creates the name of the albums folder replacing wildcards to correct metadata
1721  * @param metadata
1722  * @param foldername
1723  * @returns {XML|string|*}
1724  */
1725 function settingsRegexAlbum(foldername, artist, album, year, rtype, explicit, publisher) {
1726         foldername = foldername.replace(/%album%/g, album);
1727         foldername = foldername.replace(/%artist%/g, artist);
1728         foldername = foldername.replace(/%year%/g, year);
1729         if (rtype){
1730                 foldername = foldername.replace(/%type%/g, rtype[0].toUpperCase() + rtype.substring(1));
1731         }else{
1732                 foldername = foldername.replace(/%type%/g, "");
1733         }
1734         foldername = foldername.replace(/%label%/g, publisher);
1735         foldername = foldername.replace(/%explicit%/g, (explicit ? (foldername.indexOf(/[^%]explicit/g)>-1 ? "" : "(Explicit)") : ""));
1736         return foldername.trim();
1737 }
1738
1739 function settingsRegexCover(foldername, artist, name) {
1740         foldername = foldername.replace(/%name%/g, name);
1741         foldername = foldername.replace(/%artist%/g, artist);
1742         return foldername;
1743 }
1744
1745 function settingsRegexArtistCover(foldername, artist) {
1746         foldername = foldername.replace(/%artist%/g, artist);
1747         return foldername;
1748 }
1749
1750 /**
1751  * Pad number with 0s so max and str have the same nuber of characters
1752  * @param str
1753  * @param max
1754  * @returns {String|string|*}
1755  */
1756 function pad(str, max) {
1757         str = str.toString();
1758         max = max.toString();
1759         return str.length < max.length || str.length == 1 ? pad("0" + str, max) : str;
1760 }
1761
1762 /**
1763  * Splits the %number%
1764  * @param string str
1765  * @return string
1766  */
1767 function splitNumber(str,total){
1768         str = str.toString();
1769         let i = str.indexOf("/");
1770         if(total && i > 0){
1771                 return str.slice(i+1, str.length);
1772         }else if(i > 0){
1773                 return str.slice(0, i);
1774         }else{
1775                 return str;
1776         }
1777         return i > 0 ? str.slice(0, i) : str;
1778 }
1779
1780 function swichReleaseType(id){
1781         switch (id) {
1782                 case "0":
1783                         return "Album";
1784                 case "1":
1785                         return "Single";
1786                 case "3":
1787                         return "EP";
1788                 default:
1789                         return id;
1790         }
1791 }
1792
1793 function uniqueArray(origin, destination, removeDupes=true){
1794         Array.from(new Set(origin)).forEach(function(x){
1795                 if(destination.indexOf(x) == -1)
1796                         destination.push(x);
1797         });
1798         if (removeDupes){
1799                 destination.forEach((name,index)=>{
1800                         destination.forEach((name2,index2)=>{
1801                                 if(!(index===index2) && (name.indexOf(name2)!== -1)){
1802                                         destination.splice(index, 1);
1803                                 }
1804                         })
1805                 })
1806         }
1807 }
1808
1809 // Show crash error in console for debugging
1810 process.on('unhandledRejection', function (err) {
1811         if (err) logger.error(err.stack ? err.stack : err)
1812
1813 })
1814 process.on('uncaughtException', function (err) {
1815         if (err) logger.error(err.stack ? err.stack : err)
1816 })
1817
1818 // Exporting vars
1819 module.exports.mainFolder = mainFolder
1820 module.exports.defaultSettings = defaultSettings
1821 module.exports.defaultDownloadFolder = defaultDownloadFolder