d361cdcf9f6390d229a9cd38892f336a36f19298
[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         /*
397          * Downloading section of the app
398         */
399
400         // Gets data from the frontend and creates the track object
401         async function downloadTrack(data){
402                 logger.info(`Added to Queue ${data.id}`)
403                 try{
404                         var track = await s.Deezer.getTrack(data.id)
405                         let _track = {
406                                 name: track.title,
407                                 artist: track.artist.name,
408                                 size: 1,
409                                 downloaded: 0,
410                                 failed: 0,
411                                 queueId: `id${Math.random().toString(36).substring(2)}`,
412                                 id: `${track.id}:${data.settings.maxBitrate}`,
413                                 type: 'track',
414                                 settings: data.settings || {},
415                                 obj: track,
416                         }
417                         addToQueue(_track)
418                 }catch(err){
419                         logger.error(`downloadTrack failed: ${err.stack ? err.stack : err}`)
420                         return
421                 }
422         }
423         s.on("downloadtrack", async data=>{await downloadTrack(data)})
424
425         // Gets data from the frontend and creates the album object
426         async function downloadAlbum(data){
427                 logger.info(`Added to Queue ${data.id}`)
428                 try{
429                         var album = await s.Deezer.legacyGetAlbum(data.id)
430                         if (data.settings.tags.discTotal || data.settings.createCDFolder){
431                                 var discTotal = await s.Deezer.getAlbum(data.id)
432                                 album.discTotal = discTotal.discTotal
433                         }
434                         album.tracks = await s.Deezer.getAlbumTracks(data.id)
435                         let _album = {
436                                 name: album.title,
437                                 artist: album.artist.name,
438                                 size: album.tracks.length,
439                                 downloaded: 0,
440                                 failed: 0,
441                                 queueId: `id${Math.random().toString(36).substring(2)}`,
442                                 id: `${album.id}:${data.settings.maxBitrate}`,
443                                 type: 'album',
444                                 settings: data.settings || {},
445                                 obj: album,
446                         }
447                         addToQueue(_album)
448                         return
449                 }catch(err){
450                         logger.error(`downloadAlbum failed: ${err.stack ? err.stack : err}`)
451                         return
452                 }
453         }
454         s.on("downloadalbum", async data=>{await downloadAlbum(data)});
455
456         // Gets data from the frontend and creates for each album an album object
457         async function downloadArtist(data){
458                 logger.info(`Added to Queue ${data.id}`)
459                 try{
460                         var albums = await s.Deezer.legacyGetArtistAlbums(data.id);
461                         (function sendAllAlbums(i) {
462                                 setTimeout(function () {
463                                         data.id = albums.data[albums.data.length-1-i].id
464                                         downloadAlbum(JSON.parse(JSON.stringify(data)))
465                                         if (--i+1) sendAllAlbums(i)
466                                 }, 100)
467                         })(albums.data.length-1)
468                 }catch(err){
469                         logger.error(`downloadArtist failed: ${err.stack ? err.stack : err}`)
470                         return
471                 }
472         }
473         s.on("downloadartist", async data=>{ await downloadArtist(data)});
474
475         // Gets data from the frontend and creates the playlist object
476         async function downloadPlaylist(data){
477                 logger.info(`Added to Queue ${data.id}`)
478                 try{
479                         var playlist = await s.Deezer.legacyGetPlaylist(data.id)
480                         playlist.tracks = await s.Deezer.getPlaylistTracks(data.id)
481                         let _playlist = {
482                                 name: playlist.title,
483                                 artist: playlist.creator.name,
484                                 size: playlist.tracks.length,
485                                 downloaded: 0,
486                                 failed: 0,
487                                 queueId: `id${Math.random().toString(36).substring(2)}`,
488                                 id: `${playlist.id}:${data.settings.maxBitrate}`,
489                                 type: "playlist",
490                                 settings: data.settings || {},
491                                 obj: playlist,
492                         }
493                         addToQueue(_playlist)
494                 }catch(err){
495                         logger.error(`downloadPlaylist failed: ${err.stack ? err.stack : err}`)
496                         return
497                 }
498         }
499         s.on("downloadplaylist", data=>{downloadPlaylist(data)});
500
501         // Gets data from the frontend and creates the object fot the artist top tracks
502         async function downloadArtistTop(data){
503                 logger.info(`Added to Queue ${data.id}`)
504                 try{
505                         var artist = await s.Deezer.legacyGetArtist(data.id)
506                         artist.tracks = await s.Deezer.getArtistTopTracks(data.id)
507                         let _playlist = {
508                                 name: artist.name + " Most played tracks",
509                                 artist: artist.name,
510                                 size: artist.tracks.length,
511                                 downloaded: 0,
512                                 failed: 0,
513                                 queueId: `id${Math.random().toString(36).substring(2)}`,
514                                 id: `${artist.id}:${data.settings.maxBitrate}`,
515                                 type: "playlist",
516                                 settings: data.settings || {},
517                                 obj: artist,
518                         }
519                         addToQueue(_playlist)
520                 }catch(err){
521                         logger.error(`downloadArtistTop failed: ${err.stack ? err.stack : err}`)
522                         return
523                 }
524         }
525         s.on("downloadartisttop", data=>{downloadArtistTop(data)});
526
527         // Gets data from the frontend and creates the spotify playlist object
528         async function downloadSpotifyPlaylist(data){
529                 logger.info(`Added to Queue ${data.id}`)
530                 if (spotifySupport){
531                         try{
532                                 let creds = await Spotify.clientCredentialsGrant()
533                                 Spotify.setAccessToken(creds.body['access_token'])
534                                 let first = true
535                                 let offset = 0
536                                 do{
537                                         var resp = await Spotify.getPlaylist(data.id, {fields: "id,name,owner,images,tracks(total,items(track(artists,name,album,external_ids)))", offset: offset*100})
538                                         if (first){
539                                                 var _playlist = {
540                                                         name: resp.body.name,
541                                                         artist: (resp.body.owner.display_name ? resp.body.owner.display_name : resp.body.owner.id),
542                                                         size: resp.body.tracks.total,
543                                                         downloaded: 0,
544                                                         failed: 0,
545                                                         queueId: `id${Math.random().toString(36).substring(2)}`,
546                                                         settings: data.settings || {},
547                                                         id: `${resp.body.id}:${data.settings.maxBitrate}`,
548                                                         type: "spotifyplaylist",
549                                                         obj: resp.body
550                                                 }
551                                                 var numPages=Math.floor((_playlist.size-1)/100)
552                                                 var trackList = new Array(_playlist.size)
553                                                 first = false
554                                         }
555                                         resp.body.tracks.items.forEach((track, i) => {
556                                                 trackList[(offset*20)+i] = track.track
557                                         })
558                                         offset++
559                                 }while(offset<=numPages)
560                                 _playlist.obj.tracks = trackList
561                                 addToQueue(_playlist)
562                         }catch(err){
563                                 logger.error(`downloadSpotifyPlaylist failed: ${err.stack ? err.stack : err}`)
564                                 return
565                         }
566                 }else{
567                         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>"})
568                 }
569         }
570         s.on("downloadspotifyplaylist", data=>{downloadSpotifyPlaylist(data)})
571
572         // Converts the spotify track to a deezer one
573         // It tries first with the isrc (best way of conversion)
574         // Fallbacks to the old way, using search
575         async function convertSpotify2Deezer(track){
576                 try{
577                         if (track.external_ids.isrc){
578                                 let resp = await s.Deezer.legacyGetTrackByISRC(track.external_ids.isrc)
579                                 return resp.id
580                         }
581                 }catch(err){
582                         logger.warn("ISRC not found, falling back to old method")
583                 }
584
585                 let resp
586                 track.artists[0].name = track.artists[0].name.replace(/–/g,"-").replace(/’/g, "'")
587                 track.name = track.name.replace(/–/g,"-").replace(/’/g, "'")
588                 track.album.name = track.album.name.replace(/–/g,"-").replace(/’/g, "'")
589                 try{
590                         resp = await s.Deezer.legacySearch(`artist:"${track.artists[0].name}" track:"${track.name}" album:"${track.album.name}"`, "track", 1)
591                 }catch(err){logger.err(`Convert2Spotify: ${err.stack ? err.stack : err}`)}
592                 if (resp.data) return resp.data[0].id
593                 try{
594                         resp = await s.Deezer.legacySearch(`artist:"${track.artists[0].name}" track:"${track.name}"`, "track", 1)
595                 }catch(err){logger.err(`Convert2Spotify: ${err.stack ? err.stack : err}`)}
596                 if (resp.data) return resp.data[0].id
597                 if (track.name.indexOf("(") < track.name.indexOf(")")){
598                         try{
599                                 resp = await s.Deezer.legacySearch(`artist:"${track.artists[0].name}" track:"${track.name.split("(")[0]}"`, "track", 1)
600                         }catch(err){logger.err(`Convert2Spotify: ${err.stack ? err.stack : err}`)}
601                         if (resp.data) return resp.data[0].id
602                 }else if (track.indexOf(" - ")>0){
603                         try{
604                                 resp = await s.Deezer.legacySearch(`artist:"${track.artists[0].name}" track:"${track.name.split(" - ")[0]}"`, "track", 1)
605                         }catch(err){logger.err(`Convert2Spotify: ${err.stack ? err.stack : err}`)}
606                         if (resp.data) return resp.data[0].id
607                 }else{
608                         return 0
609                 }
610                 return 0
611         }
612
613         // All the above functions call this function
614         // It adds the object to an array and adds the promise for the download to the object itself
615         function addToQueue(object) {
616                 s.downloadQueue[object.queueId] = object
617                 s.emit('addToQueue', object)
618                 s.downloadQueue[object.queueId].downloadQueuePromise = s.dqueue.push(addNextDownload, { args: object })
619         }
620
621         // Wrapper for queue download
622         function addNextDownload(obj, token){
623                 return new Promise(async (resolve, reject) => {
624       await queueDownload(obj)
625                         resolve()
626     }).then(() => new Promise((resolve, reject) => {
627       if (token.cancelled)
628         reject()
629       else
630         resolve()
631     }))
632         }
633
634         // Cancels download
635         // TODO: Might check this one, could be a little buggy
636         function cancelDownload(queueId, cleanAll=false){
637                 if (!queueId) return
638                 let cancel = false
639                 let cancelSuccess
640                 if (s.downloadQueue[queueId]){
641                         cancel = true;
642                         if (s.downloadQueue[queueId].downloadQueuePromise) s.downloadQueue[queueId].downloadQueuePromise.cancel()
643                         if (s.downloadQueue[Object.keys(s.downloadQueue)[0]].queueId == queueId) {
644                                 s.trackQueue = queue({
645                                         autostart: true,
646                                         concurrency: s.trackQueue.concurrency
647                                 })
648                         }
649                         delete s.downloadQueue[queueId]
650                 }
651
652                 if (cancel) {
653                         s.emit("cancelDownload", {queueId: queueId, cleanAll: cleanAll});
654                 }
655         }
656         s.on("cancelDownload", function (data) {cancelDownload(data.queueId)});
657
658         s.on("cancelAllDownloads", function(data){
659                 data.queueList.forEach(x=>{
660                         cancelDownload(x, true);
661                 })
662                 s.emit("cancelAllDownloads")
663         })
664
665         /*function getNextDownload() {
666                 if (s.currentItem != null || Object.keys(s.downloadQueue).length == 0) {
667                         if (Object.keys(s.downloadQueue).length == 0 && s.currentItem == null) {
668                                 s.emit("emptyDownloadQueue", {})
669                         }
670                         return null
671                 }
672                 s.currentItem = s.downloadQueue[Object.keys(s.downloadQueue)[0]]
673                 return s.currentItem
674         }*/
675
676         //downloadQueue: the tracks in the queue to be downloaded
677         //queueId: random number generated when user clicks download on something
678         async function queueDownload(downloading) {
679                 if (!downloading) return
680
681                 if (downloading.type != "spotifyplaylist"){
682                         s.emit("downloadStarted", {queueId: downloading.queueId})
683                 }
684
685                 downloading.errorLog = "";
686                 downloading.searchedLog = "";
687
688                 let filePath;
689                 logger.info(`Registered ${downloading.type}: ${downloading.id} | ${downloading.artist} - ${downloading.name}`);
690                 switch(downloading.type){
691                         /*
692                         *  TRACK DOWNLOAD
693                         */
694                         case "track":
695                                 var downloadPromise = new Promise(async (resolve,reject)=>{
696                                         try{
697                                                 await downloadTrackObject(downloading.obj, downloading.queueId, downloading.settings)
698                                                 downloading.downloaded++
699                                         }catch(err){
700                                                 logger.error(`queueDownload:track failed: ${err.stack ? err.stack : err}`)
701                                                 downloading.failed++
702                                         }
703                                         s.emit("updateQueue", {
704                                                 name: downloading.name,
705                                                 artist: downloading.artist,
706                                                 size: downloading.size,
707                                                 downloaded: downloading.downloaded,
708                                                 failed: downloading.failed,
709                                                 queueId: downloading.queueId,
710                                                 id: downloading.id,
711                                                 type: downloading.type,
712                                         })
713                                         s.emit("downloadProgress", {
714                                                 queueId: downloading.queueId,
715                                                 percentage: 100
716                                         })
717                                         resolve()
718                                 })
719                                 try{
720                                         await downloadPromise
721                                 }catch(err){
722                                         if (err) logger.error(`queueDownload:track failed: ${err.stack ? err.stack : err}`)
723                                         logger.info("Downloading Stopped")
724                                 }
725                         break
726                         /*
727                         *  ALBUM DOWNLOAD
728                         */
729                         case "album":
730                                 downloading.settings.albName = downloading.name;
731                                 downloading.settings.artName = downloading.artist;
732                                 downloading.playlistArr = Array(downloading.size);
733                                 filePath = mainFolder;
734                                 if (downloading.settings.createArtistFolder || downloading.settings.createAlbumFolder) {
735                                         if (downloading.settings.createArtistFolder) {
736                                                 filePath += antiDot(fixName(downloading.settings.artName)) + path.sep;
737                                         }
738                                         if (downloading.settings.createAlbumFolder) {
739                                                 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;
740                                         }
741                                 } else if (downloading.settings.artName) {
742                                         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;
743                                 }
744                                 let ajson = {
745                                         artist : downloading.obj.artist,
746                                         nb_tracks : downloading.obj.nb_tracks,
747                                         upc : downloading.obj.upc,
748                                         record_type : downloading.obj.record_type,
749                                         explicit_lyrics : downloading.obj.explicit_lyrics,
750                                         label : downloading.obj.label,
751                                         release_date : downloading.obj.release_date,
752                                         genres : downloading.obj.genres,
753                                         discTotal: downloading.obj.discTotal ? downloading.obj.discTotal : null
754                                 }
755                                 downloading.downloadPromise = new Promise((resolve,reject)=>{
756                                         downloading.obj.tracks.every(function (t) {
757                                                 s.trackQueue.push(async cb=>{
758                                                         if (!s.downloadQueue[downloading.queueId]) {
759                                                                 reject()
760                                                                 return false
761                                                         }
762                                                         t.ajson = ajson
763                                                         logger.info(`Now downloading: ${t.artist.name} - ${t.title}`)
764                                                         try{
765                                                                 await downloadTrackObject(t, downloading.queueId, downloading.settings)
766                                                                 downloading.downloaded++
767                                                                 downloading.playlistArr[t.playlistData[0]] = t.playlistData[1].split(filePath)[1]
768                                                                 if (t.searched) downloading.searchedLog += `${t.artist.name} - ${t.name}\r\n`
769                                                         }catch(err){
770                                                                 logger.error(`queueDownload:album failed: ${err.stack ? err.stack : err}`)
771                                                                 downloading.failed++
772                                                                 downloading.errorLog += `${t.id} | ${t.artist.name} - ${t.title} | ${err}\r\n`
773                                                         }
774                                                         s.emit("downloadProgress", {
775                                                                 queueId: downloading.queueId,
776                                                                 percentage: ((downloading.downloaded+downloading.failed) / downloading.size) * 100
777                                                         });
778                                                         s.emit("updateQueue", {
779                                                                 name: downloading.name,
780                                                                 artist: downloading.artist,
781                                                                 size: downloading.size,
782                                                                 downloaded: downloading.downloaded,
783                                                                 failed: downloading.failed,
784                                                                 queueId: downloading.queueId,
785                                                                 id: downloading.id,
786                                                                 type: downloading.type,
787                                                         })
788                                                         if (downloading.downloaded + downloading.failed >= downloading.size) resolve()
789                                                         cb()
790                                                 })
791                                                 return true
792                                         })
793                                 })
794                                 try{
795                                         await downloading.downloadPromise
796                                         logger.info("Album finished downloading: "+downloading.name);
797                                         s.emit("downloadProgress", {
798                                                 queueId: downloading.queueId,
799                                                 percentage: 100
800                                         });
801                                         if (downloading.settings.logErrors){
802                                                 if (downloading.errorLog != ""){
803                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
804                                                         fs.writeFileSync(filePath+"notFound.txt",downloading.errorLog)
805                                                 }else{
806                                                         if (fs.existsSync(filePath+"notFound.txt")) fs.unlinkSync(filePath+"notFound.txt");
807                                                 }
808                                         }
809                                         if (downloading.settings.logSearched){
810                                                 if (downloading.searchedLog != ""){
811                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
812                                                         fs.writeFileSync(filePath+"alternativeSongs.txt",downloading.searchedLog)
813                                                 }else{
814                                                         if (fs.existsSync(filePath+"alternativeSongs.txt")) fs.unlinkSync(filePath+"alternativeSongs.txt");
815                                                 }
816                                         }
817                                         if (downloading.settings.createM3UFile){
818                                                 fs.writeFileSync(filePath+"playlist.m3u", downloading.playlistArr.join("\r\n"));
819                                         }
820                                 }catch(err){
821                                         if (err) logger.error(`queueDownload:album failed: ${err.stack ? err.stack : err}`)
822                                         logger.info("Stopping the album queue");
823                                 }
824                         break
825                         /*
826                         *  PLAYLIST DOWNLOAD
827                         */
828                         case "playlist":
829                                 downloading.settings.plName = downloading.name;
830                                 downloading.playlistArr = Array(downloading.size);
831                                 downloading.settings.playlist = {
832                                         fullSize: downloading.obj.tracks.length
833                                 };
834                                 filePath = mainFolder+antiDot(fixName(downloading.settings.plName)) + path.sep
835                                 downloading.downloadPromise = new Promise((resolve,reject)=>{
836                                         downloading.obj.tracks.every(function (t, index) {
837                                                 s.trackQueue.push(async cb=>{
838                                                         if (!s.downloadQueue[downloading.queueId]) {
839                                                                 reject()
840                                                                 return false
841                                                         }
842                                                         try{
843                                                                 await downloadTrackObject(t, downloading.queueId, downloading.settings)
844                                                                 downloading.downloaded++
845                                                                 downloading.playlistArr[t.playlistData[0]] = t.playlistData[1].split(filePath)[1]
846                                                                 if (t.searched) downloading.searchedLog += `${t.artist.name} - ${t.name}\r\n`
847                                                         }catch(err){
848                                                                 logger.error(`queueDownload:playlist failed: ${err.stack ? err.stack : err}`)
849                                                                 downloading.failed++
850                                                                 downloading.errorLog += `${t.id} | ${t.artist.name} - ${t.title} | ${err}\r\n`
851                                                         }
852                                                         s.emit("downloadProgress", {
853                                                                 queueId: downloading.queueId,
854                                                                 percentage: ((downloading.downloaded+downloading.failed) / downloading.size) * 100
855                                                         });
856                                                         s.emit("updateQueue", {
857                                                                 name: downloading.name,
858                                                                 artist: downloading.artist,
859                                                                 size: downloading.size,
860                                                                 downloaded: downloading.downloaded,
861                                                                 failed: downloading.failed,
862                                                                 queueId: downloading.queueId,
863                                                                 id: downloading.id,
864                                                                 type: downloading.type,
865                                                         })
866                                                         if (downloading.downloaded + downloading.failed >= downloading.size) resolve()
867                                                         cb()
868                                                 })
869                                                 return true
870                                         })
871                                 })
872                                 try{
873                                         await downloading.downloadPromise
874                                         logger.info("Playlist finished "+downloading.name);
875                                         s.emit("downloadProgress", {
876                                                 queueId: downloading.queueId,
877                                                 percentage: 100
878                                         });
879                                         if (downloading.settings.logErrors){
880                                                 if (downloading.errorLog != ""){
881                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
882                                                         fs.writeFileSync(filePath+"notFound.txt",downloading.errorLog)
883                                                 }else{
884                                                         if (fs.existsSync(filePath+"notFound.txt")) fs.unlinkSync(filePath+"notFound.txt");
885                                                 }
886                                         }
887                                         if (downloading.settings.logSearched){
888                                                 if (downloading.searchedLog != ""){
889                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
890                                                         fs.writeFileSync(filePath+"alternativeSongs.txt",downloading.searchedLog)
891                                                 }else{
892                                                         if (fs.existsSync(filePath+"alternativeSongs.txt")) fs.unlinkSync(filePath+"alternativeSongs.txt");
893                                                 }
894                                         }
895                                         if (downloading.settings.createM3UFile){
896                                                 fs.writeFileSync(filePath + "playlist.m3u", downloading.playlistArr.join("\r\n"));
897                                         }
898                                         if (downloading.settings.saveArtwork){
899                                                 if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
900                                                 let imgPath = filePath + antiDot(fixName(settingsRegexCover(downloading.settings.coverImageTemplate,downloading.artist,downloading.name)))+(downloading.settings.PNGcovers ? ".png" : ".jpg");
901                                                 if (downloading.cover){
902                                                         downloading.cover = downloading.cover.replace("56x56",`${downloading.settings.artworkSize}x${downloading.settings.artworkSize}`)
903                                                         request.get(downloading.cover, {strictSSL: false,encoding: 'binary'}, function(error,response,body){
904                                                                 if(error){
905                                                                         logger.error(error.stack);
906                                                                         return;
907                                                                 }
908                                                                 fs.outputFile(imgPath,body,'binary',function(err){
909                                                                         if(err){
910                                                                                 logger.error(err.stack);
911                                                                                 return;
912                                                                         }
913                                                                         logger.info(`Cover downloaded for: ${downloading.settings.plName}`)
914                                                                 })
915                                                         });
916                                                 }
917                                         }
918                                 }catch(err){
919                                         if (err) logger.error(`queueDownload:playlist failed: ${err.stack ? err.stack : err}`)
920                                         logger.info("Stopping the playlist queue")
921                                 }
922                         break
923                         /*
924                         *  SPOTIFY PLAYLIST DOWNLOAD
925                         */
926                         case "spotifyplaylist":
927                                 downloading.settings.plName = downloading.name
928                                 downloading.playlistArr = Array(downloading.size)
929                                 downloading.playlistContent = new Array(downloading.size);
930                                 logger.info("Waiting for all tracks to be converted");
931                                 downloading.obj.tracks.map(async (t,i)=>{
932                                         try{
933                                                 downloading.playlistContent[i] = await convertSpotify2Deezer(t)
934                                         }catch(err){
935                                                 logger.error(`queueDownload:spotifyplaylist failed during conversion: ${err.stack ? err.stack : err}`)
936                                         }
937                                 })
938                                 if (!s.downloadQueue[downloading.queueId]) {
939                                         logger.info("Stopping the playlist queue")
940                                         break
941                                 }
942                                 downloading.trackList = await s.Deezer.getTracks(downloading.playlistContent)
943                                 logger.info("All tracks converted, starting download")
944                                 s.emit("downloadStarted", {queueId: downloading.queueId})
945                                 downloading.settings.playlist = {
946                                         fullSize: downloading.trackList.length
947                                 }
948                                 filePath = `${mainFolder}${antiDot(fixName(downloading.settings.plName))}${path.sep}`
949                                 downloading.downloadPromise = new Promise((resolve,reject)=>{
950                                         downloading.trackList.every(function (t, index) {
951                                                 s.trackQueue.push(async cb=>{
952                                                         if (!s.downloadQueue[downloading.queueId]) {
953                                                                 reject()
954                                                                 return false
955                                                         }
956                                                         t.position = index
957                                                         try{
958                                                                 await downloadTrackObject(t, downloading.queueId, downloading.settings)
959                                                                 downloading.downloaded++
960                                                                 downloading.playlistArr[t.playlistData[0]] = t.playlistData[1].split(filePath)[1]
961                                                                 if (t.searched) downloading.searchedLog += `${t.artist.name} - ${t.name}\r\n`
962                                                         }catch(err){
963                                                                 logger.error(`queueDownload:spotifyplaylist failed: ${err.stack ? err.stack : err}`)
964                                                                 downloading.failed++
965                                                                 downloading.errorLog += `${t.id} | ${t.artist.name} - ${t.title} | ${err}\r\n`
966                                                         }
967                                                         s.emit("downloadProgress", {
968                                                                 queueId: downloading.queueId,
969                                                                 percentage: ((downloading.downloaded+downloading.failed) / downloading.size) * 100
970                                                         });
971                                                         s.emit("updateQueue", {
972                                                                 name: downloading.name,
973                                                                 artist: downloading.artist,
974                                                                 size: downloading.size,
975                                                                 downloaded: downloading.downloaded,
976                                                                 failed: downloading.failed,
977                                                                 queueId: downloading.queueId,
978                                                                 id: downloading.id,
979                                                                 type: downloading.type,
980                                                         })
981                                                         if (downloading.downloaded + downloading.failed >= downloading.size) resolve()
982                                                         cb()
983                                                 })
984                                                 return true
985                                         })
986                                 })
987                                 try{
988                                         await downloading.downloadPromise
989                                         logger.info("Playlist finished "+downloading.name);
990                                         s.emit("downloadProgress", {
991                                                 queueId: downloading.queueId,
992                                                 percentage: 100
993                                         });
994                                         if (downloading.settings.logErrors){
995                                                 if (downloading.errorLog != ""){
996                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
997                                                         fs.writeFileSync(filePath+"notFound.txt",downloading.errorLog)
998                                                 }else{
999                                                         if (fs.existsSync(filePath+"notFound.txt")) fs.unlinkSync(filePath+"notFound.txt");
1000                                                 }
1001                                         }
1002                                         if (downloading.settings.logSearched){
1003                                                 if (downloading.searchedLog != ""){
1004                                                         if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1005                                                         fs.writeFileSync(filePath+"alternativeSongs.txt",downloading.searchedLog)
1006                                                 }else{
1007                                                         if (fs.existsSync(filePath+"alternativeSongs.txt")) fs.unlinkSync(filePath+"alternativeSongs.txt");
1008                                                 }
1009                                         }
1010                                         if (downloading.settings.createM3UFile){
1011                                                 fs.writeFileSync(filePath + "playlist.m3u", downloading.playlistArr.join("\r\n"));
1012                                         }
1013                                         if (downloading.settings.saveArtwork){
1014                                                 if (!fs.existsSync(filePath)) fs.mkdirSync(filePath);
1015                                                 let imgPath = filePath + antiDot(fixName(settingsRegexCover(downloading.settings.coverImageTemplate,downloading.artist,downloading.name)))+(downloading.settings.PNGcovers ? ".png" : ".jpg");
1016                                                 if (downloading.obj.images){
1017                                                         downloading.cover = downloading.obj.images[0].url.replace("56x56",`${downloading.settings.artworkSize}x${downloading.settings.artworkSize}`)
1018                                                         request.get(downloading.cover, {strictSSL: false,encoding: 'binary'}, function(error,response,body){
1019                                                                 if(error){
1020                                                                         logger.error(error.stack);
1021                                                                         return;
1022                                                                 }
1023                                                                 fs.outputFile(imgPath,body,'binary',function(err){
1024                                                                         if(err){
1025                                                                                 logger.error(err.stack);
1026                                                                                 return;
1027                                                                         }
1028                                                                         logger.info(`Cover downloaded for: ${downloading.settings.plName}`)
1029                                                                 })
1030                                                         });
1031                                                 }
1032                                         }
1033                                 }catch(err){
1034                                         if (err) logger.error(`queueDownload:spotifyplaylist failed: ${err.stack ? err.stack : err}`)
1035                                         logger.info("Stopping the playlist queue")
1036                                 }
1037                         break
1038                 }
1039                 if (downloading && s.downloadQueue[Object.keys(s.downloadQueue)[0]] && (Object.keys(s.downloadQueue)[0] == downloading.queueId)) delete s.downloadQueue[Object.keys(s.downloadQueue)[0]]
1040                 if (Object.keys(s.downloadQueue).length == 0) {
1041                         s.emit("emptyDownloadQueue", {})
1042                 }
1043         }
1044
1045         // This function takes the track object and does all the stuff to download it
1046         async function downloadTrackObject(track, queueId, settings) {
1047                 if (!s.downloadQueue[queueId]) {
1048                         logger.error(`[${track.artist.name} - ${track.title}] Failed to download: Not in queue`)
1049                         throw new Error(`Failed to download: Not in queue`)
1050                         return
1051                 }
1052                 if (track.id == 0){
1053                         logger.error(`[${track.artist.name} - ${track.title}] Failed to download: Wrong ID`)
1054                         throw new Error(`Failed to download: Wrong ID`)
1055                         return
1056                 }
1057
1058                 /* Album information is necessary for the following tags:
1059                  * album_artist
1060                  * album_artist_picture
1061                  * trackTotal
1062                  * recordType
1063                  * barcode
1064                  * explicit
1065                  * label
1066                  * genres
1067                  * date
1068                 */
1069                 if (parseInt(track.id)>0){
1070                         var ajson
1071                         if (!track.ajson){
1072                                 try{
1073                                         logger.info(`[${track.artist.name} - ${track.title}] Getting album info`)
1074                                         ajson = await s.Deezer.legacyGetAlbum(track.album.id)
1075                                 }catch(err){
1076                                         logger.warn(`[${track.artist.name} - ${track.title}] Album not found, trying to reach deeper`)
1077                                         try{
1078                                                 ajson = await s.Deezer.getAlbum(track.album.id)
1079                                                 ajson.fromNewAPI = true
1080                                         } catch(err){
1081                                                 if(track.fallbackId){
1082                                                         logger.warn(`[${track.artist.name} - ${track.title}] Failed to download track, falling on alternative`)
1083                                                         track = await s.Deezer.getTrack(track.fallbackId)
1084                                                         return downloadTrackObject(track, queueId, settings)
1085                                                 }else{
1086                                                         logger.error(`[${track.artist.name} - ${track.title}] Failed to download: ${err}`)
1087                                                         return
1088                                                 }
1089                                         }
1090                                 }
1091                         }else{
1092                                 ajson = track.ajson
1093                         }
1094                         if (!ajson.fromNewAPI){
1095                                 // Aquiring discTotal (only if necessary)
1096                                 if ((settings.tags.discTotal || settings.createCDFolder) && parseInt(track.id)>0){
1097                                         if (!ajson.discTotal){
1098                                                 logger.info(`[${track.artist.name} - ${track.title}] Getting total disc number`);
1099                                                 var discTotal = await s.Deezer.getAlbum(ajson.id)
1100                                                 track.discTotal = discTotal.discTotal
1101                                         }else{
1102                                                 track.discTotal = ajson.discTotal
1103                                         }
1104                                 }
1105                                 track.album.artist = {
1106                                         id: ajson.artist.id,
1107                                         name: ajson.artist.name,
1108                                         picture: ajson.artist.picture_small.split("/56x56-000000-80-0-0.jpg")[0].split(s.Deezer.artistPicturesHost)[1],
1109                                 }
1110                                 track.trackTotal = ajson.nb_tracks
1111                                 track.album.barcode = ajson.upc
1112                                 if (!ajson.record_type){
1113                                         track.recordType = swichReleaseType(track.recordType)
1114                                 }else{
1115                                         track.recordType = ajson.record_type
1116                                 }
1117                                 if (ajson.explicit_lyrics){
1118                                         track.album.explicit = ajson.explicit_lyrics;
1119                                 }
1120                                 if(ajson.label){
1121                                         track.publisher = ajson.label;
1122                                 }
1123                                 if (ajson.release_date) {
1124                                         track.date = {
1125                                                 day: ajson.release_date.slice(8,10),
1126                                                 month: ajson.release_date.slice(5,7),
1127                                                 year: ajson.release_date.slice(0, 4),
1128                                                 slicedYear: (settings.dateFormatYear == "2" ? ajson.release_date.slice(2, 4) : ajson.release_date.slice(0, 4))
1129                                         }
1130                                 }else if(!track.date){
1131                                         track.date = {
1132                                                 day: 0,
1133                                                 month: 0,
1134                                                 year: 0,
1135                                                 slicedYear: 0
1136                                         }
1137                                 }
1138                                 if(ajson.genres && ajson.genres.data[0] && ajson.genres.data[0].name){
1139                                         track.genre = [];
1140                                         genreArray = [];
1141                                         ajson.genres.data.forEach(function(genre){
1142                                                 genreArray.push(genre.name);
1143                                         });
1144                                         uniqueArray(genreArray, track.genre, false)
1145                                 }
1146                         }else{
1147                                 // Missing barcode, genre, recordType
1148                                 track.album = ajson
1149                                 track.date = track.album.date
1150                                 // TODO: Make a loop for each artist
1151
1152                         }
1153
1154                         // Acquiring bpm (only if necessary)
1155                         if (settings.tags.bpm){
1156                                 logger.info(`[${track.artist.name} - ${track.title}] Getting BPM`);
1157                                 try{
1158                                         var bpm = await s.Deezer.legacyGetTrack(track.id)
1159                                         track.bpm = bpm.bpm
1160                                 }catch(err){
1161                                         track.bpm = 0
1162                                 }
1163                         }else{
1164                                 track.bpm = 0
1165                         }
1166
1167                         // Acquiring ReplayGain value (only if necessary)
1168                         if (settings.tags.replayGain){
1169                                 logger.info(`[${track.artist.name} - ${track.title}] Getting track gain`);
1170                                 try{
1171                                         var gain = await s.Deezer.legacyGetTrack(track.id)
1172                                         track.replayGain = gain.gain
1173                                 }catch(err){
1174                                         track.replayGain = 0
1175                                 }
1176                         }else{
1177                                 track.replayGain = 0
1178                         }
1179
1180                         let separator = settings.multitagSeparator
1181                         if (separator == "null") separator = String.fromCharCode(parseInt("\u0000",16))
1182
1183                         // Autoremoves (Album Version) from the title
1184                         if (settings.removeAlbumVersion){
1185                                 if(track.title.indexOf("Album Version")>-1){
1186                                         track.title = track.title.replace(/\(Album Version\)/g,"")
1187                                         track.title.trim()
1188                                 }
1189                         }
1190
1191                         track.album.artist.pictureUrl = `${s.Deezer.artistPicturesHost}${track.album.artist.picture}/${settings.artworkSize}x${settings.artworkSize}-000000-80-0-0${(settings.PNGcovers ? ".png" : ".jpg")}`
1192                         track.album.pictureUrl = `${s.Deezer.albumPicturesHost}${track.album.picture}/${settings.artworkSize}x${settings.artworkSize}-000000-80-0-0${(settings.PNGcovers ? ".png" : ".jpg")}`
1193                         if(track.contributor){
1194                                 if(track.contributor.composer){
1195                                         track.composerString = []
1196                                         uniqueArray(track.contributor.composer, track.composerString, settings.removeDupedTags)
1197                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.composerString = track.composerString.join(separator)
1198                                 }
1199                                 if(track.contributor.musicpublisher){
1200                                         track.musicpublisherString = []
1201                                         uniqueArray(track.contributor.musicpublisher, track.musicpublisherString, settings.removeDupedTags)
1202                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.musicpublisherString = track.musicpublisherString.join(separator)
1203                                 }
1204                                 if(track.contributor.producer){
1205                                         track.producerString = []
1206                                         uniqueArray(track.contributor.producer, track.producerString, settings.removeDupedTags)
1207                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.producerString = track.producerString.join(separator)
1208                                 }
1209                                 if(track.contributor.engineer){
1210                                         track.engineerString = []
1211                                         uniqueArray(track.contributor.engineer, track.engineerString, settings.removeDupedTags)
1212                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.engineerString = track.engineerString.join(separator)
1213                                 }
1214                                 if(track.contributor.writer){
1215                                         track.writerString = []
1216                                         uniqueArray(track.contributor.writer, track.writerString, settings.removeDupedTags)
1217                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.writerString = track.writerString.join(separator)
1218                                 }
1219                                 if(track.contributor.author){
1220                                         track.authorString = []
1221                                         uniqueArray(track.contributor.author, track.authorString, settings.removeDupedTags)
1222                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.authorString = track.authorString.join(separator)
1223                                 }
1224                                 if(track.contributor.mixer){
1225                                         track.mixerString = [];
1226                                         uniqueArray(track.contributor.mixer, track.mixerString, settings.removeDupedTags)
1227                                         if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.mixerString = track.mixerString.join(separator)
1228                                 }
1229                         }
1230
1231                         if(track.artists || track.artistsString){
1232                                 if (!track.artistsString){
1233                                         track.artistsString = []
1234                                         artistArray = []
1235                                         track.artists.forEach(function(artist){
1236                                                 artistArray.push(artist.name)
1237                                         })
1238                                 }else{
1239                                         artistArray = track.artistsString
1240                                 }
1241                                 uniqueArray(artistArray, track.artistsString, settings.removeDupedTags)
1242                                 let posMainArtist = track.artistsString.indexOf(track.album.artist.name)
1243                                 if (posMainArtist !== -1 && posMainArtist !== 0 && settings.removeDupedTags){
1244                                         let element = track.artistsString[posMainArtist]
1245                                 track.artistsString.splice(posMainArtist, 1)
1246                                 track.artistsString.splice(0, 0, element)
1247                                 }
1248                                 if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.artistsString = track.artistsString.join(separator)
1249                         }
1250                         if (track.genre){
1251                                 if (!(track.selectedFormat == 9 && separator==String.fromCharCode(parseInt("\u0000",16)))) track.genreString = track.genre.join(separator)
1252                         }
1253
1254                         if (track.date){
1255                                 let date
1256                                 switch (settings.dateFormat){
1257                                         case "0": date = `${track.date.slicedYear}-${track.date.month}-${track.date.day}`; break;
1258                                         case "1": date = `${track.date.day}-${track.date.month}-${track.date.slicedYear}`; break;
1259                                         case "2": date = `${track.date.month}-${track.date.day}-${track.date.slicedYear}`; break;
1260                                         case "3": date = `${track.date.slicedYear}-${track.date.day}-${track.date.month}`; break;
1261                                         case "4": date = `${track.date.day}${track.date.month}`; break;
1262                                         default: date = `${track.date.day}${track.date.month}`; break;
1263                                 }
1264                                 track.dateString = date;
1265                         }
1266                 }else{
1267                         track.date = {year: 0,day: 0,month: 0}
1268                 }
1269
1270                 if(settings.plName && !(settings.createArtistFolder || settings.createAlbumFolder) && !settings.numplaylistbyalbum){
1271                         track.trackNumber = (track.position+1).toString();
1272                         track.trackTotal = settings.playlist.fullSize;
1273                         track.discNumber = "1";
1274                         track.discTotal = "1";
1275                 }
1276
1277                 // Auto detect aviable track format from settings
1278                 if (parseInt(track.id)>0){
1279                         switch(settings.maxBitrate){
1280                                 case "9":
1281                                         track.selectedFormat = 9
1282                                         track.selectedFilesize = track.filesize.flac
1283                                         if (track.filesize.flac>0) break
1284                                         if (!settings.fallbackBitrate) throw new Error("Song not found at desired bitrate.")
1285                                 case "3":
1286                                         track.selectedFormat = 3
1287                                         track.selectedFilesize = track.filesize.mp3_320
1288                                         if (track.filesize.mp3_320>0) break
1289                                         if (!settings.fallbackBitrate) throw new Error("Song not found at desired bitrate.")
1290                                 case "1":
1291                                         track.selectedFormat = 1
1292                                         track.selectedFilesize = track.filesize.mp3_128
1293                                         if (track.filesize.mp3_128>0) break
1294                                         if (!settings.fallbackBitrate) throw new Error("Song not found at desired bitrate.")
1295                                 default:
1296                                         track.selectedFormat = 8
1297                                         track.selectedFilesize = track.filesize.default
1298                         }
1299                 }else{
1300                         track.selectedFilesize = track.filesize
1301                         track.selectedFormat = 3
1302                 }
1303
1304                 // TODO: Move to a separate function
1305                 // Generating file name
1306                 if (settings.saveFullArtists && settings.multitagSeparator != null){
1307                         let filename = fixName(`${track.artistsString} - ${track.title}`);
1308                 }else{
1309                         let filename = fixName(`${track.artist.name} - ${track.title}`);
1310                 }
1311                 if (settings.filename) {
1312                         filename = fixName(settingsRegex(track, settings.filename, settings.playlist, settings.saveFullArtists && settings.multitagSeparator != null, settings.paddingSize));
1313                 }
1314
1315                 // TODO: Move to a separate function
1316                 // Generating file path
1317                 let filepath = mainFolder;
1318                 let artistPath;
1319                 if (settings.createArtistFolder || settings.createAlbumFolder) {
1320                         if(settings.plName){
1321                                 filepath += antiDot(fixName(settings.plName)) + path.sep;
1322                         }
1323                         if (settings.createArtistFolder) {
1324                                 if(settings.artName){
1325                                         filepath += antiDot(fixName(settings.artName)) + path.sep;
1326                                 }else{
1327                                         filepath += antiDot(fixName(track.album.artist.name)) + path.sep;
1328                                 }
1329                                 artistPath = filepath;
1330                         }
1331
1332                         if (settings.createAlbumFolder) {
1333                                 if(settings.artName){
1334                                         filepath += antiDot(fixName(settingsRegexAlbum(settings.foldername,settings.artName,settings.albName,track.date.year,track.recordType,track.album.explicit,track.publisher))) + path.sep;
1335                                 }else{
1336                                         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;
1337                                 }
1338                         }
1339                 } else if (settings.plName) {
1340                         filepath += antiDot(fixName(settings.plName)) + path.sep;
1341                 } else if (settings.artName) {
1342                         filepath += antiDot(fixName(settingsRegexAlbum(settings.foldername,settings.artName,settings.albName,track.date.year,track.recordType,track.album.explicit,track.publisher))) + path.sep;
1343                 }
1344                 let coverpath = filepath;
1345                 if (track.discTotal > 1 && (settings.artName || settings.createAlbumFolder) && settings.createCDFolder){
1346                         filepath += `CD${track.discNumber +  path.sep}`
1347                 }
1348                 let writePath;
1349
1350                 if(track.selectedFormat == 9){
1351                         writePath = filepath + filename + '.flac';
1352                 }else{
1353                         writePath = filepath + filename + '.mp3';
1354                 }
1355
1356                 if ((settings.syncedlyrics || settings.tags.unsynchronisedLyrics) && track.lyricsId>0){
1357                         let lyr = await s.Deezer.getLyrics(track.id)
1358                         track.syncLyrics = lyr.syncLyrics
1359                         track.unsyncLyrics = lyr.unsyncLyrics
1360                 }
1361
1362                 if(track.syncLyrics && settings.syncedlyrics){
1363                         fs.outputFile(writePath.substring(0,writePath.lastIndexOf('.'))+".lrc",track.syncLyrics,function(){});
1364                 }
1365
1366                 track.playlistData = [0,""]
1367                 if (settings.createM3UFile && (settings.plName || settings.albName)) {
1368                         if (track.position){
1369                                 track.playlistData = [parseInt(track.position), writePath];
1370                         }else{
1371                                 track.playlistData = [track.trackNumber-1, writePath];
1372                         }
1373                 }
1374                 if (fs.existsSync(writePath)) {
1375                         logger.info(`[${track.artist.name} - ${track.title}] Already downloaded`);
1376                         return;
1377                 }else{
1378                         logger.info(`[${track.artist.name} - ${track.title}] Downloading file to ${writePath}`);
1379                 }
1380                 // Get cover image
1381                 if (track.album.pictureUrl) {
1382                         let imgPath;
1383                         //If its not from an album but a playlist.
1384                         if(!(settings.albName || settings.createAlbumFolder)){
1385                                 imgPath = coverArtFolder + (track.album.barcode ? fixName(track.album.barcode) : fixName(`${track.album.artist.name} - ${track.album.title}`))+(settings.PNGcovers ? ".png" : ".jpg");
1386                         }else{
1387                                 if (settings.saveArtwork)
1388                                         imgPath = coverpath + fixName(settingsRegexCover(settings.coverImageTemplate,settings.artName,settings.albName))+(settings.PNGcovers ? ".png" : ".jpg");
1389                                 else
1390                                         imgPath = coverArtFolder + fixName(track.album.barcode ? fixName(track.album.barcode) : fixName(`${track.album.artist.name} - ${track.album.title}`))+(settings.PNGcovers ? ".png" : ".jpg");
1391                         }
1392                         if(fs.existsSync(imgPath)){
1393                                 track.album.picturePath = (imgPath).replace(/\\/g, "/")
1394                                 logger.info(`[${track.artist.name} - ${track.title}] Starting the download process CODE:1`)
1395                         }else{
1396                                 try{
1397                                         var body = await request.get(track.album.pictureUrl, {strictSSL: false,encoding: 'binary'})
1398                                         fs.outputFileSync(imgPath,body,'binary')
1399                                         track.album.picturePath = (imgPath).replace(/\\/g, "/")
1400                                         logger.info(`[${track.artist.name} - ${track.title}] Starting the download process CODE:2`)
1401                                 }catch(error){
1402                                         logger.error(`[${track.artist.name} - ${track.title}] Cannot download Album Image: ${error}`)
1403                                         track.album.pictureUrl = undefined
1404                                         track.album.picturePath = undefined
1405                                 }
1406                         }
1407                 }else{
1408                         track.album.pictureUrl = undefined
1409                         logger.info(`[${track.artist.name} - ${track.title}] Starting the download process CODE:3`)
1410                 }
1411
1412                 // Get Artist Image
1413                 if (parseInt(this.id)>0 && track.album.artist.picture && settings.saveArtworkArtist) {
1414                         let imgPath;
1415                         if(settings.createArtistFolder){
1416                                 imgPath = artistPath + antiDot(fixName(settingsRegexArtistCover(settings.artistImageTemplate,track.album.artist.name)))+(settings.PNGcovers ? ".png" : ".jpg");
1417                                 if(!fs.existsSync(imgPath)){
1418                                         try{
1419                                                 var body = await request.get(track.album.artist.pictureUrl, {strictSSL: false,encoding: 'binary'})
1420                                                 if (body.indexOf("unauthorized")>-1) throw new Error("Unauthorized")
1421                                                 fs.outputFileSync(imgPath,body,'binary')
1422                                                 logger.info(`[${track.artist.name} - ${track.title}] Saved Artist Image`)
1423                                         }catch(err){
1424                                                 logger.error(`[${track.artist.name} - ${track.title}] Cannot download Artist Image: ${err}`)
1425                                         }
1426                                 }
1427                         }
1428                 }
1429
1430                 let tempPath
1431                 if(parseInt(track.id)>0)
1432                         tempPath = `${filepath}${track.id}_${track.selectedFormat}.temp`
1433                 else
1434                         tempPath = writePath
1435
1436                 logger.info(`[${track.artist.name} - ${track.title}] Downloading track`)
1437                 var downloadingPromise = new Promise((resolve, reject)=>{
1438                         let req = requestOld.get({url: track.getDownloadUrl(track.selectedFormat), strictSSL: false, headers: s.Deezer.httpHeaders, encoding: 'binary'}, function (error, response, body) {
1439                                 if (error){
1440                                         logger.error(`[${track.artist.name} - ${track.title}] Downloading error: ${error}`)
1441                                         reject("Downloading error: "+error)
1442                                 }
1443                                 if (!s.downloadQueue[queueId]){
1444                                         fs.remove(tempPath)
1445                                         return reject()
1446                                 }
1447                                 logger.info(`[${track.artist.name} - ${track.title}] Decrypting track`)
1448                                 var decryptedSource = s.Deezer.decryptDownload(Buffer.from(body, 'binary'), track.id)
1449                                 try{
1450                                         fs.outputFileSync(tempPath,decryptedSource)
1451                                         resolve()
1452                                 }catch(err){
1453                                         return logger.error(`[${track.artist.name} - ${track.title}] Decryption error: ${err.stack}`)
1454                                 }
1455                         }).on("data", function(data) {
1456                                 if (!s.downloadQueue[queueId]) reject()
1457                         })
1458                         if((s.downloadQueue[queueId]) && s.downloadQueue[queueId].type == "track"){
1459                                 let chunkLength = 0
1460                                 req.on("data", function(data) {
1461                                         if (!s.downloadQueue[queueId]) reject()
1462                                         chunkLength += data.length
1463                                         try{
1464                                                 if (!s.downloadQueue[queueId].percentage) {
1465                                                         s.downloadQueue[queueId].percentage = 0
1466                                                 }
1467                                                 let complete = track.selectedFilesize
1468                                                 let percentage = (chunkLength / complete) * 100;
1469                                                 if ((percentage - s.downloadQueue[queueId].percentage > 1) || (chunkLength == complete)) {
1470                                                         s.downloadQueue[queueId].percentage = percentage
1471                                                         s.emit("downloadProgress", {
1472                                                                 queueId: queueId,
1473                                                                 percentage: s.downloadQueue[queueId].percentage-5
1474                                                         })
1475                                                 }
1476                                         }catch(err){}
1477                                 })
1478                         }
1479                 })
1480                 try{
1481                         await downloadingPromise
1482                 }catch(err){
1483                         if (err) logger.error(`downloadTrackObject failed: ${err.stack ? err.stack : err}`)
1484                         return
1485                 }
1486
1487                 logger.info(`[${track.artist.name} - ${track.title}] Adding Tags`)
1488                 if (parseInt(track.id)>0){
1489                         if(track.selectedFormat == 9){
1490                                 let flacComments = [];
1491                                 if (settings.tags.title)
1492                                         flacComments.push('TITLE=' + track.title);
1493                                 if (settings.tags.album)
1494                                         flacComments.push('ALBUM=' + track.album.title);
1495                                 if (settings.tags.albumArtist)
1496                                         flacComments.push('ALBUMARTIST=' + track.album.artist.name);
1497                                 if (settings.tags.trackNumber)
1498                                         flacComments.push('TRACKNUMBER=' + track.trackNumber);
1499                                 if (settings.tags.discNumber)
1500                                         flacComments.push('DISCNUMBER=' + track.discNumber);
1501                                 if (settings.tags.trackTotal)
1502                                         flacComments.push('TRACKTOTAL=' + track.trackTotal);
1503                                 if (settings.tags.explicit)
1504                                         flacComments.push('ITUNESADVISORY=' + track.explicit);
1505                                 if (settings.tags.isrc)
1506                                         flacComments.push('ISRC=' + track.ISRC);
1507                                 if (settings.tags.artist && track.artistsString)
1508                                         if (Array.isArray(track.artistsString)){
1509                                                 track.artistsString.forEach(x=>{
1510                                                         flacComments.push('ARTIST=' + x);
1511                                                 });
1512                                         }else{
1513                                                 flacComments.push('ARTIST=' + track.artistsString);
1514                                         }
1515                                 if (settings.tags.discTotal)
1516                                         flacComments.push('DISCTOTAL='+track.discTotal);
1517                                 if (settings.tags.length)
1518                                         flacComments.push('LENGTH=' + track.duration);
1519                                 if (settings.tags.barcode && track.album.barcode)
1520                                         flacComments.push('BARCODE=' + track.album.barcode);
1521                                 if (track.unsyncLyrics && settings.tags.unsynchronisedLyrics)
1522                                         flacComments.push('LYRICS='+track.unsyncLyrics.lyrics);
1523                                 if (track.genreString && settings.tags.genre)
1524                                         if (Array.isArray(track.genreString)){
1525                                                 track.genreString.forEach(x=>{
1526                                                         flacComments.push('GENRE=' + x);
1527                                                 });
1528                                         }else{
1529                                                 flacComments.push('GENRE=' + track.genreString);
1530                                         }
1531                                 if (track.copyright && settings.tags.copyright)
1532                                         flacComments.push('COPYRIGHT=' + track.copyright);
1533                                 if (0 < parseInt(track.date.year)){
1534                                         if (settings.tags.year)
1535                                                 flacComments.push('YEAR=' + track.date.year);
1536                                         if (settings.tags.date)
1537                                         flacComments.push('DATE=' + track.dateString);
1538                                 }
1539                                 if (0 < parseInt(track.bpm) && settings.tags.bpm)
1540                                         flacComments.push('BPM=' + track.bpm);
1541                                 if(track.publisher && settings.tags.publisher)
1542                                         flacComments.push('PUBLISHER=' + track.publisher);
1543                                 if(track.composerString && settings.tags.composer)
1544                                         if (Array.isArray(track.composerString)){
1545                                                 track.composerString.forEach(x=>{
1546                                                         flacComments.push('COMPOSER=' + x);
1547                                                 });
1548                                         }else{
1549                                                 flacComments.push('COMPOSER=' + track.composerString);
1550                                         }
1551                                 if(track.musicpublisherString && settings.tags.musicpublisher)
1552                                         if (Array.isArray(track.musicpublisherString)){
1553                                                 track.musicpublisherString.forEach(x=>{
1554                                                         flacComments.push('ORGANIZATION=' + x);
1555                                                 });
1556                                         }else{
1557                                                 flacComments.push('ORGANIZATION=' + track.musicpublisherString);
1558                                         }
1559                                 if(track.mixerString && settings.tags.mixer)
1560                                         if (Array.isArray(track.mixerString)){
1561                                                 track.mixerString.forEach(x=>{
1562                                                         flacComments.push('MIXER=' + x);
1563                                                 });
1564                                         }else{
1565                                                 flacComments.push('MIXER=' + track.mixerString);
1566                                         }
1567                                 if(track.authorString && settings.tags.author)
1568                                         if (Array.isArray(track.authorString)){
1569                                                 track.authorString.forEach(x=>{
1570                                                         flacComments.push('AUTHOR=' + x);
1571                                                 });
1572                                         }else{
1573                                                 flacComments.push('AUTHOR=' + track.authorString);
1574                                         }
1575                                 if(track.writerString && settings.tags.writer)
1576                                         if (Array.isArray(track.writerString)){
1577                                                 track.writerString.forEach(x=>{
1578                                                         flacComments.push('WRITER=' + x);
1579                                                 });
1580                                         }else{
1581                                                 flacComments.push('WRITER=' + track.writerString);
1582                                         }
1583                                 if(track.engineerString && settings.tags.engineer)
1584                                         if (Array.isArray(track.engineerString)){
1585                                                 track.engineerString.forEach(x=>{
1586                                                         flacComments.push('ENGINEER=' + x);
1587                                                 });
1588                                         }else{
1589                                                 flacComments.push('ENGINEER=' + track.engineerString);
1590                                         }
1591                                 if(track.producerString && settings.tags.producer)
1592                                         if (Array.isArray(track.producerString)){
1593                                                 track.producerString.forEach(x=>{
1594                                                         flacComments.push('PRODUCER=' + x);
1595                                                 });
1596                                         }else{
1597                                                 flacComments.push('PRODUCER=' + track.producerString);
1598                                         }
1599                                 if(track.replayGain && settings.tags.replayGain)
1600                                         flacComments.push('REPLAYGAIN_TRACK_GAIN=' + track.replayGain);
1601
1602                                 const reader = fs.createReadStream(tempPath);
1603                                 const writer = fs.createWriteStream(writePath);
1604                                 let processor = new mflac.Processor({parseMetaDataBlocks: true});
1605                                 let vendor = 'reference libFLAC 1.2.1 20070917';
1606                                 let cover = null;
1607                                 if(track.album.picturePath && settings.tags.cover){
1608                                         cover = fs.readFileSync(track.album.picturePath)
1609                                 }
1610                                 let mdbVorbisPicture
1611                                 let mdbVorbisComment
1612                                 processor.on('preprocess', (mdb) => {
1613                                         // Remove existing VORBIS_COMMENT and PICTURE blocks, if any.
1614                                         if (mflac.Processor.MDB_TYPE_VORBIS_COMMENT === mdb.type) {
1615                                                 mdb.remove();
1616                                         } else if (mflac.Processor.MDB_TYPE_PICTURE === mdb.type) {
1617                                                 mdb.remove();
1618                                         }
1619                                         if (mdb.isLast) {
1620                                                 if(cover){
1621                                                         mdbVorbisPicture = mflac.data.MetaDataBlockPicture.create(true, 3, `image/${(settings.PNGcovers ? "png" : "jpeg")}`, '', settings.artworkSize, settings.artworkSize, 24, 0, cover);
1622                                                 }
1623                                                 mdbVorbisComment = mflac.data.MetaDataBlockVorbisComment.create(!cover, vendor, flacComments);
1624                                                 mdb.isLast = false;
1625                                         }
1626                                 });
1627                                 processor.on('postprocess', (mdb) => {
1628                                         if (mflac.Processor.MDB_TYPE_VORBIS_COMMENT === mdb.type && null !== mdb.vendor) {
1629                                                 vendor = mdb.vendor;
1630                                         }
1631                                         if (mdbVorbisPicture && mdbVorbisComment) {
1632                                                         processor.push(mdbVorbisComment.publish());
1633                                                         processor.push(mdbVorbisPicture.publish());
1634                                                 }else if(mdbVorbisComment){
1635                                                         processor.push(mdbVorbisComment.publish());
1636                                         }
1637                                 });
1638                                 reader.on('end', () => {
1639                                         fs.remove(tempPath);
1640                                 });
1641                                 await reader.pipe(processor).pipe(writer);
1642                         }else{
1643                                 const songBuffer = fs.readFileSync(tempPath);
1644                                 const writer = new ID3Writer(songBuffer);
1645                                 if (settings.tags.title)
1646                                         writer.setFrame('TIT2', track.title)
1647                                 if (settings.tags.artist)
1648                                         writer.setFrame('TPE1', [track.artistsString])
1649                                 if (settings.tags.album)
1650                                         writer.setFrame('TALB', track.album.title)
1651                                 if (settings.tags.albumArtist && track.album.artist)
1652                                         writer.setFrame('TPE2', track.album.artist.name)
1653                                 if (settings.tags.trackNumber)
1654                                         writer.setFrame('TRCK', (settings.tags.trackTotal ? track.trackNumber+"/"+track.trackTotal : track.trackNumber))
1655                                 if (settings.tags.discNumber)
1656                                         writer.setFrame('TPOS', (settings.tags.discTotal ? track.discNumber+"/"+track.discTotal : track.discNumber))
1657                                 if (settings.tags.isrc)
1658                                         writer.setFrame('TSRC', track.ISRC);
1659
1660                                 if (settings.tags.length)
1661                                         writer.setFrame('TLEN', track.duration);
1662                                 if (settings.tags.barcode && track.album.barcode)
1663                                         writer.setFrame('TXXX', {
1664                                                 description: 'BARCODE',
1665                                                 value: track.album.barcode
1666                                         });
1667                                 if(track.album.picturePath && settings.tags.cover){
1668                                         const coverBuffer = fs.readFileSync(track.album.picturePath);
1669                                         writer.setFrame('APIC', {
1670                                                 type: 3,
1671                                                 data: coverBuffer,
1672                                                 description: ''
1673                                         });
1674                                 }
1675                                 if(track.unsyncLyrics && settings.tags.unsynchronisedLyrics)
1676                                         writer.setFrame('USLT', track.unsyncLyrics);
1677                                 if(track.publisher && settings.tags.publisher)
1678                                         writer.setFrame('TPUB', track.publisher);
1679                                 if(track.genreString && settings.tags.genre)
1680                                         writer.setFrame('TCON', [track.genreString]);
1681                                 if(track.copyright && settings.tags.copyright)
1682                                         writer.setFrame('TCOP', track.copyright);
1683                                 if (0 < parseInt(track.date.year)) {
1684                                         if (settings.tags.date)
1685                                                 writer.setFrame('TDAT', track.dateString);
1686                                         if (settings.tags.year)
1687                                                 writer.setFrame('TYER', track.date.year);
1688                                 }
1689                                 if (0 < parseInt(track.bpm) && settings.tags.bpm)
1690                                         writer.setFrame('TBPM', track.bpm);
1691                                 if(track.composerString && settings.tags.composer)
1692                                         writer.setFrame('TCOM', [track.composerString]);
1693                                 if(track.replayGain && settings.tags.replayGain)
1694                                         writer.setFrame('TXXX', {
1695                                                 description: 'REPLAYGAIN_TRACK_GAIN',
1696                                                 value: track.replayGain
1697                                         });
1698                                 writer.addTag();
1699                                 const taggedSongBuffer = Buffer.from(writer.arrayBuffer);
1700                                 fs.writeFileSync(writePath, taggedSongBuffer);
1701                                 fs.remove(tempPath);
1702                         }
1703                 }
1704                 logger.info(`[${track.artist.name} - ${track.title}] Downloaded`)
1705         }
1706 })
1707
1708 // Helper functions
1709
1710 /**
1711  * Updates individual parameters in the settings file
1712  * @param config
1713  * @param value
1714  */
1715 function updateSettingsFile(config, value) {
1716         configFile.userDefined[config] = value;
1717
1718         fs.outputFile(configFileLocation, JSON.stringify(configFile, null, 2), function (err) {
1719                 if (err) return;
1720                 logger.info("Settings updated");
1721
1722                 // FIXME: Endless Loop, due to call from initFolders()...crashes soon after startup
1723                 // initFolders();
1724         });
1725 }
1726
1727 function fixName (txt) {
1728   const regEx = /[\0\/\\:*?"<>|]/g;
1729   txt = txt.replace(regEx, '_');
1730   txt = txt.slice(0,200);
1731   return txt;
1732 }
1733
1734 function antiDot(str){
1735         while(str[str.length-1] == "." || str[str.length-1] == " " || str[str.length-1] == "\n"){
1736                 str = str.substring(0,str.length-1);
1737         }
1738         if(str.length < 1){
1739                 str = "dot";
1740         }
1741         return fixName(str);
1742 }
1743
1744 /**
1745  * Initialize the temp folder for covers and main folder for downloads
1746  */
1747 function initFolders() {
1748         // Check if main folder exists
1749         if (!fs.existsSync(mainFolder)) {
1750                 mainFolder = defaultDownloadFolder;
1751                 updateSettingsFile('downloadLocation', defaultDownloadFolder);
1752         }
1753         //fs.removeSync(coverArtFolder);
1754         //fs.ensureFolderSync(coverArtFolder);
1755 }
1756
1757 /**
1758  * Creates the name of the tracks replacing wildcards to correct metadata
1759  * @param track
1760  * @param filename
1761  * @param playlist
1762  * @returns {XML|string|*}
1763  */
1764 function settingsRegex(track, filename, playlist, saveFullArtists, paddingSize) {
1765         try{
1766                 filename = filename.replace(/%title%/g, track.title);
1767                 filename = filename.replace(/%album%/g, track.album);
1768                 filename = filename.replace(/%artist%/g, (saveFullArtists ? track.artistsString : track.artist.name));
1769                 filename = filename.replace(/%year%/g, track.date.year);
1770                 filename = filename.replace(/%label%/g, track.publisher);
1771                 if(typeof track.trackNumber != 'undefined'){
1772                         if(configFile.userDefined.padtrck){
1773                                  filename = filename.replace(/%number%/g, pad(track.trackNumber, (parseInt(paddingSize)>0 ? parseInt(paddingSize) : track.trackTotal)));
1774                         }else{
1775                                 filename = filename.replace(/%number%/g, track.trackNumber);
1776                         }
1777                 } else {
1778                         filename = filename.replace(/%number%/g, '');
1779                 }
1780                 filename = filename.replace(/%explicit%/g, (track.explicit==="1" ? (filename.indexOf(/[^%]explicit/g)>-1 ? "" : "(Explicit Version)") : ""));
1781                 return filename.trim();
1782         }catch(e){
1783                 if (typeof e == "Error") throw e; else throw new Error(e)
1784         }
1785 }
1786
1787 /**
1788  * Creates the name of the albums folder replacing wildcards to correct metadata
1789  * @param metadata
1790  * @param foldername
1791  * @returns {XML|string|*}
1792  */
1793 function settingsRegexAlbum(foldername, artist, album, year, rtype, explicit, publisher) {
1794         foldername = foldername.replace(/%album%/g, album);
1795         foldername = foldername.replace(/%artist%/g, artist);
1796         foldername = foldername.replace(/%year%/g, year);
1797         if (rtype){
1798                 foldername = foldername.replace(/%type%/g, rtype[0].toUpperCase() + rtype.substring(1));
1799         }else{
1800                 foldername = foldername.replace(/%type%/g, "");
1801         }
1802         foldername = foldername.replace(/%label%/g, publisher);
1803         foldername = foldername.replace(/%explicit%/g, (explicit ? (foldername.indexOf(/[^%]explicit/g)>-1 ? "" : "(Explicit)") : ""));
1804         return foldername.trim();
1805 }
1806
1807 function settingsRegexCover(foldername, artist, name) {
1808         foldername = foldername.replace(/%name%/g, name);
1809         foldername = foldername.replace(/%artist%/g, artist);
1810         return foldername;
1811 }
1812
1813 function settingsRegexArtistCover(foldername, artist) {
1814         foldername = foldername.replace(/%artist%/g, artist);
1815         return foldername;
1816 }
1817
1818 /**
1819  * Pad number with 0s so max and str have the same nuber of characters
1820  * @param str
1821  * @param max
1822  * @returns {String|string|*}
1823  */
1824 function pad(str, max) {
1825         str = str.toString();
1826         max = max.toString();
1827         return str.length < max.length || str.length == 1 ? pad("0" + str, max) : str;
1828 }
1829
1830 /**
1831  * Splits the %number%
1832  * @param string str
1833  * @return string
1834  */
1835 function splitNumber(str,total){
1836         str = str.toString();
1837         let i = str.indexOf("/");
1838         if(total && i > 0){
1839                 return str.slice(i+1, str.length);
1840         }else if(i > 0){
1841                 return str.slice(0, i);
1842         }else{
1843                 return str;
1844         }
1845         return i > 0 ? str.slice(0, i) : str;
1846 }
1847
1848 function swichReleaseType(id){
1849         switch (id) {
1850                 case "0":
1851                         return "Album";
1852                 case "1":
1853                         return "Single";
1854                 case "3":
1855                         return "EP";
1856                 default:
1857                         return id;
1858         }
1859 }
1860
1861 function uniqueArray(origin, destination, removeDupes=true){
1862         Array.from(new Set(origin)).forEach(function(x){
1863                 if(destination.indexOf(x) == -1)
1864                         destination.push(x);
1865         });
1866         if (removeDupes){
1867                 destination.forEach((name,index)=>{
1868                         destination.forEach((name2,index2)=>{
1869                                 if(!(index===index2) && (name.indexOf(name2)!== -1)){
1870                                         destination.splice(index, 1);
1871                                 }
1872                         })
1873                 })
1874         }
1875 }
1876
1877 // Show crash error in console for debugging
1878 process.on('unhandledRejection', function (err) {
1879         if (err) logger.error(err.stack ? err.stack : err)
1880
1881 })
1882 process.on('uncaughtException', function (err) {
1883         if (err) logger.error(err.stack ? err.stack : err)
1884 })
1885
1886 // Exporting vars
1887 module.exports.mainFolder = mainFolder
1888 module.exports.defaultSettings = defaultSettings
1889 module.exports.defaultDownloadFolder = defaultDownloadFolder