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