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