-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.html
2816 lines (2497 loc) · 94.6 KB
/
client.html
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
<!DOCTYPE html>
<html>
<head>
<script src="src/hls.js"></script>
<script src="src/js.cookie.js"></script>
<link rel="stylesheet" href="src/bootstrap-icons.css">
<link rel="stylesheet" type="text/css" href="src/toastify.min.css">
<!--
Thanks for jsDelivr providing such amazing libraries
Some of our users might not able to access through the cdn, so we have to download it to our server
But we will never forgot where those libraries from and this is for PERSONAL USE ONLY.
https://cdn.jsdelivr.net/npm/hls.js@1
https://cdn.jsdelivr.net/npm/[email protected]/dist/js.cookie.min.js
https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css
-->
<script type="text/javascript">
window.onload = function() {
'use strict';
// SECTION: constants
const FILE_CHUNK_SIZE = 1024 * 1024;
const MEDIA_FRAGMENT_DURATION = 10;
const MAX_RETRY = 3;
const BASE_URL = /^(.*)\/$/.exec(window.location.href)[1];
// SECTION: icon
const formatIcon = className => `<i class='bi bi-${className}'></i>`;
const Eye = formatIcon('eye');
const EyeSlash = formatIcon('eye-slash');
const SkipStartFill = formatIcon('skip-start-fill');
const SkipEndFill = formatIcon(`skip-end-fill`);
const PauseFill = formatIcon('pause-fill');
const Play = formatIcon('play');
const List = formatIcon('list');
const XLg = formatIcon('x-lg');
const Shuffle = formatIcon('shuffle');
const MusicNoteList = formatIcon('music-note-list');
const Repeat = formatIcon('repeat');
const RepeatOne = formatIcon('repeat-1');
const ListUl = formatIcon('list-ul');
const VolumeUpFill = formatIcon('volume-up-fill');
const VolumeDownFill = formatIcon('volume-down-fill');
const VinylFill = formatIcon('vinyl-fill');
const PencilFill = formatIcon('pencil-fill');
// SECTION: components
const notificationContainer = document.getElementById('notification-container');
const popupContainer = document.getElementById('popup-container');
const popupWindow = document.getElementById('popup-window');
const contextMenuContainer = document.getElementById('context-menu-container');
const main = document.getElementById('main');
// SECTION: notification
const showNotification = (text, className = 'info', duration = 5000) => {
Toastify({
text, className, duration,
close: true,
position: "center", gravity: 'bottom'
}).showToast();
}
// SECTION: popup
let popupWindowVisibility = false;
async function showPopup(buildPage) {
if(!buildPage) {
popupContainer.style.backgroundColor = 'unset';
popupContainer.style.pointerEvents = 'none';
popupWindow.style.transform = 'scale(0)';
await new Promise(s=>setTimeout(s, 300));
popupWindow.innerHTML = '';
popupWindowVisibility = false;
} else {
popupContainer.style.backgroundColor = 'rgba(0,0,0,.7)';
popupContainer.style.pointerEvents = 'initial';
buildPage();
popupWindow.style.transform = 'unset';
popupWindowVisibility = true;
}
}
const closePopup = () => showPopup(null);
popupContainer.onclick = evt => {
if(evt.target === popupContainer) {
closePopup();
}
}
// SECTION: context menu
let onTextMenuClose = null;
function showContextMenu(elem, onclose = null) {
elem.classList.add('context-menu');
contextMenuContainer.appendChild(elem);
contextMenuContainer.style.pointerEvents = 'initial';
onTextMenuClose = onclose;
}
function closeContextMenu() {
contextMenuContainer.innerHTML = ''
contextMenuContainer.style.pointerEvents = 'none';
onTextMenuClose && onTextMenuClose();
onTextMenuClose = null;
}
contextMenuContainer.onclick = evt => {
if(evt.target !== contextMenuContainer) return;
closeContextMenu();
}
contextMenuContainer.oncontextmenu = evt => {
evt.preventDefault();
closeContextMenu();
}
// SECTION: utils
function shuffle(arr) {
return [...arr].sort(()=> .5 - Math.random())
}
// SECTION: pages
function askLogin() {
if(Cookies.get('session-id')) {
return party();
}
function submitLogin(evt) {
evt.preventDefault();
const account = evt.target.account.value;
const password = evt.target.password.value;
fetch(`${BASE_URL}/account/login`, {
method: 'POST',
body: JSON.stringify({account, password}),
headers: {'Content-Type': 'application/json'}
}).then(async res => {
const { result, sessionID } = await res.json();
if(result !== 'login-failed') {
if(result === 'login-success') showNotification('登陆成功!', 'success')
else if(result === 'account-created') showNotification('注册成功, 将为您登录', 'success')
Cookies.set('session-id', sessionID, { expires: 365 } );
if(evt.target['remember-password'].checked) {
localStorage.setItem('remember-password', true);
localStorage.setItem('account', account);
localStorage.setItem('password', password);
} else if(localStorage.getItem('remember-password')) {
localStorage.removeItem('remember-password');
localStorage.removeItem('account');
localStorage.removeItem('password');
}
// go to party main
party();
} else {
showNotification('密码不正确!', 'err')
}
})
}
main.innerHTML = `
<form id='login-form'>
<span class='description'>请输入账号密码登录,如果账号不存在将会直接创建</span>
<input type='text' name='account' id='login-account' placeholder="请输入您的账号" >
<div id='show-password' class='clickable'>${Eye}</div>
<input type='password' name='password' id='login-password' placeholder='请输入您的密码' >
<div class='remember-password-container'>
<input type='checkbox' id='remember-password' name='remember-password'>
<span>记住密码</span>
</div>
<button class='clickable' type='submit'>登录</button>
</form>
`
let password_display = false;
const password_elem = document.getElementById('login-password');
const show_password_elem = document.getElementById('show-password');
if(localStorage.getItem('remember-password')) {
password_elem.value = localStorage.getItem('password');
document.getElementById('login-account').value = localStorage.getItem('account');
document.getElementById('remember-password').checked = true;
}
show_password_elem.onclick = () => {
password_display = !password_display;
show_password_elem.innerHTML = password_display ? EyeSlash : Eye;
password_elem.type = password_display ? 'text' : 'password';
}
document.getElementById('login-form').onsubmit = submitLogin;
}
async function party() {
const sessionID = Cookies.get('session-id')
// validate current login information
const user_login_validated = await (await fetch(`${BASE_URL}/account/validate-login`,{
method: 'POST',
body: JSON.stringify({ sessionID }),
headers: { 'Content-Type': 'application/json' }
})).json();
if(!user_login_validated) {
showNotification('登陆凭证已过期!', 'warn')
Cookies.remove('session-id');
return askLogin();
}
// check hls capability, if not capable return to login page
let HLSType = null;
(function () {
if(document.createElement('video').canPlayType('application/x-mpegURL')) {
HLSType = 'browser'
} else if(Hls.isSupported()) {
HLSType = 'library'
} else {
Cookies.remove('session-id');
askLogin();
showNotification('您的浏览器似乎不支持通过HLS播放!')
}
})();
// init states
const PLAY_WAYS = ['loop', 'single', 'random', 'playlist']
let displaying = {
type: '', elem: null, currentVolume: 0.5
}
const playStates = {
playlist: {},
playing: -1, order: [],
random_order: [],
_how: 'loop',
set how(way) {
how_to_play.innerHTML =
way === 'playlist' ? ListUl :
way === 'single' ? RepeatOne :
way === 'random' ? Shuffle :
Repeat
const playing_id = getFollowOrder()[this.playing]
if(way === 'random') this.random_order = shuffle(this.order)
this._how = way;
this.playing = getFollowOrder().indexOf(playing_id)
},
get how() {
return this._how;
}
}
let last_toggled_resize = 0;
let manual_update_media_time = false,
manual_toggle_play = false,
can_sync_media_time = false;
let pause_after = 0;
const roomMode = {
activate: false, playlist: {}, order: [], extra: {},
syncProgress: null, exitRoom: null, requestUpdatePlaylist: null
};
// functions
function createHLSController(bound_elem, type) {
let hls;
if(HLSType === 'library') {
hls = new Hls();
hls.attachMedia(bound_elem);
}
return function(url) {
if(HLSType === 'browser') {
bound_elem.src = url;
} else if(HLSType === 'library') {
hls.loadSource(url);
}
}
}
function loadHls(bound_elem, type) {
const hls = createHLSController(bound_elem, type);
return async (url, startPlay)=>{
hls(url)
if(displaying.type !== type) {
if(displaying.elem) {
displaying.elem.style.display = 'none';
displaying.elem.pause();
displaying.type = type;
}
displaying.elem = bound_elem;
bound_elem.style.display = 'block';
}
startPlay && bound_elem.play();
bound_elem.volume = displaying.currentVolume;
}
}
function getMediaDuration(media_file, fileType) {
return new Promise(resolve => {
const media_elem = document.createElement(fileType);
const url = URL.createObjectURL(media_file);
media_elem.preload = 'metadata';
media_elem.onloadedmetadata = () => {
resolve(media_elem.duration);
URL.revokeObjectURL(url);
}
media_elem.src = url;
})
}
function getFollowOrder() {
return (
roomMode.activate ? roomMode.order :
playStates.how === 'random' ? playStates.random_order :
playStates.order
)
}
async function uploadFile(file, rename, progressControl) {
let totalChunks = Math.ceil(file.size / FILE_CHUNK_SIZE),
currentChunkIndex = 0,
fileType = file.type.split('/'),
referenceID = -1,
updateProgress = progressControl(abort),
retry = 0, pauseUpdateTill = 0;
async function init() {
const estFragments = Math.ceil((await getMediaDuration(file, fileType[0])) / MEDIA_FRAGMENT_DURATION);
referenceID = + (await (await fetch(`${BASE_URL}/playlist/pre-upload`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
sessionID,
title: (rename || file.name),
suffix: `${fileType[1]}.${file.name.split('.').pop()}`,
fileType: fileType[0],
estChunks: totalChunks,
estFragments
})
})).text());
cutFileChunk();
}
async function abort() {
if(currentChunkIndex !== -1 && referenceID !== -1) {
currentChunkIndex = -1;
const abort_result = await (await fetch(`${BASE_URL}/playlist/`, {
method: 'DELETE',
body: JSON.stringify({id: referenceID, sessionID}),
headers: {'Content-Type': 'application/json'},
})).json()
updateProgress(`aborted${abort_result ? '' : '-failed'}`);
if(!abort_result) {
pauseUpdateTill = Date.now() + 5000
}
}
}
function cutFileChunk() {
if(currentChunkIndex < 0) return;
const start = currentChunkIndex * FILE_CHUNK_SIZE;
const end = Math.min(start + FILE_CHUNK_SIZE, file.size);
sendFileChunk(file.slice(start, end));
}
async function sendFileChunk(chunk) {
if(currentChunkIndex < 0) return;
const isLastChunk = + (currentChunkIndex === totalChunks - 1)
const searchParams = new URLSearchParams({
sessionID, referenceID, chunkIndex: currentChunkIndex
})
const upload_result = await (await fetch(`${BASE_URL}/playlist/upload-chunk?${searchParams.toString()}`, {
method: 'POST',
body: chunk,
headers: {'Content-Type': 'application/octet-stream'}
})).json();
if(upload_result) {
if(isLastChunk) {
currentChunkIndex = -1;
updateProgress('waiting-process', 0);
const interval_id = setInterval(async () => {
const fragment_status = await getUploadProgress(referenceID);
if(pauseUpdateTill) {
if(Date.now() <= pauseUpdateTill) return;
pauseUpdateTill = 0;
}
if(!fragment_status.error_msg) {
updateProgress(
fragment_status.status === 'fragmenting' ?
'waiting-process' :
fragment_status.status === 'finished' ?
'finished' : 'upload', Math.floor(fragment_status.progress * 100))
}
(!popupWindowVisibility || fragment_status.error_msg || fragment_status.status === 'finished') && clearInterval(interval_id)
}, 1000);
} else if(currentChunkIndex >= 0) {
currentChunkIndex ++;
updateProgress('upload', Math.floor((currentChunkIndex / (totalChunks - 1)) * 100))
cutFileChunk();
}
} else {
if(retry < MAX_RETRY) {
retry ++;
cutFileChunk()
updateProgress('retry', retry)
} else {
retry = 0;
updateProgress('failed')
}
}
}
init();
}
async function getPlaylist() {
const user_playlists = await (await fetch(
`${BASE_URL}/playlist/user-playlist?${new URLSearchParams({sessionID}).toString()}`)
).json()
const updatedIDs = user_playlists.map(e=>e.id);
const playing_id = getFollowOrder()[playStates.playing]
let removed_playing = false;
// check if any media removed
Object.keys(playStates.playlist).filter(e=>!updatedIDs.includes(+e))
.forEach(removedMedia => {
let media_id = +removedMedia;
if(playing_id === media_id) removed_playing = true;
playStates.order = playStates.order.filter(e => e !== media_id);
delete playStates.playlist[media_id];
if(roomMode.activate) {
roomMode.order = roomMode.order.filter(e => e !== media_id);
delete roomMode.playlist[media_id];
}
})
// update details and add any media not added
for(const media of user_playlists) {
playStates.playlist[media.id] = media;
playStates.order.includes(media.id) || playStates.order.push(media.id);
roomMode.activate &&
(roomMode.order.includes(media.id) || roomMode.order.push(media.id));
}
roomMode.activate && roomMode.requestUpdatePlaylist();
if(removed_playing) {
playStates.playing = 0;
playMedia({manualPlay: true, startPlay: !displaying.elem.paused});
} else {
playStates.playing = getFollowOrder().indexOf(playing_id);
}
return;
}
async function getUploadProgress(referenceID = -1) {
const url = referenceID > 0 ? 'media' : 'user'
const query = { sessionID }
if(referenceID > 0) query.referenceID = referenceID;
return await (
await fetch(
`${BASE_URL}/playlist/${url}-upload-status?${new URLSearchParams(query).toString()}`
)
).json()
}
function togglePlay() {
if(displaying.elem) {
displaying.elem.paused ? displaying.elem.play() : displaying.elem.pause();
} else if(((roomMode.activate && roomMode.order.length) || playStates.order.length) && playStates.playing === -1) {
playNext(false);
}
manual_toggle_play = true;
}
function playMedia({manualPlay = false, startPlay = true}) {
const media_list = roomMode.activate ? roomMode.playlist : playStates.playlist
const media = media_list[getFollowOrder()[playStates.playing]]
media.type === 'audio' ?
setAudioHls(`${BASE_URL}/playlist/${sessionID}/${media.id}/${media.filename}.m3u8`, startPlay) :
setVideoHls(`${BASE_URL}/playlist/${sessionID}/${media.id}/${media.filename}.m3u8`, startPlay)
if(media.type === 'audio') {
audio_title_container.style.display = 'block';
audio_title.textContent = media.title;
audio_title.style.animationName = 'unset';
audio_title.style.animationDuration = `${
Math.max(
audio_title.clientWidth,
audio_title_container.clientWidth
) / 70}s`;
audio_title.style.animationName = 'music-title-scroll';
} else {
audio_title_container.style.display = 'none';
}
if(roomMode.activate && manualPlay) roomMode.syncProgress()
}
function playNext(manual = true) {
if(!(roomMode.activate && roomMode.order.length) && !playStates.order.length) return;
if(playStates.how === 'single') {
playMedia({manualPlay: manual}); return;
}
const followOrder = getFollowOrder();
// if is last
if(playStates.playing >= followOrder.length - 1) {
if(playStates.how === 'playlist') return;
playStates.playing = 0;
if(playStates.how === 'random')
playStates.random_order = shuffle(playStates.order)
} else playStates.playing ++;
playMedia({manualPlay: manual});
}
function playLast() {
if((!(roomMode.activate && roomMode.order.length) && !playStates.order.length)) return;
if(playStates.how === 'single') {
playMedia({manualPlay: true}); return;
}
const followOrder = getFollowOrder();
// if is first
if(playStates.playing <= 0) {
if(playStates.how === 'playlist') return;
else playStates.playing = followOrder.length - 1
} else playStates.playing --;
playMedia({manualPlay: true});
}
function keyboardControl(evt) {
// disable keyboard control when there's a popup window
if(popupWindowVisibility || document.activeElement === displaying.elem) return;
switch(evt.key) {
case ' ': togglePlay(); break;
case 'ArrowLeft': calculateSetProgressByTime(-5); break;
case 'ArrowRight': calculateSetProgressByTime(5); break;
case 'ArrowUp': setVolume(0.02); break;
case 'ArrowDown': setVolume(-0.02); break;
default: break;
}
}
function interactableProgressBar(name, setElemProgress) {
const states = { mouseDown: false, X: -1, width: -1, locOnPage: -1 }
const container = document.querySelector(`#media-${name}-interactive.media-interactive-container`);
const bar = document.querySelector(`#media-${name}-interactive.media-interactive-container .bar .bg`)
const node = document.querySelector(`#media-${name}-interactive.media-interactive-container #node`)
// read layout property to force render
container.offsetWidth;
container.onmousedown = () => {states.mouseDown = true}
container.onmouseup = () => {
if(name==='progress') can_sync_media_time = true;
states.mouseDown = false
}
container.onmouseleave = () => {
if(name==='progress' && states.mouseDown)
can_sync_media_time = true;
states.mouseDown = false
}
container.ontouchstart = () => {states.mouseDown = true}
container.ontouchend = () => {
if(name==='progress') can_sync_media_time = true;
states.mouseDown = false
}
container.ontouchcancel = () => {
if(name==='progress' && states.mouseDown)
can_sync_media_time = true;
states.mouseDown = false
}
container.onclick = evt => {
states.X = evt.offsetX;
calculateProgress(null, true);
}
container.onmousemove = evt => {
states.X = evt.offsetX;
states.mouseDown && calculateProgress(null, true);
}
container.ontouchmove = evt => {
states.X = evt.changedTouches[0].pageX - states.locOnPage;
states.mouseDown && calculateProgress(null, true);
}
function setUIProgress() {
bar.style.transform = `translateX(${states.X}px)`;
node.style.transform = `translateX(${states.X}px)`;
}
function updateWidth() {
states.width = container.offsetWidth;
states.locOnPage = container.getBoundingClientRect().left
}
function calculateProgress(params = {value: null, total: null}, isInside = false) {
states.X = Math.max(Math.min(states.width, states.X), 0)
if(isInside) {
setElemProgress(states.X / states.width);
} else {
const {value, total} = params;
states.X = Math.round(states.width * (value / total));
setUIProgress()
}
}
updateWidth();
return [calculateProgress, updateWidth]
}
function windowResized() {
if(Date.now() - last_toggled_resize < 100) return;
last_toggled_resize = Date.now();
updateMediaProgressWidth();
updateMediaVolumeWidth();
checkPartyOverflow();
}
function checkPartyOverflow() {
// check observers to determine overflow
if(
top_observer.getBoundingClientRect().top < 0 ||
bottom_observer.getBoundingClientRect().top > party_page.offsetHeight
) {
party_page.style.overflowY = 'scroll';
} else {
party_page.style.overflowY = 'hidden';
}
}
function calculateSetProgressByTime(time = 0) {
if(!displaying.elem) return;
let duration = displaying.elem.duration,
currentTime = displaying.elem.currentTime;
time = Math.max(Math.min(currentTime + time, duration), 0);
displaying.elem.currentTime = time;
can_sync_media_time = true;
}
function setVolume(change) {
if(!displaying.elem) return;
const newVol = Math.max(Math.min(displaying.currentVolume + change, 1), 0);
displaying.elem.volume = newVol;
}
function updatePlayIcon() {
if(displaying.elem) {
if(displaying.elem.paused) {
toggle_play_btn.innerHTML = Play;
toggle_play_btn.title = '播放';
} else {
toggle_play_btn.innerHTML = PauseFill;
toggle_play_btn.title = '暂停';
}
}
roomMode.activate && manual_toggle_play && roomMode.syncProgress();
manual_toggle_play = false;
}
function pauseTimerAction() {
if(displaying.elem) {
manual_toggle_play = true;
displaying.elem.pause();
}
pause_after = 0;
}
function mediaElemEvtListeners() {
let media_time_update_cooldown = 0;
function mediaVolumeChanged() {
displaying.currentVolume = displaying.elem.volume;
calculateMediaVolume({
value: displaying.currentVolume,
total: 1
})
}
function mediaTimeUpdated() {
const current = Date.now();
if(pause_after && current >= pause_after) {
pauseTimerAction();
}
if(current < media_time_update_cooldown && !manual_update_media_time) return;
media_time_update_cooldown = current + 100;
if(can_sync_media_time && roomMode.activate) roomMode.syncProgress();
manual_update_media_time = false;
can_sync_media_time = false;
if(displaying.elem) {
calculateMediaProgress({
value: displaying.elem.currentTime,
total: displaying.elem.duration
})
}
}
video_component.onended = playNext;
audio_component.onended = playNext;
video_component.onvolumechange = mediaVolumeChanged;
audio_component.onvolumechange = mediaVolumeChanged;
video_component.onpause = updatePlayIcon;
audio_component.onpause = updatePlayIcon;
video_component.onplay = updatePlayIcon;
audio_component.onplay = updatePlayIcon;
video_component.ontimeupdate = mediaTimeUpdated;
audio_component.ontimeupdate = mediaTimeUpdated;
}
function updateTextScrollAnimation(elem, parentElem = null, pauseAfterFinish = 2000, speed = 70) {
parentElem = parentElem || elem.parentElement;
let not_available = elem.offsetWidth <= parentElem.offsetWidth,
moveDistance = elem.offsetWidth - parentElem.offsetWidth + 10,
last_update_time = Date.now(),
play_end = false,
position = 0;
function move() {
not_available || requestAnimationFrame(move)
const time_past = Date.now() - last_update_time;
if(!play_end) {
elem.style.transform = `translateX(${Math.floor(position)}px)`;
position -= last_update_time < 0 ? 0 : time_past / 1000 * speed;
last_update_time = Date.now();
if(Math.abs(position) > moveDistance) {
play_end = true;
position = 0;
}
} else if(time_past >= pauseAfterFinish) {
play_end = false;
last_update_time = Date.now();
}
}
not_available || requestAnimationFrame(move)
return function requestUpdate() {
const previous_available = not_available;
not_available = elem.offsetWidth <= parentElem.offsetWidth;
moveDistance = elem.offsetWidth - parentElem.offsetWidth + 10;
last_update_time = Date.now();
play_end = false;
position = 0;
!not_available && !previous_available && requestAnimationFrame(move)
}
}
// main page
main.innerHTML = `
<div id='party'>
<div class='overflow-observer' name='top-observer'></div>
<div class='party-main'>
<div class='media-container-block'>
<div class='media-container'>
<div class='music-title-container'>
<div class='music-title'><div class='music-title-text'></div></div>
${VinylFill}
</div>
<video id='video-component' controls></video>
<audio id='audio-component'></audio>
</div>
</div>
<div id='media-progress-interactive' class='media-interactive-container clickable'>
<div class='bar'><div class='bg'></div></div>
<div id='node'></div>
</div>
<div class='controllers'>
<div class='controller clickable sub-icon' id='show-playlist-icon' title='播放列表'>${MusicNoteList}</div>
<div class='controller clickable' id='last' title='上一媒体'>${SkipStartFill}</div>
<div class='controller clickable' id='toggle-play' title='播放'>${Play}</div>
<div class='controller clickable' id='next' title='下一媒体'>${SkipEndFill}</div>
<div class='controller clickable sub-icon' id='how-to-play' title='切换播放方式'>${Repeat}</div>
</div>
<div id='media-volume-interactive' class='media-interactive-container clickable'>
${VolumeDownFill}
<div class='bar'><div class='bg'></div></div>
<div id='node'></div>
${VolumeUpFill}
</div>
</div>
<div id='nav-bar'>
<div class='clickable' id='hamburger-icon'>${List}</div>
<div class='items'>
<div class='item clickable' id='user-center'><div>用户中心</div></div>
<div class='item clickable' id='get-playlist'><div>播放列表</div></div>
<div class='item clickable' id='pause-timer'><div>定时关闭</div></div>
<div class='item clickable' id='upload-media'><div>上传媒体文件</div></div>
<div class='item clickable' id='upload-manager'><div>管理我的上传</div></div>
<div class='item clickable' id='join-room-menu'><div>创建/加入房间</div></div>
<div class='item clickable' id='update-playlist'><div>更新播放列表</div></div>
<div class='item clickable' id='logout'><div>退出登录</div></div>
</div>
</div>
<div class='overflow-observer' name='bottom-observer'></div>
</div>`
// components on main page
const video_component = document.getElementById('video-component');
const audio_component = document.getElementById('audio-component');
const audio_title_container = document.querySelector('.media-container .music-title-container')
const audio_title = document.querySelector('.media-container .music-title-container .music-title .music-title-text')
// observers and references
const top_observer = document.querySelector('.overflow-observer[name="top-observer"]');
const bottom_observer = document.querySelector('.overflow-observer[name="bottom-observer"]');
const party_page = document.getElementById('party');
const setVideoHls = loadHls(video_component, 'video');
const setAudioHls = loadHls(audio_component, 'audio');
const toggle_play_btn = document.getElementById('toggle-play')
const how_to_play = document.getElementById('how-to-play')
// listeners
mediaElemEvtListeners();
toggle_play_btn.onclick = togglePlay;
document.getElementById('last').onclick = playLast
document.getElementById('next').onclick = playNext
document.getElementById('show-playlist-icon').onclick = () => showPopup(showPlaylist)
how_to_play.onclick = function() {
if((!(roomMode.activate && roomMode.order.length) && !playStates.order.length)) return;
const idx = PLAY_WAYS.indexOf(playStates.how)
playStates.how = PLAY_WAYS[idx === PLAY_WAYS.length - 1 ? 0 : idx + 1]
if(roomMode.activate) {
roomMode.requestUpdatePlaylist(true);
}
}
window.addEventListener('resize', windowResized);
document.addEventListener('keydown', keyboardControl)
const [calculateMediaProgress, updateMediaProgressWidth] = interactableProgressBar('progress', value => {
manual_update_media_time = true;
if(displaying.elem) displaying.elem.currentTime = displaying.elem.duration * value;
})
const [calculateMediaVolume, updateMediaVolumeWidth] = interactableProgressBar('volume', value => {
if(displaying.elem) displaying.elem.volume = value;
})
// nav bar
const nav_bar = document.getElementById('nav-bar');
document.getElementById('hamburger-icon').onclick = () => {
nav_bar.classList.toggle('expanded-nav-bar')
}
// nav bar items
function uploadMediaFile() {
popupWindow.innerHTML = `
<div id='upload-media-container'>
<div class='upload-file-container'>
<input type='file' name='media-files' id='files-input' class='clickable' multiple>
<div class='show-upload'><span>点击或拖拽文件到此处以上传</span></div>
</div>
<div class='btn-container'>
<button id='upload-btn'>上传</button>
<button id='cancel-btn'>取消</button>
</div>
</div>
`
function updateProgress(playlist_name, elem, bgElem, stats) {
let updateAnimation = updateTextScrollAnimation(elem)
const updatedAnimation = {
'upload': false,
'waiting-process': false
}
return function(abort) {
stats.abort = abort;
return function(progress, additional = null) {
if(progress === 'finished') getPlaylist()
const msg =
progress === 'upload' ? `[${playlist_name}] 上传中... ${`${additional}`.padStart(2, '0')}%` :
progress === 'waiting-process' ? `[${playlist_name}] 生成分片文件中... ${`${additional}`.padStart(2, '0')}%` :
progress === 'finished' ? `[${playlist_name}] 上传完成!` :
progress === 'aborted' ? `[${playlist_name}] 上传中断!` :
progress === 'aborted-failed' ? `[${playlist_name}] 上传无法中断, 请等待上传完成后手动删除!` :
progress === 'failed' ? `[${playlist_name}] 上传重试${MAX_RETRY}次后失败, 请尝试重新上传或联系管理员!` :
progress === 'retry' ? `[${playlist_name}] 上传失败, 重试第${additional}次.` :
''
if(!popupWindowVisibility) {
if(progress === 'upload' || progress === 'waiting-process') return;
showNotification(
msg,
progress === 'aborted' || progress === 'failed' ? 'err' :
progress === 'aborted-failed' || progress === 'retry' ? 'warn' :
'success'
)
return;
} else {
elem.textContent = msg;
bgElem.style.backgroundColor = 'lightgreen';
elem.style.color = `black`;
if(progress === 'upload' || progress === 'waiting-process') {
bgElem.style.transform = `translateX(-${100 - additional}%)`
if(!updatedAnimation[progress]) {
updatedAnimation[progress] = true;
updateAnimation();
}
return;
} else if(progress === 'retry') {
bgElem.style.backgroundColor = `gold`;
updatedAnimation['upload'] = false;
updatedAnimation['waiting-process'] = false;
} else {
bgElem.style.transform = 'translateX(0)';
stats.finished = true;
switch(progress) {
case 'finished': break;
case 'aborted':
case 'failed':
bgElem.style.backgroundColor = `red`;
elem.style.color = `white`;
break;
case 'aborted-failed':
bgElem.style.backgroundColor = `gold`;
break;
default: stats.finished = false;
}
}
updateAnimation();
return;
}
}
}
}
const uploadMediaContainer = document.getElementById('upload-media-container'),
uploadBtn = document.getElementById('upload-btn'),
cancelBtn = document.getElementById('cancel-btn')
const selectedFiles = []
const filesInput = document.getElementById('files-input')
filesInput.onchange = evt => {
const files = evt.target.files;
const all_files_index = selectedFiles.length
for(var i = 0, j = all_files_index; i < files.length; i ++, j ++) {
const file = files[i];
if(! /^(audio|video)\/.*$/.test(file.type)) {
showNotification(`[${file.name}]不是视频/音频文件!`, 'err');
j --;
continue;
}
const index = j;
const displayElemContainer = document.createElement('div');
displayElemContainer.className = 'progress-bar';
const defaultName = file.name.split('.').slice(0, -1).join('.')
const renameInput = document.createElement('input')
renameInput.type = 'text';
renameInput.placeholder = defaultName;
renameInput.value = defaultName;
renameInput.oninput = evt => {
const value = evt.target.value;
selectedFiles[index].rename = value;
}
const removeFile = document.createElement('div')
removeFile.className = 'remove-file clickable';
removeFile.innerHTML = XLg;
removeFile.onclick = () => {
selectedFiles.splice(index, 1, null);
displayElemContainer.remove();
}
displayElemContainer.appendChild(renameInput);
displayElemContainer.appendChild(removeFile);
uploadBtn.parentElement.insertAdjacentElement('beforebegin', displayElemContainer)
selectedFiles[index] = {
rename: defaultName, finished: false,
file, displayElemContainer
}
}
}
function cleanUp() {
selectedFiles.length = 0;
closePopup();
}