-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaudioplayer.js
1088 lines (1024 loc) · 34.3 KB
/
audioplayer.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
import { S3Client } from "@aws-sdk/client-s3"
import { ListObjectsV2Command, HeadObjectCommand, GetObjectCommand } from "@aws-sdk/client-s3"
import { getSignedUrl } from "@aws-sdk/s3-request-presigner"
const EXPIRE_SECONDS = 7 * 24 * 60 * 60
const WAKELOCK_CLEAR_TIMEOUT = 5 * 60 * 1000
const SEEK_TARGET_TIMEOUT = 100
const folderDelimiter = '/'
const locale = {}
locale.play = 'Play'
locale.previous = 'Previous'
locale.next = 'Next'
locale.playFolder = `Add all tracks to queue`
locale.playSong = `Add track to queue`
locale.playlistTitle = `Playlists`
locale.playPlaylist = `Add playlist contents to queue`
locale.jumpTo = `Jump to`
// locale.playAlbum = `Add all album tracks to queue`
let s3, err, f, bucketName, playerList, browserList, playlistList, db
let skipMenu, previousFirst, sourceLink, wakeLock, wakelockCooldown
let seekTarget, seekTimeout
const preloadCache = {}
let preloading = false
const dbRequest = indexedDB.open("audio-library", 3)
dbRequest.onupgradeneeded = function(event) {
const db = dbRequest.result
if (event.oldVersion < 1) {
const cache = db.createObjectStore("meta", {keyPath: "key"})
const artistIndex = cache.createIndex("by_artist", "artist")
const albumIndex = cache.createIndex("by_album", "album")
const titleIndex = cache.createIndex("by_title", "title")
const tracknumberIndex = cache.createIndex("by_tracknumber", "tracknumber")
const yearIndex = cache.createIndex("by_year", "year")
const playlistIndex = cache.createIndex("by_playlist", "playlist")
const genreIndex = cache.createIndex("by_genre", "genre")
const commentIndex = cache.createIndex("by_comment", "comment")
}
if (event.oldVersion < 2) {
const cache = dbRequest.transaction.objectStore("meta")
const keyIndex = cache.createIndex("key", "key", {unique: true})
}
if (event.oldVersion < 3) {
const cache = dbRequest.transaction.objectStore("meta")
const commentIndex = cache.createIndex("image", "image")
}
}
dbRequest.onsuccess = function() {
db = dbRequest.result
}
const myUri = new URL(document.location.href)
let myPath = decodeURIComponent(myUri.hash.replace('#', '')).split(folderDelimiter)
const player = document.querySelector('audio-player')
if (!player) {
throw new Error("Didn't find an audio-player element in HTML document")
}
if (!player.id) {
player.id = 'my-audio-player' // possible clash...
}
const browser = document.querySelector('audio-browser')
if (!browser) {
throw new Error("Didn't find an audio-browser element in HTML document")
}
else {
const skipNav = document.createElement('nav')
skipNav.id = 'skipNav'
skipMenu = document.createElement('ol')
const li = document.createElement('li')
const a = document.createElement('a')
a.href = `#${player.id}`
a.title = `#${locale.jumpTo} ${locale.play}`
a.innerHTML = '⏵'
li.appendChild(a)
skipMenu.appendChild(li)
skipNav.appendChild(skipMenu)
browserList = document.createElement('nav')
const playlistParent = document.createElement('ol')
playlistParent.id = 'playlists'
playlistParent.className = 'playlists'
const pli = document.createElement('li')
pli.className = 'folder'
pli.innerHTML = locale.playlistTitle
pli.onclick = function(e) {
e.preventDefault()
e.stopPropagation()
const isOpen = this.classList.toggle('open')
}
playlistList = document.createElement('ol')
playlistList.className = 'playlists'
pli.appendChild(playlistList)
playlistParent.appendChild(pli)
const mli = document.createElement('li')
const pa = document.createElement('a')
pa.title = `#${locale.jumpTo} ${locale.playlistTitle}`
pa.href = `#playlists`
pa.innerHTML = '#'
mli.appendChild(pa)
skipMenu.appendChild(mli)
browser.innerHTML = ''
browser.appendChild(skipNav)
browserList.appendChild(playlistParent)
browser.appendChild(browserList)
}
try {
initS3()
}
catch(e) {
if (!err) {
err = document.createElement('div')
err.className = 'error'
document.body.appendChild(err)
}
err.textContent = e.toString()
if (!f) {
ss = document.createElement('storage-settings')
f = document.createElement('form')
const accessKeyIdInput = document.createElement('input')
const accessKeyIdLabel = document.createElement('label')
accessKeyIdInput.id = 'accessKeyIdInput'
accessKeyIdLabel.for = accessKeyIdInput.id
accessKeyIdLabel.textContent = 'S3 accessKeyId'
f.appendChild(accessKeyIdLabel)
accessKeyIdInput.type = 'text'
accessKeyIdInput.size = '40'
accessKeyIdInput.required = 'required'
f.appendChild(accessKeyIdInput)
const secretAccessKeyInput = document.createElement('input')
const secretAccessKeyLabel = document.createElement('label')
secretAccessKeyInput.id = 'secretAccessKeyInput'
secretAccessKeyLabel.for = secretAccessKeyInput.id
secretAccessKeyLabel.textContent = 'S3 secretAccessKey'
f.appendChild(secretAccessKeyLabel)
secretAccessKeyInput.type = 'password'
secretAccessKeyInput.size = '40'
secretAccessKeyInput.required = 'required'
f.appendChild(secretAccessKeyInput)
const endpointInput = document.createElement('input')
const endpointLabel = document.createElement('label')
endpointInput.id = 'endpointInput'
endpointLabel.for = endpointInput.id
endpointLabel.textContent = 'S3 endpoint'
f.appendChild(endpointLabel)
endpointInput.type = 'text'
endpointInput.size = '40'
endpointInput.required = 'required'
f.appendChild(endpointInput)
const regionInput = document.createElement('input')
const regionLabel = document.createElement('label')
regionInput.id = 'regionInput'
regionLabel.for = regionInput.id
regionLabel.textContent = 'S3 region'
f.appendChild(regionLabel)
regionInput.type = 'text'
regionInput.size = '40'
regionInput.required = 'required'
f.appendChild(regionInput)
const bucketInput = document.createElement('input')
const bucketLabel = document.createElement('label')
bucketInput.id = 'bucket'
bucketLabel.for = bucketInput.id
bucketLabel.textContent = 'S3 bucket'
f.appendChild(bucketLabel)
bucketInput.type = 'text'
bucketInput.size = '40'
bucketInput.required = 'required'
f.appendChild(bucketInput)
const submit = document.createElement('input')
submit.type = 'submit'
submit.value = 'Submit'
f.appendChild(submit)
f.onsubmit = () => {
localStorage.setItem('accessKeyId', accessKeyIdInput.value)
localStorage.setItem('secretAccessKey', secretAccessKeyInput.value)
localStorage.setItem('endpoint', endpointInput.value)
localStorage.setItem('region', regionInput.value)
localStorage.setItem('bucketName', bucketInput.value)
initS3()
}
ss.appendChild(f)
document.body.appendChild(ss)
}
}
function initS3() {
const keys = [
'accessKeyId',
'secretAccessKey',
'endpoint',
'region',
'bucketName'
]
const params = {}
keys.forEach(key => {
params[key] = localStorage.getItem(key)
if (!params[key]) {
throw new Error(`S3 ${key} is missing`)
}
})
const s3opts = {
credentials: {
accessKeyId: params['accessKeyId'],
secretAccessKey: params['secretAccessKey'],
},
endpoint: params['endpoint'],
s3BucketEndpoint: true,
forcePathStyle: true,
region: params['region']
}
bucketName = params['bucketName']
s3 = new S3Client(s3opts)
if (browserList) {
getFolders(browserList)
}
const a = document.createElement('a')
a.href = document.location.href
const query = new URLSearchParams(params).toString()
a.search += (a?.search.includes('?') ? '&' : '?') + query
}
/*
const dbName = 'music'
const dbVersion = 1
let db
const request = window.indexedDB.open(dbName, dbVersion)
request.onerror = (event) => {
console.error(`Error: can't use IndexedDB ${Name}, ${dbVersion}!`)
}
request.onsuccess = (event) => {
db = event.target.result
}
*/
const buttons = document.createElement('div')
buttons.id = 'buttons'
const prev = document.createElement('button')
prev.title = locale.previous
// prev.textContent = '⏮'
prev.innerHTML = '<span class="fa-solid fa-backward"></span>'
buttons.appendChild(prev)
const play = document.createElement('button')
play.title = locale.play
// play.textContent = '⏵'
play.innerHTML = '<span class="fa-solid fa-play"></span>'
play.disabled = true
buttons.appendChild(play)
const next = document.createElement('button')
next.title = locale.next
// next.textContent = '⏭'
next.innerHTML = '<span class="fa-solid fa-forward"></span>'
buttons.appendChild(next)
player.appendChild(buttons)
const audio = document.createElement('audio')
audio.className = 'current'
audio.preload = 'auto'
player.appendChild(audio)
const audioTime = document.createElement('div')
audioTime.className = 'audio-time'
const cursor = document.createElement('input')
cursor.id = 'cursor'
// cursor.type = 'time'
// cursor.step = '1'
// cursor.value = '00:00:00'
cursor.size = 5
cursor.pattern = '[0-9]{1,2}:[0-9]{2}'
cursor.value = '0:00'
cursor.disabled = true
cursor.addEventListener('blur', (e) => {
const parts = e.target.value.split(':')
const secs = parseInt(parts[0]) * 60 + parseInt(parts[1])
audio.currentTime = secs
})
audioTime.appendChild(cursor)
audioTime.appendChild(document.createTextNode(' / '))
const trackLength = document.createElement('input')
trackLength.id = 'trackLength'
// trackLength.type = 'time'
// trackLength.step = '1'
trackLength.size = 5
trackLength.value = '0:00'
trackLength.disabled = true
audioTime.appendChild(trackLength)
player.appendChild(audioTime)
const titleHolder = document.createElement('div')
titleHolder.className = 'track'
const trackTitle = document.createElement('input')
trackTitle.id = 'trackTitle'
trackTitle.size = 70
trackTitle.className = 'track-title'
trackTitle.disabled = true
titleHolder.appendChild(trackTitle)
player.appendChild(titleHolder)
const progress = document.createElement('input')
progress.type = 'range'
progress.id = 'progress'
progress.addEventListener('input', (e) => {
// Safari gets confused from scrubbing
// too many concurrent seek requests set currentTime to 0
// avoid many seeks by setting currentTime on a timeOut
seekTarget = parseInt(e.target.value)
if (seekTimeout) {
// cancel previous seek request
clearTimeout(seekTimeout)
}
seekTimeout = setTimeout(function() {
audio.currentTime = seekTarget
}, SEEK_TARGET_TIMEOUT)
})
player.appendChild(progress)
updateDuration = function() {
const seconds = parseInt(audio.duration)
progress.max = seconds
trackLength.value = parseInt(seconds/60) + ':' + parseInt(seconds%60).toString().padStart(2, '0')
cursor.max = '0:' + trackLength.value
}
const requestWakeLock = async () => {
if (wakelockCooldown) {
wakelockCooldown = clearTimeout(wakelockCooldown) // returns undefined
}
try {
wakeLock = await navigator.wakeLock.request("screen")
} catch (err) {
console.error(`${err.name}: ${err.message}`)
}
}
audio.onloadedmetadata = updateDuration
audio.oncanplay = (e) => {
audio.play()
play.disabled = false
}
audio.onplay = () => {
// play.textContent = '⏸'
play.innerHTML = '<span class="fa-solid fa-pause"></span>'
cursor.disabled = true
navigator.mediaSession.playbackState = 'playing'
play.classList.remove('stalled')
requestWakeLock()
}
audio.onpause = () => {
// play.textContent = '⏵'
cursor.disabled = false
play.innerHTML = '<span class="fa-solid fa-play"></span>'
navigator.mediaSession.playbackState = 'paused'
wakelockCooldown = setTimeout(wakeLock?.release, WAKELOCK_CLEAR_TIMEOUT)
}
audio.onwaiting = (e) => {
cursor.disabled = false
play.innerHTML = '<span class="fa-solid fa-play"></span>'
navigator.mediaSession.playbackState = 'paused'
}
audio.onplaying = (e) => {
play.innerHTML = '<span class="fa-solid fa-pause"></span>'
play.classList.remove('stalled')
navigator.mediaSession.playbackState = 'playing'
cursor.disabled = true
}
audio.onstalled = (e) => {
// play.innerHTML = '<span class="fa-solid fa-play"></span>'
play.classList.add('stalled')
cursor.disabled = false
}
audio.onseeking = audio.onseeked = (e) => {
// console.log(e.timeStamp, e.target.currentTime, e.target.seekable, e)
// for (let i=0; i<e.target.seekable.length; i++) {
// console.log(e.target.seekable.start(i), e.target.seekable.end(i))
// }
}
audio.onended = next.onclick = (e) => {
playNext()
}
const collection = document.createElement('ol')
collection.className = 'collection'
player.appendChild(collection)
playerList = document.createElement('nav')
player.appendChild(playerList)
const updateTime = () => {
const seconds = parseInt(audio.currentTime)
/*
cursor.value = [
'00',
parseInt(seconds/60).toString().padStart(2, '0'),
parseInt(seconds%60).toString().padStart(2, '0')
].join(':')
*/
cursor.value = parseInt(seconds/60) + ':' +
parseInt(seconds%60).toString().padStart(2, '0')
progress.value = seconds
if ('setPositionState' in navigator.mediaSession) {
if (audio.duration && audio.currentTime) {
navigator.mediaSession.setPositionState({
duration: audio.duration,
position: audio.currentTime,
playbackRate: audio.playbackRate,
})
}
}
}
audio.addEventListener("timeupdate", updateTime)
prev.onclick = (e) => {
playPrevious()
}
play.onclick = async (e) => {
if (!audio.getAttribute('src')) {
return playNext()
}
if (audio.paused) {
await audio.play()
// play.textContent = '⏸'
// play.innerHTML = '<span class="fa-solid fa-pause"></span>'
}
else {
audio.pause()
// play.textContent = '⏵'
// play.innerHTML = '<span class="fa-solid fa-play"></span>'
}
}
window.addEventListener('keydown', (e) => {
if (e.target.tagName.toLowerCase() == 'button') return
if (e.target.type == 'range') return
let current = document.querySelector('audio-track:focus-within')
let newCurrent = false
switch(e.key) {
case " ": e.preventDefault(); play.click(); break
// case "Enter": play.disabled = true; audio.src = current.dataset.src; break
case "Enter": current.querySelector('.name a')?.click(); break
case "ArrowRight": playNext(); break
case "ArrowLeft": playPrevious(); break
case "ArrowDown":
e.preventDefault()
if (current) {
if (current.nextElementSibling) {
newCurrent = current.nextElementSibling
}
else {
newCurrent = current.parentNode.firstElementChild
}
}
break
case "ArrowUp":
e.preventDefault()
if (current) {
if (current.previousElementSibling) {
newCurrent = current.previousElementSibling
}
else {
newCurrent = current.parentNode.lastElementChild
}
}
break
}
if (newCurrent) {
newCurrent.focus()
}
})
async function getFolders(parentElement=null, autoAdd=false, token=null) {
const input = {Bucket: bucketName}
if (token) {
input.ContinuationToken = token
}
if (parentElement.dataset.folder) {
input['Prefix'] = decodeURIComponent(parentElement.dataset.folder) + '/'
}
else {
input['Delimiter'] = folderDelimiter
}
try {
let olRef = parentElement.querySelector('ol:not(.playlists)')
if (!olRef) {
const ol = document.createElement('ol')
parentElement.appendChild(ol)
olRef = ol
}
const command = new ListObjectsV2Command(input)
const response = await s3.send(command)
if (response.CommonPrefixes) {
for (const obj of response.CommonPrefixes) {
const folderName = obj.Prefix.replace(/\/$/, '')
const li = createFolderElement(folderName, olRef)
let first = folderName.slice(0, 1)
if (first.match(/\d+/)) {
first = '1'
}
if (first && first != previousFirst) {
li.id = first
const skipLi = document.createElement('li')
const a = document.createElement('a')
a.href = `#${first}`
a.innerHTML = first
a.title = `#${locale.jumpTo} ${first}`
skipLi.appendChild(a)
skipMenu.appendChild(skipLi)
previousFirst = first
}
// folders[folderName] = folderName
}
}
if (response.Contents) {
let subRef = olRef
for (const obj of response.Contents) {
let trimmed = obj.Key
if (input.Prefix) {
trimmed = trimmed.replace(input.Prefix + '/', '')
}
const match = trimmed.match(/^(.*)\/[^\/]*$/)
if (match) {
const li = createFolderElement(match[1], olRef)
li.classList.toggle('open', true)
let ol = li.querySelector('ol')
if (!ol) {
ol = document.createElement('ol')
li.appendChild(ol)
}
// ol.classList.toggle('hidden', false)
subRef = ol
}
if (obj.Key.endsWith('.mp3')) {
obj.Metadata = await getS3Meta(obj.Key)
const getParams = {Bucket: bucketName, Key: obj.Key}
const command = new GetObjectCommand(getParams)
obj.href = await getSignedUrl(s3, command, { expiresIn: EXPIRE_SECONDS })
createSongElement(obj, subRef).then(li => {
if (autoAdd) {
li.querySelector('a')?.click()
}
})
}
else if (obj.Key.endsWith('.json')) {
const getParams = {Bucket: bucketName, Key: obj.Key}
const command = new GetObjectCommand(getParams)
const li = createPlaylistElement(obj, playlistList)
}
else if (obj.Key.endsWith('.m3u')) {
// playlists.push(obj.Key)
}
}
}
if (response.IsTruncated) {
getFolders(parentElement, autoAdd, response.NextContinuationToken)
}
}
catch(e) {
console.error(e)
}
}
function scrollToFirstTrack(e) {
const source = this.dataset.source
const track = this.closest('audio-player').querySelector(`audio-track[data-source="${source}"]`)
if (track) {
track.scrollIntoView({block: "nearest", inline: "nearest", behavior: 'smooth'})
track.focus()
}
}
function removeTracks(e) {
e.stopPropagation()
const cli = this.closest('li')
const source = cli.dataset.source
const tracks = cli.closest('audio-player').querySelectorAll(`audio-track[data-source="${source}"]`)
for (const track of tracks) {
if (track.classList.contains('playing')) {
if (!audio.paused) {
play.click()
}
trackLength.value = progress.value = 0
// cursor.value = '00:00:00'
cursor.value = '0:00'
trackTitle.value = ''
audio.src = ''
}
track.parentNode.removeChild(track)
}
const li = this.closest('li')
li?.parentNode?.removeChild(li)
}
function createFolderElement(folder, ol) {
const candidate = ol.querySelector(`[data-folder="${folder}"]`)
if (candidate) return candidate
const parent = ol.parentNode.dataset.folder
const li = document.createElement('li')
li.className = 'folder'
li.dataset.folder = folder
li.textContent = folder.replace(`${parent}/`, '')
const a = document.createElement('a')
// a.href = '#' + (parent ? encodeURIComponent(parent) + '/' : '') + encodeURIComponent(folder)
a.href = '#' + encodeURIComponent(folder)
a.className = 'action'
a.title = locale.playFolder
// a.textContent = '⥅' // '⤅' '⧐' '⏵'
// a.innerHTML = '<i class="fa-solid fa-album-circle-plus"></i>'
a.innerHTML = '<span class="fa-solid fa-circle-play"></span>'
a.onclick = async function(e) {
e.preventDefault()
e.stopPropagation()
li.classList.add('open')
history.pushState(folder, '', a.href)
document.title = folder
const cli = document.createElement('li')
cli.onclick = scrollToFirstTrack
cli.className = 'folder'
cli.textContent = folder + ' '
cli.dataset.source = folder
sourceLink = cli.dataset.source
const ca = document.createElement('a')
ca.innerHTML = '<span class="fa-sharp fa-regular fa-circle-xmark"></span>'
ca.onclick = removeTracks
cli.appendChild(ca)
if (!li.querySelector('ol')) {
await getFolders(li, true)
}
else {
const tracks = e?.target?.closest('.folder')?.querySelectorAll('.song a')
tracks.forEach((link) => {
link.click()
})
}
collection.appendChild(cli)
// collection.innerHTML = (parent ? `${parent}: ` : '') + folder
// collection.innerHTML = folder
}
li.appendChild(document.createTextNode(' '))
li.appendChild(a)
li.onclick = function(e) {
e.preventDefault()
e.stopPropagation()
const isOpen = this.classList.toggle('open')
// history.pushState(folder, '', a.href)
document.title = folder
const subLists = this.querySelectorAll('li ol')
if (subLists.length > 0) {
for (const subList of subLists) {
subList.classList.toggle('hidden', !isOpen)
}
}
else {
getFolders(li)
}
}
li.appendChild(a)
const pathIndex = myPath.indexOf(folder.trim())
if (pathIndex >= 0) {
myPath = myPath.toSpliced(pathIndex, 1)
a.click()
}
ol.appendChild(li)
return li
}
async function createSongElement(obj, ol) {
const parent = ol.parentNode.dataset.folder
const li = document.createElement('li')
li.className = 'song'
li.textContent = obj.Key.replace(`${parent}/`, '') + ' '
const a = document.createElement('a')
a.className = 'action'
a.href = obj.href
a.title = locale.playSong
// a.textContent = '⧐' // '⥅' '⏵'
a.innerHTML = '<span class="fa-solid fa-circle-plus"></span>'
a.onclick = (e) => {
e.preventDefault()
e.stopPropagation()
if (e?.pointerId > 0) {
history.pushState(a.href, '', `#${obj.Key}`)
document.title = a.textContent
// collection.innerHTML = obj.Key
const cli = document.createElement('li')
cli.onclick = scrollToFirstTrack
cli.className = 'song'
cli.textContent = obj.Key + ' '
cli.dataset.source = obj.Key
sourceLink = cli.dataset.source
const ca = document.createElement('a')
ca.innerHTML = '<span class="fa-sharp fa-regular fa-circle-xmark"></span>'
ca.onclick = removeTracks
cli.appendChild(ca)
collection.appendChild(cli)
}
createAudioTrack(obj)
}
li.appendChild(a)
ol.appendChild(li)
const pathIndex = myPath.indexOf(li.textContent.trim())
if (pathIndex >= 0) {
a.click()
myPath = myPath.slice(pathIndex)
}
return li
}
async function createPlaylistElement(obj, ol) {
const parent = ol.parentNode.dataset.folder
const li = document.createElement('li')
li.className = 'playlist'
li.textContent = obj.Key.replace(`${parent}/`, '') + ' '
const a = document.createElement('a')
a.className = 'action'
a.href = obj.Key
a.title = locale.playPlaylist
// a.textContent = '⧐' // '⥅' '⏵'
a.innerHTML = '<span class="fa-solid fa-circle-plus"></span>'
a.onclick = async (e) => {
e.preventDefault()
e.stopPropagation()
// if (e?.pointerId > 0) {
history.pushState(a.href, '', `#${obj.Key}`)
document.title = a.textContent
// collection.innerHTML = obj.Key
const cli = document.createElement('li')
cli.onclick = scrollToFirstTrack
cli.className = 'playlist'
cli.textContent = obj.Key + ' '
cli.dataset.source = obj.Key
sourceLink = cli.dataset.source
const ca = document.createElement('a')
ca.innerHTML = '<span class="fa-sharp fa-regular fa-circle-xmark"></span>'
ca.onclick = removeTracks
cli.appendChild(ca)
collection.appendChild(cli)
// }
const getParams = {Bucket: bucketName, Key: obj.Key}
const command = new GetObjectCommand(getParams)
const res = await s3.send(command)
const json = await res.Body.transformToString()
try {
const playlist = JSON.parse(json)
const base = obj.Key.replace(/\/[^\/]+$/, '')
playlist?.track.forEach(async (track) => {
const song = {
Bucket: bucketName,
Key: track.url,
Metadata: track,
}
const getParams = {Bucket: bucketName, Key: song.Key}
const command = new GetObjectCommand(getParams)
song.href = await getSignedUrl(s3, command, { expiresIn: EXPIRE_SECONDS })
createAudioTrack(song)
})
}
catch(e) {
console.error(e)
}
}
li.appendChild(a)
ol.appendChild(li)
return li
}
function getS3Meta(key) {
return new Promise(
function(resolve, reject) {
let meta
const tx = db.transaction("meta", "readonly")
const cache = tx.objectStore("meta")
const index = cache.index("key")
const dbRequest = index.get(key)
dbRequest.onerror = function(event) {
reject(new Error(event))
}
dbRequest.onsuccess = async function() {
const matching = dbRequest.result
if (matching !== undefined) {
meta = matching
resolve(meta)
} else {
try {
const get = new HeadObjectCommand({Bucket: bucketName, Key: key})
metaQuery = await s3.send(get)
meta = metaQuery.Metadata
meta.key = key
putx = db.transaction("meta", "readwrite")
putx.objectStore("meta").put(meta)
resolve(meta)
}
catch(e) {
console.warn(`Error retrieving metadata for '${key}' from S3 bucket '${bucketName}'`)
console.log(e)
reject(new Error(e))
}
}
}
}
)
}
const playNext = () => {
const playing = playerList.querySelector('.playing')
let candidate = playing?.nextElementSibling
if (!candidate) {
// pick the first item on the list
candidate = playerList.querySelector('audio-track')
}
playTrack(candidate)
}
const playPrevious = () => {
const playing = playerList.querySelector('.playing')
const candidate = playing?.previousElementSibling
playTrack(candidate)
}
const playTrack = async (track) => {
if (track) {
document.title = track.querySelector('.name').textContent
let sessionOpts
if ('mediaSession' in navigator) {
sessionOpts = {
title: document.title,
artist: track.querySelector('.artist')?.textContent || 'Unknown Artist',
album: track.querySelector('.album')?.textContent || 'Unknown Album',
}
}
trackTitle.value = document.title
playerList.querySelector('.playing')?.classList.remove('playing')
track.classList.add('playing')
track.scrollIntoView({block: "nearest", inline: "nearest"})
audio.src = track.dataset['src']
audio.load()
if (track.dataset.albumArt) {
const image = new Image()
let url = track.dataset.albumArt
image.src = url
image.crossOrigin = "Anonymous"
image.onload = async function() {
if ('mediaSession' in navigator) {
const response = await fetch(url)
const blob = await response.blob()
if (blob) {
sessionOpts.artwork = [ {
src: url,
sizes: `${image.naturalWidth}x${image.naturalHeight}`,
type: blob.type
} ]
}
}
const ctx = document.createElement("canvas").getContext("2d")
ctx.drawImage(image, 0, 0, 1, 1)
const rgba = ctx.getImageData(0, 0, 1, 1).data
const hue = getHue(rgba[0], rgba[1], rgba[2])
document.documentElement.style.setProperty('--base-hue', hue)
}
}
if (sessionOpts) {
navigator.mediaSession.metadata = new MediaMetadata(sessionOpts)
}
}
}
if ('mediaSession' in navigator) {
navigator.mediaSession.setActionHandler('play', (e) => { audio.play() })
navigator.mediaSession.setActionHandler('pause', (e) => { audio.pause() })
navigator.mediaSession.setActionHandler('previoustrack', playPrevious)
navigator.mediaSession.setActionHandler('nexttrack', playNext)
navigator.mediaSession.setActionHandler('stop', (e) => { audio.pause() })
navigator.mediaSession.setActionHandler('seekto', (details) => {
audio.currentTime = details.seekTime
})
navigator.mediaSession.setActionHandler('seekbackward', (details) => {
audio.currentTime = Math.max(audio.currentTime - details.seekOffset, 0)
})
navigator.mediaSession.setActionHandler('seekforward', (details) => {
audio.currentTime = Math.min(audio.currentTime + details.seekOffset, audio.duration)
})
}
function getHue(r, g, b) {
r /= 255, g /= 255, b /= 255
const max = Math.max(r, g, b)
const min = Math.min(r, g, b)
let h = 0
if(max != min){
const d = max - min;
switch(max){
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6
}
return Math.round(h*360)
}
async function preloadAudio() {
const cacheKeys = Object.keys(preloadCache)
if (preloading || cacheKeys.length < 1) {
return false
}
const href = cacheKeys[0]
delete(preloadCache[href])
preloading = href
const dummyAudio = document.createElement('audio')
dummyAudio.src = href
dummyAudio.load()
dummyAudio.oncanplay = (e) => {
preloading = false
preloadAudio()
}
}
async function queuePreload(href) {
preloadCache[href] = true
preloadAudio()
}
async function createAudioTrack(obj, source) {
// pre-fetch content to cache
queuePreload(obj.href)
let myArtist = ''
let myAlbum = ''
let myTitle = ''
let myTrackNumber = ''
let myDuration = '0:00'
let myYear = ''
let myPlaylist = ''
let myGenre = ''
let myKeywords = ''
let myImage = ''
const matches = obj.Key.match(/([^\/]*)\/?([^\/]*)\/([^\/]*)\.mp3/)
if (matches && matches.length == 4) {
myArtist = matches[1]
myAlbum = matches[2]
myTitle = matches[3]
}
else if (matches && matches.length > 0) {
myArtist = matches[1]
myTitle = matches[2]
}
if (obj.Metadata['artist']) myArtist = decodeURIComponent(obj.Metadata['artist'])
if (obj.Metadata['album']) myAlbum = decodeURIComponent(obj.Metadata['album'])
if (obj.Metadata['name']) myTitle = decodeURIComponent(obj.Metadata['name'])
if (obj.Metadata['title']) myTitle = decodeURIComponent(obj.Metadata['title'])
if (obj.Metadata['tracknumber']) myTrackNumber = decodeURIComponent(obj.Metadata['tracknumber'])
if (obj.Metadata['length']) myDuration = decodeURIComponent(obj.Metadata['length'])
if (obj.Metadata['datePublished']) myYear = decodeURIComponent(obj.Metadata['datePublished'])
if (obj.Metadata['recordingtime']) myYear = decodeURIComponent(obj.Metadata['recordingtime'])
if (obj.Metadata['year']) myYear = decodeURIComponent(obj.Metadata['year'])
if (obj.Metadata['playlist']) myPlaylist = decodeURIComponent(obj.Metadata['playlist'])
if (obj.Metadata['genre']) myGenre = decodeURIComponent(obj.Metadata['genre'])
if (obj.Metadata['keywords']) myKeywords = decodeURIComponent(obj.Metadata['keywords'])
if (obj.Metadata['image']) myImage = decodeURIComponent(obj.Metadata['image'])
const track = document.createElement('audio-track')
track.tabIndex = 0
track.itemprop = 'track'
track.itemscope = ''
track.itemtype = 'https://schema.org/MusicRecording'
track.dataset.src = obj.href
track.dataset.source = sourceLink
if (myImage) {
const img = {
Bucket: bucketName,
Key: myImage
}
const getParams = {Bucket: bucketName, Key: img.Key}
const command = new GetObjectCommand(getParams)
const url = await getSignedUrl(s3, command, { expiresIn: EXPIRE_SECONDS })
track.style.backgroundImage = `url(${url})`
track.dataset.albumArt = url
}
const artist = document.createElement('section')
artist.className = 'artist'
const byArtist = document.createElement('a')
byArtist.itemprop = 'byArtist'
byArtist.textContent = myArtist
artist.appendChild(byArtist)
track.appendChild(artist)