-
Notifications
You must be signed in to change notification settings - Fork 3
/
preload.js
1349 lines (1201 loc) · 52.6 KB
/
preload.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.
const electron = require('electron').remote
const dialog = electron.dialog
const fs = require('fs')
const utils = require('./node_modules/roseboxlib/utils.js')
const walk = require('fs-walk')
const mm = require('music-metadata');
const Autocomplete = require('@trevoreyre/autocomplete-js')
//const sortable = require('html5sortable/dist/html5sortable.cjs.js')
const slash = process.platform === 'win32' ? "\\" : "/" //desktop file slash
const pslash = "/" //playlist file slash
const bull = `•`
const specialRegex = new RegExp("[^\x00-\x7F]", "gm")
var config = utils.initOrLoadConfig("./config.json")
console.log("config: ", config)
var allSongs = []
var allPlaylists = []
var currPlaylist = []
var editablePlaylists = []
var songsAndPlaylists = []
var playlistName = "Untitled Playlist"
var lastPlaylistName = "" //so we don't have to prompt to save every time
var savePath = ""
var unsavedChanges = false
var mainsearch
var specialMode = false
var artistMode = false
var allSongsAreTagged = false
var autocompArr = "both" //both = songsAndPlaylists, playlists = allPlaylists
/* ui and other handling */
window.addEventListener('DOMContentLoaded', () => {
console.log("loaded")
if (!fs.existsSync("./covers")){fs.mkdirSync("./covers")} //create covers dir if neccessary
if (config.maindir !== "") {selectfolder(null, config)}
//bottom bar
document.getElementById('cancel').addEventListener("click", discardPlaylistPrompt)
document.getElementById('save').addEventListener("click", savePlaylistPrompt)
document.getElementById("folder-open").addEventListener("click", selectfolder)
document.getElementById('settings').addEventListener("click", initSettings)
document.getElementById("printPlaylist").addEventListener("click", () => {console.log("currPlaylist: ", currPlaylist)})
document.getElementById("spe-hide").addEventListener("click", () => {document.getElementById("sp-extra").classList.add("hidden-f")}) //hide extra preview
//sidebar
document.getElementById("gen").addEventListener("click",gen)
document.getElementById('prg').addEventListener("click", purgePlaylists)
document.getElementById('com').addEventListener("click", playlistOnlyToggle)
//playlist bar
document.getElementById('new').addEventListener("click", renamePlaylist)
document.getElementById('titleh').addEventListener("scroll", (event) => {event.target.scrollTop = 0})
//search
document.getElementById('special').addEventListener("click", specialSearch)
document.getElementById('mode-toggle').addEventListener("click", artistModeToggle)
document.addEventListener("keydown", (e) => { //make tab do the same thing as enter
if(e.which == 9){
let song = {}
//get the song index from the index attribute
if (autocompArr == "both") {
song = songsAndPlaylists[parseInt(e.target.value.replaceAll('<span index="', "").split('"')[0])]
} else if (autocompArr == "playlists") {
song = allPlaylists[parseInt(e.target.value.replaceAll('<span index="', "").split('"')[0])]
}
autocompleteSubmit(song, true)
e.target.focus()
}
})
//settings
document.getElementById("g-repo").addEventListener("click", () => {
electron.shell.openExternal("http://github.com/KraXen72/playlist-manager")
})
})
//select main dir
async function selectfolder(mouseevent, inputconfig) {
if (typeof inputconfig === "undefined") { //clicked on the pick button
pick = await dialog.showOpenDialog({properties: ['openDirectory']})
console.log(pick)
if (pick.canceled == false) {
//we need to reload the app when picking a new folder. this checks if user wants to proceed or not
if (currPlaylist.length > 0 && unsavedChanges == true) {
let msgc = await dialog.showMessageBoxSync({
message: "selecting a new main directory clears your current playlist. do you wish to proceed?",
type: "question",
buttons: ["Discard playlist and Proceed", "Cancel"],
noLink: true
})
if (msgc == 0) {
config.maindir = pick.filePaths[0]
utils.saveConfig("./config.json", config)
window.location.reload()
}
} else { //if user didn't make a playlist then just reload without asking
config.maindir = pick.filePaths[0]
utils.saveConfig("./config.json", config)
window.location.reload()
}
}
} else { //loaded from config
config.maindir = inputconfig.maindir
document.getElementById("selected-folder").innerText = utils.shortenFilename(config.maindir.toString(), 40)
document.getElementById("gen").removeAttribute("disabled")
document.getElementById("input-placeholder").innerHTML = "Getting all songs, plese wait..."
fetchAllSongs()
}
}
async function notReady(mode) { //true, turn on notReady, false, turn off notready
if (mode == true) {
unsavedChanges = true
document.getElementById("save").classList.add("btn-danger")
} else if (mode == false) {
unsavedChanges = false
document.getElementById("save").classList.remove("btn-danger")
}
}
//autocomplete
//autocomplete
function setupAutocomplete(message) {
document.getElementById("input-placeholder").innerHTML = `Start typing a name of a ${message}...`
mainsearch = new Autocomplete('#autocomplete', {
search: input => {
if (input.length < 1 && specialMode == false && autocompArr == "both") { return [] }
let res = autocompArr == "both" ? songsAndPlaylists : autocompArr == "playlists" ? allPlaylists : []
if (artistMode == false) {
res = res.filter(song => { //find matches
return song.filename.toLowerCase().includes(input.toLowerCase()) //fuck regex we doin includes
})
} else {
res = res.filter(song => { //find matches
return song.tag.artist.toLowerCase().includes(input.toLowerCase()) //fuck regex we doin includes
})
}
res = res.filter(song => { //filter out things already in playlist to avoid duplicates
for (let i = 0; i < currPlaylist.length; i++) {if (song.filename == currPlaylist[i].filename) {return false} };return true
})
if (specialMode == true) {
res = res.filter(song => {
const regex = new RegExp(`[^\\x00-\\x7F]`, 'gi');
return song.filename.match(regex)
})
}
//sort the results so playlists are on top
res.sort((a, b) => { if (a.type == "playlist" && b.type == "song") { return -1 } else if (a.type == "song" && b.type == "playlist") { return 1 } else { return 0} })
//if specialmode or playlist only mode then return full results, otherwise first 10
return specialMode == true || autocompArr == "playlists" || artistMode == true ? res : res.slice(0, 10)
},
onUpdate: (results, selectedIndex) => {
if (selectedIndex > -1) { updatePreview(results[selectedIndex], false)} //update the song preview
},
onSubmit: result => { //final pick
autocompleteSubmit(result, true)
},
autoSelect: true,
getResultValue: result => {
let final = utils.getExtOrFn(result.filename).fn
let res = autocompArr == "both" ? songsAndPlaylists : autocompArr == "playlists" ? allPlaylists : []
return `<span index="${res.indexOf(result)}">${final}${result.type == "playlist" && autocompArr == "both" ? ` (Playlist)` : ""}</span>`
} //show the filename in the result
})
mainsearch.destroy = () => {autocompleteDestroy(mainsearch)}
}
//autocomplete onSubmit
async function autocompleteSubmit(result, refocus, update) {
if (update !== undefined) {
await updatePreview(result, false, update) //update preview without updating, basically just tag song
} else {
await updatePreview(result, false) //update preview
}
document.getElementById("command-line-input").value = '' //clear the input
await addSong(result, refocus) //add the song to current playlist
}
//special serach
function specialSearch() {
document.getElementById("special").classList.toggle("btn-active")
specialMode = specialMode == true ? false : true
}
//playlist only mode
function playlistOnlyToggle() {
let com = document.getElementById("com")
let con = -1
let onlyContainsPlaylists = true
for (let i = 0; i < currPlaylist.length; i++) {
const song = currPlaylist[i];
if (song.type == "song") {
onlyContainsPlaylists = false;
break;
}
}
if (currPlaylist.length == 0 || unsavedChanges == false || onlyContainsPlaylists == true) {
con = 0
} else {
let act = autocompArr == "both" ? "change to" : "exit from"
con = dialog.showMessageBoxSync({
message: `Do you wish to discard current playlist and ${act} Playlist only mode?`,
type: "question",
buttons: [`Discard playlist and ${act} Playlist only mode`, "Cancel"],
noLink: true
})
}
if (con == 0) {
if (onlyContainsPlaylists == false){discardPlaylist()}
if (autocompArr == "both") {
com.classList.add("btn-active")
mainsearch.destroy()
autocompArr = "playlists"
setupAutocomplete("playlist")
} else {
com.classList.remove("btn-active")
mainsearch.destroy()
autocompArr = "both"
setupAutocomplete("song or playlist")
}
return true
} else {
return false
}
}
async function artistModeToggle() {
let btn = document.getElementById("mode-toggle")
if (artistMode == false) {
let disablepom = false
if (autocompArr == "playlists") {
disablepom = dialog.showMessageBoxSync({
message: "Searching by artist is not available in playlist only mode. What do you want to do?",
type: "question",
buttons: ["Exit playlist-only mode and search by artist", "Stay in playlist-only mode"],
noLink: true
})
if (disablepom == 0){
disablepom = true
playlistOnlyToggle()
} else {
disablepom = false
}
} else {
disablepom = true
}
if (disablepom == true) {
btn.querySelector('.md-person_search').setAttribute("hidden", "true")
artistMode = true
if (allSongsAreTagged == false) {
let throbber = btn.querySelector('.md-autorenew')
throbber.removeAttribute("hidden")
throbber.classList.add("rotate")
await fetchMissingArtists()
throbber.classList.remove("rotate")
throbber.setAttribute("hidden", "true")
}
btn.querySelector('.md-library_music').removeAttribute("hidden")
document.getElementById('input-placeholder').textContent = `Search songs by artist...`
btn.title = "search by title"
}
} else {
btn.querySelector('.md-person_search').removeAttribute("hidden")
btn.querySelector('.md-library_music').setAttribute("hidden", "true")
artistMode = false
btn.title = "search by artist"
document.getElementById('input-placeholder').textContent = `Start typing a name of a ${autocompArr == "both" ? "song or playlist" : "playlist"}...`
}
}
async function fetchMissingArtists() {
let inp = document.getElementById('command-line-input')
let btn = document.getElementById("mode-toggle")
let sprog = document.getElementById("sprog")
sprog.style.width = `0`
sprog.style.opacity = `100%`
inp.setAttribute("disabled", "true")
btn.setAttribute("disabled", "true")
document.getElementById('input-placeholder').textContent = "Getting artist for each song, please wait..."
for (let i = 0; i < songsAndPlaylists.length; i++) {
var song = songsAndPlaylists[i];
sprog.style.width = `${i / songsAndPlaylists.length * 100}%`
if (song.tag == undefined) {
song.tag = await getEXTINF(song.fullpath, song.filename, true, false)
} else {
continue;
}
}
allSongsAreTagged = true
sprog.style.width = `100%`
setTimeout(() => {sprog.style.opacity = `0%`}, 500)
setTimeout(() => {sprog.style.width = `0%`}, 1250)
mainsearch.destroy()
inp.removeAttribute("disabled")
btn.removeAttribute("disabled")
setupAutocomplete(autocompArr == "both" ? "song or playlist" : "playlist")
}
//preview
/**
* update the song preview
* @param {Object} song object
* @param {Boolean} empty True means clear preveiw
* @param {Boolean} updateOverride override if we should update
* @param {Boolean} extraInfo if we should fetch extra info about the song and display everything
*/
async function updatePreview(song, empty, updateOverride, extraInfo) {
let index = document.getElementById("song-preview").getAttribute("index")
let type = document.getElementById("song-preview").getAttribute("type")
let tag = {} //artist, title, album, duration, cover, extinf, coverobj
let update = true //if we should update
if (updateOverride !== undefined) {
update = updateOverride
}
if (empty == false) {
if (song.index !== index || song.type !== type || update == true) {
if (song.type == "song") {
if (extraInfo !== undefined && extraInfo === true) { //fetch extra info if wanted
tag = await getEXTINF(song.fullpath, song.filename, true, false, true)
} else {
tag = await getEXTINF(song.fullpath, song.filename, true, false)
}
//console.log(song)
} else if (song.type == "playlist") {
tag = {
title: song.filename,
artist: `Playlist ${bull} ${song.songs.length / 2} Songs`,
album: utils.shortenFilename(song.fullpath, 55),
cover: config.comPlaylists[song.fullpath] !== undefined ? "img/generated.png" : "img/playlist.png"
}
}
song.tag = tag
document.getElementById("song-preview").setAttribute("index", song.index.toString())
document.getElementById("song-preview").setAttribute("type", song.type.toString())
} else { //its the same song
update = false
}
} else { tag = { artist: "", title: "", album: "", cover: "" } } //just clear the preview
//console.log(tag)
if (update == true) {
if (document.getElementById("song-preview").style.visibility == "hidden"){document.getElementById("song-preview").style.visibility = "visible"}
document.getElementById("sp-cover").src = `${tag.cover}`
document.getElementById("sp-title").textContent = tag.title
document.getElementById("sp-artist").innerHTML = tag.artist
document.getElementById("sp-album").textContent = tag.album
if (extraInfo !== undefined && extraInfo === true) {
let dur = `${Math.floor(Math.floor(tag.duration)/1000 / 60)}:${utils.zeropad(Math.floor(tag.duration/1000) % 60, 2)}` //get min and sec from duration, zeropad it
//TODO rewrite complex preview assignment
//there probably has to be a better way to do this?
//maybe like pass these as an object or an array where there is the desired value + queryselector. and map/assign in a loop
document.getElementById("sp-extra").classList.remove("hidden-f")
document.getElementById("spe-fullpath").textContent = utils.shortenFilename(song.fullpath, 35)
document.getElementById("spe-fullpath").setAttribute("title", song.fullpath)
document.getElementById("spe-genre").textContent = tag.extrainfo.genre
document.getElementById("spe-format").textContent = tag.extrainfo.format
document.getElementById("spe-duration").textContent = dur == "0:0" ? "Unknown" : dur
document.getElementById("spe-bitrate").textContent = tag.extrainfo.bitrate
document.getElementById("spe-size").textContent = tag.extrainfo.size
document.getElementById("spe-samplerate").textContent = tag.extrainfo.samplerate
document.getElementById("spe-year").textContent = tag.extrainfo.year
} else {
document.getElementById("sp-extra").classList.add("hidden-f")
}
}
}
//settings
function initSettings() {
let body = document.getElementById("settings-body")
//closeSettings()
if (body.style.display !== "block") {
body.style.display = "block"
document.getElementById("coverpop-body").classList.add("hidden-f") //hide previous popup if there was one
document.getElementById('settings-close').onclick = closeSettings
document.getElementById("settings-submit").onclick = saveSettings
fillSettingPills("settings-exts", config.exts)
document.getElementById('settings-exts-add').onclick = () => {addPill('settings-exts', 'settings-exts-input')}
fillSettingPills("settings-ign", config.ignore)
document.getElementById('settings-ign-add').onclick = () => {addPill('settings-ign', 'settings-ign-input')}
document.getElementById('settings-ign-pick').onclick = () => {pickFolderAndFillInput('settings-ign-input')}
document.getElementById('settings-config-import').onclick = () => {importSettings()}
}
}
function closeSettings() {
document.getElementById("settings-body").style.display = "none"
}
function saveSettings() {
config.exts = [...document.getElementById("settings-exts").querySelectorAll(".pillval")].map(pill => pill.innerText)
config.ignore = [...document.getElementById("settings-ign").querySelectorAll(".pillval")].map(pill => pill.innerText)
utils.saveConfig("./config.json", config)
}
function importSettings() {
let inp = document.getElementById('settings-config-input')
let sp = inp.nextElementSibling //span
let conf = {}
try { //import config
conf = JSON.parse(inp.value)
console.log(conf)
inp.value = ""
utils.saveConfig("./config.json", conf)
window.location.reload()
} catch (e) { //error message
sp.textContent = "invalid json"
sp.classList.add("btn-dangerf")
inp.value = ""
setTimeout(() => {sp.textContent = "Paste json here";sp.classList.remove("btn-dangerf")}, 2000)
}
}
//TODO rewrite this in either like object/constructor type of thing (i do new TagArea(querySelector) and it would set all this up) or react/vue any other frontend framework
//settings pills
//add a pill to wrapper
function addPill(wrapperid, inputid) {
add = document.getElementById(inputid).value
if (document.getElementById(wrapperid).innerText == "Nothing found"){document.getElementById(wrapperid).innerHTML = ""} //clear the nothing found
if (add !== "") {
document.getElementById(wrapperid).innerHTML +=
`<div class="pill"><span class="pillval">${add}</span><button class="closepill" onclick="this.parentElement.remove()">×</button></div>`
document.getElementById(inputid).value = ""
}
}
//fill a wrapper with pills from an array
function fillSettingPills(wrapperid, settingarr) {
document.getElementById(wrapperid).innerHTML = ""
if (settingarr.length > 0) {
for (let i = 0; i < settingarr.length; i++) {
document.getElementById(wrapperid).innerHTML +=
`<div class="pill"><span class="pillval">${settingarr[i]}</span><button class="closepill" onclick="this.parentElement.remove()">×</button></div>`
}
} else {
document.getElementById(wrapperid).innerHTML = `Nothing found`
}
}
//pick a folder using electron dialog and then add the folder name to the #${inputid} input
async function pickFolderAndFillInput(inputid) {
pick = await dialog.showOpenDialog({properties: ['openDirectory']})
console.log(pick)
if (pick.canceled == false) {
let fullpath = pick.filePaths[0]
let splitarr = fullpath.split(slash)
document.getElementById(inputid).value = splitarr[splitarr.length - 1]
}
}
//album cover display popup
/**
* show the cover of clicked song but big
* @param {String} src path to album cover image
*/
function popCover(src) {
let popBody = document.getElementById("coverpop-body")
let popImg = document.getElementById("coverdisplay")
document.getElementById("coverpop-close").onclick = () => {popBody.classList.add("hidden-f")}
popBody.classList.remove("hidden-f")
popImg.setAttribute("src", src)
}
/*playlist handling*/
/*new playlist*/
function renamePlaylist() {
let newbtn = document.getElementById("new")
let titleh = document.getElementById("titleh")
let inp = document.getElementById("playlist-name-input")
let sub = document.getElementById("playlist-name-submit")
let canc = document.getElementById("playlist-name-cancel")
let wrap = document.getElementById("playlist-name-wrapper")
wrap.style.display = "block"
sub.style.display = "flex"
canc.style.display = "flex"
newbtn.style.display = "none"
titleh.style.display = "none"
inp.focus()
sub.onclick = () => {
if (inp.value.replaceAll(" ", "") !== "") {
playlistName = inp.value
sub.style.display = "none"
canc.style.display = "none"
titleh.style.display = "-webkit-box"
wrap.style.display = "none"
sub.onclick = ""
canc.onclick = ""
titleh.textContent = playlistName
newbtn.style.display = "flex"
}
}
canc.onclick = () => {
sub.style.display = "none"
canc.style.display = "none"
titleh.style.display = "-webkit-box"
wrap.style.display = "none"
sub.onclick = ""
canc.onclick = ""
newbtn.style.display = "flex"
}
}
function discardPlaylistPrompt() {
if (currPlaylist.length > 0 && unsavedChanges == true) {
document.getElementById("command-line-input").blur()
let con = dialog.showMessageBoxSync({
message: "do you wish to discard current playlist?",
type: "question",
buttons: ["Discard playlist", "Cancel"],
noLink: true
})
if (con == 0) {
discardPlaylist()
}
} else {
discardPlaylist()
}
}
//discard the current playlist
function discardPlaylist() {
notReady(false)
utils.clearFolder("./covers")
document.getElementById("playlist-bar").querySelectorAll(".songitem").forEach(s => s.remove())
currPlaylist = []
document.getElementById("song-preview").style.visibility = "hidden"
document.getElementById("openspan").style.display = "block"
playlistName = "Untitled Playlist"
document.getElementById("titleh").textContent = playlistName
if (autocompArr == "playlists"){document.getElementById("com").click()}
}
function savePlaylistPrompt() {
if (currPlaylist.length > 0) {
let onlyContainsPlaylists = true
for (let i = 0; i < currPlaylist.length; i++) {
const song = currPlaylist[i];
if (song.type == "song") {
onlyContainsPlaylists = false;
break;
}
}
if (onlyContainsPlaylists && autocompArr == "both") {
let con = -1
con = dialog.showMessageBoxSync({
message: "Do you want to save this as a combined playlist?",
detail: `Combined Playlists can only consist of other playlists, but if if any of the playlists update (you add a new song), you can easily re-make/update the generated playlist to include all the new stuff.`,
type: "question",
buttons: ["Save as Combined Playlist", "Save as a normal Playlist"],
noLink: true
})
if (con == 0) {
document.getElementById("com").click()
}
}
if (playlistName == "Untitled Playlist") {
dialog.showMessageBoxSync({"message": "Please name your playlist first"})
} else {
if (autocompArr == 'playlists') {
let cPlaylist = currPlaylist.map(p => {return {"filename": p.filename, "fullpath": p.fullpath, "relativepath": p.relativepath}})
config.comPlaylists[`${config.maindir + slash + playlistName}.m3u`] = cPlaylist
utils.saveConfig("./config.json", config)
}
if (playlistName == lastPlaylistName && savePath !== undefined) {
savePlaylist()
} else {
new Notification("playlist-manager", {
body: `Your playlist has been saved to:\n${config.maindir + slash + playlistName}.m3u`,
icon: "img/playlist.png",
timeoutType: "default",
})
savePath = `${config.maindir + slash + playlistName}.m3u`
if (savePath !== undefined) { lastPlaylistName = playlistName; savePlaylist() }
}
}
}
}
function savePlaylist() { //actually save the playlist
notReady(false)
let lines = getPlaylistContent() //this is with duplicate songs possible
lines = removeDuplicatesFromPlaylist(lines)
fs.writeFileSync(savePath, lines.join("\n"))
document.getElementById("save").classList.add("btn-active")
loadPlaylistsSidebar(editablePlaylists)
setTimeout(() => {document.getElementById("save").classList.remove("btn-active")}, 1000)
}
/**
* get a array of lines in extm3u (to write) from the currPlaylist (global)
*/
function getPlaylistContent() {
//console.log(currPlaylist)
let play = []
play.push("#EXTM3U")
for (let i = 0; i < currPlaylist.length; i++) {
const song = currPlaylist[i];
if (song.type == "song") {
play.push(song.tag.extinf)
play.push(song.relativepath.replaceAll(slash, pslash))
} else if (song.type == "playlist") {
let spl = song.relativepath.split(slash)
let relpath = spl.slice(0, spl.length-1).join(pslash) //what does this shit even do??
//console.log(relpath)
for (let i = 0; i < song.songs.length; i++) {
const item = song.songs[i];
if (item.includes("#EXTINF")) {
play.push(item)
} else {
play.push([relpath, item].join(pslash))
}
}
}
}
//it saves all paths with normal slashes
return play
}
/**
* remove duplicates from an array of m3u lines
* @param {Array} arr array of lines in extm3u syntax
* @returns array of lines in extm3u syntax without duplicates
*/
function removeDuplicatesFromPlaylist(arr) {
//console.log("initial_songs: ", arr)
let uniqueSongs = new Set(arr)
uniqueSongs = [...uniqueSongs]
//console.log("unique: ", uniqueSongs)
return uniqueSongs
}
//add a song to the current playlist
async function addSong(songobj, refocus) {
notReady(true)
let tag = songobj.tag
let songElem = document.createElement("div")
let remElem = document.createElement("div")
let moreElem = document.createElement("div")
let id = Date.now().toString()
if (tag.coverobj !== false && songobj.type == "song") {
fs.writeFileSync(`covers${slash}cover-${id}.${tag.coverobj.frmt}`, tag.coverobj.data)
}
let imgpath = ""
if (songobj.type == "song") {
imgpath = `covers/cover-${id}.${tag.coverobj !== false ? tag.coverobj.frmt : "png"}`
} else if (songobj.type == "playlist") {
imgpath = config.comPlaylists[songobj.fullpath] !== undefined ? "img/generated.png" : "img/playlist.png"
}
songElem.className = "songitem"
let siOptions = {
coverid: id,
coversrc: imgpath,
title: tag.title,
artist: tag.artist,
album: tag.album,
filename: songobj.filename,
strong: false
}
songElem.innerHTML = generateSongitem(siOptions)
songElem.setAttribute("index", songobj.index.toString())
moreElem.classList.add("songitem-button"/*, "hidden", "vertical-icon-minwidth"*/)
moreElem.setAttribute("title", "more options")
let mmfunction = (event) => {
let opt = {event, buttons: []}
if (songobj.type == "playlist") { //playlist specific
opt.buttons.push({
text: "Details",
run: () => {
let msg = ""
if (config.comPlaylists[songobj.fullpath] !== undefined) {
msg = `This generated playlist contains these playlists:\n${config.comPlaylists[songobj.fullpath].map(pl => pl.filename).join("\n")}`
} else {
msg = `This playlist contains:\n${songobj.songs.filter(line => !line.includes("#EXTINF")).join("\n")}`
}
dialog.showMessageBoxSync({
message: msg,
type: "info",
noLink: true
})
}
})
} else { //song specific
opt.buttons.push(
{ text: "Details",
run: () => {
updatePreview(songobj, false, true, true)
}},
{ text: "View cover",
run: () => {
popCover(imgpath)
}}/*,
{ text: "Edit Tags",
run: () => {
alert("placeholder for tag editor")
}}*/
)
}
utils.summonMenu(opt)
}
moreElem.innerHTML = `<i class="material-icons-round md-more_vert"></i>`
moreElem.onclick = mmfunction
songElem.oncontextmenu = mmfunction
remElem.classList.add("songitem-button")
remElem.setAttribute("title", "Remove song from this playlist")
remElem.innerHTML = `<i class="material-icons-round md-close"></i>`
remElem.onclick = () => {
notReady(true)
if (currPlaylist.length == 1) { document.getElementById("song-preview").style.visibility = "hidden" }
for (let i = 0; i < currPlaylist.length; i++) {
const song = currPlaylist[i];
if (songobj.fullpath == song.fullpath) {
currPlaylist.splice(i, 1)
break;
}
}
if (currPlaylist.length == 0) {
document.getElementById("openspan").style.display = "block"
}
if (songobj.type == "song"){
try {fs.unlinkSync(`covers${slash}cover-${id}.${tag.coverobj.frmt}`)} catch(e){
console.log("failed to delete cover, probably")
}
}
songElem.remove()
}
songElem.querySelector(".songitem-button-wrap").appendChild(moreElem)
songElem.querySelector(".songitem-button-wrap").appendChild(remElem)
if (currPlaylist.length == 0) {
document.getElementById("openspan").style.display = "none"
}
let pb = document.getElementById("playlist-bar")
pb.appendChild(songElem)
songElem.scrollIntoView()
//this briefly selects the image to update it because some images are wierd and don't render on their own
setTimeout(() => {
document.getElementById("command-line-input").blur()
var s = window.getSelection()
var r = document.createRange();
s.removeAllRanges()
r.selectNode(songElem.querySelector(".songitem-cover-wrap"));
s.addRange(r)
setTimeout(() => {s.removeAllRanges();
setTimeout((refocus) => {
if (refocus == true) { document.getElementById("command-line-input").focus() }
}, 3, refocus)
}, 10, refocus)
}, 2, refocus)
if (songobj.type == "song") {
songobj.tag.cover = ""
songobj.tag.coverobj.data = ""
}
currPlaylist.push(songobj)
}
//return the innerhtml for a songitem element
function generateSongitem(val) {
let strongtag = val.strong !== undefined && val.strong == true ? ["<strong>", "</strong>"] : ["", ""];
if (!fs.existsSync(val.coversrc)) {val.coversrc = ""};
return `
<div class="songitem-cover-wrap">
<div class="songitem-cover-placeholder" style = "${val.coversrc !== "" ? "display: none": ""}"></div>
<img class="songitem-cover cover-${val.coverid}" draggable="false" loading="lazy" src="${val.coversrc}" onerror = "this.src = 'img/placeholder.png'" style = "${val.coversrc == "" ? "display: none": ""}"></img>
</div>
<div class="songitem-title" title="${utils.fixQuotes(val.title)}">${strongtag[0]}${val.title}${strongtag[1]}</div>
<div class="songitem-aa">
<span class="songitem-artist" title="${utils.fixQuotes(val.artist)}">${val.artist}</span> • <span class = "songitem-album" title="${utils.fixQuotes(val.album)}">${val.album}</span>
</div>
<div class="songitem-filename" hidden>${val.filename}</div>
<div class="songitem-button-wrap"></div>
`
}
/*playlist handling - file manipulation etc*/
//walk all directories and then call generateM3U()
const gen = async () => {
let alldirs = []
let gprog = document.getElementById("gprog") //generate progress bar
let genbutton = document.getElementById("gen")
genbutton.setAttribute("disabled","true")
gprog.style.width = `0`
gprog.style.opacity = `100%`
walk.dirsSync(config.maindir, (basedir, filename, stats) => {
alldirs.push({basedir, filename, "fullpath": basedir + slash + filename, stats})
})
if (config.ignore.length > 0) { //if there are some folders to ignore, then filter out the folders
alldirs = alldirs.filter(dir => {
for (let i = 0; i < config.ignore.length; i++) { //traditional for loop so i can return out of filter and not forEach
const word = config.ignore[i];
if (dir.fullpath.includes(word)) { //if the full path includes the blacklisted word, filter the dir out.
return false
}
}
return true
})
}
//console.log(alldirs)
for (let i = 0; i < alldirs.length; i++) {
const dir = alldirs[i];
await generateM3U(dir.fullpath, true)
gprog.style.width = `${i / alldirs.length * 100}%`
}
gprog.style.width = `100%`
setTimeout(() => {gprog.style.opacity = `0%`}, 500)
setTimeout(() => {gprog.style.width = `0%`}, 1250)
//await generateM3U(alldirs[22].fullpath, true)
console.log("done")
genbutton.removeAttribute("disabled")
genbutton.classList.add("btn-active")
setTimeout(() => { genbutton.classList.remove("btn-active") }, 1000)
};
//generate a m3u for given folder
async function generateM3U(folder, useEXTINF) {
const allsongs = []
if (useEXTINF) {allsongs.push("#EXTM3U")}
let relativedir = folder.split(slash)
relativedir = relativedir[relativedir.length -1]
let appendname = ""
//console.log(relativedir)
let walksongs = []
//find all songs in the folder
walk.filesSync(folder, (basedir, filename) => {
walksongs.push({basedir, filename})
})
//loop through all of them
for (let i = 0; i < walksongs.length; i++) {
const walksong = walksongs[i];
let filename = walksong.filename
let basedir = walksong.basedir
song = filename
songext = utils.getExtOrFn(song).ext
if (basedir.replace(folder, "").length > 0) { //stupid fucking piece of shit
appendname = basedir.replace(folder, "").replace(slash, "")
if (appendname.length > 0) {appendname += pslash}
}
//if the song extension is in allowed list
if (config.exts.includes(songext)) {
if (useEXTINF == true) {
//get info about the song
let extinf = await getEXTINF(basedir + slash + song, song, false, true)
allsongs.push(extinf.toString())
allsongs.push(`${appendname}${filename}`)
} else {
allsongs.push(`${appendname}${filename}`)
}
}
}
//console.log(allsongs)
let lines = allsongs.join("\n")
//console.log(lines)
fs.writeFileSync(`${folder + slash + relativedir}.m3u`, lines)
}
//read the file and get it's metadata
/**
* read song file to get metadata
* @param {String} song full path to file
* @param {String} onlysong relative path to file (no folder)
* @param {Boolean} returnObj if true, return full object instead of EXTINF string
* @param {Boolean} skipCovers if true, skip fetching covers (faster)
* @param {Boolean} fetchExtraInfo if true, fetch extra info
*/
async function getEXTINF(song, onlysong, returnObj, skipCovers, fetchExtraInfo) {
var metadata
try {
metadata = await mm.parseFile(song, {"skipCovers": skipCovers, "duration": false})
} catch (e) {
console.warn(song, e)
metadata = { //when we get Error: EINVAL: invalid argument, read for certain songs, make a dummy extinf
common: {}, format: { duration: 1, bitrate: "unknown", sampleRate: "unknown" }, quality: {warnings: ["failed to get extinf"]}
}
}
metadata.quality.warnings = metadata.quality.warnings.length //replace warnings array with just the number of warnings
//console.log("metadata: ",metadata)
let extrainfo = {}
var artist = metadata.common.artist == undefined ? "Unknown Artist" : metadata.common.artist
const title = metadata.common.title == undefined ? onlysong : metadata.common.title
const album = metadata.common.album == undefined ? "Unknown Album" : metadata.common.album
const duration = metadata.format.duration == undefined || parseInt(metadata.format.duration) < 1 ? "000001" : metadata.format.duration.toFixed(3).replaceAll(".","")
if (metadata.common.artists !== undefined && metadata.common.artists.length > 1) {
artist = metadata.common.artists.join(" / ")
}
if (fetchExtraInfo !== undefined && fetchExtraInfo === true) {
let lstat = fs.lstatSync(song)
extrainfo.size = (lstat.size / 1000000).toFixed(2).toString() + " MB"
extrainfo.format = metadata.format.codec
extrainfo.bitrate = Math.round(metadata.format.bitrate / 1000).toString() + " kb/s"
extrainfo.samplerate = metadata.format.sampleRate.toString() + " Hz"
if (metadata.common.genre !== undefined && metadata.common.genre.length !== 0) {
extrainfo.genre = metadata.common.genre.join(" / ")
} else {
extrainfo.genre = "Unknown Genre"
}
extrainfo.year = metadata.common.year !== undefined ? metadata.common.year : "Unknown Year"
//console.log(extrainfo)
}
const extinf = `#EXTINF:${duration},${artist} - ${title}`
if (skipCovers == false) {
const pic = mm.selectCover(metadata.common.picture)
var cover = ""
if (pic !== undefined && pic !== null) {
let frmt = pic.format.replaceAll("image/", "")
cover = `data:${pic.format};base64,${pic.data.toString('base64')}`
coverobj = {frmt, "data": pic.data }
} else {
cover = ""
coverobj = false
}
}
//console.log(extinf)
if (returnObj == true) {
return {artist, title, album, duration, cover, extinf, coverobj, extrainfo}
} else {
return extinf
}
}
async function fetchAllSongs() {
//clear the playlists
allSongs = []
allPlaylists = []
songsAndPlaylists = []
editablePlaylists = []