This repository has been archived by the owner on Jun 1, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
app.js
897 lines (811 loc) · 29.4 KB
/
app.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
var html = require("choo/html")
var devtools = require("choo-devtools")
var Nanocomponent = require("nanocomponent")
var choo = require("choo")
var css = require("sheetify")
css("./links/style.css")
var remoteRoute = "/remote/:url/:playlist"
var archive = new DatArchive(window.location.toString())
var title = "datradio"
var app = choo()
app.use(devtools())
app.use(init)
app.use(inputHandler)
app.route(remoteRoute, mainView)
app.route("/:playlist", mainView)
app.mount("body")
// fix modulo for negative integers
function mod(n, m) {
return ((n % m) + m) % m
}
function format(durationStr) {
durationStr = parseInt(durationStr)
var min = pad(parseInt(durationStr / 60), 2)
var sec = pad(parseInt(durationStr % 60), 2)
return `${min}:${sec}`
}
function shuffle(inArr) {
var output = [].concat(inArr)
// fisher-yates shuffle
for (var i = output.length-1; i > 1; i--) {
// 0 <= j <= i
var j = Math.floor(Math.random() * (i+1))
// do the swap
var temp = output[i]
output[i] = output[j]
output[j] = temp
}
return output
}
class Counter extends Nanocomponent {
constructor() {
super()
this.time = "--:--"
this.duration = "--:--"
}
createElement(time, duration) {
this.time = time
this.duration = duration
return html`<div id="time">${format(this.time)}/${format(this.duration)}</div>`
}
update(time, duration) {
console.log("nanocomponent update - time:", time)
time = format(time)
duration = format(duration)
return time != this.time || duration != this.duration
}
}
var hotkeySheet = {
"toggle play/pause": {
key: "spacebar",
},
"next track": {
key: "n",
},
"previous track": {
key: "p",
},
"random track": {
key: "r",
},
"close info": {
key: "x",
}
}
var commands = {
"bg": {
value: "#1d1d1d",
desc: "change the background colour",
call: function(state, emit, value) {
state.profile.bg = value
}
},
"color": {
value: "pink",
desc: "change the font colour",
call: function(state, emit, value) {
state.profile.color = value
}
},
"nick": {
value: "<your nickname>",
desc: "sets the name of your profile",
call: function(state, emit, value) {
state.user.name = value
}
},
"desc": {
value: "<description>",
desc: "a description of this playlist",
call: function(state, emit, value) {
state.description = value
save(state)
emit.emit("render")
}
},
"create": {
value: "playlist-name-no-spaces",
desc: "create a playlist",
call: function(state, emit, value) {
value = value.replace(/\W*/g, "")
state.playlists.push(value)
window.location.hash = value
reset(state)
savePlaylist(state, value)
.then(() => {
save(state)
emit.emit("render")
})
}
},
"delete-playlist": {
value: "playlist-name",
desc: "delete the playlist",
call: function(state, emit, value) {
deletePlaylist(value).then(() => {
loadPlaylists().then((playlists) => {
state.playlists = playlists
// handle deleting the current playlist
if (value === state.params.playlist) {
window.location.hash = "playlist"
}
emit.emit("render")
})
})
}
},
"rename": {
value: "new-playlist-name-no-spaces",
desc: "rename the current playlist",
call: function(state, emit, value) {
if (value) {
value = value.replace(/\W*/g, "")
var oldPlaylist = state.params.playlist ? state.params.playlist : "playlist"
state.playlists.splice(state.playlists.indexOf(oldPlaylist), 1)
savePlaylist(state, value).then(() => {
deletePlaylist(oldPlaylist).then(() => {
loadPlaylists().then((playlists) => {
state.playlists = playlists
window.location.hash = value.replace(" ", "")
emit.emit("render")
})
})
})
}
}
},
"unsub": {
value: "",
desc: "unsub from current playlist",
call: function(state, emit, value) {
parts = window.location.pathname.split("/remote/")
if (parts.length <= 1) {
return
}
value = prefix(parts[1])
state.following.forEach((f, index) => {
if (f.link === value) {
state.following.splice(index, 1)
return
}
})
}
},
"sub": {
value: "dat://1337...7331/#playlist-name",
desc: "subscribe to a playlist",
call: function(state, emit, value) {
extractSub(value).then((info) => {
state.following.push(info)
emit.emit("render")
save(state)
})
}
},
"del": {
value: "track index",
desc: "delete track from playlist",
call: function(state, emit, value) {
emit.emit("deleteTrack", parseInt(value))
}
},
"del-archive": {
value: "dat://1337...7331",
desc: "delete all tracks from the archive",
call: function(state, emit, value) {
emit.emit("deleteArchive", value)
}
},
"mv": {
value: "trackIndex newIndex",
desc: "move a track in the current playlist",
call: function(state, emit, value) {
var [src, dst] = value.split(/\W+/g)
emit.emit("moveTrack", src, dst)
}
},
"shuffle": {
value: "on|off",
desc: "turn on/off shuffle for playlist. [COMING SOON]",
call: function(state, emit, value) {
console.log(shuffle(state.tracks))
}
}
}
async function loadTracks(playlist) {
var tracks = playlist.tracks
var fromArchives = []
return new Promise((resolve, reject) => {
// TODO: refactor/clean this?
if (playlist) {
var promises = playlist.archives.map((address) => {
return new Promise((res1, rej1) => {
var a = new DatArchive(address)
var path = address.substring(70) || "/"
var files = await a.readdir(path)
var archiveTracks = files.filter((i) => isTrack(i)).map((i) => prefix(address, i))
var newTracks = archiveTracks.filter((i) => {
return playlist.removed.indexOf(i) < 0 && tracks.indexOf(i) < 0
})
tracks = tracks.concat(newTracks)
fromArchives = fromArchives.concat(archiveTracks)
res1()
})
})
await Promise.all(promises)
// TODO: is this good? would we rather preserve tracks that have been added
// and load them using version numbers?
// filter out tracks that have been added to our playlist previously
// but have been removed from the hosting archive (i.e. outside of datradio)
tracks = tracks.filter((i) => fromArchives.indexOf(i) >= 0)
resolve(tracks)
}
})
}
async function deletePlaylist(name) {
// don't delete the default playlist
if (name === "playlist") {
var emptyState = {archives: [], tracks: [], removed: [], description: "", profile: {bg: "black", color: "#f2f2f2"}}
return savePlaylist(emptyState, "playlist")
}
await archive.unlink(`playlists/${name}.json`)
}
function createHelpSidebar() {
var items = []
var hotkeyItems = []
for (var key in commands) {
items.push({key: key, cmd: commands[key]})
}
for (var key in hotkeySheet) {
hotkeyItems.push({key: key, hotkey: hotkeySheet[key].key})
}
function createHelpEl(p) {
return html`<div onclick=${fillTerminal} class="help-container"><div class="help-cmd">${p.key}</div><div class="help-value">${p.cmd.value}</div><div class="help-desc">${p.cmd.desc}</div></div>`
function fillTerminal() {
var term = document.getElementById("terminal")
term.value = `.${p.key} ${p.cmd.value}`
term.focus()
}
}
function createHotkeyEl(p) {
return html`<div class="hotkey-container"><div class="help-hotkey">${p.key} =</div><div class="help-value">${p.hotkey}</div></div>`
}
return html`<h3 id="commands"><div>commands</div><div>${items.map(createHelpEl)}</div>
<div>hotkeys</div><div>${hotkeyItems.map(createHotkeyEl)}</div></div>`
}
var counter = new Counter()
function mainView(state, emit) {
emit("DOMTitleChange", title + `/${state.user.name}`)
var playlistName = state.params.playlist ? state.params.playlist : "playlist"
return html`
<body ondragleave=${dragleave} ondrop=${drop} ondragover=${dragover} onkeydown=${hotkeys} style="background-color: ${state.profile.bg}!important; color: ${state.profile.color}!important;">
<a id="fork-url" href="dat://31efd7c43603b57d18d0dcc4e2a32bf5cae08ab5930071e4da3513dbc4c60f5f/">create your own radio</div>
<a id="tutorial-url" href="dat://31efd7c43603b57d18d0dcc4e2a32bf5cae08ab5930071e4da3513dbc4c60f5f/tutorial.md">how to use</div>
<div id="grid-container">
<ul id="archives-container">
<h3>archives in playlist</h3>
${state.archives.map(createArchiveEl)}
</ul>
<ul id="playlists">
<h3>${state.user.name}'s playlists </h3>
${state.playlists.map(createPlaylistEl)}
${state.following.map(createPlaylistSub)}
</ul>
<div class="center">
<h1 id="title">${title} (${playlistName})</h1>
<div id="description">${state.description}</div>
<input id="terminal" placeholder="i love tracks" onkeydown=${keydown}>
<ul id="tracks">
${state.tracks.map(createTrack)}
</ul>
${counter.render(state.time, state.duration)}
${createInfoModal()}
</div>
${createHelpSidebar()}
<audio id="player" onended=${trackEnded} controls="controls" >
Yer browser dinnae support the audio element :(
</audio>
</div>
</body>
`
// '
function dragover(e) {
e.preventDefault()
var body = document.querySelectorAll('body')[0];
body.classList = "drag-fade"
}
function dragleave(e) {
e.preventDefault()
var body = document.querySelectorAll('body')[0];
body.classList = ""
}
function drop(e) {
e.preventDefault()
var body = document.querySelectorAll('body')[0];
body.classList = ""
console.log(e.dataTransfer.files)
var files = Array.prototype.filter.call(e.dataTransfer.files,
((i) => isTrack(i.name) || i.name === "info.txt"))
// only allow tracks or info.txt to be added
if (files.length === 0) { return }
// var d = await DatArchive.selectArchive({
// title: 'Hello, world!',
// buttonLabel: 'My new site'
// })
var playlistName = state.params.playlist ? state.params.playlist : "playlist"
if (!state.profile.archive) {
var d = await DatArchive.create({
title: `[datradio tracks] ${state.user.name}/${playlistName}`,
description: `datradio tracks for ${state.user.name}/${playlistName}`
})
state.profile.archive = d.url
// add the playlist-specific archive to our list of archives
state.archives.push(d.url)
} else {
var d = new DatArchive(state.profile.archive)
}
var reader = new FileReader()
async function next(i=0) {
reader.readAsArrayBuffer(files[i])
reader.onload = async function (e) {
await d.writeFile(`/${files[i].name}`, e.target.result)
if (i + 1 < files.length) {
next(i+1)
}
}
}
next()
var tracks = files.filter((i) => i.name !== "info.txt").map((i) => `${d.url}/${i.name}`)
state.tracks = state.tracks.concat(tracks)
save(state)
emit("render")
}
function createArchiveEl(arch) {
return html`<li class="archive-el"><a href="${arch}">${shorten(arch)}</a></li>`
}
function createTrack(track, index) {
var parts = track.split("/")
var title = parts[parts.length - 1].trim()
return html`<li id="track-${index}">
<div class="track-link" onclick=${showInfo}>INFO</div>
<div class="track-title" onclick=${play}>
${pad(index, 3)} ${title}
</div>
</li>`
function showInfo() {
state.modalInfo = {track: track, title: title, index: index, info: "loading.."}
state.showModal = true
emit("render")
var path = track.substring(70, track.lastIndexOf("/"))
var d = new DatArchive(track)
d.readFile(path + "/info.txt")
.then((info) => {
state.modalInfo.info = info
emit("render")
})
.catch((e) => {
state.modalInfo.info = "info.txt missing from archive"
emit("render")
})
}
// play the track when clicked on
function play() {
// current track clicked on
if (state.trackIndex === index) {
var player = document.getElementById("player")
// lets resume the current track
if (player.paused) {
emit("resumeTrack")
// pause the current track
} else {
emit("pauseTrack")
}
// we wanted to play a new track
} else {
emit("playTrack", index)
}
}
}
function createInfoModal() {
var index = state.modalInfo.track.lastIndexOf("/")
var archiveUrl = state.modalInfo.track.substring(0,70)
if (state.showModal) {
return html`
<div id="info-modal">
<div id="info-title">${state.modalInfo.title}</div>
<div id="info-archive">
<div>from archive:</div>
<a href="${archiveUrl}">${archiveUrl}</a>
</div>
<div id="info-text">
<div>info.txt:</div>
<pre id="info-pre">${state.modalInfo.info}</pre>
</div>
<div id="info-close" onclick=${close}>close</div>
</div>`
}
return html``
function close() {
state.showModal = false
emit("render")
}
}
function trackEnded(evt) {
emit("nextTrack")
}
function hotkeys(e) {
var term = document.getElementById("terminal")
var player = document.getElementById("player")
if (document.activeElement != term) {
if (e.key === "n") { emit("nextTrack") }
else if (e.key === "p") { emit("previousTrack") }
else if (e.key === "r") { emit("randTrack") }
else if (e.key === "r") { emit("randTrack") }
else if (e.key === "x") {
state.showModal = false
emit("render")
} else if (e.key === " ") {
e.preventDefault()
if (player.paused) emit("resumeTrack")
else emit("pauseTrack")
}
}
}
function keydown(e) {
if (e.key === "Enter") {
emit("inputEvt", e.target.value)
e.target.value = ""
}
}
}
function shorten(url) {
return url.substring(0,15) + ".." + url.substring(66,70)
}
function createPlaylistEl(playlist) {
return html`<li><a href="/#${playlist}">${playlist}</a></li>`
}
function createPlaylistSub(sub) {
var playlist = `${sub.name}/${sub.playlist}`
return html`<li><a href="/remote/${sub.source}/${sub.playlist}">+ ${playlist}</a></li>`
}
function reset(state) {
state.time = 0
state.duration = 0
state.trackIndex = -1
state.tracks = []
state.removed = []
state.archives = []
state.description = ""
state.profile = {bg: "black", color: "#f2f2f2", archive: ""}
}
function loadPlaylists() {
return new Promise((res, rej) => {
archive.readdir("playlists").then((playlists) => {
playlists = playlists.filter((i) => { return i.substring(i.length - 5) === ".json" }).map((p) => p.substring(0,p.length-5))
res(playlists)
}).catch((e) => {
console.error("loadPlaylists failed with", e)
})
})
}
function prefix(url, path) {
if (path) {
// append /
if (url.substring(-1) != "/") {
url += "/"
}
url += path
}
if (url.substring(0, 6) != "dat://") {
return `dat://${url}`
}
return url
}
async function init(state, emitter) {
reset(state)
// TODO:
// implement
// state.isPlaying
//
// figure out why choo-based state playing bugs out;
// is it due to the player being reloaded somehow??
// should the player component be a Nanocomponent??
state.playlists = []
state.modalInfo = {track: "", title: "", index: -1, info: "loading.."}
state.showModal = false
state.following = []
state.user = {}
state.isOwner = false
setInterval(function() {
var player = document.getElementById("player")
if (player) {
state.time = player.currentTime
state.duration = player.duration || 0
}
counter.render(state.time, state.duration)
}, 1000)
archive.getInfo().then((info) => {
state.isOwner = info.isOwner
emitter.emit("render")
})
state.user = JSON.parse(await archive.readFile("profile.json"))
state.following = await Promise.all(state.user.following.map((url) => extractSub(url)))
state.playlists = await loadPlaylists()
var initialPlaylist = window.location.hash ? `playlists/${window.location.hash.substring(1)}.json` : `playlists/playlist.json`
archive.stat(initialPlaylist).then((info) => {
loadPlaylist(archive, initialPlaylist)
}).catch((err) => {
window.location = "/#playlist"
})
async function loadPlaylist(playlistArchive, path) {
// try to load the user's playlist
try {
var playlist = JSON.parse(await playlistArchive.readFile(path))
state.profile = playlist.profile
state.description = playlist.description
state.archives = playlist.archives
state.removed = playlist.removed
// render once before loading the tracks
// as loading them takes a noticeable time
// (might be premature optimization oops :^)
emitter.emit("render")
state.tracks = await loadTracks(playlist)
// TODO: use .watch() instead
state.archives.forEach((arch) => {
var trackArchive = new DatArchive(arch)
var tracePath = arch.substring(70).replace(/\/$/, "") // remove trailing slash
var patterns = ["wav", "ogg", "mp3"].map((fmt) => `${tracePath}/*.${fmt}`)
// /**/
var evts = trackArchive.createFileActivityStream(patterns)
evts.addEventListener("changed", ({path}) => {
console.log(`update found for ${arch}: ${path}`)
var trackPath = prefix(normalizeArchive(arch) + path)
trackArchive.stat(path)
.then((info) => {
// track was either updated or added to playlist
// check if track exists in playlist already
if (state.tracks.indexOf(trackPath) < 0) {
console.log("track was added to playlist, update state.tracks")
state.tracks.push(trackPath)
save(state)
emitter.emit("render")
}
})
.catch((e) => {
console.error(e)
console.log("track was probably removed from the playlist")
console.log("remove from state.tracks")
state.tracks.splice(state.tracks.indexOf(trackPath), 1)
save(state)
emitter.emit("render")
})
})
})
save(state)
// render again after having loaded the tracks
emitter.emit("render")
} catch (e) {
console.error("failed to read playlist's json; malformed json?")
console.error(e)
}
}
// load the playlist we clicked on
emitter.on("navigate", function() {
reset(state)
var arch = archive
var playlistName = state.params.playlist ? state.params.playlist : "playlist"
if (state.route === remoteRoute) {
arch = new DatArchive(state.params.url)
}
loadPlaylist(arch, `playlists/${playlistName}.json`)
})
emitter.on("playTrack", function(index) {
console.log("playTrack received index: " + index, typeof index)
state.trackIndex = index
playTrack(state.tracks[index], index)
})
emitter.on("randTrack", function() {
var index = Math.floor(Math.random() * state.tracks.length)
emitter.emit("playTrack", index)
})
emitter.on("resumeTrack", function() {
var player = document.getElementById("player")
removeClass("paused")
addClass(state.trackIndex, "playing")
player.play()
})
emitter.on("pauseTrack", function() {
var player = document.getElementById("player")
removeClass("playing")
addClass(state.trackIndex, "paused")
player.pause()
})
emitter.on("nextTrack", function() {
// TODO: add logic for shuffle :)
console.log("b4, track index is: " + state.trackIndex)
state.trackIndex = mod((state.trackIndex + 1), state.tracks.length)
console.log("after, track index is: " + state.trackIndex)
playTrack(state.tracks[state.trackIndex], state.trackIndex)
})
emitter.on("previousTrack", function() {
// TODO: add logic for shuffle :)
state.trackIndex = mod((state.trackIndex - 1), state.tracks.length)
playTrack(state.tracks[state.trackIndex], state.trackIndex)
})
emitter.on("moveTrack", function(srcIndex, dstIndex) {
console.log(`move from ${srcIndex} to ${dstIndex}`)
var track = state.tracks.splice(srcIndex, 1)[0]
state.tracks.splice(dstIndex, 0, track)
emitter.emit("render")
})
emitter.on("deleteTrack", function(index) {
var emitNextTrack = false
state.trackIndex = parseInt(state.trackIndex)
index = parseInt(index)
var removedTrack = state.tracks.splice(index, 1)[0]
state.removed.push(removedTrack)
save(state)
if (state.trackIndex >= index) {
var emitNextTrack = (state.trackIndex === index && state.tracks.length > 0)
state.trackIndex = state.trackIndex - 1
// if current was deleted, play next
if (emitNextTrack) { emitter.emit("nextTrack") }
}
})
emitter.on("deleteArchive", function(url) {
url = prefix(normalizeArchive(url))
// var emitNextTrack = false
// state.trackIndex = parseInt(state.trackIndex)
// if (differentFromUrl(state.tracks[state.trackIndex]) {
// if (state.trackIndex >= index) {
// var emitNextTrack = (state.trackIndex === index && state.tracks.length > 0)
// state.trackIndex = state.trackIndex - 1
// // if current was deleted, play next
// if (emitNextTrack) { emitter.emit("nextTrack") }
// }
// }
state.archives = state.archives.filter(differentFromUrl)
state.tracks = state.tracks.filter(differentFromUrl)
save(state)
function differentFromUrl(a) {
return a.substr(0, url.length) !== url
}
})
function playTrack(track, index) {
removeClass("playing")
removeClass("paused")
addClass(index, "playing")
console.log(`playing ${track}`)
var player = document.getElementById("player")
player.src = track
player.load()
player.play()
var duration = player.duration || 0
counter.render(player.currentTime, duration)
}
}
function addClass(index, cssClass) {
console.log(`to track-${index} add ${cssClass}`)
document.getElementById(`track-${index}`).classList.add(cssClass)
}
function removeClass(cssClass) {
var items = document.getElementsByClassName(cssClass)
for (var i = 0; i < items.length; i++) {
var item = items[i]
if (item) {
item.classList.remove(cssClass)
}
}
}
async function save(state) {
var playlistName = state.params.playlist ? state.params.playlist : "playlist"
console.log(`saving ${state.tracks[state.tracks.length - 1]} to ${playlistName}.json`)
savePlaylist(state, playlistName)
archive.writeFile(`profile.json`, JSON.stringify(
{name: state.user.name, following: state.following.map((o) => o.link)},
null, 2))
}
async function extractSub(url) {
return {
source: url.substring(6, 64),
playlist: extractPlaylist(url),
name: await getProfileName(url),
link: url
}
}
async function getProfileName(datUrl) {
var remote = new DatArchive(datUrl)
var profile = JSON.parse(await remote.readFile("profile.json"))
return profile.name
}
function extractPlaylist(input) {
var playlistName = input.substring(71)
if (playlistName.length === 0) {
return "playlist"
}
return playlistName
}
var audioRegexp = new RegExp("\.[wav|ogg|mp3]$")
function isTrack(msg) {
return audioRegexp.test(msg)
}
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
// thx to 0xade & rotonde for this wonderful function <3
function normalizeArchive(url) {
if (!url)
return null;
// This is microoptimized heavily because it's called often.
// "Make slow things fast" applies here, but not literally:
// "Make medium-fast things being called very often even faster."
if (
url.length > 6 &&
url[0] == 'd' && url[1] == 'a' && url[2] == 't' && url[3] == ':'
)
// We check if length > 6 but remove 4.
// The other 2 will be removed below.
url = url.substring(4);
if (
url.length > 2 &&
url[0] == '/' && url[1] == '/'
)
url = url.substring(2);
var index = url.indexOf("/");
url = index == -1 ? url : url.substring(0, index);
url = url.toLowerCase().trim();
return url;
}
async function savePlaylist(state, name) {
return archive.writeFile(`playlists/${name}.json`, JSON.stringify({
archives: state.archives,
tracks: state.tracks,
removed: state.removed,
description: state.description,
profile: state.profile}, null, 2))
}
function inputHandler(state, emitter) {
emitter.on("inputEvt", function (msg) {
if (msg.length) {
if (msg[0] === ".") {
var sep = msg.indexOf(" ")
var cmd = sep >= 0 ? msg.substr(1, sep-1).trim() : msg.substr(1)
var val = sep >= 0 ? msg.substr(sep).trim() : ""
handleCommand(cmd, val)
} else {
// assume it's a dat archive folder, and try to read its contents
var url = normalizeArchive(msg)
if (!url || url.length != 64) {
return
}
var a = new DatArchive(msg)
// length of dat:// + hash = 70
var path = msg.substring(70) || "/"
// disallow adding the same archive folder multiple times
if (state.archives.indexOf(msg) >= 0) {
return
}
state.archives.push(msg)
a.readdir(path).then((dir) => {
dir.filter((i) => isTrack(i)).forEach((i) => {
var p = prefix(url, i)
state.tracks.push(p)
})
emitter.emit("render")
save(state)
})
}
save(state)
emitter.emit("render")
}
})
function handleCommand(command, value) {
if (command in commands) {
commands[command].call(state, emitter, value)
emitter.emit("render")
save(state)
}
}
}