@kangsicj/nexussync 1.3.1 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -2
- package/dist/NexusSync.meta.js +4 -1
- package/dist/NexusSync.user.js +1684 -72
- package/package.json +1 -1
package/dist/NexusSync.user.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// @icon https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/assets/icon.svg
|
|
9
9
|
// @updateURL https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/dist/NexusSync.meta.js
|
|
10
10
|
// @downloadURL https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/dist/NexusSync.user.js
|
|
11
|
-
// @version 1.
|
|
11
|
+
// @version 1.5.0
|
|
12
12
|
// @description Watch any web video together in perfect sync: cinema mode, live AI subtitles & translation, chat bubbles with auto-translation, quick ink, cover, go-together to the next episode.
|
|
13
13
|
// @description:ko 어떤 웹 영상이든 완벽한 싱크로 함께 보기: 시네마 모드, 실시간 AI 자막·번역, 자동 번역 말풍선 채팅, 잠깐 그리기, 가리기, 다음 화도 함께.
|
|
14
14
|
// @match *://*/*
|
|
@@ -32,6 +32,9 @@
|
|
|
32
32
|
// @connect api.anthropic.com
|
|
33
33
|
// @connect api-free.deepl.com
|
|
34
34
|
// @connect api.deepl.com
|
|
35
|
+
// @connect rest.opensubtitles.org
|
|
36
|
+
// @connect dl.opensubtitles.org
|
|
37
|
+
// @connect www.themoviedb.org
|
|
35
38
|
// ==/UserScript==
|
|
36
39
|
|
|
37
40
|
(async function () {
|
|
@@ -43,12 +46,12 @@
|
|
|
43
46
|
|
|
44
47
|
// The version of the code that is actually running (the manager's metadata can lag
|
|
45
48
|
// behind when an old copy is still installed).
|
|
46
|
-
const NXU_VERSION = '1.
|
|
49
|
+
const NXU_VERSION = '1.5.0';
|
|
47
50
|
// Rank used by the one-instance guard below and to tell newer builds apart in a room.
|
|
48
51
|
// It is independent of the public version (1.0.0 is the first public release, after
|
|
49
52
|
// private builds that reached ranks up to 10.2.0), so every older copy still installed
|
|
50
53
|
// steps aside instead of this release.
|
|
51
|
-
const NXU_RANK = '11.
|
|
54
|
+
const NXU_RANK = '11.5.0';
|
|
52
55
|
const NXU_SESSION = Math.random().toString(36).slice(2, 10); // this page load // raise with every release
|
|
53
56
|
// App icon (same artwork as assets/icon.svg / @icon), inlined so it shows offline too.
|
|
54
57
|
const NXU_ICON = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTYgMjU2IiByb2xlPSJpbWciIGFyaWEtbGFiZWw9Ik5leHVzU3luYyI+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJueGJnIiB4MT0iMCIgeTE9IjAiIHgyPSIxIiB5Mj0iMSI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjNWIyZWZmIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjZmY0ZmEzIi8+PC9saW5lYXJHcmFkaWVudD48cmFkaWFsR3JhZGllbnQgaWQ9Im54Z2xvdyIgY3g9IjAuODIiIGN5PSIwLjE0IiByPSIwLjciPjxzdG9wIG9mZnNldD0iMCIgc3RvcC1jb2xvcj0iIzdjZjlmZiIgc3RvcC1vcGFjaXR5PSIwLjU1Ii8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjN2NmOWZmIiBzdG9wLW9wYWNpdHk9IjAiLz48L3JhZGlhbEdyYWRpZW50PjxsaW5lYXJHcmFkaWVudCBpZD0ibnhwbGF5IiB4MT0iMCIgeTE9IjAiIHgyPSIxIiB5Mj0iMSI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjZmZmZmZmIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjZmZlM2YxIi8+PC9saW5lYXJHcmFkaWVudD48Y2xpcFBhdGggaWQ9Im54ciI+PHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIHJ4PSI1OCIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNueHIpIj48cmVjdCB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgZmlsbD0idXJsKCNueGJnKSIvPjxyZWN0IHdpZHRoPSIyNTYiIGhlaWdodD0iMjU2IiBmaWxsPSJ1cmwoI254Z2xvdykiLz48ZyBmaWxsPSJub25lIiBzdHJva2U9IiNmZmZmZmYiIHN0cm9rZS13aWR0aD0iMTUiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCI+PHBhdGggZD0iTTYwIDExNiBBNzAgNzAgMCAwIDEgMTc4IDcyIi8+PHBhdGggZD0iTTE5NiAxNDAgQTcwIDcwIDAgMCAxIDc4IDE4NCIvPjwvZz48cGF0aCBkPSJNMTg2IDUwIEwyMDAgOTIgTDE1NyA4NiBaIiBmaWxsPSIjZmZmZmZmIi8+PHBhdGggZD0iTTcwIDIwNiBMNTYgMTY0IEw5OSAxNzAgWiIgZmlsbD0iI2ZmZmZmZiIvPjxwYXRoIGQ9Ik0xMTAgOTIgUTEwNCA4OCAxMDQgOTYgTDEwNCAxNjAgUTEwNCAxNjggMTEwIDE2NCBMMTYyIDEzMiBRMTY4IDEyOCAxNjIgMTI0IFoiIGZpbGw9InVybCgjbnhwbGF5KSIvPjwvZz48L3N2Zz4=';
|
|
@@ -171,6 +174,8 @@
|
|
|
171
174
|
const HOST = location.hostname || 'local';
|
|
172
175
|
await STORE.init([
|
|
173
176
|
'nxu_hide_fab_' + HOST,
|
|
177
|
+
'nxu_avatar', 'nxu_status', 'nxu_reactions', 'nxu_recv_react', 'nxu_recv_nudge', 'nxu_recv_ink', 'nxu_recv_chat', 'nxu_recv_ping', 'nxu_bm_lib', 'nxu_pending_jump', 'nxu_moff',
|
|
178
|
+
'nxu_bright', 'nxu_boost', 'nxu_xsub_size', 'nxu_os_lang', 'nxu_panel_size_settings-modal', 'nxu_panel_size_bm-panel', 'nxu_panel_size_tune-panel', 'nxu_panel_size_os-panel',
|
|
174
179
|
'nxu_idle_timeout', 'nxu_sub_size', 'nxu_sub_opacity', 'nxu_sub_position', 'nxu_speaker_language',
|
|
175
180
|
'nxu_subtitle_language', 'nxu_audio_mode', 'nxu_translation_provider', 'nxu_stt_local_first',
|
|
176
181
|
'nxu_smart_speech_locale', 'nxu_fab_pos', 'nxu_asr_provider', 'nxu_key_openai', 'nxu_key_anthropic', 'nxu_key_groq', 'nxu_key_deepl',
|
|
@@ -341,6 +346,12 @@
|
|
|
341
346
|
return ['play', 'pause', 'toggle', 'seek', 'seekBy', 'volume', 'mute'].includes(data.action) && num(data.value);
|
|
342
347
|
case 'NXU_SYNC_CMD':
|
|
343
348
|
return ['play', 'pause', 'rate'].includes(data.cmd) && num(data.time) && num(data.rate) && str(data.eventId) && str(data.action) && num(data.startIn);
|
|
349
|
+
case 'NXU_TUNE':
|
|
350
|
+
return ['snap', 'env', 'arm'].includes(data.op) && str(data.rid) && bool(data.on);
|
|
351
|
+
case 'NXU_TUNE_DATA': {
|
|
352
|
+
const arr = a => a === undefined || (Array.isArray(a) && a.length <= 4000 && a.every(x => Number.isFinite(x)));
|
|
353
|
+
return ['snap', 'env'].includes(data.op) && str(data.rid) && (data.img === undefined || data.img === null || (typeof data.img === 'string' && data.img.length < 90000 && data.img.startsWith('data:image/'))) && num(data.t) && arr(data.a) && arr(data.l) && arr(data.ts);
|
|
354
|
+
}
|
|
344
355
|
case 'NXU_CAPTION':
|
|
345
356
|
return ['final', 'interim', 'clear'].includes(data.mode) && str(data.text) && str(data.original) && str(data.color) && num(data.size);
|
|
346
357
|
default:
|
|
@@ -663,10 +674,29 @@
|
|
|
663
674
|
canvas: 'Canvas', bookmark: 'Bookmark', bookmarkTitle: 'Bookmark the current position', chat: 'Chat', aiSub: 'AI Sub', aiSubTitle: 'Live subtitles & translation (Alt+Shift+T)',
|
|
664
675
|
subLog: 'Sub Log', debug: 'Debug', hideOnSite: 'Hide on this site', hideOnSiteTitle: 'Hide the floating button on this site (restore with Alt+Shift+N or the userscript menu)',
|
|
665
676
|
hiddenOnSite: '🙈 Hidden on this site · Alt+Shift+N to show', shownOnSite: '⚙️ Button shown on this site',
|
|
666
|
-
roomChat: 'Room Chat', nickname: 'Nickname (optional)', chatPlaceholder: 'Message…', newMessages: 'New', latest: 'Latest',
|
|
677
|
+
roomChat: 'Room Chat', chatLog: 'Chat history', chatCleared: '🧹 Chat history cleared', nickname: 'Nickname (optional)', chatPlaceholder: 'Message…', newMessages: 'New', latest: 'Latest',
|
|
667
678
|
subHistory: 'Subtitle History', export: 'Export', clear: 'Clear', logCleared: '🧹 Subtitle history cleared', logExported: '💾 Subtitle history exported',
|
|
668
679
|
createRoom: 'Create a room', copyPin: 'Copy PIN', enterPin: 'Enter PIN', joinRoom: 'Join Room', viewerMode: 'Viewer mode (follow without controlling)',
|
|
669
680
|
aiSubSettings: 'AI Subtitles', debugConsole: 'Debug Console', uiHide: 'Auto-hide', keepOpen: 'Keep open',
|
|
681
|
+
bmLibrary: 'Bookmarks', bmAddHere: 'Bookmark this moment', bmSearch: 'Search bookmarks', bmEmpty: 'No bookmarks yet. Tap “Bookmark this moment” while watching.', bmLive: 'LIVE', bmOpening: '📌 Opening the bookmark…', bmJumped: '📌 Back to {time}', bmLiveOpened: '🔴 Playing the live stream', bmDelete: 'Delete', bmThisPage: 'this page', bmCopy: 'Copy link', bmCopied: '📋 Link copied',
|
|
682
|
+
tuneTitle: 'Sync timing', tuneMenu: 'Sync timing', tuneOffset: 'My offset', tuneOffsetZero: 'Same timing as the room', tuneAhead: 'My video runs {s} ahead of the room', tuneBehind: 'My video runs {s} behind the room',
|
|
683
|
+
tuneResync: 'Re-sync now', tuneReset: 'Reset', tuneHelp: 'Different site, different version (an extra studio logo, a shorter intro)? Move your own timing until the pictures match. Only your device changes.',
|
|
684
|
+
tuneCompare: 'Compare pictures', tuneMine: 'Me', tuneTheirs: '{name}', tuneNoPicture: 'Protected video — compare by time', tuneDiffSame: 'Same position as the other device', tuneDiffAhead: 'You are {s} ahead of {name}', tuneDiffBehind: 'You are {s} behind {name}', tuneWaiting: 'Waiting for the picture…',
|
|
685
|
+
tuneMark: 'Same scene', tuneMarkHint: 'Each of you pauses on the same moment (e.g. the first shot after the logos) and taps “This scene”.', tuneMarkBtn: '📍 This scene', tuneMarkMine: 'Mine: {t}', tuneMarkTheirs: '{name}: {t}', tuneApply: 'Apply',
|
|
686
|
+
tuneAuto: 'Automatic', tuneAutoBtn: '🤖 Find the timing automatically', tuneAutoHint: 'Uses the sound (or the picture) of what both of you have played over the last minutes. Play together for a little while first.',
|
|
687
|
+
tuneAutoNeed: 'Not enough to compare yet — play together for a little longer and try again.', tuneAutoFound: 'Found: {s} ({c}% sure)', tuneAutoNone: 'No clear match. Try “Same scene” instead.', tuneAsking: 'Asking the others…', tuneApplied: '⏱ Timing set: {s}',
|
|
688
|
+
tuneMarkReceived: '📍 {name} marked a scene', tuneNoPeer: 'Nobody else is in the room yet.',
|
|
689
|
+
tuneSrcSame: '🟢 Same video on every device — kept in step automatically, frame by frame.', tuneSrcDiff: '🟠 Different versions (length differs by {s}) — the timing is found automatically after a little playing, or set it here.', tuneSrcUnknown: 'Waiting for the others’ video…',
|
|
690
|
+
tuneSameReset: '⏱ Same video as the others: timing correction removed.', tuneAutoApplied: 'Different version: timing set to {s} automatically (tap to undo).', tuneSuggest: 'Your videos differ by {s}. Tap to line them up.',
|
|
691
|
+
subMenu: 'Subtitles', xsubOff: 'Off', subTrack: 'From the video', subSearch: '🔎 Find subtitles (OpenSubtitles)', subFile: '📂 Open a subtitle file…', subAi: '🧠 AI live subtitles', subDelay: 'Timing', subLater: 'later', subEarlier: 'earlier', xsubSize: 'Size',
|
|
692
|
+
subLoaded: '💬 Subtitles: {name}', subMulti: 'Several subtitles at once — tap one to take it away.', subNone: 'No subtitles found in this video.', subSuggest: '💬 No subtitles? Find them', subLoadFail: 'Could not load these subtitles.',
|
|
693
|
+
osTitle: 'Find subtitles', osTmdbLooking: 'Looking up the English title on TMDB…', osTmdbNone: 'No English title found on TMDB — type it yourself if you know it.', osQuery: 'Title (English titles work best)', osSeason: 'Season', osEpisode: 'Episode', osLang: 'Language', osSearch: 'Search', osSearching: 'Searching…', osNone: 'Nothing found. Try the English title, or remove the year.', osError: 'OpenSubtitles did not answer. Try again in a moment.', osDownloads: '{n} downloads', osLoading: 'Loading…', osHint: 'Subtitles come from OpenSubtitles.org and are shown in NexusSync’s own style; use “Timing” in the subtitle menu if they are early or late.',
|
|
694
|
+
viewMenu: 'Picture', viewAudio: 'Soundtrack', viewBright: 'Brightness', viewBoost: 'Volume boost', viewReset: 'Reset', boostBlocked: 'This video’s sound cannot be boosted here (it comes from another site).',
|
|
695
|
+
settings: 'Settings', setProfile: 'Profile', setAvatar: 'Avatar', setStatus: 'Status message', setStatusPh: 'e.g. Popcorn ready 🍿', setReactions: 'My reactions',
|
|
696
|
+
setReactionsHint: 'Tap a slot, then pick an emoji (or type any emoji). Add or remove slots (1–16).', setReactionsReset: 'Back to the default reactions', setPlayback: 'Playback', setAutoNext: 'Next episode automatically',
|
|
697
|
+
setTogether: 'Watching together', setRecvReact: 'Show others’ reactions', setRecvNudge: 'Receive nudges (shake)', setRecvInk: 'Show others’ sketches', setRecvChat: 'Show chat bubbles', setRecvPing: 'Show pointers',
|
|
698
|
+
setPeople: 'People in this room', setMute: 'Hide', setUnmute: 'Show', setMutedHint: 'Hidden people’s messages, reactions and sketches are not shown on this device (only for this room).',
|
|
699
|
+
setAdvanced: 'Advanced', setAvatarCustom: 'Any emoji or initials', setAvatarPhoto: 'Photo', setAvatarClear: 'Remove', setAvatarFail: 'Could not use this picture.', setSlotAdd: '+ Add a slot', setSlotRemove: '- Remove this slot', setEmojiPh: 'Any emoji', setNobody: 'Nobody else is here yet.',
|
|
670
700
|
speakerLanguage: 'Spoken language', speakerHelp: 'The language spoken in the video or by you. Recognition only understands this language.',
|
|
671
701
|
subtitleLanguage: 'Translate subtitles to', audioSource: 'Audio source', audioAuto: 'Auto (video audio when possible + mic)', audioMic: 'Microphone only',
|
|
672
702
|
audioMedia: 'Video / tab audio only', audioDual: 'Microphone + video audio',
|
|
@@ -683,7 +713,7 @@
|
|
|
683
713
|
subUsingMicFallback: 'The video sound could not be heard directly — listening through the microphone (turn the speakers up).',
|
|
684
714
|
subTabShareEnded: 'Tab audio sharing stopped, so subtitles were turned off.',
|
|
685
715
|
subHearVideo: '🎧 Listening to the video', subHearMic: '🎧 Listening through the microphone', subVideoSilent: '🔇 No sound reaches the subtitles from this video',
|
|
686
|
-
subIssueNet: '⚠️ Speech service connection is unstable — retrying', subShareTab: '🎬 Connect tab sound', subTabNotShared: 'Tab audio was not shared. Choose this tab and turn on “Share tab audio”.',
|
|
716
|
+
subIssueNet: '⚠️ Speech service connection is unstable — retrying', subIssueNoResult: '⚠️ Sound arrives but no words are recognised', subSiteBlocksSpeech: 'This site does not allow the browser’s speech recognition. Add an OpenAI or Groq key (AI subtitles → Advanced) to use AI subtitles here.', subSiteBlocksSpeechKey: 'This site blocks the browser’s speech recognition — switching to cloud recognition with your key.', subTryMic: '🎤 Listen through the mic', subTryKey: '🔑 Use an AI recognition key', subShareTab: '🎬 Connect tab sound', subTabNotShared: 'Tab audio was not shared. Choose this tab and turn on “Share tab audio”.',
|
|
687
717
|
subPosition: 'Subtitle position', posVideo: 'Over the video', posScreen: 'Bottom of the screen', subSize: 'Size', subOpacity: 'Opacity',
|
|
688
718
|
advanced: 'Advanced', translationEngine: 'Translation engine', providerAuto: 'Google first, on-device as backup (best quality)', providerBrowser: 'On-device only (private)',
|
|
689
719
|
providerGoogle: 'Google only', providerHelp: 'Online translation reads whole sentences far better; the on-device model shows the live line and steps in when offline.',
|
|
@@ -707,7 +737,7 @@
|
|
|
707
737
|
noVideo: '⚠️ No video detected', noPlayingVideo: '⚠️ No playing video found', pipUnsupported: '⚠️ Picture-in-Picture not supported', pipBlocked: '⚠️ Picture-in-Picture was blocked',
|
|
708
738
|
mediaFound: '✅ Media detected', mediaNotFound: '🔎 No media yet — start the video and try again',
|
|
709
739
|
canvasOn: '🎨 Canvas ON', canvasOff: '🎨 Canvas OFF', canvasViewOnly: '🎨 Canvas (view only)', nothingToUndo: '↩️ Nothing to undo', undo: 'Undo (Ctrl+Z)',
|
|
710
|
-
pen: 'Pen', eraser: 'Eraser', clearCanvas: 'Clear canvas', watching: '{n} watching', meTag: '(me)', whoViewer: 'watching only', whoAway: 'away (screen off or another tab)', whoOldVer: 'different version — please update', whoTitle: 'Watching together',
|
|
740
|
+
pen: 'Pen', eraser: 'Eraser', clearCanvas: 'Clear canvas', watching: '{n} watching', meTag: '(me)', whoViewer: 'watching only', whoAway: 'away (screen off or another tab)', whoOldVer: 'different version — please update', whoTitle: 'Watching together', whoSleeping: 'screen off — still in the room, back when it wakes', whoReconnecting: 'Reconnecting…',
|
|
711
741
|
shieldTitle: 'Connected', shieldText: 'Tap to enable synchronized playback in this tab.', shieldButton: 'START SYNC ▶️',
|
|
712
742
|
menuCinema: 'Toggle cinema mode', menuSubtitles: 'Start / stop AI subtitles', menuShowButton: 'Show / hide the NexusSync button on this site'
|
|
713
743
|
},
|
|
@@ -759,10 +789,29 @@
|
|
|
759
789
|
canvas: '캔버스', bookmark: '북마크', bookmarkTitle: '현재 위치를 북마크', chat: '채팅', aiSub: 'AI 자막', aiSubTitle: '실시간 자막·번역 (Alt+Shift+T)',
|
|
760
790
|
subLog: '자막 기록', debug: '디버그', hideOnSite: '이 사이트에서 숨기기', hideOnSiteTitle: '이 사이트에서 떠 있는 버튼 숨기기 (Alt+Shift+N 또는 유저스크립트 메뉴로 복원)',
|
|
761
791
|
hiddenOnSite: '🙈 이 사이트에서 숨김 · Alt+Shift+N으로 표시', shownOnSite: '⚙️ 이 사이트에서 버튼 표시',
|
|
762
|
-
roomChat: '방 채팅', nickname: '닉네임 (선택)', chatPlaceholder: '메시지…', newMessages: '새 메시지', latest: '최신',
|
|
792
|
+
roomChat: '방 채팅', chatLog: '채팅 기록', chatCleared: '🧹 채팅 기록을 지웠어요', nickname: '닉네임 (선택)', chatPlaceholder: '메시지…', newMessages: '새 메시지', latest: '최신',
|
|
763
793
|
subHistory: '자막 기록', export: '내보내기', clear: '지우기', logCleared: '🧹 자막 기록을 지웠습니다', logExported: '💾 자막 기록을 저장했습니다',
|
|
764
794
|
createRoom: '방 만들기', copyPin: 'PIN 복사', enterPin: 'PIN 입력', joinRoom: '방 참여', viewerMode: '시청자 모드 (조작 없이 따라보기)',
|
|
765
795
|
aiSubSettings: 'AI 자막', debugConsole: '디버그 콘솔', uiHide: '자동 숨김', keepOpen: '고정',
|
|
796
|
+
bmLibrary: '북마크', bmAddHere: '지금 장면 북마크', bmSearch: '북마크 검색', bmEmpty: '아직 북마크가 없어요. 보는 중에 “지금 장면 북마크”를 눌러 보세요.', bmLive: '라이브', bmOpening: '📌 북마크를 여는 중…', bmJumped: '📌 {time}(으)로 돌아왔어요', bmLiveOpened: '🔴 라이브 방송을 바로 재생해요', bmDelete: '삭제', bmThisPage: '이 페이지', bmCopy: '링크 복사', bmCopied: '📋 링크를 복사했어요',
|
|
797
|
+
tuneTitle: '싱크 맞추기', tuneMenu: '싱크 맞추기', tuneOffset: '내 시간 보정', tuneOffsetZero: '방과 같은 타이밍', tuneAhead: '내 영상이 방보다 {s} 앞서 재생돼요', tuneBehind: '내 영상이 방보다 {s} 늦게 재생돼요',
|
|
798
|
+
tuneResync: '지금 다시 맞추기', tuneReset: '초기화', tuneHelp: '사이트가 달라 영상 길이가 다른가요? (배급사 로고·인트로 차이) 화면이 같아질 때까지 내 타이밍만 옮기면 돼요. 다른 사람에겐 영향이 없어요.',
|
|
799
|
+
tuneCompare: '화면 비교', tuneMine: '나', tuneTheirs: '{name}', tuneNoPicture: '보호된 영상이라 화면 대신 시간으로 비교해요', tuneDiffSame: '상대와 같은 위치예요', tuneDiffAhead: '내가 {name}님보다 {s} 앞서 있어요', tuneDiffBehind: '내가 {name}님보다 {s} 뒤에 있어요', tuneWaiting: '화면을 받는 중…',
|
|
800
|
+
tuneMark: '같은 장면', tuneMarkHint: '각자 같은 장면(예: 로고가 끝난 첫 장면)에서 멈춘 뒤 “이 장면”을 누르세요.', tuneMarkBtn: '📍 이 장면', tuneMarkMine: '나: {t}', tuneMarkTheirs: '{name}: {t}', tuneApply: '적용',
|
|
801
|
+
tuneAuto: '자동', tuneAutoBtn: '🤖 자동으로 맞추기', tuneAutoHint: '최근 몇 분 동안 서로 재생한 소리(또는 화면)를 비교해요. 먼저 잠시 함께 재생해 주세요.',
|
|
802
|
+
tuneAutoNeed: '아직 비교할 내용이 부족해요 — 조금 더 함께 재생한 뒤 다시 시도하세요.', tuneAutoFound: '찾았어요: {s} (확신 {c}%)', tuneAutoNone: '뚜렷한 일치를 못 찾았어요. “같은 장면”으로 맞춰 보세요.', tuneAsking: '다른 사람에게 요청하는 중…', tuneApplied: '⏱ 타이밍 보정: {s}',
|
|
803
|
+
tuneMarkReceived: '📍 {name}님이 장면을 표시했어요', tuneNoPeer: '아직 방에 다른 사람이 없어요.',
|
|
804
|
+
tuneSrcSame: '🟢 모두 같은 영상이에요 — 프레임 단위로 자동으로 맞추고 있어요.', tuneSrcDiff: '🟠 서로 다른 버전이에요 (길이 차이 {s}) — 잠시 재생하면 자동으로 맞추고, 여기서 직접 맞출 수도 있어요.', tuneSrcUnknown: '다른 사람의 영상 정보를 기다리는 중…',
|
|
805
|
+
tuneSameReset: '⏱ 상대와 같은 영상이라 타이밍 보정을 해제했어요.', tuneAutoApplied: '다른 버전이라 타이밍을 {s} 자동 보정했어요 (누르면 되돌리기).', tuneSuggest: '서로 영상 길이가 {s} 달라요. 눌러서 맞춰 보세요.',
|
|
806
|
+
subMenu: '자막', xsubOff: '끄기', subTrack: '영상에 포함된 자막', subSearch: '🔎 자막 찾기 (OpenSubtitles)', subFile: '📂 자막 파일 열기…', subAi: '🧠 AI 실시간 자막', subDelay: '싱크', subLater: '늦게', subEarlier: '빠르게', xsubSize: '크기',
|
|
807
|
+
subLoaded: '💬 자막: {name}', subMulti: '자막 여러 개를 함께 보는 중 — 누르면 그 자막만 꺼져요.', subNone: '이 영상에는 포함된 자막이 없어요.', subSuggest: '💬 자막이 없나요? 찾아보기', subLoadFail: '자막을 불러오지 못했어요.',
|
|
808
|
+
osTitle: '자막 찾기', osTmdbLooking: 'TMDB에서 영어 제목을 찾는 중…', osTmdbNone: 'TMDB에서 영어 제목을 찾지 못했어요 — 알고 있다면 직접 입력하세요.', osQuery: '제목 (영어 제목이 가장 잘 찾아져요)', osSeason: '시즌', osEpisode: '회차', osLang: '언어', osSearch: '검색', osSearching: '찾는 중…', osNone: '찾지 못했어요. 영어 제목으로 바꾸거나 연도를 빼 보세요.', osError: 'OpenSubtitles가 응답하지 않아요. 잠시 후 다시 시도하세요.', osDownloads: '다운로드 {n}회', osLoading: '불러오는 중…', osHint: '자막은 OpenSubtitles.org에서 가져와 NexusSync 스타일로 보여 줘요. 빠르거나 늦으면 자막 메뉴의 “싱크”로 맞추세요.',
|
|
809
|
+
viewMenu: '화면', viewAudio: '오디오 트랙', viewBright: '밝기', viewBoost: '볼륨 부스트', viewReset: '초기화', boostBlocked: '이 영상은 다른 사이트에서 오는 소리라 여기서 키울 수 없어요.',
|
|
810
|
+
settings: '설정', setProfile: '프로필', setAvatar: '아바타', setStatus: '상태 메시지', setStatusPh: '예: 팝콘 준비 완료 🍿', setReactions: '내 리액션',
|
|
811
|
+
setReactionsHint: '칸을 누른 뒤 이모지를 고르세요 (아무 이모지나 입력해도 돼요). 칸은 1~16개로 늘리거나 줄일 수 있어요.', setReactionsReset: '기본 리액션으로', setPlayback: '재생', setAutoNext: '다음 화 자동으로 넘기기',
|
|
812
|
+
setTogether: '함께 보기', setRecvReact: '다른 사람 리액션 보기', setRecvNudge: '찌르기 받기 (흔들림)', setRecvInk: '다른 사람 그림 보기', setRecvChat: '말풍선 보기', setRecvPing: '포인터 보기',
|
|
813
|
+
setPeople: '이 방의 사람들', setMute: '숨기기', setUnmute: '보이기', setMutedHint: '숨긴 사람의 메시지·리액션·그림은 이 기기에서 보이지 않아요 (이 방에서만).',
|
|
814
|
+
setAdvanced: '고급', setAvatarCustom: '이모지나 이니셜 입력', setAvatarPhoto: '사진', setAvatarClear: '지우기', setAvatarFail: '이 사진은 사용할 수 없어요.', setSlotAdd: '+ 칸 추가', setSlotRemove: '- 선택한 칸 삭제', setEmojiPh: '이모지 입력', setNobody: '아직 다른 사람이 없어요.',
|
|
766
815
|
speakerLanguage: '말하는 언어', speakerHelp: '영상(또는 말하는 사람)의 언어를 선택하세요. 음성 인식은 이 언어만 알아듣습니다.',
|
|
767
816
|
subtitleLanguage: '자막 번역 언어', audioSource: '오디오 입력', audioAuto: '자동 (가능하면 영상 소리 + 마이크)', audioMic: '마이크만',
|
|
768
817
|
audioMedia: '영상/탭 소리만', audioDual: '마이크 + 영상 소리',
|
|
@@ -779,7 +828,7 @@
|
|
|
779
828
|
subUsingMicFallback: '영상 소리를 직접 들을 수 없어 마이크로 들어요. 스피커 소리를 키워 주세요.',
|
|
780
829
|
subTabShareEnded: '탭 오디오 공유가 끝나서 자막을 껐어요.',
|
|
781
830
|
subHearVideo: '🎧 영상 소리 듣는 중', subHearMic: '🎧 마이크로 듣는 중', subVideoSilent: '🔇 이 영상의 소리가 자막에 전달되지 않아요',
|
|
782
|
-
subIssueNet: '⚠️ 음성 인식 서버 연결이 불안정해요 — 다시 시도 중', subShareTab: '🎬 탭 소리 연결', subTabNotShared: '탭 오디오가 공유되지 않았어요. 이 탭을 고르고 “탭 오디오 공유”를 켜 주세요.',
|
|
831
|
+
subIssueNet: '⚠️ 음성 인식 서버 연결이 불안정해요 — 다시 시도 중', subIssueNoResult: '⚠️ 소리는 들어오는데 말이 인식되지 않아요', subSiteBlocksSpeech: '이 사이트는 브라우저 음성 인식을 막아 두었어요. AI 자막 → 고급에서 OpenAI 또는 Groq 키를 넣으면 여기서도 쓸 수 있어요.', subSiteBlocksSpeechKey: '이 사이트는 브라우저 음성 인식을 막아 두어서, 넣어 둔 키로 클라우드 인식으로 바꿀게요.', subTryMic: '🎤 마이크로 듣기', subTryKey: '🔑 AI 인식 키 사용', subShareTab: '🎬 탭 소리 연결', subTabNotShared: '탭 오디오가 공유되지 않았어요. 이 탭을 고르고 “탭 오디오 공유”를 켜 주세요.',
|
|
783
832
|
subPosition: '자막 위치', posVideo: '영상 위', posScreen: '화면 하단', subSize: '크기', subOpacity: '불투명도',
|
|
784
833
|
advanced: '고급', translationEngine: '번역 엔진', providerAuto: 'Google 우선, 기기 내 번역 보조 (최고 품질)', providerBrowser: '기기 내 번역만 (개인정보 보호)',
|
|
785
834
|
providerGoogle: 'Google만', providerHelp: '문장 번역 품질은 온라인(Google)이 훨씬 좋습니다. 기기 내 모델은 실시간 임시 줄과 오프라인 상황을 맡습니다.',
|
|
@@ -803,7 +852,7 @@
|
|
|
803
852
|
noVideo: '⚠️ 감지된 영상이 없습니다', noPlayingVideo: '⚠️ 재생 중인 영상이 없습니다', pipUnsupported: '⚠️ PiP를 지원하지 않습니다', pipBlocked: '⚠️ PiP가 차단되었습니다',
|
|
804
853
|
mediaFound: '✅ 미디어 감지됨', mediaNotFound: '🔎 아직 미디어가 없습니다 — 영상을 재생한 뒤 다시 시도하세요',
|
|
805
854
|
canvasOn: '🎨 캔버스 켜짐', canvasOff: '🎨 캔버스 꺼짐', canvasViewOnly: '🎨 캔버스 (보기 전용)', nothingToUndo: '↩️ 되돌릴 내용이 없습니다', undo: '되돌리기 (Ctrl+Z)',
|
|
806
|
-
pen: '펜', eraser: '지우개', clearCanvas: '모두 지우기', watching: '{n}명 시청 중', meTag: '(나)', whoViewer: '보기 전용', whoAway: '자리 비움 (화면 꺼짐·다른 탭)', whoOldVer: '다른 버전 — 업데이트가 필요해요', whoTitle: '함께 보는 사람',
|
|
855
|
+
pen: '펜', eraser: '지우개', clearCanvas: '모두 지우기', watching: '{n}명 시청 중', meTag: '(나)', whoViewer: '보기 전용', whoAway: '자리 비움 (화면 꺼짐·다른 탭)', whoOldVer: '다른 버전 — 업데이트가 필요해요', whoTitle: '함께 보는 사람', whoSleeping: '화면 꺼짐 — 방에 그대로 있고, 화면이 켜지면 돌아와요', whoReconnecting: '다시 연결하는 중…',
|
|
807
856
|
shieldTitle: '연결됨', shieldText: '눌러서 이 탭의 동기화 재생을 활성화하세요.', shieldButton: '동기화 시작 ▶️',
|
|
808
857
|
menuCinema: '시네마 모드 켜기/끄기', menuSubtitles: 'AI 자막 시작/중지', menuShowButton: '이 사이트에서 NexusSync 버튼 표시/숨기기'
|
|
809
858
|
}
|
|
@@ -1131,6 +1180,7 @@
|
|
|
1131
1180
|
visibility: hidden !important; pointer-events: none !important; transition: none !important; animation: none !important; }
|
|
1132
1181
|
.nxu-site-ui-off :is([class*="caption" i], [class*="subtitle" i], [class*="text-track" i], [class*="cue" i], [class*="danmaku" i]) { visibility: visible !important; }
|
|
1133
1182
|
.nxu-site-ui-off .nxu-site-hide { visibility: hidden !important; pointer-events: none !important; transition: none !important; animation: none !important; }
|
|
1183
|
+
.nxu-site-ui-off .nxu-dsub-src, .nxu-site-ui-off .nxu-dsub-src * { visibility: hidden !important; }
|
|
1134
1184
|
.nxu-cue-mirror { position: absolute !important; left: calc(50% + var(--nxu-cue-shift, 0px)) !important; right: auto !important; top: auto !important; bottom: var(--nxu-cue-bottom, 6%) !important; transform: translateX(-50%) !important;
|
|
1135
1185
|
width: var(--nxu-cue-width, 90%) !important; max-width: 96% !important; height: auto !important; margin: 0 !important; padding: 0 !important; border: 0 !important; background: none !important;
|
|
1136
1186
|
flex-direction: column !important; align-items: center !important; gap: 3px !important; z-index: 2147483646 !important; transition: bottom 0.3s ease !important; pointer-events: none !important; visibility: visible !important; opacity: 1 !important; }
|
|
@@ -1416,6 +1466,7 @@
|
|
|
1416
1466
|
};
|
|
1417
1467
|
if (!hide || !root || !video || root === video) { undo(); return; }
|
|
1418
1468
|
const run = () => {
|
|
1469
|
+
const textLayers = [];
|
|
1419
1470
|
const chain = new Set();
|
|
1420
1471
|
for (let n = video; n && n !== root; n = n.parentElement) chain.add(n);
|
|
1421
1472
|
const hidden = [];
|
|
@@ -1430,13 +1481,14 @@
|
|
|
1430
1481
|
const interactive = child.matches(CTRL) || !!child.querySelector(CTRL);
|
|
1431
1482
|
const text = (child.textContent || '').trim();
|
|
1432
1483
|
// Text without any control: most likely the site's own subtitles.
|
|
1433
|
-
if (!interactive && text) continue;
|
|
1484
|
+
if (!interactive && text) { textLayers.push(child); continue; }
|
|
1434
1485
|
child.classList.add('nxu-site-hide');
|
|
1435
1486
|
hidden.push(child);
|
|
1436
1487
|
}
|
|
1437
1488
|
}
|
|
1438
1489
|
(this._hidden || []).forEach(n => { if (!hidden.includes(n)) n.classList.remove('nxu-site-hide'); });
|
|
1439
1490
|
this._hidden = hidden;
|
|
1491
|
+
this._textLayers = textLayers;
|
|
1440
1492
|
};
|
|
1441
1493
|
run();
|
|
1442
1494
|
if (!this._hideObs || this._hideObsRoot !== root) {
|
|
@@ -1715,7 +1767,8 @@
|
|
|
1715
1767
|
render() {
|
|
1716
1768
|
const v = this.video, root = this._root();
|
|
1717
1769
|
if (!v || !root) { this.box?.remove(); this.box = null; return; }
|
|
1718
|
-
|
|
1770
|
+
// NexusSync's own subtitle layer has taken over: no second copy.
|
|
1771
|
+
const cues = typeof SUBS !== 'undefined' && SUBS.active() ? [] : this._cues();
|
|
1719
1772
|
const doc = v.ownerDocument;
|
|
1720
1773
|
if (!this.box || !this.box.isConnected || this.box.parentNode !== root) {
|
|
1721
1774
|
this.box?.remove();
|
|
@@ -2640,6 +2693,7 @@
|
|
|
2640
2693
|
const media = this._readLevel(a.media);
|
|
2641
2694
|
this._levels = { mic, media };
|
|
2642
2695
|
this._mediaPeak = Math.max(this._mediaPeak, media);
|
|
2696
|
+
if (Math.max(mic, media) > SPEECH_LEVEL) this._soundMs = (this._soundMs || 0) + 400;
|
|
2643
2697
|
const keys = [];
|
|
2644
2698
|
if (mic > SPEECH_LEVEL) keys.push('mic');
|
|
2645
2699
|
if (media > SPEECH_LEVEL) keys.push('media');
|
|
@@ -2701,6 +2755,7 @@
|
|
|
2701
2755
|
}
|
|
2702
2756
|
} catch (_) { }
|
|
2703
2757
|
},
|
|
2758
|
+
_diag: { sound: 0, results: 0, err: '' },
|
|
2704
2759
|
_createRecognizer() {
|
|
2705
2760
|
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
|
|
2706
2761
|
const r = new SR();
|
|
@@ -2733,10 +2788,10 @@
|
|
|
2733
2788
|
this._appleRestoreTimer = setTimeout(() => this._setAppleSession('playback'), 220);
|
|
2734
2789
|
}
|
|
2735
2790
|
};
|
|
2736
|
-
r.onsoundstart = () => { if (alive()) { this._touch(); this._soundHeard = true; } };
|
|
2791
|
+
r.onsoundstart = () => { if (alive()) { this._touch(); this._soundHeard = true; this._diag.sound++; } };
|
|
2737
2792
|
r.onspeechstart = () => { if (alive()) this._touch(); };
|
|
2738
|
-
r.onresult = (event) => { if (alive()) this._onResult(event); };
|
|
2739
|
-
r.onerror = (event) => { if (alive()) this._onError(event); };
|
|
2793
|
+
r.onresult = (event) => { if (alive()) { this._diag.results++; this._onResult(event); } };
|
|
2794
|
+
r.onerror = (event) => { if (alive()) { this._diag.err = event?.error || '?'; this._onError(event); } };
|
|
2740
2795
|
r.onend = () => { if (alive()) this._onEnd(); };
|
|
2741
2796
|
this.recognizer = r;
|
|
2742
2797
|
},
|
|
@@ -2834,6 +2889,8 @@
|
|
|
2834
2889
|
this._createRecognizer();
|
|
2835
2890
|
this._scheduleRestart('track-fallback', 150, true);
|
|
2836
2891
|
}
|
|
2892
|
+
// Plenty of sound but not a single word back: say so, with a one-tap way out.
|
|
2893
|
+
if (this._useWebSpeech && !this._issue && this._soundMs > 15000 && (this._lastResultAt || 0) < (this._startedAt || 0)) this._issue = 'noresult';
|
|
2837
2894
|
this._updateListenChip();
|
|
2838
2895
|
updateAIBtnUX();
|
|
2839
2896
|
},
|
|
@@ -2918,10 +2975,22 @@
|
|
|
2918
2975
|
chip.classList.toggle('warn', silent);
|
|
2919
2976
|
chip.classList.toggle('warn', silent || !!this._issue);
|
|
2920
2977
|
if (this._issue) chip.classList.remove('hide');
|
|
2921
|
-
chip.querySelector('.sub-listen-text').textContent = this._issue === 'net' ? t('subIssueNet') : silent ? t('subVideoSilent') : this.webMediaStream && !this._micMixed ? t('subHearVideo') : t('subHearMic');
|
|
2978
|
+
chip.querySelector('.sub-listen-text').textContent = this._issue === 'noresult' ? t('subIssueNoResult') : this._issue === 'net' ? t('subIssueNet') : silent ? t('subVideoSilent') : this.webMediaStream && !this._micMixed ? t('subHearVideo') : t('subHearMic');
|
|
2922
2979
|
const level = Math.max(this._levels.media || 0, this._levels.mic || 0);
|
|
2923
2980
|
chip.querySelector('.sub-listen-meter i').style.width = Math.min(100, Math.round(level * 400)) + '%';
|
|
2924
2981
|
chip.querySelector('.sub-listen-btn').style.display = offer ? '' : 'none';
|
|
2982
|
+
let alt = chip.querySelector('.sub-listen-alt');
|
|
2983
|
+
const wantAlt = this._issue === 'noresult';
|
|
2984
|
+
if (wantAlt && !alt) {
|
|
2985
|
+
alt = createEl('button', 'sub-listen-btn sub-listen-alt', '', { type: 'button' });
|
|
2986
|
+
alt.addEventListener('click', (e) => {
|
|
2987
|
+
e.stopPropagation();
|
|
2988
|
+
if (this.audioMode === 'media') { STORE.set('nxu_audio_mode', 'mic'); this.restart('no words from the video sound'); }
|
|
2989
|
+
else { const m = shadow?.getElementById('trans-modal'); if (m) { openPanel(m); const d = m.querySelector('.ai-advanced'); if (d) d.open = true; } }
|
|
2990
|
+
});
|
|
2991
|
+
chip.appendChild(alt);
|
|
2992
|
+
}
|
|
2993
|
+
if (alt) { alt.style.display = wantAlt ? '' : 'none'; alt.textContent = this.audioMode === 'media' ? t('subTryMic') : t('subTryKey'); }
|
|
2925
2994
|
},
|
|
2926
2995
|
_preparePlaybackMic() {
|
|
2927
2996
|
const track = this.mediaStream?.getAudioTracks?.()[0];
|
|
@@ -3092,10 +3161,26 @@
|
|
|
3092
3161
|
switch (error) {
|
|
3093
3162
|
case 'aborted':
|
|
3094
3163
|
return;
|
|
3095
|
-
case 'not-allowed':
|
|
3096
|
-
|
|
3097
|
-
|
|
3164
|
+
case 'not-allowed': {
|
|
3165
|
+
// Fed from a captured track, try once more with the engine's own input
|
|
3166
|
+
// (some browsers refuse a track); then say exactly why it cannot listen.
|
|
3167
|
+
if (this._recognitionInput === 'track' && !this._trackDisabled) {
|
|
3168
|
+
this._trackDisabled = true;
|
|
3169
|
+
logDebug('AI Sub: the speech engine refused the captured audio, trying its own input.', 'warn');
|
|
3170
|
+
this._destroyRecognizer(); this._createRecognizer(); this._scheduleRestart('track-refused', 200, true);
|
|
3171
|
+
return;
|
|
3172
|
+
}
|
|
3173
|
+
const policy = this._micBlockedByPolicy();
|
|
3174
|
+
logDebug('AI Sub: speech recognition not allowed' + (policy ? ' (blocked by this site)' : ''), 'error');
|
|
3175
|
+
const cloudKey = AI.key('openai') || AI.key('groq');
|
|
3176
|
+
this.stop(t(policy ? (cloudKey ? 'subSiteBlocksSpeechKey' : 'subSiteBlocksSpeech') : 'subMicDenied'));
|
|
3177
|
+
// With a key, cloud recognition does not need the browser's speech engine.
|
|
3178
|
+
if (policy && cloudKey && STORE.get('nxu_asr_provider', 'browser') === 'browser') {
|
|
3179
|
+
STORE.set('nxu_asr_provider', AI.key('groq') ? 'groq' : 'openai');
|
|
3180
|
+
setTimeout(() => this.start().catch(() => { }), 400);
|
|
3181
|
+
}
|
|
3098
3182
|
return;
|
|
3183
|
+
}
|
|
3099
3184
|
case 'service-not-allowed':
|
|
3100
3185
|
if (this.recognizer?.processLocally) {
|
|
3101
3186
|
this._localSpeechReady = false;
|
|
@@ -3711,6 +3796,9 @@
|
|
|
3711
3796
|
if (this._useWebSpeech) await this._prepareLocalSpeech(SR).catch(() => { });
|
|
3712
3797
|
if (token !== this._startToken) return;
|
|
3713
3798
|
this.state = 'running';
|
|
3799
|
+
this._diag = { sound: 0, results: 0, err: '' };
|
|
3800
|
+
this._startedAt = Date.now();
|
|
3801
|
+
this._soundMs = 0;
|
|
3714
3802
|
this.active = true;
|
|
3715
3803
|
if (this._useWebSpeech) {
|
|
3716
3804
|
this._createRecognizer();
|
|
@@ -3878,7 +3966,9 @@
|
|
|
3878
3966
|
const engine = T._cloud ? AI.asrModel() + (T._useWebSpeech ? ' + live' : '') : (T._sttProvider === 'web-speech-local' ? t('engineLocal') : t('engineOnline'));
|
|
3879
3967
|
const tx = T._providerStatus ? ` · ${t('translation')}: ${T._providerStatus}` : '';
|
|
3880
3968
|
const level = T.audioNodes ? ` · 🎚 ${Math.round(Math.max(T._levels.mic, T._levels.media) * 400)}` : '';
|
|
3881
|
-
|
|
3969
|
+
// What the speech engine reports (helps tell "no sound" from "no words").
|
|
3970
|
+
const dg = T._useWebSpeech ? ` · 🔎 ${T._diag.sound}/${T._diag.results}${T._diag.err ? ' · ⚠ ' + T._diag.err : ''}` : '';
|
|
3971
|
+
status.textContent = `● ${t('subListening')} · ${lang} → ${T._label(T.outLang)} · ${input} · ${engine}${tx}${level}${dg}`;
|
|
3882
3972
|
}
|
|
3883
3973
|
}
|
|
3884
3974
|
}
|
|
@@ -4167,6 +4257,8 @@
|
|
|
4167
4257
|
|
|
4168
4258
|
function _commitVideoState({ play, time, action = 'user', rate = 1.0, videoId = '', timestamp: at = null }) {
|
|
4169
4259
|
if (!ydoc || !yVideo) return null;
|
|
4260
|
+
// The room speaks in room time; this device's own timing correction is taken off.
|
|
4261
|
+
if (Number.isFinite(time)) time = Math.max(0, time - TUNE.offset());
|
|
4170
4262
|
const sequenceNumber = ++STATE._videoSequence;
|
|
4171
4263
|
const timestamp = Number.isFinite(at) ? at : getSyncedTime();
|
|
4172
4264
|
const intent = STATE._acceptedIntent;
|
|
@@ -5116,6 +5208,7 @@
|
|
|
5116
5208
|
if (uid && typeof d.sess === 'string' && cur && typeof cur.sess === 'string' && cur.sess !== d.sess) break;
|
|
5117
5209
|
if (uid && uid !== STATE.userId) {
|
|
5118
5210
|
const name = participantName(uid);
|
|
5211
|
+
PRESENCE.left.add(uid);
|
|
5119
5212
|
PRESENCE.seen.delete(uid);
|
|
5120
5213
|
PRESENCE.refresh();
|
|
5121
5214
|
showToast(t('peerLeft', { name }));
|
|
@@ -5176,12 +5269,12 @@
|
|
|
5176
5269
|
if (ydoc && Array.isArray(d.data)) d.data.forEach(u => { try { Y.applyUpdate(ydoc, new Uint8Array(u), 'remote'); } catch (_) { } });
|
|
5177
5270
|
break;
|
|
5178
5271
|
case 'yjs_sync_request':
|
|
5179
|
-
if (ydoc)
|
|
5272
|
+
if (ydoc) HEAL.pushFull('asked');
|
|
5180
5273
|
break;
|
|
5181
5274
|
case 'reaction':
|
|
5182
5275
|
onRemoteReaction(d);
|
|
5183
5276
|
break;
|
|
5184
|
-
case 'nudge': case 'pointer': case 'countdown': case 'typing': case 'ink': case 'cover': case 'goto':
|
|
5277
|
+
case 'nudge': case 'pointer': case 'countdown': case 'typing': case 'ink': case 'cover': case 'goto': case 'tune': case 'avatar':
|
|
5185
5278
|
SOCIAL.receive(p.t, d);
|
|
5186
5279
|
break;
|
|
5187
5280
|
}
|
|
@@ -5192,9 +5285,44 @@
|
|
|
5192
5285
|
if (!RTC.sendData('yjs_sync_request', {})) sendFirebaseCmd('yjs_sync_request', {}, 'nexus_rooms');
|
|
5193
5286
|
}
|
|
5194
5287
|
|
|
5288
|
+
// Room-state healing. An update sent just as a phone went to sleep can be lost; the
|
|
5289
|
+
// others then hold that device's later updates aside forever (they build on the lost
|
|
5290
|
+
// one), so its presence, play/pause and seeks stopped arriving while plain messages
|
|
5291
|
+
// (reactions) still did. Every device now resends its whole state after waking, and
|
|
5292
|
+
// anyone who notices missing pieces (or hears from someone it cannot see) asks for it.
|
|
5293
|
+
const HEAL = {
|
|
5294
|
+
_askAt: 0, _pushAt: 0,
|
|
5295
|
+
pushFull(reason) {
|
|
5296
|
+
if (!ydoc || !SOCIAL.live() || Date.now() - this._pushAt < 4000) return;
|
|
5297
|
+
this._pushAt = Date.now();
|
|
5298
|
+
const full = { data: Array.from(Y.encodeStateAsUpdate(ydoc)) };
|
|
5299
|
+
sendFirebaseCmd('yjs_update', full, 'nexus_rooms');
|
|
5300
|
+
if (STATE.connectionMode === 'WEBRTC_P2P') RTC.sendData('yjs_update', full);
|
|
5301
|
+
logDebug('Room state resent (' + reason + ').', 'info');
|
|
5302
|
+
},
|
|
5303
|
+
ask(reason) {
|
|
5304
|
+
if (!ydoc || !SOCIAL.live() || Date.now() - this._askAt < 8000) return;
|
|
5305
|
+
this._askAt = Date.now();
|
|
5306
|
+
requestRoomState();
|
|
5307
|
+
logDebug('Asked the room for its full state (' + reason + ').', 'info');
|
|
5308
|
+
},
|
|
5309
|
+
check() {
|
|
5310
|
+
if (!ydoc || !STATE.handshakeVerified) return;
|
|
5311
|
+
const st = ydoc.store;
|
|
5312
|
+
if (st && (st.pendingStructs || st.pendingDs)) this.ask('missing updates');
|
|
5313
|
+
},
|
|
5314
|
+
// A message from someone who is not in the list: their state did not reach us.
|
|
5315
|
+
heard(uid) {
|
|
5316
|
+
if (!uid || uid === STATE.userId || !STATE.handshakeVerified) return;
|
|
5317
|
+
if (!STATE.presenceMap?.[uid]) { this.ask('message from an unlisted device'); this.pushFull('peer unseen'); }
|
|
5318
|
+
}
|
|
5319
|
+
};
|
|
5320
|
+
if (IS_TOP) setInterval(() => { try { HEAL.check(); } catch (_) { } }, 10000);
|
|
5321
|
+
|
|
5195
5322
|
// Sends room authority to the player inside a cross-origin frame.
|
|
5196
5323
|
function sendStateToFrame(state, frame = STATE.cinemaIframe) {
|
|
5197
5324
|
if (!frame || !state) return;
|
|
5325
|
+
state = TUNE.local(state);
|
|
5198
5326
|
const rate = clampRate(state.rate);
|
|
5199
5327
|
const wait = state.timestamp - getSyncedTime();
|
|
5200
5328
|
const elapsed = state.play && wait < 0 ? (-wait / 1000) * rate : 0;
|
|
@@ -5205,7 +5333,7 @@
|
|
|
5205
5333
|
rate,
|
|
5206
5334
|
eventId: state.eventId,
|
|
5207
5335
|
action: state.action,
|
|
5208
|
-
startIn: state.play && wait > 40 ? Math.min(wait,
|
|
5336
|
+
startIn: state.play && wait > 40 ? Math.min(wait, 10000) : 0
|
|
5209
5337
|
});
|
|
5210
5338
|
}
|
|
5211
5339
|
|
|
@@ -5279,8 +5407,9 @@
|
|
|
5279
5407
|
yChat.observe(event => {
|
|
5280
5408
|
event.changes.added.forEach(item => {
|
|
5281
5409
|
item.content.getContent().forEach(content => {
|
|
5410
|
+
if (content && content.sender !== STATE.userId && !SAFETY.allows(content.sender)) return;
|
|
5282
5411
|
appendChatMessage(content);
|
|
5283
|
-
if (content.sender !== STATE.userId) { triggerUINotify('chat'); SOCIAL.onChat(content); }
|
|
5412
|
+
if (content.sender !== STATE.userId && SAFETY.receive('chat')) { triggerUINotify('chat'); SOCIAL.onChat(content); }
|
|
5284
5413
|
});
|
|
5285
5414
|
});
|
|
5286
5415
|
});
|
|
@@ -5305,7 +5434,7 @@
|
|
|
5305
5434
|
const now = Date.now();
|
|
5306
5435
|
// Freshness uses the time *we* received an update, not the sender's clock: phones and
|
|
5307
5436
|
// PCs often disagree by many seconds, which made the head count differ per device.
|
|
5308
|
-
event.changes.keys.forEach((change, uid) => { if (change.action !== 'delete') PRESENCE.seen.set(uid, now); else PRESENCE.seen.delete(uid); });
|
|
5437
|
+
event.changes.keys.forEach((change, uid) => { if (change.action !== 'delete') { PRESENCE.seen.set(uid, now); PRESENCE.left.delete(uid); } else PRESENCE.seen.delete(uid); });
|
|
5309
5438
|
PRESENCE.refresh();
|
|
5310
5439
|
// Someone on an older NexusSync: play/pause/seek from mixed versions do not line up
|
|
5311
5440
|
// as well (older builds let heartbeats override other devices) — say so once.
|
|
@@ -5362,6 +5491,7 @@
|
|
|
5362
5491
|
function applyRemoteStateToVideo(remoteState) {
|
|
5363
5492
|
const video = STATE.video;
|
|
5364
5493
|
if (!video) return;
|
|
5494
|
+
remoteState = TUNE.local(remoteState);
|
|
5365
5495
|
const { play, time, timestamp: ts, action, rate } = remoteState;
|
|
5366
5496
|
const base = clampRate(rate);
|
|
5367
5497
|
STATE._lastRemoteApplyAt = Date.now();
|
|
@@ -5378,7 +5508,11 @@
|
|
|
5378
5508
|
return;
|
|
5379
5509
|
}
|
|
5380
5510
|
}
|
|
5511
|
+
// A synchronized start (countdown, shared resume) is waiting: a heartbeat arriving
|
|
5512
|
+
// meanwhile must not cancel it (that left everyone paused after the countdown).
|
|
5513
|
+
if (STATE._scheduledPlay && action === 'heartbeat' && Date.now() < (STATE._scheduledPlayAt || 0) + 500) return;
|
|
5381
5514
|
clearTimeout(STATE._scheduledPlay);
|
|
5515
|
+
STATE._scheduledPlay = null;
|
|
5382
5516
|
STATE.remoteLockUntil = Date.now() + 100;
|
|
5383
5517
|
STATE._remoteApplying = true;
|
|
5384
5518
|
if (play) {
|
|
@@ -5387,13 +5521,21 @@
|
|
|
5387
5521
|
if (wait > 40) {
|
|
5388
5522
|
// Synchronized start: every device begins at the same shared instant.
|
|
5389
5523
|
if (Math.abs(video.currentTime - time) > 0.25) remoteSeek(video, time);
|
|
5524
|
+
// This hold-and-wait pause is ours: when its event arrives late it must not be
|
|
5525
|
+
// taken for someone pausing (that stopped the room right after a countdown).
|
|
5526
|
+
video._nxuOwnPauseUntil = Date.now() + Math.min(wait, 10000) + 500;
|
|
5527
|
+
video._nxuOwnPauseSince = Date.now();
|
|
5390
5528
|
if (!video.paused) { try { video.pause(); } catch (_) { } }
|
|
5391
5529
|
RATE.apply(video, base);
|
|
5530
|
+
STATE._scheduledPlayAt = Date.now() + Math.min(wait, 10000);
|
|
5392
5531
|
STATE._scheduledPlay = setTimeout(() => {
|
|
5532
|
+
STATE._scheduledPlay = null;
|
|
5393
5533
|
STATE._remoteApplying = true;
|
|
5394
5534
|
MEDIA_SAFE.play(video);
|
|
5395
5535
|
setTimeout(() => { STATE._remoteApplying = false; }, 120);
|
|
5396
|
-
|
|
5536
|
+
// Some players refuse or swallow the first play(): check once more.
|
|
5537
|
+
setTimeout(() => { const r = _getVideoState(); if (r && r.play && video.paused && STATE.video === video) MEDIA_SAFE.play(video); }, 900);
|
|
5538
|
+
}, Math.min(wait, 10000));
|
|
5397
5539
|
setTimeout(() => { STATE._remoteApplying = false; }, 80);
|
|
5398
5540
|
return;
|
|
5399
5541
|
}
|
|
@@ -5429,6 +5571,494 @@
|
|
|
5429
5571
|
}
|
|
5430
5572
|
}
|
|
5431
5573
|
|
|
5574
|
+
// ───────────────────────── Sync timing between different versions of a movie
|
|
5575
|
+
// Watching the same film on two different sites often means two different cuts: one
|
|
5576
|
+
// starts with a studio logo or a longer intro. Each device can shift its own timing
|
|
5577
|
+
// ("offset", seconds: my picture = room time + offset). Three ways to find it:
|
|
5578
|
+
// • Compare pictures: both screens side by side (small snapshots, about once a second).
|
|
5579
|
+
// • Same scene: each pauses on the same moment and marks it; the difference is the offset.
|
|
5580
|
+
// • Automatic: the sound (or, without sound access, the picture's brightness) of what
|
|
5581
|
+
// each device played over the last minutes is compared; the best match is the offset.
|
|
5582
|
+
const TUNE = {
|
|
5583
|
+
LIMIT: 900,
|
|
5584
|
+
_off: null,
|
|
5585
|
+
_key() { return location.href.split('#')[0].slice(0, 300); },
|
|
5586
|
+
offset() {
|
|
5587
|
+
if (!STATE.handshakeVerified && IS_TOP) return 0;
|
|
5588
|
+
if (this._off === null) {
|
|
5589
|
+
const all = STORE.get('nxu_moff', {});
|
|
5590
|
+
const v = all && typeof all === 'object' ? Number(all[this._key()]) : 0;
|
|
5591
|
+
this._off = Number.isFinite(v) ? Math.max(-this.LIMIT, Math.min(this.LIMIT, v)) : 0;
|
|
5592
|
+
}
|
|
5593
|
+
return this._off;
|
|
5594
|
+
},
|
|
5595
|
+
local(state) {
|
|
5596
|
+
const off = this.offset();
|
|
5597
|
+
if (!off || !state || !Number.isFinite(state.time)) return state;
|
|
5598
|
+
return { ...state, time: Math.max(0, state.time + off) };
|
|
5599
|
+
},
|
|
5600
|
+
set(seconds, { quiet = false } = {}) {
|
|
5601
|
+
const v = Math.round(Math.max(-this.LIMIT, Math.min(this.LIMIT, Number(seconds) || 0)) * 10) / 10;
|
|
5602
|
+
this._off = v;
|
|
5603
|
+
const all = { ...(STORE.get('nxu_moff', {}) || {}) };
|
|
5604
|
+
if (v) all[this._key()] = v; else delete all[this._key()];
|
|
5605
|
+
const keys = Object.keys(all);
|
|
5606
|
+
if (keys.length > 120) delete all[keys[0]];
|
|
5607
|
+
STORE.set('nxu_moff', all);
|
|
5608
|
+
// Move to the new timing right away.
|
|
5609
|
+
const room = _getVideoState();
|
|
5610
|
+
if (room && STATE.video) applyRemoteStateToVideo({ ...room, action: 'user' });
|
|
5611
|
+
else if (room && STATE.cinemaIframe) sendStateToFrame({ ...room, action: 'user' });
|
|
5612
|
+
this.paint();
|
|
5613
|
+
if (!quiet) showToast(t('tuneApplied', { s: this.fmt(v) }));
|
|
5614
|
+
},
|
|
5615
|
+
fmt(v) { return (v > 0 ? '+' : v < 0 ? '−' : '') + Math.abs(v).toFixed(Math.abs(v) < 100 ? 1 : 0) + 's'; },
|
|
5616
|
+
|
|
5617
|
+
// ── what this device played: sound energy and picture brightness by media time
|
|
5618
|
+
REC: { hz: 10, keep: 2400 },
|
|
5619
|
+
_rec: null,
|
|
5620
|
+
arm(on) {
|
|
5621
|
+
if (!on) { this._stopRec(); return; }
|
|
5622
|
+
const v = STATE.video;
|
|
5623
|
+
if (!v) { if (STATE.cinemaIframe) FRAME.postToFrame(STATE.cinemaIframe, { type: 'NXU_TUNE', op: 'arm', rid: '', on: true }); return; }
|
|
5624
|
+
if (this._rec && this._rec.v === v) return;
|
|
5625
|
+
this._stopRec();
|
|
5626
|
+
const rec = { v, ts: [], a: [], l: [], an: null, ctx: null, cvs: null, cx: null, tainted: false, timer: 0 };
|
|
5627
|
+
try {
|
|
5628
|
+
// The video's own audio (no change to what is heard). Not on Firefox's
|
|
5629
|
+
// mozCaptureStream, which silences the element.
|
|
5630
|
+
if (typeof v.captureStream === 'function') {
|
|
5631
|
+
const tracks = v.captureStream().getAudioTracks();
|
|
5632
|
+
const Ctx = window.AudioContext || window.webkitAudioContext;
|
|
5633
|
+
if (tracks.length && Ctx) {
|
|
5634
|
+
rec.ctx = new Ctx();
|
|
5635
|
+
const src = rec.ctx.createMediaStreamSource(new MediaStream(tracks));
|
|
5636
|
+
rec.an = rec.ctx.createAnalyser();
|
|
5637
|
+
rec.an.fftSize = 1024;
|
|
5638
|
+
src.connect(rec.an);
|
|
5639
|
+
rec.buf = new Float32Array(rec.an.fftSize);
|
|
5640
|
+
}
|
|
5641
|
+
}
|
|
5642
|
+
} catch (_) { rec.an = null; }
|
|
5643
|
+
rec.cvs = document.createElement('canvas');
|
|
5644
|
+
rec.cvs.width = 16; rec.cvs.height = 9;
|
|
5645
|
+
rec.cx = rec.cvs.getContext('2d', { willReadFrequently: true });
|
|
5646
|
+
let n = 0;
|
|
5647
|
+
rec.timer = setInterval(() => {
|
|
5648
|
+
if (v.paused || v.seeking || v.readyState < 2 || document.hidden) return;
|
|
5649
|
+
if (rec.ctx && rec.ctx.state === 'suspended') { try { rec.ctx.resume(); } catch (_) { } }
|
|
5650
|
+
let a = 0, l = -1;
|
|
5651
|
+
if (rec.an) {
|
|
5652
|
+
rec.an.getFloatTimeDomainData(rec.buf);
|
|
5653
|
+
let s = 0; for (let i = 0; i < rec.buf.length; i++) s += rec.buf[i] * rec.buf[i];
|
|
5654
|
+
a = Math.sqrt(s / rec.buf.length);
|
|
5655
|
+
}
|
|
5656
|
+
// Brightness: 10 per second on computers, 5 on phones (reading pixels back costs).
|
|
5657
|
+
if (!rec.tainted && (n++ % (IS_TOUCH ? 2 : 1)) === 0) {
|
|
5658
|
+
try {
|
|
5659
|
+
rec.cx.drawImage(v, 0, 0, 16, 9);
|
|
5660
|
+
const d = rec.cx.getImageData(0, 0, 16, 9).data;
|
|
5661
|
+
let s = 0; for (let i = 0; i < d.length; i += 4) s += d[i] * 0.3 + d[i + 1] * 0.59 + d[i + 2] * 0.11;
|
|
5662
|
+
l = s / (d.length / 4);
|
|
5663
|
+
} catch (_) { rec.tainted = true; }
|
|
5664
|
+
}
|
|
5665
|
+
rec.ts.push(Math.round(v.currentTime * 100) / 100); rec.a.push(Math.round(a * 1e5) / 1e5); rec.l.push(Math.round(l * 10) / 10);
|
|
5666
|
+
if (rec.ts.length > this.REC.keep) { rec.ts.shift(); rec.a.shift(); rec.l.shift(); }
|
|
5667
|
+
}, 1000 / this.REC.hz);
|
|
5668
|
+
this._rec = rec;
|
|
5669
|
+
},
|
|
5670
|
+
_stopRec() {
|
|
5671
|
+
const r = this._rec;
|
|
5672
|
+
this._rec = null;
|
|
5673
|
+
if (!r) return;
|
|
5674
|
+
clearInterval(r.timer);
|
|
5675
|
+
try { r.ctx?.close(); } catch (_) { }
|
|
5676
|
+
},
|
|
5677
|
+
_envelope() {
|
|
5678
|
+
const r = this._rec;
|
|
5679
|
+
if (!r || r.ts.length < 100) return null;
|
|
5680
|
+
return { ts: r.ts.slice(), a: r.a.slice(), l: r.l.slice() };
|
|
5681
|
+
},
|
|
5682
|
+
snapshot() {
|
|
5683
|
+
const v = STATE.video;
|
|
5684
|
+
if (!v || v.readyState < 2) return null;
|
|
5685
|
+
try {
|
|
5686
|
+
const c = document.createElement('canvas');
|
|
5687
|
+
const w = 240, h = Math.round(240 * ((v.videoHeight || 9) / (v.videoWidth || 16)));
|
|
5688
|
+
c.width = w; c.height = Math.max(60, Math.min(180, h));
|
|
5689
|
+
c.getContext('2d').drawImage(v, 0, 0, c.width, c.height);
|
|
5690
|
+
return c.toDataURL('image/jpeg', 0.55);
|
|
5691
|
+
} catch (_) { return null; } // protected / cross-origin picture
|
|
5692
|
+
},
|
|
5693
|
+
mediaTime() {
|
|
5694
|
+
const info = currentMediaInfo();
|
|
5695
|
+
return info && Number.isFinite(info.time) ? info.time : 0;
|
|
5696
|
+
},
|
|
5697
|
+
|
|
5698
|
+
// ── frames: the player may sit in another site's frame
|
|
5699
|
+
_frameWait: new Map(),
|
|
5700
|
+
_askFrame(op) {
|
|
5701
|
+
return new Promise((resolve) => {
|
|
5702
|
+
if (!STATE.cinemaIframe) { resolve(null); return; }
|
|
5703
|
+
const rid = Math.random().toString(36).slice(2, 10);
|
|
5704
|
+
this._frameWait.set(rid, resolve);
|
|
5705
|
+
FRAME.postToFrame(STATE.cinemaIframe, { type: 'NXU_TUNE', op, rid, on: true });
|
|
5706
|
+
setTimeout(() => { if (this._frameWait.has(rid)) { this._frameWait.delete(rid); resolve(null); } }, 2500);
|
|
5707
|
+
});
|
|
5708
|
+
},
|
|
5709
|
+
onFrameRequest(data) {
|
|
5710
|
+
if (data.op === 'arm') { this.arm(!!data.on); return; }
|
|
5711
|
+
const reply = { type: 'NXU_TUNE_DATA', op: data.op, rid: data.rid, t: STATE.video ? STATE.video.currentTime : 0 };
|
|
5712
|
+
if (data.op === 'snap') reply.img = this.snapshot();
|
|
5713
|
+
else { this.arm(true); const env = this._envelope(); if (env) Object.assign(reply, env); }
|
|
5714
|
+
FRAME.postToParent(reply);
|
|
5715
|
+
},
|
|
5716
|
+
onFrameData(data) {
|
|
5717
|
+
const res = this._frameWait.get(data.rid);
|
|
5718
|
+
if (res) { this._frameWait.delete(data.rid); res(data); }
|
|
5719
|
+
},
|
|
5720
|
+
async _mySnap() {
|
|
5721
|
+
const playing = !(currentMediaInfo()?.paused ?? true);
|
|
5722
|
+
if (STATE.video) return { img: this.snapshot(), t: STATE.video.currentTime, playing, at: Date.now() };
|
|
5723
|
+
const d = await this._askFrame('snap');
|
|
5724
|
+
return d ? { img: d.img || null, t: d.t, playing, at: Date.now() } : { img: null, t: this.mediaTime(), playing, at: Date.now() };
|
|
5725
|
+
},
|
|
5726
|
+
async _myEnv() {
|
|
5727
|
+
if (STATE.video) { this.arm(true); return this._envelope(); }
|
|
5728
|
+
const d = await this._askFrame('env');
|
|
5729
|
+
return d && Array.isArray(d.ts) ? { ts: d.ts, a: d.a || [], l: d.l || [] } : null;
|
|
5730
|
+
},
|
|
5731
|
+
|
|
5732
|
+
// ── room messages
|
|
5733
|
+
_peer: null, // last picture from someone else
|
|
5734
|
+
_marks: new Map(), // uid → { t, off, name }
|
|
5735
|
+
_peekUntil: 0,
|
|
5736
|
+
onRemote(who, d) {
|
|
5737
|
+
const op = d.op;
|
|
5738
|
+
if (op === 'peek') {
|
|
5739
|
+
// Someone opened "Compare pictures": send ours about once a second for a while.
|
|
5740
|
+
this._peekUntil = Date.now() + 45000;
|
|
5741
|
+
this._startPeek();
|
|
5742
|
+
} else if (op === 'snap' && (d.img === null || (typeof d.img === 'string' && d.img.startsWith('data:image/jpeg') && d.img.length < 90000))) {
|
|
5743
|
+
this._peer = { uid: d.uid, name: who.name, color: who.color, img: d.img, t: Number(d.t) || 0, playing: !!d.playing, off: Number(d.off) || 0, at: Date.now() };
|
|
5744
|
+
this.paint();
|
|
5745
|
+
} else if (op === 'mark' && Number.isFinite(d.t)) {
|
|
5746
|
+
this._marks.set(d.uid, { t: d.t, off: Number(d.off) || 0, name: who.name, color: who.color });
|
|
5747
|
+
showToast(t('tuneMarkReceived', { name: who.name }));
|
|
5748
|
+
this.paint();
|
|
5749
|
+
} else if (op === 'envreq') {
|
|
5750
|
+
this._myEnv().then(env => { if (env) SOCIAL.send('tune', { op: 'env', ...this._pack(env), off: this.offset(), to: d.uid }); });
|
|
5751
|
+
} else if (op === 'env' && d.to === STATE.userId && this._autoWait) {
|
|
5752
|
+
const env = this._unpack(d);
|
|
5753
|
+
const done = this._autoWait;
|
|
5754
|
+
this._autoWait = null;
|
|
5755
|
+
done(env ? { env, off: Number(d.off) || 0, name: who.name } : null);
|
|
5756
|
+
}
|
|
5757
|
+
},
|
|
5758
|
+
// Envelopes go over the room channel as compact integer lists.
|
|
5759
|
+
_pack(env) {
|
|
5760
|
+
return { ts0: env.ts[0], ts: env.ts.map(x => Math.round((x - env.ts[0]) * 10)), a: env.a.map(x => Math.round(x * 1e4)), l: env.l.map(x => Math.round(x)) };
|
|
5761
|
+
},
|
|
5762
|
+
_unpack(d) {
|
|
5763
|
+
const ok = arr => Array.isArray(arr) && arr.length <= 4000 && arr.every(Number.isFinite);
|
|
5764
|
+
if (!Number.isFinite(d.ts0) || !ok(d.ts) || !ok(d.a) || !ok(d.l) || d.ts.length !== d.a.length) return null;
|
|
5765
|
+
return { ts: d.ts.map(x => d.ts0 + x / 10), a: d.a.map(x => x / 1e4), l: d.l };
|
|
5766
|
+
},
|
|
5767
|
+
_startPeek() {
|
|
5768
|
+
if (this._peekTimer) return;
|
|
5769
|
+
const loop = async () => {
|
|
5770
|
+
if (Date.now() > this._peekUntil || !SOCIAL.live()) { this._peekTimer = null; return; }
|
|
5771
|
+
const s = await this._mySnap();
|
|
5772
|
+
SOCIAL.send('tune', { op: 'snap', img: s ? s.img : null, t: s ? s.t : 0, playing: !!(s && s.playing), off: this.offset() });
|
|
5773
|
+
this._peekTimer = setTimeout(loop, 1200);
|
|
5774
|
+
};
|
|
5775
|
+
this._peekTimer = setTimeout(loop, 50);
|
|
5776
|
+
},
|
|
5777
|
+
async mark() {
|
|
5778
|
+
const t0 = this.mediaTime();
|
|
5779
|
+
this._myMark = { t: t0, off: this.offset() };
|
|
5780
|
+
SOCIAL.send('tune', { op: 'mark', t: t0, off: this.offset() });
|
|
5781
|
+
this.paint();
|
|
5782
|
+
},
|
|
5783
|
+
// My offset so that my marked scene and theirs line up: off_me = off_them + (mine − theirs).
|
|
5784
|
+
markOffset() {
|
|
5785
|
+
const mine = this._myMark;
|
|
5786
|
+
const theirs = [...this._marks.values()].pop();
|
|
5787
|
+
if (!mine || !theirs) return null;
|
|
5788
|
+
return theirs.off + (mine.t - theirs.t);
|
|
5789
|
+
},
|
|
5790
|
+
|
|
5791
|
+
// ── automatic: cross-correlation of what both played (onsets of sound / brightness)
|
|
5792
|
+
_series(env, useLuma) {
|
|
5793
|
+
// Uniform 0.1 s grid by media time; onset strength = rise of log energy (or change of brightness).
|
|
5794
|
+
const step = 0.1;
|
|
5795
|
+
const pts = [];
|
|
5796
|
+
for (let i = 0; i < env.ts.length; i++) {
|
|
5797
|
+
const val = useLuma ? env.l[i] : env.a[i];
|
|
5798
|
+
if (useLuma && val < 0) continue;
|
|
5799
|
+
pts.push([env.ts[i], val]);
|
|
5800
|
+
}
|
|
5801
|
+
if (pts.length < 80) return null;
|
|
5802
|
+
pts.sort((x, y) => x[0] - y[0]);
|
|
5803
|
+
const t0 = pts[0][0], t1 = pts[pts.length - 1][0];
|
|
5804
|
+
const n = Math.min(6000, Math.floor((t1 - t0) / step) + 1);
|
|
5805
|
+
const raw = new Float64Array(n).fill(NaN);
|
|
5806
|
+
for (const [ts, val] of pts) { const k = Math.round((ts - t0) / step); if (k >= 0 && k < n) raw[k] = useLuma ? val : Math.log(1e-4 + val); }
|
|
5807
|
+
// fill small gaps
|
|
5808
|
+
for (let i = 1; i < n; i++) if (Number.isNaN(raw[i])) raw[i] = raw[i - 1];
|
|
5809
|
+
const out = new Float64Array(n);
|
|
5810
|
+
// Sound: rises of loudness (onsets). Picture: the brightness curve itself plus its
|
|
5811
|
+
// jumps (scene cuts), so slow fades and hard cuts both count.
|
|
5812
|
+
// High-pass (minus the 2 s running mean) keeps the changes, not the slow level.
|
|
5813
|
+
const W = 20;
|
|
5814
|
+
let acc = 0;
|
|
5815
|
+
for (let i = 0; i < n; i++) {
|
|
5816
|
+
acc += raw[i]; if (i >= W) acc -= raw[i - W];
|
|
5817
|
+
const mean = acc / Math.min(i + 1, W);
|
|
5818
|
+
const d = i ? raw[i] - raw[i - 1] : 0;
|
|
5819
|
+
out[i] = useLuma ? (raw[i] - mean) / 32 + Math.abs(d) / 8 : Math.max(0, d);
|
|
5820
|
+
}
|
|
5821
|
+
return { t0, step, v: out };
|
|
5822
|
+
},
|
|
5823
|
+
_correlate(me, them, maxLag) {
|
|
5824
|
+
// lag d (seconds): my content at time x equals theirs at time x − d.
|
|
5825
|
+
const step = me.step;
|
|
5826
|
+
let best = { score: -Infinity, d: 0 }, second = -Infinity;
|
|
5827
|
+
const norm = (arr, a, b) => { let m = 0, c = 0; for (let i = a; i < b; i++) { m += arr[i]; c++; } m /= Math.max(1, c); let s = 0; for (let i = a; i < b; i++) s += (arr[i] - m) ** 2; return { m, s: Math.sqrt(s) || 1 }; };
|
|
5828
|
+
const scores = [];
|
|
5829
|
+
for (let k = -Math.round(maxLag / step); k <= Math.round(maxLag / step); k++) {
|
|
5830
|
+
const d = k * step;
|
|
5831
|
+
// my index i ↔ their time (me.t0 + i*step − d)
|
|
5832
|
+
const shift = (me.t0 - d - them.t0) / step;
|
|
5833
|
+
const j0 = Math.round(shift);
|
|
5834
|
+
const a = Math.max(0, -j0), b = Math.min(me.v.length, them.v.length - j0);
|
|
5835
|
+
if (b - a < 150) { scores.push(-Infinity); continue; } // at least 15 s together
|
|
5836
|
+
const nm = norm(me.v, a, b), nt = norm(them.v, a + j0, b + j0);
|
|
5837
|
+
let s = 0;
|
|
5838
|
+
for (let i = a; i < b; i++) s += (me.v[i] - nm.m) * (them.v[i + j0] - nt.m);
|
|
5839
|
+
const r = s / (nm.s * nt.s);
|
|
5840
|
+
scores.push(r);
|
|
5841
|
+
if (r > best.score) best = { score: r, d };
|
|
5842
|
+
}
|
|
5843
|
+
// second best away from the peak (±1.5 s), and how far the peak stands out
|
|
5844
|
+
const bk = Math.round(best.d / step) + Math.round(maxLag / step);
|
|
5845
|
+
scores.forEach((r, idx) => { if (Math.abs(idx - bk) > 15 && r > second) second = r; });
|
|
5846
|
+
// Sub-step peak (parabola through the best score and its neighbours).
|
|
5847
|
+
const s0 = scores[bk - 1], s2 = scores[bk + 1];
|
|
5848
|
+
if (Number.isFinite(s0) && Number.isFinite(s2)) {
|
|
5849
|
+
const den = s0 - 2 * best.score + s2;
|
|
5850
|
+
if (den < 0) best.d += step * Math.max(-0.5, Math.min(0.5, (s0 - s2) / (2 * den)));
|
|
5851
|
+
}
|
|
5852
|
+
const fin = scores.filter(Number.isFinite);
|
|
5853
|
+
const mean = fin.reduce((s, x) => s + x, 0) / Math.max(1, fin.length);
|
|
5854
|
+
const sd = Math.sqrt(fin.reduce((s, x) => s + (x - mean) ** 2, 0) / Math.max(1, fin.length)) || 1;
|
|
5855
|
+
return { d: best.d, score: best.score, second, z: (best.score - mean) / sd };
|
|
5856
|
+
},
|
|
5857
|
+
async auto({ silent = false } = {}) {
|
|
5858
|
+
if (!PRESENCE.others().length) { if (!silent) { this._autoMsg = t('tuneNoPeer'); this.paint(); } return null; }
|
|
5859
|
+
if (!silent) { this._autoMsg = t('tuneAsking'); this.paint(); }
|
|
5860
|
+
const mine = await this._myEnv();
|
|
5861
|
+
const theirs = await new Promise((resolve) => {
|
|
5862
|
+
this._autoWait = resolve;
|
|
5863
|
+
SOCIAL.send('tune', { op: 'envreq' });
|
|
5864
|
+
setTimeout(() => { if (this._autoWait === resolve) { this._autoWait = null; resolve(null); } }, 9000);
|
|
5865
|
+
});
|
|
5866
|
+
if (!mine || !theirs) { if (!silent) { this._autoMsg = t('tuneAutoNeed'); this.paint(); } return null; }
|
|
5867
|
+
let res = null;
|
|
5868
|
+
for (const luma of [false, true]) {
|
|
5869
|
+
const a = this._series(mine, luma), b = this._series(theirs.env, luma);
|
|
5870
|
+
if (!a || !b) continue;
|
|
5871
|
+
const r = this._correlate(a, b, 240);
|
|
5872
|
+
if (Number.isFinite(r.score) && (!res || r.z > res.z)) res = r;
|
|
5873
|
+
}
|
|
5874
|
+
logDebug(`Sync timing: compared ${mine.ts.length} / ${theirs.env.ts.length} samples → ${res ? `lag ${res.d.toFixed(1)}s, r=${res.score.toFixed(2)}, next ${res.second.toFixed(2)}, z=${res.z.toFixed(1)}` : 'nothing comparable'}`, 'info');
|
|
5875
|
+
if (!res || !(res.score > 0.3) || !(res.z >= 4)) { if (!silent) { this._autoMsg = t('tuneAutoNone'); this._autoFound = null; this.paint(); } return null; }
|
|
5876
|
+
// d: my content at time x = theirs at x − d. With both following the room, my
|
|
5877
|
+
// offset must be theirs + d.
|
|
5878
|
+
const want = Math.round((theirs.off + res.d) * 10) / 10;
|
|
5879
|
+
const sure = Math.round(Math.min(0.99, Math.max(0.5, 0.5 + (res.z - 4) * 0.06 + (res.score - 0.3) * 0.4)) * 100);
|
|
5880
|
+
if (silent) return { want, sure, score: res.score, z: res.z };
|
|
5881
|
+
this._autoFound = want;
|
|
5882
|
+
this._autoMsg = t('tuneAutoFound', { s: this.fmt(want), c: sure });
|
|
5883
|
+
this.paint();
|
|
5884
|
+
return { want, sure, score: res.score, z: res.z };
|
|
5885
|
+
},
|
|
5886
|
+
|
|
5887
|
+
// ── same source or a different version? (decided from each device's media length)
|
|
5888
|
+
mediaSig() {
|
|
5889
|
+
const info = currentMediaInfo();
|
|
5890
|
+
if (!info) return null;
|
|
5891
|
+
if (info.live) return { d: -1 };
|
|
5892
|
+
return Number.isFinite(info.duration) && info.duration > 0 ? { d: Math.round(info.duration * 10) / 10 } : null;
|
|
5893
|
+
},
|
|
5894
|
+
source() {
|
|
5895
|
+
const mine = this.mediaSig();
|
|
5896
|
+
const others = PRESENCE.others().map(uid => STATE.presenceMap[uid]?.md).filter(m => m && Number.isFinite(m.d));
|
|
5897
|
+
if (!mine || !others.length) return { kind: 'unknown' };
|
|
5898
|
+
if (mine.d < 0 || others.some(m => m.d < 0)) return { kind: 'same' }; // live: one timeline
|
|
5899
|
+
const diffs = others.map(m => mine.d - m.d);
|
|
5900
|
+
const big = diffs.reduce((a, b) => (Math.abs(b) > Math.abs(a) ? b : a), 0);
|
|
5901
|
+
return Math.abs(big) < 1.5 ? { kind: 'same' } : { kind: 'different', diff: Math.round(big * 10) / 10 };
|
|
5902
|
+
},
|
|
5903
|
+
// Only one device shifts its timing: the one with the longer version (extra intro), or
|
|
5904
|
+
// with equal length the lowest id.
|
|
5905
|
+
_adjuster() {
|
|
5906
|
+
const mine = this.mediaSig();
|
|
5907
|
+
if (!mine) return false;
|
|
5908
|
+
const others = PRESENCE.others().map(uid => [uid, STATE.presenceMap[uid]?.md]).filter(([, m]) => m && Number.isFinite(m.d) && m.d > 0);
|
|
5909
|
+
return others.every(([uid, m]) => mine.d > m.d + 1.5 || (Math.abs(mine.d - m.d) <= 1.5 && STATE.userId < uid));
|
|
5910
|
+
},
|
|
5911
|
+
// Runs every few seconds in a room: same source → no shift (the room's own fine sync
|
|
5912
|
+
// does the frame-level work); different versions → find the shift by itself.
|
|
5913
|
+
_watchStart: 0, _tries: 0, _lastKind: '',
|
|
5914
|
+
async autoTick() {
|
|
5915
|
+
if (!IS_TOP || !STATE.handshakeVerified || STATE.isReadOnly || this._autoBusy) return;
|
|
5916
|
+
const src = this.source();
|
|
5917
|
+
if (src.kind !== this._lastKind) { this._lastKind = src.kind; this._tries = 0; this.paint(); }
|
|
5918
|
+
if (src.kind === 'same') {
|
|
5919
|
+
if (this.offset()) { this.set(0, { quiet: true }); showToast(t('tuneSameReset')); }
|
|
5920
|
+
return;
|
|
5921
|
+
}
|
|
5922
|
+
if (src.kind !== 'different' || this.offset() || this._autoDone === location.href || !this._adjuster()) return;
|
|
5923
|
+
const info = currentMediaInfo();
|
|
5924
|
+
if (!info || info.paused) return;
|
|
5925
|
+
const env = this._rec;
|
|
5926
|
+
if (STATE.video && (!env || env.ts.length < 450)) return; // ~45 s of history first
|
|
5927
|
+
if (this._tries >= 5) {
|
|
5928
|
+
if (!this._suggested) { this._suggested = true; BUBBLES.show({ icon: '🎯', name: 'NexusSync', color: '#ffca28', text: t('tuneSuggest', { s: this.fmt(src.diff) }), key: 'tune-suggest', ms: 12000, onTap: () => this.open() }); }
|
|
5929
|
+
return;
|
|
5930
|
+
}
|
|
5931
|
+
if (Date.now() - (this._lastTry || 0) < 30000) return;
|
|
5932
|
+
this._lastTry = Date.now();
|
|
5933
|
+
this._tries++;
|
|
5934
|
+
this._autoBusy = true;
|
|
5935
|
+
try {
|
|
5936
|
+
const r = await this.auto({ silent: true });
|
|
5937
|
+
// A very clear match is used at once; a fair one only when two tries agree.
|
|
5938
|
+
const prev = this._prevAuto;
|
|
5939
|
+
this._prevAuto = r;
|
|
5940
|
+
const clear = r && r.score > 0.45 && r.z >= 7;
|
|
5941
|
+
const agreed = r && prev && r.z >= 5 && prev.z >= 5 && Math.abs(r.want - prev.want) < 0.5;
|
|
5942
|
+
if ((clear || agreed) && Math.abs(r.want) <= this.LIMIT) {
|
|
5943
|
+
this._autoDone = location.href;
|
|
5944
|
+
const before = this.offset();
|
|
5945
|
+
this.set(r.want, { quiet: true });
|
|
5946
|
+
BUBBLES.show({ icon: '🎯', name: 'NexusSync', color: '#69f0ae', text: t('tuneAutoApplied', { s: this.fmt(r.want) }), key: 'tune-auto', ms: 12000, onTap: () => { this.set(before); this._autoDone = location.href; } });
|
|
5947
|
+
}
|
|
5948
|
+
} catch (_) { } finally { this._autoBusy = false; }
|
|
5949
|
+
},
|
|
5950
|
+
|
|
5951
|
+
// ── panel
|
|
5952
|
+
open() {
|
|
5953
|
+
const panel = shadow?.getElementById('tune-panel');
|
|
5954
|
+
if (!panel) return;
|
|
5955
|
+
this._armedByUser = true;
|
|
5956
|
+
this.arm(true);
|
|
5957
|
+
openPanel(panel);
|
|
5958
|
+
this.paint();
|
|
5959
|
+
// Ask the others for their picture while the panel is open.
|
|
5960
|
+
if (SOCIAL.live()) SOCIAL.send('tune', { op: 'peek' });
|
|
5961
|
+
clearInterval(this._paintTimer);
|
|
5962
|
+
this._paintTimer = setInterval(async () => {
|
|
5963
|
+
if (panel.style.display !== 'flex') { clearInterval(this._paintTimer); return; }
|
|
5964
|
+
const s = await this._mySnap();
|
|
5965
|
+
this._mine = s;
|
|
5966
|
+
if (Date.now() - (this._lastPeekReq || 0) > 30000 && SOCIAL.live()) { this._lastPeekReq = Date.now(); SOCIAL.send('tune', { op: 'peek' }); }
|
|
5967
|
+
this.paint();
|
|
5968
|
+
}, 1000);
|
|
5969
|
+
},
|
|
5970
|
+
paint() {
|
|
5971
|
+
const panel = shadow?.getElementById('tune-panel');
|
|
5972
|
+
if (!panel || panel.style.display !== 'flex') return;
|
|
5973
|
+
const off = this.offset();
|
|
5974
|
+
const q = s => panel.querySelector(s);
|
|
5975
|
+
const src = this.source();
|
|
5976
|
+
q('.tune-src').textContent = src.kind === 'same' ? t('tuneSrcSame') : src.kind === 'different' ? t('tuneSrcDiff', { s: this.fmt(src.diff) }) : t('tuneSrcUnknown');
|
|
5977
|
+
q('.tune-src').dataset.kind = src.kind;
|
|
5978
|
+
panel.querySelector('.tune-body').classList.toggle('same', src.kind === 'same');
|
|
5979
|
+
q('.tune-off-val').textContent = this.fmt(off);
|
|
5980
|
+
q('.tune-off-desc').textContent = !off ? t('tuneOffsetZero') : t(off > 0 ? 'tuneAhead' : 'tuneBehind', { s: Math.abs(off).toFixed(1) + 's' });
|
|
5981
|
+
// A protected or cross-site picture cannot be copied (the browser forbids reading
|
|
5982
|
+
// it): instead of a black box the card shows that device's position in large type,
|
|
5983
|
+
// so the two can still be compared by time.
|
|
5984
|
+
const pic = (box, data, label, waiting) => {
|
|
5985
|
+
const img = box.querySelector('img'), cap = box.querySelector('.tune-cap'), ph = box.querySelector('.tune-ph');
|
|
5986
|
+
const hasImg = !!(data && data.img);
|
|
5987
|
+
if (hasImg) { img.src = data.img; img.style.visibility = 'visible'; }
|
|
5988
|
+
else img.style.visibility = 'hidden';
|
|
5989
|
+
ph.style.display = hasImg ? 'none' : '';
|
|
5990
|
+
const age = data ? Math.max(0, (Date.now() - (data.at || Date.now())) / 1000) : 0;
|
|
5991
|
+
ph.querySelector('.tune-ph-time').textContent = data ? formatTime((data.t || 0) + (data.playing ? age : 0)) : '··:··';
|
|
5992
|
+
ph.querySelector('.tune-ph-note').textContent = !data ? (waiting ? t('tuneWaiting') : '') : t('tuneNoPicture');
|
|
5993
|
+
cap.textContent = label + (data ? ' · ' + formatTime(data.t || 0) : '');
|
|
5994
|
+
};
|
|
5995
|
+
pic(q('.tune-pic.mine'), this._mine ? { ...this._mine, at: this._mine.at || Date.now() } : null, t('tuneMine'), false);
|
|
5996
|
+
const p = this._peer && Date.now() - this._peer.at < 8000 ? this._peer : null;
|
|
5997
|
+
// Time comparison (works for protected pictures too).
|
|
5998
|
+
const diffEl = q('.tune-diff');
|
|
5999
|
+
if (p && this._mine) {
|
|
6000
|
+
const mineNow = (this._mine.t || 0) + (this._mine.playing ? (Date.now() - (this._mine.at || Date.now())) / 1000 : 0);
|
|
6001
|
+
const theirNow = (p.t || 0) + (p.playing ? (Date.now() - p.at) / 1000 : 0);
|
|
6002
|
+
const d = Math.round((mineNow - theirNow) * 10) / 10;
|
|
6003
|
+
diffEl.textContent = Math.abs(d) < 0.3 ? t('tuneDiffSame') : t(d > 0 ? 'tuneDiffAhead' : 'tuneDiffBehind', { s: Math.abs(d).toFixed(1) + 's', name: p.name });
|
|
6004
|
+
} else diffEl.textContent = '';
|
|
6005
|
+
pic(q('.tune-pic.theirs'), p, p ? p.name : (PRESENCE.others().length ? participantName(PRESENCE.others()[0]) : '—'), !!PRESENCE.others().length);
|
|
6006
|
+
const theirs = [...this._marks.values()].pop();
|
|
6007
|
+
q('.tune-marks').textContent = [this._myMark ? t('tuneMarkMine', { t: formatTime(this._myMark.t) }) : '', theirs ? t('tuneMarkTheirs', { name: theirs.name, t: formatTime(theirs.t) }) : ''].filter(Boolean).join(' · ');
|
|
6008
|
+
const mo = this.markOffset();
|
|
6009
|
+
const ma = q('.tune-mark-apply');
|
|
6010
|
+
ma.style.display = mo === null ? 'none' : '';
|
|
6011
|
+
if (mo !== null) ma.textContent = t('tuneApply') + ' ' + this.fmt(Math.round(mo * 10) / 10);
|
|
6012
|
+
q('.tune-auto-msg').textContent = this._autoMsg || '';
|
|
6013
|
+
const aa = q('.tune-auto-apply');
|
|
6014
|
+
aa.style.display = this._autoFound == null ? 'none' : '';
|
|
6015
|
+
if (this._autoFound != null) aa.textContent = t('tuneApply') + ' ' + this.fmt(this._autoFound);
|
|
6016
|
+
},
|
|
6017
|
+
build() {
|
|
6018
|
+
const body = createEl('div', 'manual-body tune-body');
|
|
6019
|
+
const offRow = createEl('div', 'tune-off');
|
|
6020
|
+
offRow.append(createEl('span', 'tune-off-val', '0.0s'), createEl('span', 'tune-off-desc', ''));
|
|
6021
|
+
const nudges = createEl('div', 'tune-nudges');
|
|
6022
|
+
[-10, -1, -0.1, 0.1, 1, 10].forEach(dv => {
|
|
6023
|
+
const b = createEl('button', 'btn subtle', (dv > 0 ? '+' : '−') + Math.abs(dv) + 's', { type: 'button' });
|
|
6024
|
+
b.onclick = (ev) => { ev.stopPropagation(); this.set(this.offset() + dv, { quiet: true }); };
|
|
6025
|
+
nudges.appendChild(b);
|
|
6026
|
+
});
|
|
6027
|
+
const tools = createEl('div', 'tune-tools');
|
|
6028
|
+
const resync = createEl('button', 'btn tune-keep', '🔄 ' + t('tuneResync'), { type: 'button' });
|
|
6029
|
+
resync.onclick = () => uiElements.btnSyncStatus?.click();
|
|
6030
|
+
const reset = createEl('button', 'btn subtle', '↺ ' + t('tuneReset'), { type: 'button' });
|
|
6031
|
+
reset.onclick = () => this.set(0);
|
|
6032
|
+
tools.append(reset);
|
|
6033
|
+
const pics = createEl('div', 'tune-pics');
|
|
6034
|
+
['mine', 'theirs'].forEach(k => {
|
|
6035
|
+
const box = createEl('div', 'tune-pic ' + k);
|
|
6036
|
+
const ph = createEl('div', 'tune-ph');
|
|
6037
|
+
ph.append(createEl('div', 'tune-ph-time', '··:··'), createEl('div', 'tune-ph-note'));
|
|
6038
|
+
box.append(createEl('img', '', '', { alt: '' }), ph, createEl('div', 'tune-cap'));
|
|
6039
|
+
pics.appendChild(box);
|
|
6040
|
+
});
|
|
6041
|
+
const markBtn = createEl('button', 'btn', t('tuneMarkBtn'), { type: 'button' });
|
|
6042
|
+
markBtn.onclick = () => this.mark();
|
|
6043
|
+
const markApply = createEl('button', 'btn primary tune-mark-apply', t('tuneApply'), { type: 'button' });
|
|
6044
|
+
markApply.onclick = () => { const mo = this.markOffset(); if (mo !== null) this.set(mo); };
|
|
6045
|
+
const autoBtn = createEl('button', 'btn', t('tuneAutoBtn'), { type: 'button' });
|
|
6046
|
+
autoBtn.onclick = () => this.auto();
|
|
6047
|
+
const autoApply = createEl('button', 'btn primary tune-auto-apply', t('tuneApply'), { type: 'button' });
|
|
6048
|
+
autoApply.onclick = () => { if (this._autoFound != null) this.set(this._autoFound); };
|
|
6049
|
+
const h = text => createEl('div', 'field-label', text);
|
|
6050
|
+
// Version tools (offset, same scene, automatic) only matter for different versions.
|
|
6051
|
+
const ver = createEl('div', 'tune-ver');
|
|
6052
|
+
ver.append(
|
|
6053
|
+
h(t('tuneOffset')), offRow, nudges, reset, createEl('div', 'trans-help', t('tuneHelp')),
|
|
6054
|
+
h(t('tuneMark')), createEl('div', 'trans-help', t('tuneMarkHint')), markBtn, createEl('div', 'tune-marks trans-help'), markApply,
|
|
6055
|
+
h(t('tuneAuto')), createEl('div', 'trans-help', t('tuneAutoHint')), autoBtn, createEl('div', 'tune-auto-msg trans-help'), autoApply
|
|
6056
|
+
);
|
|
6057
|
+
body.append(createEl('div', 'tune-src'), resync, h(t('tuneCompare')), pics, createEl('div', 'tune-diff'), ver);
|
|
6058
|
+
return body;
|
|
6059
|
+
}
|
|
6060
|
+
};
|
|
6061
|
+
|
|
5432
6062
|
// ───────────────────────── Fine sync
|
|
5433
6063
|
// Heartbeats alone left devices up to a quarter of a second apart (corrections only
|
|
5434
6064
|
// started beyond 0.25 s and only when a heartbeat arrived). Now every follower compares
|
|
@@ -5477,7 +6107,7 @@
|
|
|
5477
6107
|
if (this._steps) { this._steps = 0; if (!idle) RATE.apply(v, room ? room.rate : RATE.base(v)); }
|
|
5478
6108
|
return;
|
|
5479
6109
|
}
|
|
5480
|
-
const expected = Math.min(room.time + (getSyncedTime() - room.timestamp) / 1000 * room.rate + this.offset(), (v.duration || Infinity) - 0.1);
|
|
6110
|
+
const expected = Math.min(room.time + TUNE.offset() + (getSyncedTime() - room.timestamp) / 1000 * room.rate + this.offset(), (v.duration || Infinity) - 0.1);
|
|
5481
6111
|
const drift = expected - this.mediaTime(v);
|
|
5482
6112
|
this.drift = drift;
|
|
5483
6113
|
this._ema = Math.abs(drift - this._ema) > 0.5 ? drift : this._ema * 0.6 + drift * 0.4;
|
|
@@ -5514,6 +6144,19 @@
|
|
|
5514
6144
|
}
|
|
5515
6145
|
};
|
|
5516
6146
|
|
|
6147
|
+
// Sync timing keeps a short history of what was played while in a room (on a computer
|
|
6148
|
+
// all the time; on phones only once the timing panel was opened, to save battery).
|
|
6149
|
+
if (IS_TOP) setInterval(() => {
|
|
6150
|
+
try { TUNE.autoTick(); } catch (_) { }
|
|
6151
|
+
try {
|
|
6152
|
+
// Different versions need the history; same source does not.
|
|
6153
|
+
const want = STATE.handshakeVerified && (!IS_TOUCH || TUNE._armedByUser || TUNE.source().kind === 'different') && !!(STATE.video || STATE.cinemaIframe);
|
|
6154
|
+
if (want && !TUNE._armed) { TUNE._armed = true; TUNE.arm(true); }
|
|
6155
|
+
else if (!want && TUNE._armed) { TUNE._armed = false; TUNE.arm(false); }
|
|
6156
|
+
else if (want && STATE.video && TUNE._rec && TUNE._rec.v !== STATE.video) TUNE.arm(true);
|
|
6157
|
+
} catch (_) { }
|
|
6158
|
+
}, 3000);
|
|
6159
|
+
|
|
5517
6160
|
// The shared clock drifts a little over a long movie: measure it again every 10 minutes.
|
|
5518
6161
|
if (IS_TOP) setInterval(() => { if (STATE.handshakeVerified && !document.hidden) syncServerClock(); }, 600000);
|
|
5519
6162
|
|
|
@@ -5792,12 +6435,19 @@
|
|
|
5792
6435
|
const PRESENCE = {
|
|
5793
6436
|
seen: new Map(),
|
|
5794
6437
|
STALE_MS: 25000,
|
|
6438
|
+
// A device that went quiet (screen off, app in the background) stays in the room as
|
|
6439
|
+
// "sleeping" until it says goodbye or has been silent this long; it comes back by itself.
|
|
6440
|
+
LONG_MS: 30 * 60 * 1000,
|
|
6441
|
+
left: new Set(),
|
|
5795
6442
|
refresh() {
|
|
5796
6443
|
const now = Date.now();
|
|
5797
6444
|
STATE.presenceMap = {};
|
|
6445
|
+
STATE.sleepingMap = {};
|
|
5798
6446
|
if (yPresence) yPresence.forEach((val, uid) => {
|
|
5799
6447
|
if (!val) return;
|
|
5800
|
-
|
|
6448
|
+
const age = now - (this.seen.get(uid) || 0);
|
|
6449
|
+
if (uid === STATE.userId || age < this.STALE_MS) STATE.presenceMap[uid] = val;
|
|
6450
|
+
else if (this.seen.has(uid) && age < this.LONG_MS && !this.left.has(uid)) STATE.sleepingMap[uid] = val;
|
|
5801
6451
|
});
|
|
5802
6452
|
if (STATE.role !== 'IDLE' && !STATE.presenceMap[STATE.userId]) STATE.presenceMap[STATE.userId] = { nick: STATE.nickname || '', color: STATE.color, viewer: !!STATE.isViewer };
|
|
5803
6453
|
updatePresenceUI();
|
|
@@ -5821,7 +6471,7 @@
|
|
|
5821
6471
|
if (STATE._presenceTimer) return;
|
|
5822
6472
|
const beat = () => {
|
|
5823
6473
|
if (ydoc && yPresence && STATE.role !== 'IDLE' && !STATE.isReadOnly) {
|
|
5824
|
-
ydoc.transact(() => yPresence.set(STATE.userId,
|
|
6474
|
+
ydoc.transact(() => yPresence.set(STATE.userId, PROFILE.value()), 'local');
|
|
5825
6475
|
}
|
|
5826
6476
|
PRESENCE.refresh();
|
|
5827
6477
|
};
|
|
@@ -5971,14 +6621,20 @@
|
|
|
5971
6621
|
// small mark for "watching only", "away" (screen off / other tab) and an outdated version.
|
|
5972
6622
|
function roomRoster() {
|
|
5973
6623
|
const safeColor = c => (/^#[0-9a-f]{3,8}$/i.test(String(c || '')) ? c : '#7c4dff');
|
|
5974
|
-
const
|
|
6624
|
+
const entries = [...Object.entries(STATE.presenceMap || {}), ...Object.entries(STATE.sleepingMap || {}).map(([u, p]) => [u, { ...p, _sleep: true }])];
|
|
6625
|
+
const list = entries.map(([uid, p]) => {
|
|
5975
6626
|
const self = uid === STATE.userId;
|
|
5976
6627
|
return {
|
|
5977
6628
|
uid, self,
|
|
5978
6629
|
name: self ? (STATE.nickname || t('you')) : (p?.nick || 'ID:' + String(uid).slice(0, 3)),
|
|
5979
6630
|
color: safeColor(self ? STATE.color : p?.color),
|
|
5980
6631
|
viewer: self ? !!STATE.isViewer : !!p?.viewer,
|
|
5981
|
-
|
|
6632
|
+
av: safeAvatar(self ? PROFILE.avatar() : p?.av),
|
|
6633
|
+
img: AVATAR_IMG.get(uid),
|
|
6634
|
+
st: String((self ? PROFILE.status() : p?.st) || '').slice(0, 40),
|
|
6635
|
+
muted: !self && SAFETY.muted.has(uid),
|
|
6636
|
+
away: !self && (!!p?.hid || !!p?._sleep),
|
|
6637
|
+
sleeping: !self && !!p?._sleep,
|
|
5982
6638
|
oldVer: !self && !!(p?.v && p.v !== NXU_VERSION)
|
|
5983
6639
|
};
|
|
5984
6640
|
});
|
|
@@ -5987,19 +6643,27 @@
|
|
|
5987
6643
|
}
|
|
5988
6644
|
function renderRoster(box, max = 4) {
|
|
5989
6645
|
const list = roomRoster();
|
|
5990
|
-
const
|
|
6646
|
+
const issue = STATE.handshakeVerified && STATE.connectionMode !== 'WEBRTC_P2P' && typeof relayAlive === 'function' && !relayAlive();
|
|
6647
|
+
const sig = max + '|' + issue + '|' + list.map(m => [m.uid, m.name, m.color, m.viewer, m.away, m.sleeping, m.oldVer, m.av, m.img.length, m.st, m.muted].join(',')).join(';');
|
|
5991
6648
|
if (box._rosterSig === sig) return list;
|
|
5992
6649
|
box._rosterSig = sig;
|
|
5993
6650
|
box.replaceChildren();
|
|
6651
|
+
// This device lost the room's channel: say so plainly (it reconnects by itself).
|
|
6652
|
+
if (issue) box.appendChild(createEl('span', 'nx-who warn', '⚠️ ' + t('whoReconnecting')));
|
|
5994
6653
|
list.slice(0, max).forEach(m => {
|
|
5995
6654
|
const chip = createEl('span', 'nx-who' + (m.away ? ' away' : '') + (m.self ? ' me' : ''));
|
|
5996
6655
|
const dot = createEl('i', 'nx-who-dot');
|
|
5997
6656
|
dot.style.background = m.color;
|
|
5998
|
-
|
|
6657
|
+
if (m.img) { const im = createEl('img', 'nx-who-img', '', { alt: '' }); im.src = m.img; im.style.borderColor = m.color; chip.append(im); }
|
|
6658
|
+
else chip.append(dot);
|
|
6659
|
+
if (m.av && !m.img) chip.append(createEl('span', 'nx-who-av', m.av));
|
|
6660
|
+
chip.append(createEl('span', 'nx-who-name', m.name + (m.self && STATE.nickname ? ' ' + t('meTag') : '')));
|
|
6661
|
+
if (m.muted) chip.append(createEl('span', 'nx-who-tag', '🔇'));
|
|
6662
|
+
if (m.st && max > 4) chip.append(createEl('span', 'nx-who-st', m.st));
|
|
5999
6663
|
if (m.viewer) chip.append(createEl('span', 'nx-who-tag', '👀'));
|
|
6000
6664
|
if (m.away) chip.append(createEl('span', 'nx-who-tag', '💤'));
|
|
6001
6665
|
if (m.oldVer) chip.append(createEl('span', 'nx-who-tag', '⚠️'));
|
|
6002
|
-
chip.title = [m.name, m.viewer && t('whoViewer'), m.away && t('whoAway'), m.oldVer && t('whoOldVer')].filter(Boolean).join(' · ');
|
|
6666
|
+
chip.title = [m.name, m.st, m.viewer && t('whoViewer'), m.sleeping ? t('whoSleeping') : m.away && t('whoAway'), m.oldVer && t('whoOldVer')].filter(Boolean).join(' · ');
|
|
6003
6667
|
box.appendChild(chip);
|
|
6004
6668
|
});
|
|
6005
6669
|
if (list.length > max) box.appendChild(createEl('span', 'nx-who more', '+' + (list.length - max)));
|
|
@@ -6682,6 +7346,118 @@
|
|
|
6682
7346
|
return select;
|
|
6683
7347
|
}
|
|
6684
7348
|
|
|
7349
|
+
// ⚙️ Settings: profile, my reactions, playback, what reaches me from others, advanced.
|
|
7350
|
+
function buildSettingsPanel(parts) {
|
|
7351
|
+
const body = createEl('div', 'manual-body settings-body nx-settings');
|
|
7352
|
+
const section = (icon, title) => {
|
|
7353
|
+
const sec = createEl('details', 'nx-set-sec');
|
|
7354
|
+
sec.append(createEl('summary', 'nx-set-head', icon + ' ' + title));
|
|
7355
|
+
body.appendChild(sec);
|
|
7356
|
+
return sec;
|
|
7357
|
+
};
|
|
7358
|
+
const toggle = (label, get, set) => {
|
|
7359
|
+
const row = createEl('label', 'trans-row nx-set-row');
|
|
7360
|
+
const box = createEl('input', 'trans-check', '', { type: 'checkbox' });
|
|
7361
|
+
box.checked = !!get();
|
|
7362
|
+
box.addEventListener('change', () => set(!!box.checked));
|
|
7363
|
+
row.append(createEl('span', '', label), box);
|
|
7364
|
+
return row;
|
|
7365
|
+
};
|
|
7366
|
+
// Profile
|
|
7367
|
+
const prof = section('👤', t('setProfile'));
|
|
7368
|
+
prof.open = true;
|
|
7369
|
+
prof.appendChild(PROFILE.editor());
|
|
7370
|
+
const avRow = createEl('div', 'nx-av-row');
|
|
7371
|
+
const paintAv = () => avRow.querySelectorAll('.nx-av').forEach(b => b.classList.toggle('on', b.dataset.av === PROFILE.avatar()));
|
|
7372
|
+
['', ...PROFILE.AVATARS].forEach(a => {
|
|
7373
|
+
const b = createEl('button', 'nx-av', a || '∅', { type: 'button', 'aria-label': a || 'none' });
|
|
7374
|
+
b.dataset.av = a;
|
|
7375
|
+
b.onclick = (ev) => { ev.stopPropagation(); PROFILE.setAvatar(a); paintAv(); };
|
|
7376
|
+
avRow.appendChild(b);
|
|
7377
|
+
});
|
|
7378
|
+
paintAv();
|
|
7379
|
+
const status = createEl('input', 'nx-compose-input nx-status-input', '', { type: 'text', maxlength: '40', placeholder: t('setStatusPh'), autocomplete: 'off' });
|
|
7380
|
+
status.value = PROFILE.status();
|
|
7381
|
+
status.addEventListener('input', () => PROFILE.setStatus(status.value));
|
|
7382
|
+
const preview = createEl('div', 'nx-av-preview');
|
|
7383
|
+
const paintPreview = () => {
|
|
7384
|
+
const img = PROFILE.image();
|
|
7385
|
+
preview.style.backgroundImage = img ? `url("${img}")` : '';
|
|
7386
|
+
preview.textContent = img ? '' : (PROFILE.avatar() || (STATE.nickname || '?').slice(0, 1).toUpperCase());
|
|
7387
|
+
paintAv();
|
|
7388
|
+
};
|
|
7389
|
+
const avCustom = createEl('input', 'nx-compose-input nx-av-input', '', { type: 'text', maxlength: '8', placeholder: t('setAvatarCustom'), autocomplete: 'off' });
|
|
7390
|
+
avCustom.value = PROFILE.avatar() && !PROFILE.AVATARS.includes(PROFILE.avatar()) ? PROFILE.avatar() : '';
|
|
7391
|
+
avCustom.addEventListener('input', () => { const a = safeAvatar(avCustom.value); if (a || !avCustom.value.trim()) { PROFILE.setImage(''); PROFILE.setAvatar(a); paintPreview(); } });
|
|
7392
|
+
avCustom.addEventListener('keydown', (ev) => ev.stopPropagation());
|
|
7393
|
+
const photoBtn = createEl('button', 'btn subtle', '🖼 ' + t('setAvatarPhoto'), { type: 'button' });
|
|
7394
|
+
photoBtn.onclick = () => { PROFILE._onImage = paintPreview; PROFILE.pickImage(); };
|
|
7395
|
+
const clearBtn = createEl('button', 'btn subtle', '✕', { type: 'button', title: t('setAvatarClear') });
|
|
7396
|
+
clearBtn.onclick = () => { PROFILE.setImage(''); PROFILE.setAvatar(''); avCustom.value = ''; paintPreview(); };
|
|
7397
|
+
const customRow = createEl('div', 'nx-av-custom');
|
|
7398
|
+
customRow.append(preview, avCustom, photoBtn, clearBtn);
|
|
7399
|
+
avRow.querySelectorAll('.nx-av').forEach(b => b.addEventListener('click', () => { PROFILE.setImage(''); avCustom.value = ''; paintPreview(); }));
|
|
7400
|
+
paintPreview();
|
|
7401
|
+
prof.append(createEl('div', 'field-label', t('setAvatar')), customRow, avRow, createEl('div', 'field-label', t('setStatus')), status);
|
|
7402
|
+
// My reactions
|
|
7403
|
+
const reac = section('😀', t('setReactions'));
|
|
7404
|
+
const slots = createEl('div', 'nx-react-slots');
|
|
7405
|
+
let pick = 0;
|
|
7406
|
+
const PALETTE = ['❤️', '🔥', '👏', '🤣', '😱', '😍', '🥺', '🤯', '👀', '💀', '🙏', '👍', '🎉', '💯', '😴', '🤔', '🍿', '😂', '😭', '😡', '💦', '🍪', '☕', '😘'];
|
|
7407
|
+
const paintSlots = () => {
|
|
7408
|
+
slots.replaceChildren(...REACTIONS.list().map((em, i) => {
|
|
7409
|
+
const b = createEl('button', 'nx-react-slot' + (i === pick ? ' on' : ''), em, { type: 'button' });
|
|
7410
|
+
b.onclick = (ev) => { ev.stopPropagation(); pick = i; paintSlots(); };
|
|
7411
|
+
return b;
|
|
7412
|
+
}));
|
|
7413
|
+
};
|
|
7414
|
+
const pal = createEl('div', 'nx-react-pal');
|
|
7415
|
+
PALETTE.forEach(em => {
|
|
7416
|
+
const b = createEl('button', 'nx-react-pick', em, { type: 'button' });
|
|
7417
|
+
b.onclick = (ev) => { ev.stopPropagation(); if (REACTIONS.set(pick, em)) { pick = (pick + 1) % REACTIONS.list().length; paintSlots(); } };
|
|
7418
|
+
pal.appendChild(b);
|
|
7419
|
+
});
|
|
7420
|
+
const custom = createEl('input', 'nx-compose-input nx-react-custom', '', { type: 'text', maxlength: '16', placeholder: t('setEmojiPh'), autocomplete: 'off' });
|
|
7421
|
+
custom.addEventListener('input', () => { if (REACTIONS.set(pick, custom.value)) { custom.value = ''; pick = (pick + 1) % REACTIONS.list().length; paintSlots(); } });
|
|
7422
|
+
custom.addEventListener('keydown', (ev) => ev.stopPropagation());
|
|
7423
|
+
const resetBtn = createEl('button', 'btn subtle', '↺ ' + t('setReactionsReset'), { type: 'button' });
|
|
7424
|
+
resetBtn.onclick = () => { REACTIONS.reset(); pick = 0; paintSlots(); };
|
|
7425
|
+
const slotRow = createEl('div', 'nx-slot-row');
|
|
7426
|
+
const addSlot = createEl('button', 'btn subtle', t('setSlotAdd'), { type: 'button' });
|
|
7427
|
+
addSlot.onclick = () => { const i = REACTIONS.add(); if (i >= 0) pick = i; paintSlots(); };
|
|
7428
|
+
const delSlot = createEl('button', 'btn subtle', t('setSlotRemove'), { type: 'button' });
|
|
7429
|
+
delSlot.onclick = () => { if (REACTIONS.remove(pick)) pick = Math.min(pick, REACTIONS.list().length - 1); paintSlots(); };
|
|
7430
|
+
slotRow.append(addSlot, delSlot);
|
|
7431
|
+
paintSlots();
|
|
7432
|
+
reac.append(slots, slotRow, createEl('div', 'trans-help', t('setReactionsHint')), pal, custom, resetBtn);
|
|
7433
|
+
// Playback
|
|
7434
|
+
const play = section('🎬', t('setPlayback'));
|
|
7435
|
+
play.append(parts.autoCinema, parts.adGuard, toggle(t('setAutoNext'), () => NEXT_EP.enabled(), on => STORE.set('nxu_auto_next', on)));
|
|
7436
|
+
// Watching together: what reaches me, and from whom
|
|
7437
|
+
const tog = section('🛡️', t('setTogether'));
|
|
7438
|
+
[['react', 'setRecvReact'], ['nudge', 'setRecvNudge'], ['ink', 'setRecvInk'], ['chat', 'setRecvChat'], ['ping', 'setRecvPing']].forEach(([k, label]) => tog.appendChild(toggle(t(label), () => SAFETY.receive(k), on => SAFETY.set(k, on))));
|
|
7439
|
+
const people = createEl('div', 'nx-people');
|
|
7440
|
+
const paintPeople = () => {
|
|
7441
|
+
const others = roomRoster().filter(m => !m.self);
|
|
7442
|
+
if (!others.length) { people.replaceChildren(createEl('div', 'trans-help', t('setNobody'))); return; }
|
|
7443
|
+
people.replaceChildren(...others.map(m => {
|
|
7444
|
+
const row = createEl('div', 'nx-person');
|
|
7445
|
+
const dot = createEl('i', 'nx-who-dot'); dot.style.background = m.color;
|
|
7446
|
+
const b = createEl('button', 'btn subtle', SAFETY.muted.has(m.uid) ? '👁 ' + t('setUnmute') : '🔇 ' + t('setMute'), { type: 'button' });
|
|
7447
|
+
b.onclick = (ev) => { ev.stopPropagation(); SAFETY.toggleMute(m.uid); paintPeople(); updatePresenceUI(); };
|
|
7448
|
+
row.append(dot, createEl('span', 'nx-person-name', (m.av ? m.av + ' ' : '') + m.name), b);
|
|
7449
|
+
return row;
|
|
7450
|
+
}));
|
|
7451
|
+
};
|
|
7452
|
+
tog.addEventListener('toggle', () => { if (tog.open) paintPeople(); });
|
|
7453
|
+
tog.append(createEl('div', 'field-label', t('setPeople')), people, createEl('div', 'trans-help', t('setMutedHint')));
|
|
7454
|
+
// Advanced
|
|
7455
|
+
const adv = section('🔧', t('setAdvanced'));
|
|
7456
|
+
adv.append(parts.chatLog, parts.subLog, parts.debug, parts.idleRow, parts.hideSite);
|
|
7457
|
+
body.refreshPeople = paintPeople;
|
|
7458
|
+
return body;
|
|
7459
|
+
}
|
|
7460
|
+
|
|
6685
7461
|
function buildTranslationSettings() {
|
|
6686
7462
|
const body = createEl('div', 'manual-body settings-body');
|
|
6687
7463
|
const label = text => createEl('div', 'field-label', text);
|
|
@@ -6918,10 +7694,19 @@
|
|
|
6918
7694
|
.presence-pill.open .nx-who { max-width:none; }
|
|
6919
7695
|
.nx-who.me { background:rgba(255,255,255,0.18); }
|
|
6920
7696
|
.nx-who.away { opacity:0.55; }
|
|
7697
|
+
.nx-who.warn { background:rgba(255,170,0,0.28); }
|
|
6921
7698
|
.nx-who.more { padding:2px 7px; }
|
|
6922
7699
|
.nx-who-dot { flex:none; width:8px; height:8px; border-radius:50%; box-shadow:0 0 5px currentColor; }
|
|
6923
7700
|
.nx-who-name { overflow:hidden; text-overflow:ellipsis; }
|
|
6924
7701
|
.nx-who-tag { font-size:10px; }
|
|
7702
|
+
.nx-who-av { font-size:12px; line-height:1; }
|
|
7703
|
+
.nx-who-img { width:16px; height:16px; border-radius:50%; object-fit:cover; border:1.5px solid; flex:none; }
|
|
7704
|
+
.nx-av-preview { width:44px; height:44px; border-radius:50%; background:rgba(255,255,255,0.1) center/cover; display:grid; place-items:center; font-size:22px; font-weight:800; border:2px solid var(--accent); flex:none; }
|
|
7705
|
+
.nx-av-custom { display:flex; gap:6px; align-items:center; }
|
|
7706
|
+
.nx-av-custom .nx-compose-input { flex:1; }
|
|
7707
|
+
.nx-av-custom .btn { width:auto; }
|
|
7708
|
+
.nx-who-st { font-weight:500; opacity:0.7; margin-left:4px; overflow:hidden; text-overflow:ellipsis; }
|
|
7709
|
+
.nx-talk-avatar.emoji { background:rgba(255,255,255,0.12) !important; font-size:16px; }
|
|
6925
7710
|
.dock { position:absolute; background:var(--glass-strong); border-radius:16px; padding:10px; display:flex; flex-direction:column; gap:6px; pointer-events:none; opacity:0; border:1px solid rgba(255,255,255,0.1);
|
|
6926
7711
|
transition:opacity 0.25s ease, transform 0.25s ease; box-shadow:0 10px 30px rgba(0,0,0,0.35); backdrop-filter:blur(4px); -webkit-backdrop-filter:blur(4px); z-index:90; overflow-y:auto; text-shadow:0 1px 2px rgba(0,0,0,0.8); overflow-x:hidden; width:clamp(150px, 40vw, 190px); width:clamp(150px, 40cqw, 190px); }
|
|
6927
7712
|
.dock.open { opacity:1; pointer-events:auto; border-color:rgba(0,230,118,0.3); }
|
|
@@ -6938,7 +7723,12 @@
|
|
|
6938
7723
|
border:1px solid rgba(255,255,255,0.18); overflow:hidden; box-shadow:0 15px 40px rgba(0,0,0,0.6); z-index:105; transition:opacity 0.4s ease;
|
|
6939
7724
|
width:min(420px, calc(100vw - 24px)); width:min(420px, calc(100cqw - 24px)); max-height:calc(100vh - 24px); max-height:calc(100cqh - 24px); }
|
|
6940
7725
|
#chat-panel, #sub-log-panel, #debug-panel { height:min(520px, calc(100vh - 24px)); height:min(520px, calc(100cqh - 24px)); }
|
|
6941
|
-
|
|
7726
|
+
/* The window stays put and its body scrolls, so the resize grip stays in the corner
|
|
7727
|
+
(it used to scroll away with long content, e.g. every Settings section open). */
|
|
7728
|
+
#manual-modal, #trans-modal, #settings-modal, #tune-panel, #os-panel { overflow:hidden; }
|
|
7729
|
+
#manual-modal > .manual-body, #trans-modal > .manual-body, #settings-modal > .manual-body, #tune-panel > .manual-body, #os-panel > .manual-body { flex:1 1 auto; min-height:0; overflow-y:auto; overscroll-behavior:contain; }
|
|
7730
|
+
/* Windows you read and fill in stay legible over a busy picture. */
|
|
7731
|
+
#manual-modal, #trans-modal, #settings-modal, #tune-panel, #os-panel, #debug-panel { background:rgba(16,20,26,0.9); }
|
|
6942
7732
|
.drag-header { background:rgba(0,0,0,0.3); padding:10px 14px; font-size:13px; color:#eee; font-weight:700; cursor:grab; display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid rgba(255,255,255,0.06); user-select:none; touch-action:none; flex:0 0 auto; }
|
|
6943
7733
|
.header-controls { display:flex; gap:10px; align-items:center; }
|
|
6944
7734
|
.pin-btn, .close-btn { background:transparent; border:none; cursor:pointer; color:#fff; font-size:15px; line-height:1; padding:0; opacity:0.6; }
|
|
@@ -6989,6 +7779,86 @@
|
|
|
6989
7779
|
.trans-check { width:18px; height:18px; accent-color:var(--accent); }
|
|
6990
7780
|
.trans-help { font-size:11px; line-height:1.45; color:rgba(255,255,255,0.55); }
|
|
6991
7781
|
.trans-help.center { text-align:center; margin-top:4px; }
|
|
7782
|
+
/* NexusSync subtitles: soft plate, generous line height, clear of the controls. */
|
|
7783
|
+
.nx-xsub { position:absolute; left:50%; bottom:9%; transform:translateX(-50%); width:min(92%, 1100px); display:flex; flex-direction:column; align-items:center; gap:4px; z-index:66; pointer-events:none; opacity:0; transition:opacity 0.18s ease, bottom 0.3s ease; --xs:1; }
|
|
7784
|
+
.nx-xsub.on { opacity:1; }
|
|
7785
|
+
.nx-xsub-line.l1 { color:#ffe98a; }
|
|
7786
|
+
.nx-xsub-line.l2 { color:#9be7ff; font-size:calc(clamp(13px, 2.2cqw, 28px) * var(--xs)); }
|
|
7787
|
+
.nexus-container.cinema-nexus:not(.chrome-idle) .nx-xsub { bottom:calc(104px + env(safe-area-inset-bottom, 0px)); }
|
|
7788
|
+
.nx-xsub-line { display:inline-block; max-width:100%; padding:0.12em 0.55em; border-radius:0.35em; background:rgba(8,10,14,0.62); color:#fff; text-align:center; white-space:pre-line; overflow-wrap:anywhere;
|
|
7789
|
+
font:600 calc(clamp(15px, 2.6cqw, 34px) * var(--xs)) / 1.32 system-ui, -apple-system, "Apple SD Gothic Neo", "Pretendard", "Segoe UI", sans-serif; letter-spacing:0.01em; text-shadow:0 1px 2px rgba(0,0,0,0.85), 0 0 8px rgba(0,0,0,0.35); }
|
|
7790
|
+
.nx-sub-suggest { position:absolute; right:calc(16px + env(safe-area-inset-right, 0px)); bottom:calc(112px + env(safe-area-inset-bottom, 0px)); z-index:75; border:1px solid rgba(255,255,255,0.18); border-radius:99px; padding:8px 14px; background:rgba(16,20,26,0.82); color:#fff; font:inherit; font-size:13px; font-weight:700; cursor:pointer; opacity:0; transform:translateY(8px); transition:opacity 0.3s ease, transform 0.3s ease; pointer-events:auto; }
|
|
7791
|
+
.nx-sub-suggest.in { opacity:1; transform:none; }
|
|
7792
|
+
.cc-menu-adjust, .cc-slider { display:flex; align-items:center; gap:8px; padding:6px 10px; font-size:12.5px; }
|
|
7793
|
+
.cc-adj-label { flex:1; opacity:0.8; white-space:nowrap; }
|
|
7794
|
+
.cc-adj { width:auto !important; padding:4px 9px !important; background:rgba(255,255,255,0.1) !important; border-radius:7px !important; font-variant-numeric:tabular-nums; }
|
|
7795
|
+
.cc-adj-val { min-width:46px; text-align:center; font-variant-numeric:tabular-nums; font-weight:700; }
|
|
7796
|
+
.cc-slider input { width:110px; accent-color:var(--cc-accent); }
|
|
7797
|
+
.cc-menu-note { font-size:11.5px; opacity:0.6; padding:4px 10px 6px; max-width:240px; }
|
|
7798
|
+
.os-body { gap:8px; }
|
|
7799
|
+
.os-row { display:grid; grid-template-columns:1fr 1fr 1.4fr; gap:6px; }
|
|
7800
|
+
.os-tmdb { display:flex; flex-wrap:wrap; gap:5px; align-items:center; }
|
|
7801
|
+
.os-tmdb:empty { display:none; }
|
|
7802
|
+
.os-tmdb-label { font-size:10.5px; font-weight:800; opacity:0.6; letter-spacing:0.5px; }
|
|
7803
|
+
.os-chip { border:1px solid rgba(255,255,255,0.16); border-radius:99px; padding:4px 10px; background:rgba(255,255,255,0.06); color:inherit; font:inherit; font-size:12px; cursor:pointer; }
|
|
7804
|
+
.os-chip.on { border-color:var(--accent); background:var(--glass-active); }
|
|
7805
|
+
.os-results { display:flex; flex-direction:column; gap:4px; max-height:min(46vh, 380px); overflow-y:auto; }
|
|
7806
|
+
.os-item { display:flex; flex-direction:column; align-items:flex-start; gap:2px; text-align:left; padding:8px 10px; border-radius:10px; border:0; background:rgba(255,255,255,0.06); color:inherit; font:inherit; cursor:pointer; }
|
|
7807
|
+
.os-item:hover { background:rgba(255,255,255,0.12); }
|
|
7808
|
+
.os-item.busy { opacity:0.6; }
|
|
7809
|
+
.os-name { font-size:12.5px; font-weight:700; word-break:break-all; }
|
|
7810
|
+
.os-meta { font-size:11px; opacity:0.65; }
|
|
7811
|
+
.tune-body { gap:7px; }
|
|
7812
|
+
.tune-src { padding:8px 10px; border-radius:10px; font-size:12.5px; font-weight:700; background:rgba(255,255,255,0.08); }
|
|
7813
|
+
.tune-src[data-kind="same"] { background:rgba(0,230,118,0.16); }
|
|
7814
|
+
.tune-src[data-kind="different"] { background:rgba(255,202,40,0.18); }
|
|
7815
|
+
/* Same source: the room's own frame-level sync does it all; the version tools step back. */
|
|
7816
|
+
.tune-ver { display:flex; flex-direction:column; gap:7px; }
|
|
7817
|
+
.tune-body.same .tune-ver { display:none; }
|
|
7818
|
+
.tune-off { display:flex; align-items:baseline; gap:10px; }
|
|
7819
|
+
.tune-off-val { font-size:24px; font-weight:800; font-variant-numeric:tabular-nums; color:var(--accent); }
|
|
7820
|
+
.tune-off-desc { font-size:12px; opacity:0.75; }
|
|
7821
|
+
.tune-nudges { display:grid; grid-template-columns:repeat(6, 1fr); gap:4px; }
|
|
7822
|
+
.tune-nudges .btn { padding:8px 0; font-variant-numeric:tabular-nums; }
|
|
7823
|
+
.tune-tools { display:grid; grid-template-columns:2fr 1fr; gap:6px; }
|
|
7824
|
+
.tune-pics { display:grid; grid-template-columns:1fr 1fr; gap:6px; }
|
|
7825
|
+
.tune-pic { position:relative; aspect-ratio:16/9; border-radius:10px; overflow:hidden; background:#000; border:1px solid rgba(255,255,255,0.12); }
|
|
7826
|
+
.tune-pic img { width:100%; height:100%; object-fit:cover; display:block; }
|
|
7827
|
+
.tune-ph { position:absolute; inset:0; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:4px; background:linear-gradient(135deg, #1d2430, #11151c); text-align:center; padding:6px; }
|
|
7828
|
+
.tune-ph-time { font-size:22px; font-weight:800; font-variant-numeric:tabular-nums; letter-spacing:0.5px; }
|
|
7829
|
+
.tune-ph-note { font-size:10.5px; opacity:0.65; line-height:1.3; }
|
|
7830
|
+
.tune-diff { font-size:12.5px; font-weight:700; text-align:center; min-height:16px; }
|
|
7831
|
+
.tune-cap { position:absolute; left:0; right:0; bottom:0; padding:3px 6px; font-size:11px; font-weight:700; background:linear-gradient(transparent, rgba(0,0,0,0.75)); }
|
|
7832
|
+
.nx-bm { gap:8px; }
|
|
7833
|
+
.nx-bm-list { display:flex; flex-direction:column; gap:5px; max-height:min(52vh, 420px); overflow-y:auto; }
|
|
7834
|
+
.nx-bm-item { display:flex; align-items:stretch; gap:4px; }
|
|
7835
|
+
.nx-bm-link { flex:1; min-width:0; display:grid; grid-template-columns:auto 1fr; column-gap:8px; row-gap:1px; padding:7px 9px; border-radius:10px; background:rgba(255,255,255,0.06); color:inherit; text-decoration:none; }
|
|
7836
|
+
.nx-bm-link:hover { background:rgba(255,255,255,0.12); }
|
|
7837
|
+
.nx-bm-time, .nx-bm-live { grid-row:span 2; align-self:center; font-variant-numeric:tabular-nums; font-weight:800; font-size:12px; color:var(--accent); }
|
|
7838
|
+
.nx-bm-live { color:#ff5252; }
|
|
7839
|
+
.nx-bm-title { font-size:12.5px; font-weight:700; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
|
7840
|
+
.nx-bm-meta { font-size:11px; opacity:0.6; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
|
7841
|
+
.nx-bm-act { width:34px; border:0; border-radius:9px; background:rgba(255,255,255,0.06); color:inherit; cursor:pointer; font-size:13px; padding:0; }
|
|
7842
|
+
.nx-settings { gap:8px; }
|
|
7843
|
+
.nx-set-sec { border:1px solid rgba(255,255,255,0.1); border-radius:12px; background:rgba(0,0,0,0.16); padding:2px 10px; }
|
|
7844
|
+
.nx-set-sec[open] { padding-bottom:10px; }
|
|
7845
|
+
.nx-set-head { cursor:pointer; font-weight:800; font-size:13px; padding:9px 0; list-style:none; }
|
|
7846
|
+
.nx-set-head::-webkit-details-marker { display:none; }
|
|
7847
|
+
.nx-set-head::after { content:'▾'; float:right; opacity:0.6; }
|
|
7848
|
+
.nx-set-sec[open] > .nx-set-head::after { content:'▴'; }
|
|
7849
|
+
.nx-set-sec > :not(summary) { margin-top:6px; }
|
|
7850
|
+
.nx-set-row { display:flex; align-items:center; justify-content:space-between; gap:10px; font-size:12.5px; padding:4px 0; }
|
|
7851
|
+
.nx-av-row, .nx-react-pal { display:flex; flex-wrap:wrap; gap:4px; }
|
|
7852
|
+
.nx-av, .nx-react-pick { width:34px; height:34px; border-radius:9px; border:1px solid rgba(255,255,255,0.12); background:rgba(255,255,255,0.06); font-size:18px; cursor:pointer; padding:0; color:inherit; }
|
|
7853
|
+
.nx-av.on { border-color:var(--accent); background:var(--glass-active); }
|
|
7854
|
+
.nx-react-slots { display:grid; grid-template-columns:repeat(8, 1fr); gap:4px; }
|
|
7855
|
+
.nx-slot-row { display:grid; grid-template-columns:1fr 1fr; gap:6px; }
|
|
7856
|
+
.nx-react-slot { height:40px; border-radius:10px; border:1px solid rgba(255,255,255,0.14); background:rgba(255,255,255,0.08); font-size:20px; cursor:pointer; padding:0; }
|
|
7857
|
+
.nx-react-slot.on { border-color:var(--accent); box-shadow:0 0 0 2px rgba(0,230,118,0.35); }
|
|
7858
|
+
.nx-people { display:flex; flex-direction:column; gap:4px; }
|
|
7859
|
+
.nx-person { display:flex; align-items:center; gap:8px; font-size:12.5px; }
|
|
7860
|
+
.nx-person .btn { width:auto; margin-left:auto; }
|
|
7861
|
+
.nx-person-name { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
|
6992
7862
|
.seg { display:flex; gap:6px; }
|
|
6993
7863
|
.seg-btn { flex:1; min-height:38px; padding:8px 6px; border-radius:10px; border:1px solid rgba(255,255,255,0.16); background:rgba(255,255,255,0.06); color:inherit; font:inherit; font-size:13px; font-weight:700; cursor:pointer; }
|
|
6994
7864
|
.seg-btn.on { background:rgba(124,77,255,0.38); border-color:rgba(160,130,255,0.95); }
|
|
@@ -7278,8 +8148,10 @@
|
|
|
7278
8148
|
.cc-btn:hover { background:rgba(255,255,255,0.14); }
|
|
7279
8149
|
.cc-btn:active { transform:scale(0.92); }
|
|
7280
8150
|
.cc-btn:focus-visible { outline:2px solid var(--cc-accent); outline-offset:1px; }
|
|
7281
|
-
|
|
7282
|
-
.cc-btn.on
|
|
8151
|
+
/* On / off at a glance: an "on" button gets the accent colour, a tinted pill and a bar. */
|
|
8152
|
+
.cc-btn.on { color:var(--cc-accent); background:color-mix(in srgb, var(--cc-accent) 22%, transparent); }
|
|
8153
|
+
.cc-btn.on::after { content:''; position:absolute; left:50%; bottom:3px; width:16px; height:3px; margin-left:-8px; border-radius:2px; background:var(--cc-accent); box-shadow:0 0 6px var(--cc-accent); }
|
|
8154
|
+
.cc-btn:not(.on) { opacity:0.92; }
|
|
7283
8155
|
.cc-sub.on::after { display:none; }
|
|
7284
8156
|
.cc-rate { min-width:46px; font-variant-numeric:tabular-nums; font-size:13px; }
|
|
7285
8157
|
.cc-rate.on { color:#fff; background:rgba(0,230,118,0.22); }
|
|
@@ -7409,6 +8281,7 @@
|
|
|
7409
8281
|
const fab = createEl('button', 'fab', '⚙️', { title: 'NexusSync' });
|
|
7410
8282
|
const reactPill = createEl('div');
|
|
7411
8283
|
reactPill.id = 'reaction-pill';
|
|
8284
|
+
CONFIG.emojis = REACTIONS.list();
|
|
7412
8285
|
CONFIG.emojis.forEach(emoji => {
|
|
7413
8286
|
const btn = createEl('button', 'react-btn', emoji);
|
|
7414
8287
|
btn.onclick = () => { pressFx(btn, emoji); handleLocalReactionClick(emoji); };
|
|
@@ -7451,15 +8324,17 @@
|
|
|
7451
8324
|
const btnChat = mk('', '💬 ' + t('talkMenu'));
|
|
7452
8325
|
const btnTranslate = mk('', '🌐 ' + t('aiSub'), t('aiSubTitle'));
|
|
7453
8326
|
const btnSubLog = mk('', '📝 ' + t('subLog'));
|
|
8327
|
+
const btnChatLog = mk('nxu-chat-log', '💬 ' + t('chatLog'));
|
|
7454
8328
|
const btnDebug = mk('', '🐛 ' + t('debug'));
|
|
7455
8329
|
const btnHideSite = createEl('button', 'btn subtle', '🙈 ' + t('hideOnSite'), { title: t('hideOnSiteTitle') });
|
|
8330
|
+
const btnSettings = mk('nxu-settings', '⚙️ ' + t('settings'));
|
|
7456
8331
|
[btnLink, btnSyncStatus, btnInvite, btnCinema, btnPiP, btnRate, btnDraw, btnBookmark, btnChat].forEach(b => { b.style.display = 'none'; });
|
|
7457
8332
|
btnSubLog.style.display = 'none';
|
|
7458
8333
|
|
|
7459
8334
|
// Chat panel
|
|
7460
8335
|
const chatPanel = createEl('div', 'window-frame');
|
|
7461
8336
|
chatPanel.id = 'chat-panel';
|
|
7462
|
-
const chatHeader = createWindowHeader('💬 ' + t('
|
|
8337
|
+
const chatHeader = createWindowHeader('💬 ' + t('chatLog'), [{ className: 'close-btn chat-tr-btn', text: '🌐', title: t('chatTrOn') }, { className: 'close-btn chat-export-btn', text: '💾', title: t('export') }, { className: 'close-btn chat-clear-btn', text: '🧹', title: t('clear') }, { className: 'close-btn chat-close-btn', text: '✖' }]);
|
|
7463
8338
|
const chatMessages = createEl('div');
|
|
7464
8339
|
chatMessages.id = 'chat-messages';
|
|
7465
8340
|
const nickRow = createEl('div', 'nick-row');
|
|
@@ -7488,7 +8363,9 @@
|
|
|
7488
8363
|
quickRow.appendChild(chip);
|
|
7489
8364
|
});
|
|
7490
8365
|
const chatJumpBtn = createEl('button', 'jump-btn', '↓ ' + t('newMessages'));
|
|
7491
|
-
|
|
8366
|
+
// The chat window is a history (like the subtitle log): reading, translating, saving.
|
|
8367
|
+
// Writing happens in the speech bubbles (💬 in the reaction bar, or Enter).
|
|
8368
|
+
chatPanel.append(chatHeader, chatMessages, typingRow, chatJumpBtn);
|
|
7492
8369
|
|
|
7493
8370
|
// Subtitle history panel
|
|
7494
8371
|
const subLogPanel = createEl('div', 'window-frame');
|
|
@@ -7546,7 +8423,29 @@
|
|
|
7546
8423
|
idleVal.textContent = idleSlider.value + 's';
|
|
7547
8424
|
idleSlider.addEventListener('input', () => { idleVal.textContent = idleSlider.value + 's'; STORE.set('nxu_idle_timeout', +idleSlider.value); });
|
|
7548
8425
|
idleRow.append(createEl('span', '', '⏱️ ' + t('uiHide')), idleSlider, idleVal, createEl('span', '', 'v' + NXU_VERSION, { style: 'margin-left:6px;opacity:0.6;' }));
|
|
7549
|
-
debugPanel.append(debugHeader,
|
|
8426
|
+
debugPanel.append(debugHeader, debugContent, debugJumpBtn);
|
|
8427
|
+
|
|
8428
|
+
// Sync timing (offset between different versions of a movie)
|
|
8429
|
+
const tunePanel = createEl('div', 'window-frame');
|
|
8430
|
+
tunePanel.id = 'tune-panel';
|
|
8431
|
+
const tuneHeader = createWindowHeader('🎯 ' + t('tuneTitle'), [{ className: 'close-btn', text: '✖' }]);
|
|
8432
|
+
tunePanel.append(tuneHeader, TUNE.build());
|
|
8433
|
+
const btnTune = mk('nxu-tune', '🎯 ' + t('tuneMenu'));
|
|
8434
|
+
btnTune.style.display = 'none';
|
|
8435
|
+
|
|
8436
|
+
// Find subtitles (OpenSubtitles)
|
|
8437
|
+
const osPanel = createEl('div', 'window-frame');
|
|
8438
|
+
osPanel.id = 'os-panel';
|
|
8439
|
+
const osHeader = createWindowHeader('💬 ' + t('osTitle'), [{ className: 'close-btn', text: '✖' }]);
|
|
8440
|
+
osPanel.append(osHeader, OPENSUBS.build());
|
|
8441
|
+
|
|
8442
|
+
|
|
8443
|
+
// Settings (things that are set once live here, not in the menu)
|
|
8444
|
+
const settingsModal = createEl('div', 'window-frame');
|
|
8445
|
+
settingsModal.id = 'settings-modal';
|
|
8446
|
+
const settingsHeader = createWindowHeader('⚙️ ' + t('settings'), [{ className: 'close-btn', text: '✖' }]);
|
|
8447
|
+
const settingsBody = buildSettingsPanel({ autoCinema: btnAutoCinema, adGuard: btnAdGuard, subLog: btnSubLog, chatLog: btnChatLog, debug: btnDebug, idleRow, hideSite: btnHideSite });
|
|
8448
|
+
settingsModal.append(settingsHeader, settingsBody);
|
|
7550
8449
|
|
|
7551
8450
|
const drawCanvas = createEl('canvas');
|
|
7552
8451
|
drawCanvas.id = 'draw-canvas';
|
|
@@ -7555,9 +8454,11 @@
|
|
|
7555
8454
|
toast.setAttribute('role', 'status');
|
|
7556
8455
|
|
|
7557
8456
|
// Sketching and chat live in the reaction bar (🖍️ 💬); the menu does not repeat them.
|
|
7558
|
-
|
|
8457
|
+
// The menu keeps only what is used while watching; speed and PiP live in the cinema
|
|
8458
|
+
// controls, and everything that is set once lives in ⚙️ Settings.
|
|
8459
|
+
dock.append(btnFindMedia, btnLink, btnInvite, btnTune, btnCinema, btnTranslate, btnSettings);
|
|
7559
8460
|
uiWrapper.append(dock, reactPill, fab);
|
|
7560
|
-
nexusContainer.append(drawCanvas, uiWrapper, chatPanel, subLogPanel, manualModal, transModal, toast, debugPanel);
|
|
8461
|
+
nexusContainer.append(drawCanvas, uiWrapper, chatPanel, subLogPanel, manualModal, transModal, settingsModal, tunePanel, osPanel, toast, debugPanel);
|
|
7561
8462
|
shadow.appendChild(nexusContainer);
|
|
7562
8463
|
promoteHost();
|
|
7563
8464
|
|
|
@@ -7567,7 +8468,7 @@
|
|
|
7567
8468
|
|
|
7568
8469
|
uiElements = {
|
|
7569
8470
|
uiWrapper, fab, reactPill, dock, btnFindMedia, btnLink, btnSyncStatus, btnTranslate, btnCinema, btnAutoCinema, btnPiP, btnRate, btnDraw, btnBookmark, btnChat, btnSubLog,
|
|
7570
|
-
btnDebug, btnHideSite, chatPanel, chatMessages, chatInput, chatJumpBtn, subLogPanel, subLogMessages,
|
|
8471
|
+
btnDebug, btnHideSite, btnSettings, settingsModal, btnTune, tunePanel, chatPanel, chatMessages, chatInput, chatJumpBtn, subLogPanel, subLogMessages,
|
|
7571
8472
|
subLogJumpBtn, drawCanvas, manualModal, transModal, toast, debugJumpBtn, syncBubble: null,
|
|
7572
8473
|
pinError, guestInput, pinHint, pinDisplay, pinCopyBtn, hostBtn, connectBtn, btnInvite, typingRow, nickInput
|
|
7573
8474
|
};
|
|
@@ -7577,9 +8478,9 @@
|
|
|
7577
8478
|
attachJumpLogic(subLogMessages, subLogJumpBtn);
|
|
7578
8479
|
attachJumpLogic(debugContent, debugJumpBtn);
|
|
7579
8480
|
makeDraggable(uiWrapper, fab);
|
|
7580
|
-
[[chatPanel, chatHeader], [subLogPanel, subLogHeader], [manualModal, manualHeader], [transModal, transHeader], [debugPanel, debugHeader]]
|
|
8481
|
+
[[chatPanel, chatHeader], [subLogPanel, subLogHeader], [manualModal, manualHeader], [transModal, transHeader], [settingsModal, settingsHeader], [tunePanel, tuneHeader], [osPanel, osHeader], [debugPanel, debugHeader]]
|
|
7581
8482
|
.forEach(([panel, header]) => makePanelDraggable(panel, header));
|
|
7582
|
-
[chatPanel, subLogPanel, debugPanel, transModal].forEach(panel => PANEL_SIZE.attach(panel));
|
|
8483
|
+
[chatPanel, subLogPanel, debugPanel, transModal, settingsModal, tunePanel, osPanel].forEach(panel => PANEL_SIZE.attach(panel));
|
|
7583
8484
|
|
|
7584
8485
|
shadow.querySelectorAll('.window-frame').forEach(panel => {
|
|
7585
8486
|
const pinBtn = panel.querySelector('.pin-btn');
|
|
@@ -7597,6 +8498,23 @@
|
|
|
7597
8498
|
chatMessages.querySelectorAll('.chat-msg:not(.mine) .chat-text').forEach(el => CHAT_TR.applyTo(el));
|
|
7598
8499
|
};
|
|
7599
8500
|
chatHeader.querySelector('.chat-close-btn').onclick = () => { STATE.chatActive = false; closePanel(chatPanel); btnChat.classList.remove('active'); };
|
|
8501
|
+
btnChatLog.onclick = () => { STATE.chatActive = true; openPanel(chatPanel); DOM_UTILS.forceScroll(chatMessages, chatJumpBtn); };
|
|
8502
|
+
chatHeader.querySelector('.chat-clear-btn').onclick = () => { chatMessages.replaceChildren(); showToast(t('chatCleared')); };
|
|
8503
|
+
chatHeader.querySelector('.chat-export-btn').onclick = () => {
|
|
8504
|
+
let text = 'NexusSync Chat\n==============\n\n';
|
|
8505
|
+
Array.from(chatMessages.children).forEach(row => {
|
|
8506
|
+
const who = row.querySelector('.chat-name')?.textContent || '';
|
|
8507
|
+
const at = row.querySelector('.chat-clock')?.textContent || '';
|
|
8508
|
+
const body = row.querySelector('.chat-text');
|
|
8509
|
+
text += `[${at}] ${who}: ${body?.dataset.orig || body?.textContent || ''}\n`;
|
|
8510
|
+
});
|
|
8511
|
+
const url = URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' }));
|
|
8512
|
+
const a = document.createElement('a');
|
|
8513
|
+
a.href = url;
|
|
8514
|
+
a.download = `NexusSync_Chat_${new Date().toISOString().replace(/[:T-]/g, '').slice(0, 14)}.txt`;
|
|
8515
|
+
document.body.appendChild(a); a.click(); a.remove();
|
|
8516
|
+
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
|
8517
|
+
};
|
|
7600
8518
|
subLogHeader.querySelector('.btn-close-log').onclick = () => { STATE.subLogActive = false; closePanel(subLogPanel); btnSubLog.classList.remove('active'); };
|
|
7601
8519
|
subLogHeader.querySelector('.btn-clear-log').onclick = () => { subLogMessages.replaceChildren(); showToast(t('logCleared')); };
|
|
7602
8520
|
subLogHeader.querySelector('.btn-export-log').onclick = () => {
|
|
@@ -7625,6 +8543,11 @@
|
|
|
7625
8543
|
};
|
|
7626
8544
|
|
|
7627
8545
|
btnTranslate.onclick = () => { updateAIBtnUX(); openPanel(transModal); };
|
|
8546
|
+
btnSettings.onclick = () => { settingsBody.refreshPeople?.(); openPanel(settingsModal); };
|
|
8547
|
+
btnTune.onclick = () => TUNE.open();
|
|
8548
|
+
tuneHeader.querySelector('.close-btn').onclick = () => closePanel(tunePanel);
|
|
8549
|
+
osHeader.querySelector('.close-btn').onclick = () => closePanel(osPanel);
|
|
8550
|
+
settingsHeader.querySelector('.close-btn').onclick = () => closePanel(settingsModal);
|
|
7628
8551
|
shadow.getElementById('stt-toggle').onclick = () => { TRANSLATOR.toggle(); if (TRANSLATOR.state !== 'idle') closePanel(transModal); };
|
|
7629
8552
|
|
|
7630
8553
|
btnChat.onclick = () => {
|
|
@@ -7930,7 +8853,7 @@
|
|
|
7930
8853
|
function sendChatMessage(text) {
|
|
7931
8854
|
if (!yChat) return;
|
|
7932
8855
|
const info = currentMediaInfo();
|
|
7933
|
-
yChat.push([{ sender: STATE.userId, color: STATE.color, text: text.slice(0, 500), videoTime: info && Number.isFinite(info.time) ? info.time : null, nick: STATE.nickname || null, ts: Date.now() }]);
|
|
8856
|
+
yChat.push([{ sender: STATE.userId, color: STATE.color, text: text.slice(0, 500), videoTime: info && Number.isFinite(info.time) ? info.time : null, nick: STATE.nickname || null, av: PROFILE.avatar() || null, ts: Date.now() }]);
|
|
7934
8857
|
}
|
|
7935
8858
|
|
|
7936
8859
|
function appendChatMessage(msg) {
|
|
@@ -7938,7 +8861,8 @@
|
|
|
7938
8861
|
const color = /^(#[0-9a-f]{3,8}|hsl\([\d., %]+\))$/i.test(msg.color || '') ? msg.color : '#69f0ae';
|
|
7939
8862
|
const row = createEl('div', 'chat-msg' + (msg.sender === STATE.userId ? ' mine' : ''));
|
|
7940
8863
|
row.style.borderLeft = `4px solid ${color}`;
|
|
7941
|
-
const
|
|
8864
|
+
const av = safeAvatar(msg.av);
|
|
8865
|
+
const name = createEl('span', 'chat-name', (av ? av + ' ' : '') + ((msg.nick && String(msg.nick).trim().slice(0, 16)) || ('ID:' + String(msg.sender || '').substring(0, 3))));
|
|
7942
8866
|
name.style.color = color;
|
|
7943
8867
|
row.appendChild(name);
|
|
7944
8868
|
if (msg.ts) {
|
|
@@ -8007,6 +8931,122 @@
|
|
|
8007
8931
|
}
|
|
8008
8932
|
|
|
8009
8933
|
// ───────────────────────── My profile (name + colour shown to others)
|
|
8934
|
+
// One emoji (a single grapheme that is a pictograph), or ''.
|
|
8935
|
+
function safeEmoji(s) {
|
|
8936
|
+
const str = String(s || '').trim();
|
|
8937
|
+
if (!str) return '';
|
|
8938
|
+
let first = str;
|
|
8939
|
+
try { if (typeof Intl !== 'undefined' && Intl.Segmenter) first = [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(str)][0]?.segment || ''; else first = Array.from(str).slice(0, 2).join(''); } catch (_) { first = Array.from(str)[0] || ''; }
|
|
8940
|
+
return first.length <= 16 && /\p{Extended_Pictographic}|\p{Regional_Indicator}/u.test(first) ? first : '';
|
|
8941
|
+
}
|
|
8942
|
+
|
|
8943
|
+
// An avatar: one emoji, or one or two letters/digits (initials).
|
|
8944
|
+
function safeAvatar(s) {
|
|
8945
|
+
const e = safeEmoji(s);
|
|
8946
|
+
if (e) return e;
|
|
8947
|
+
const str = String(s || '').trim();
|
|
8948
|
+
return /^[\p{L}\p{N}]{1,2}$/u.test(str) ? str.toUpperCase() : '';
|
|
8949
|
+
}
|
|
8950
|
+
|
|
8951
|
+
// Photo avatars of the others: announced by a short fingerprint in presence, fetched
|
|
8952
|
+
// once by message, kept for the session.
|
|
8953
|
+
const AVATAR_IMG = {
|
|
8954
|
+
cache: new Map(), // uid → { h, img }
|
|
8955
|
+
_asked: new Map(),
|
|
8956
|
+
get(uid) {
|
|
8957
|
+
if (uid === STATE.userId) return PROFILE.image();
|
|
8958
|
+
const want = STATE.presenceMap?.[uid]?.avh || STATE.sleepingMap?.[uid]?.avh || '';
|
|
8959
|
+
const c = this.cache.get(uid);
|
|
8960
|
+
if (!want) return '';
|
|
8961
|
+
if (c && c.h === want) return c.img;
|
|
8962
|
+
if (Date.now() - (this._asked.get(uid + want) || 0) > 20000) { this._asked.set(uid + want, Date.now()); SOCIAL.send('avatar', { op: 'req', who: uid }); }
|
|
8963
|
+
return '';
|
|
8964
|
+
},
|
|
8965
|
+
mine() { const img = PROFILE.image(); if (img && SOCIAL.live()) SOCIAL.send('avatar', { op: 'img', h: PROFILE.imageHash(), img }); },
|
|
8966
|
+
onRemote(d) {
|
|
8967
|
+
if (d.op === 'req' && d.who === STATE.userId) { if (Date.now() - (this._sentAt || 0) > 5000) { this._sentAt = Date.now(); this.mine(); } return; }
|
|
8968
|
+
if (d.op === 'img' && typeof d.img === 'string' && /^data:image\/jpeg;base64,[A-Za-z0-9+/=]+$/.test(d.img) && d.img.length < 40000 && typeof d.h === 'string') {
|
|
8969
|
+
this.cache.set(d.uid, { h: d.h, img: d.img });
|
|
8970
|
+
updatePresenceUI();
|
|
8971
|
+
}
|
|
8972
|
+
}
|
|
8973
|
+
};
|
|
8974
|
+
|
|
8975
|
+
// What reaches this device from the others, and from whom: kinds of events can be turned
|
|
8976
|
+
// off, a person can be muted for this room, and floods of reactions are thinned out.
|
|
8977
|
+
const SAFETY = {
|
|
8978
|
+
KINDS: ['react', 'nudge', 'ink', 'chat', 'ping'],
|
|
8979
|
+
muted: new Set(),
|
|
8980
|
+
receive(kind) { return STORE.get('nxu_recv_' + kind, true) !== false; },
|
|
8981
|
+
set(kind, on) { STORE.set('nxu_recv_' + kind, !!on); },
|
|
8982
|
+
allows(uid, kind) {
|
|
8983
|
+
if (uid && this.muted.has(uid)) return false;
|
|
8984
|
+
return !kind || this.receive(kind);
|
|
8985
|
+
},
|
|
8986
|
+
toggleMute(uid) { if (this.muted.has(uid)) this.muted.delete(uid); else this.muted.add(uid); },
|
|
8987
|
+
_rate: new Map(),
|
|
8988
|
+
// More than 6 reactions a second from one person: the rest are not shown.
|
|
8989
|
+
flood(uid, max = 6) {
|
|
8990
|
+
const now = Date.now();
|
|
8991
|
+
const list = (this._rate.get(uid) || []).filter(ts => now - ts < 1000);
|
|
8992
|
+
list.push(now);
|
|
8993
|
+
this._rate.set(uid, list);
|
|
8994
|
+
if (this._rate.size > 50) this._rate.delete(this._rate.keys().next().value);
|
|
8995
|
+
return list.length > max;
|
|
8996
|
+
}
|
|
8997
|
+
};
|
|
8998
|
+
|
|
8999
|
+
// The eight reaction buttons: the user's own choice (any emoji), or the defaults.
|
|
9000
|
+
const REACTIONS = {
|
|
9001
|
+
DEFAULT: ['😂', '😭', '😡', '💦', '🍪', '☕', '😘', '🖕'],
|
|
9002
|
+
MAX: 16,
|
|
9003
|
+
list() {
|
|
9004
|
+
const saved = STORE.get('nxu_reactions', null);
|
|
9005
|
+
if (!Array.isArray(saved) || !saved.length) return this.DEFAULT.slice();
|
|
9006
|
+
const arr = saved.slice(0, this.MAX).map(safeEmoji);
|
|
9007
|
+
return arr.map((e, i) => e || this.DEFAULT[i % this.DEFAULT.length]);
|
|
9008
|
+
},
|
|
9009
|
+
set(i, emoji) {
|
|
9010
|
+
const list = this.list();
|
|
9011
|
+
const e = safeEmoji(emoji);
|
|
9012
|
+
if (!e || i < 0 || i >= list.length) return false;
|
|
9013
|
+
list[i] = e;
|
|
9014
|
+
STORE.set('nxu_reactions', list);
|
|
9015
|
+
this.apply();
|
|
9016
|
+
return true;
|
|
9017
|
+
},
|
|
9018
|
+
add() {
|
|
9019
|
+
const list = this.list();
|
|
9020
|
+
if (list.length >= this.MAX) return -1;
|
|
9021
|
+
const spare = ['❤️', '🔥', '👏', '😱', '👀', '🎉', '🤔', '💯'].find(x => !list.includes(x)) || '⭐';
|
|
9022
|
+
list.push(spare);
|
|
9023
|
+
STORE.set('nxu_reactions', list);
|
|
9024
|
+
this.apply();
|
|
9025
|
+
return list.length - 1;
|
|
9026
|
+
},
|
|
9027
|
+
remove(i) {
|
|
9028
|
+
const list = this.list();
|
|
9029
|
+
if (list.length <= 1 || i < 0 || i >= list.length) return false;
|
|
9030
|
+
list.splice(i, 1);
|
|
9031
|
+
STORE.set('nxu_reactions', list);
|
|
9032
|
+
this.apply();
|
|
9033
|
+
return true;
|
|
9034
|
+
},
|
|
9035
|
+
reset() { STORE.set('nxu_reactions', null); this.apply(); },
|
|
9036
|
+
apply() {
|
|
9037
|
+
CONFIG.emojis = this.list();
|
|
9038
|
+
const pill = uiElements.reactPill;
|
|
9039
|
+
if (!pill) return;
|
|
9040
|
+
pill.querySelectorAll('.react-btn:not(.together-btn)').forEach(b => b.remove());
|
|
9041
|
+
const first = pill.firstChild;
|
|
9042
|
+
CONFIG.emojis.forEach(emoji => {
|
|
9043
|
+
const btn = createEl('button', 'react-btn', emoji);
|
|
9044
|
+
btn.onclick = () => { pressFx(btn, emoji); handleLocalReactionClick(emoji); };
|
|
9045
|
+
pill.insertBefore(btn, first);
|
|
9046
|
+
});
|
|
9047
|
+
}
|
|
9048
|
+
};
|
|
9049
|
+
|
|
8010
9050
|
const PROFILE = {
|
|
8011
9051
|
SWATCHES: ['#69f0ae', '#40c4ff', '#7c4dff', '#ff4fa3', '#ff6e40', '#ffd740', '#b2ff59', '#18ffff', '#ea80fc', '#ff8a80'],
|
|
8012
9052
|
color() {
|
|
@@ -8020,6 +9060,43 @@
|
|
|
8020
9060
|
this.publish();
|
|
8021
9061
|
shadow?.querySelectorAll('.nx-me-dot').forEach(el => el.style.setProperty('--c', c));
|
|
8022
9062
|
},
|
|
9063
|
+
// What this device announces in the room (presence): name, colour, avatar, status.
|
|
9064
|
+
value() {
|
|
9065
|
+
return { ts: Date.now(), color: STATE.color, viewer: !!STATE.isViewer, nick: STATE.nickname || '', av: this.avatar(), avh: this.imageHash(), st: this.status(), md: TUNE.mediaSig(), v: NXU_VERSION, r: NXU_RANK, sess: NXU_SESSION, hid: !!document.hidden };
|
|
9066
|
+
},
|
|
9067
|
+
AVATARS: ['🙂', '😎', '🦊', '🐱', '🐶', '🐯', '🐵', '🐼', '🐸', '🦄', '🐧', '🍿', '🎧', '🌙', '🔥', '🌸', '👾', '🤖'],
|
|
9068
|
+
avatar() { return safeAvatar(STORE.get('nxu_avatar', '')); },
|
|
9069
|
+
// A photo avatar travels once (and on request), not in every presence note.
|
|
9070
|
+
image() { const v = String(STORE.get('nxu_avatar_img', '') || ''); return /^data:image\/jpeg;base64,[A-Za-z0-9+/=]+$/.test(v) && v.length < 40000 ? v : ''; },
|
|
9071
|
+
imageHash() { const v = this.image(); if (!v) return ''; let h = 0; for (let i = 0; i < v.length; i += 7) h = (h * 31 + v.charCodeAt(i)) | 0; return (h >>> 0).toString(36) + v.length.toString(36); },
|
|
9072
|
+
setImage(dataUrl) { STORE.set('nxu_avatar_img', dataUrl || ''); AVATAR_IMG.mine(); this.publish(); updatePresenceUI(); },
|
|
9073
|
+
async pickImage() {
|
|
9074
|
+
const input = document.createElement('input');
|
|
9075
|
+
input.type = 'file'; input.accept = 'image/*';
|
|
9076
|
+
input.onchange = async () => {
|
|
9077
|
+
const f = input.files?.[0];
|
|
9078
|
+
if (!f) return;
|
|
9079
|
+
try {
|
|
9080
|
+
const url = URL.createObjectURL(f);
|
|
9081
|
+
const img = await new Promise((res, rej) => { const i = new Image(); i.onload = () => res(i); i.onerror = rej; i.src = url; });
|
|
9082
|
+
const c = document.createElement('canvas'); c.width = c.height = 96;
|
|
9083
|
+
const s = Math.min(img.naturalWidth, img.naturalHeight);
|
|
9084
|
+
c.getContext('2d').drawImage(img, (img.naturalWidth - s) / 2, (img.naturalHeight - s) / 2, s, s, 0, 0, 96, 96);
|
|
9085
|
+
URL.revokeObjectURL(url);
|
|
9086
|
+
let q = 0.82, out = c.toDataURL('image/jpeg', q);
|
|
9087
|
+
while (out.length > 30000 && q > 0.4) { q -= 0.12; out = c.toDataURL('image/jpeg', q); }
|
|
9088
|
+
this.setImage(out);
|
|
9089
|
+
this._onImage?.();
|
|
9090
|
+
} catch (_) { showToast(t('setAvatarFail')); }
|
|
9091
|
+
};
|
|
9092
|
+
input.click();
|
|
9093
|
+
},
|
|
9094
|
+
status() { return String(STORE.get('nxu_status', '') || '').replace(/\s+/g, ' ').trim().slice(0, 40); },
|
|
9095
|
+
setAvatar(a) { STORE.set('nxu_avatar', safeAvatar(a)); this.publish(); updatePresenceUI(); },
|
|
9096
|
+
setStatus(s) {
|
|
9097
|
+
STORE.set('nxu_status', String(s || '').replace(/\s+/g, ' ').slice(0, 40));
|
|
9098
|
+
clearTimeout(this._st); this._st = setTimeout(() => { this.publish(); updatePresenceUI(); }, 600);
|
|
9099
|
+
},
|
|
8023
9100
|
setName(name) {
|
|
8024
9101
|
STATE.nickname = String(name || '').trim().slice(0, 16);
|
|
8025
9102
|
STORE.set('nxu_nickname', STATE.nickname);
|
|
@@ -8029,7 +9106,7 @@
|
|
|
8029
9106
|
},
|
|
8030
9107
|
publish() {
|
|
8031
9108
|
try {
|
|
8032
|
-
if (ydoc && yPresence && STATE.handshakeVerified) ydoc.transact(() => yPresence.set(STATE.userId,
|
|
9109
|
+
if (ydoc && yPresence && STATE.handshakeVerified) ydoc.transact(() => yPresence.set(STATE.userId, this.value()), 'local');
|
|
8033
9110
|
} catch (_) { }
|
|
8034
9111
|
},
|
|
8035
9112
|
// Small editor: name + colour swatches + any colour.
|
|
@@ -8203,7 +9280,10 @@
|
|
|
8203
9280
|
const text = String(msg.text).slice(0, 200);
|
|
8204
9281
|
const card = createEl('button', 'nx-bubble nx-talk' + (mine ? ' mine' : ''), '', { type: 'button' });
|
|
8205
9282
|
card.style.setProperty('--c', color);
|
|
8206
|
-
const
|
|
9283
|
+
const av = safeAvatar(mine ? PROFILE.avatar() : (msg.av || STATE.presenceMap?.[msg.sender]?.av));
|
|
9284
|
+
const photo = AVATAR_IMG.get(mine ? STATE.userId : msg.sender);
|
|
9285
|
+
const avatar = createEl('span', 'nx-talk-avatar' + (av || photo ? ' emoji' : ''), photo ? '' : av || (Array.from(name.replace(/^ID:/, ''))[0] || '?').toUpperCase());
|
|
9286
|
+
if (photo) { avatar.style.backgroundImage = `url("${photo}")`; avatar.style.backgroundSize = 'cover'; }
|
|
8207
9287
|
const body = createEl('span', 'nx-talk-body');
|
|
8208
9288
|
body.append(createEl('span', 'nx-bubble-name', name), createEl('span', 'nx-bubble-text', text));
|
|
8209
9289
|
card.append(avatar, body);
|
|
@@ -8654,12 +9734,408 @@
|
|
|
8654
9734
|
// darker or brighter (CSS filter on the player only — subtitles and controls unchanged).
|
|
8655
9735
|
const BRIGHTNESS = {
|
|
8656
9736
|
MIN: 0.3,
|
|
8657
|
-
MAX:
|
|
9737
|
+
MAX: 2,
|
|
8658
9738
|
level: 1,
|
|
8659
|
-
|
|
9739
|
+
// A filter on the picture only while it is not at 100 % (a filtered video cannot use
|
|
9740
|
+
// the device's direct video path, which costs battery), remembered per site.
|
|
9741
|
+
set(x, { save = true } = {}) {
|
|
8660
9742
|
this.level = Math.round(Math.max(this.MIN, Math.min(this.MAX, x)) * 100) / 100;
|
|
8661
|
-
ensurePageStyle(document, 'nxu-bright-style',
|
|
9743
|
+
ensurePageStyle(document, 'nxu-bright-style', `html.nxu-bright-on .nxu-cinema-root video, html.nxu-bright-on video.nxu-cinema-root, html.nxu-bright-on iframe.nxu-cinema-root, html.nxu-bright-on .nxu-cinema-root iframe { filter: brightness(var(--nxu-bright, 1)) !important; }`);
|
|
8662
9744
|
document.documentElement.style.setProperty('--nxu-bright', String(this.level));
|
|
9745
|
+
document.documentElement.classList.toggle('nxu-bright-on', Math.abs(this.level - 1) > 0.01);
|
|
9746
|
+
if (save) { const all = { ...(STORE.get('nxu_bright', {}) || {}) }; if (Math.abs(this.level - 1) > 0.01) all[HOST] = this.level; else delete all[HOST]; STORE.set('nxu_bright', all); }
|
|
9747
|
+
},
|
|
9748
|
+
restore() { const v = Number((STORE.get('nxu_bright', {}) || {})[HOST]); if (Number.isFinite(v) && v !== 1) this.set(v, { save: false }); }
|
|
9749
|
+
};
|
|
9750
|
+
|
|
9751
|
+
// ───────────────────────── Subtitles in cinema: the video's own tracks, a file, or
|
|
9752
|
+
// OpenSubtitles — drawn by NexusSync in one consistent style, with timing and size.
|
|
9753
|
+
const SUBS = {
|
|
9754
|
+
// Up to three subtitle layers at once (e.g. Dutch + English + Korean for learning):
|
|
9755
|
+
// each is a track of the page's video or a loaded file, drawn in its own colour.
|
|
9756
|
+
layers: [], // { id, kind: 'track'|'cues', track?, cues?, label }
|
|
9757
|
+
MAX: 3,
|
|
9758
|
+
delay: 0,
|
|
9759
|
+
_box: null, _timer: 0, _last: '',
|
|
9760
|
+
size() { const v = Number(STORE.get('nxu_xsub_size', 1)); return Number.isFinite(v) ? Math.max(0.7, Math.min(1.8, v)) : 1; },
|
|
9761
|
+
tracks() {
|
|
9762
|
+
const v = STATE.video;
|
|
9763
|
+
if (!v || !v.textTracks) return [];
|
|
9764
|
+
return [...v.textTracks].filter(tr => tr.kind === 'subtitles' || tr.kind === 'captions');
|
|
9765
|
+
},
|
|
9766
|
+
active() { return this.layers.length > 0; },
|
|
9767
|
+
hasTrack(tr) { return this.layers.some(l => l.track === tr); },
|
|
9768
|
+
_ensureBox() {
|
|
9769
|
+
const c = getContainer();
|
|
9770
|
+
if (!c) return null;
|
|
9771
|
+
if (!this._box || !this._box.isConnected) { this._box = createEl('div', 'nx-xsub'); c.appendChild(this._box); }
|
|
9772
|
+
this._box.style.setProperty('--xs', String(this.size()));
|
|
9773
|
+
return this._box;
|
|
9774
|
+
},
|
|
9775
|
+
_drop(l) {
|
|
9776
|
+
if (l.track) { try { l.track.removeEventListener('cuechange', this._onCue); l.track.mode = 'disabled'; } catch (_) { } }
|
|
9777
|
+
},
|
|
9778
|
+
off() {
|
|
9779
|
+
this.layers.forEach(l => this._drop(l));
|
|
9780
|
+
this.layers = [];
|
|
9781
|
+
clearInterval(this._timer); this._timer = 0;
|
|
9782
|
+
this._render('');
|
|
9783
|
+
try { CUE_MIRROR.render(); } catch (_) { }
|
|
9784
|
+
},
|
|
9785
|
+
remove(id) {
|
|
9786
|
+
const l = this.layers.find(x => x.id === id);
|
|
9787
|
+
if (!l) return;
|
|
9788
|
+
this._drop(l);
|
|
9789
|
+
this.layers = this.layers.filter(x => x !== l);
|
|
9790
|
+
if (!this.layers.length) this.off(); else this.tick(true);
|
|
9791
|
+
},
|
|
9792
|
+
_add(layer) {
|
|
9793
|
+
while (this.layers.length >= this.MAX) { this._drop(this.layers[0]); this.layers.shift(); }
|
|
9794
|
+
layer.id = Math.random().toString(36).slice(2, 8);
|
|
9795
|
+
this.layers.push(layer);
|
|
9796
|
+
try { CUE_MIRROR.render(); } catch (_) { }
|
|
9797
|
+
this._loop();
|
|
9798
|
+
showToast(t('subLoaded', { name: layer.label }));
|
|
9799
|
+
},
|
|
9800
|
+
// A track of the video: tapping it again takes it away.
|
|
9801
|
+
useTrack(tr) {
|
|
9802
|
+
const has = this.layers.find(l => l.track === tr);
|
|
9803
|
+
if (has) { this.remove(has.id); return; }
|
|
9804
|
+
this._onCue = this._onCue || (() => this.tick());
|
|
9805
|
+
tr.mode = 'hidden'; // cues still arrive, the browser does not draw them itself
|
|
9806
|
+
tr.addEventListener('cuechange', this._onCue);
|
|
9807
|
+
this._add({ kind: 'track', track: tr, label: tr.label || tr.language || t('subTrack') });
|
|
9808
|
+
},
|
|
9809
|
+
useCues(cues, label) { this._add({ kind: 'cues', cues: cues.sort((a, b) => a.s - b.s), label }); },
|
|
9810
|
+
_loop() { clearInterval(this._timer); this._timer = setInterval(() => this.tick(), 150); this.tick(true); },
|
|
9811
|
+
setDelay(d) { this.delay = Math.round(Math.max(-120, Math.min(120, d)) * 10) / 10; this.tick(true); },
|
|
9812
|
+
_now() {
|
|
9813
|
+
const info = currentMediaInfo();
|
|
9814
|
+
if (!info) return null;
|
|
9815
|
+
let tm = info.time || 0;
|
|
9816
|
+
if (info.kind === 'iframe' && !info.paused) {
|
|
9817
|
+
const rep = VIDEO_DETECTOR.frameReports.get(info.el);
|
|
9818
|
+
if (rep?.ts) tm = (rep.currentTime || 0) + Math.min(1, (Date.now() - rep.ts) / 1000) * (rep.rate || 1);
|
|
9819
|
+
}
|
|
9820
|
+
return tm;
|
|
9821
|
+
},
|
|
9822
|
+
_textOf(l, at) {
|
|
9823
|
+
if (l.kind === 'cues') {
|
|
9824
|
+
let lo = 0, hi = l.cues.length - 1, idx = -1;
|
|
9825
|
+
while (lo <= hi) { const mid = (lo + hi) >> 1; if (l.cues[mid].s <= at) { idx = mid; lo = mid + 1; } else hi = mid - 1; }
|
|
9826
|
+
const parts = [];
|
|
9827
|
+
for (let i = idx; i >= 0 && i > idx - 4; i--) { const c = l.cues[i]; if (c.s <= at && at < c.e) parts.unshift(c.text); }
|
|
9828
|
+
return this._clean(parts.join('\n'));
|
|
9829
|
+
}
|
|
9830
|
+
const list = l.track.cues ? [...l.track.cues] : [];
|
|
9831
|
+
const act = this.delay ? list.filter(c => c.startTime <= at && at < c.endTime) : [...(l.track.activeCues || [])];
|
|
9832
|
+
return this._clean(act.map(c => (c.text || '')).join('\n'));
|
|
9833
|
+
},
|
|
9834
|
+
tick(force = false) {
|
|
9835
|
+
if (!this.active()) return;
|
|
9836
|
+
const tm = this._now();
|
|
9837
|
+
if (tm == null) return;
|
|
9838
|
+
const at = tm - this.delay;
|
|
9839
|
+
const groups = this.layers.map((l, i) => ({ i, text: this._textOf(l, at) }));
|
|
9840
|
+
const sig = groups.map(g => g.text).join('\u0001');
|
|
9841
|
+
if (!force && sig === this._last && this._box?.isConnected) return;
|
|
9842
|
+
this._last = sig;
|
|
9843
|
+
const any = groups.some(g => g.text);
|
|
9844
|
+
const box = any ? this._ensureBox() : this._box;
|
|
9845
|
+
if (!box) return;
|
|
9846
|
+
const kids = [];
|
|
9847
|
+
groups.forEach(g => { if (g.text) g.text.split('\n').filter(Boolean).slice(0, 3).forEach(line => kids.push(createEl('span', 'nx-xsub-line l' + g.i, line))); });
|
|
9848
|
+
box.replaceChildren(...kids);
|
|
9849
|
+
box.classList.toggle('on', any);
|
|
9850
|
+
},
|
|
9851
|
+
_clean(s) { return String(s || '').replace(/<[^>]+>/g, '').replace(/\{\\[^}]*\}/g, '').replace(/ /g, ' ').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').trim(); },
|
|
9852
|
+
// Plain text into the layer (the site's own subtitles, see DOM_SUBS).
|
|
9853
|
+
_render(text) {
|
|
9854
|
+
if (text === this._last && this._box?.isConnected) return;
|
|
9855
|
+
this._last = text;
|
|
9856
|
+
const box = text ? this._ensureBox() : this._box;
|
|
9857
|
+
if (!box) return;
|
|
9858
|
+
box.replaceChildren(...(text ? text.split('\n').filter(Boolean).slice(0, 4).map(line => createEl('span', 'nx-xsub-line', line)) : []));
|
|
9859
|
+
box.classList.toggle('on', !!text);
|
|
9860
|
+
},
|
|
9861
|
+
// ── parsing: SRT, WebVTT and (basic) ASS/SSA
|
|
9862
|
+
parse(text) {
|
|
9863
|
+
const src = String(text || '').replace(/^\uFEFF/, '').replace(/\r/g, '');
|
|
9864
|
+
const ts = s => { const m = s.trim().match(/(?:(\d+):)?(\d{1,2}):(\d{2})[,.](\d{1,3})/); return m ? (+(m[1] || 0)) * 3600 + (+m[2]) * 60 + (+m[3]) + (+m[4].padEnd(3, '0')) / 1000 : NaN; };
|
|
9865
|
+
const out = [];
|
|
9866
|
+
if (/^\[Script Info\]/m.test(src) || /^Dialogue:/m.test(src)) {
|
|
9867
|
+
const fmt = (src.match(/^Format:\s*(.+)$/m)?.[1] || 'Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text').split(',').map(x => x.trim().toLowerCase());
|
|
9868
|
+
const iS = fmt.indexOf('start'), iE = fmt.indexOf('end'), iT = fmt.indexOf('text');
|
|
9869
|
+
const assTs = s => { const m = s.trim().match(/(\d+):(\d{2}):(\d{2})[.](\d{1,2})/); return m ? +m[1] * 3600 + +m[2] * 60 + +m[3] + +m[4] / 100 : NaN; };
|
|
9870
|
+
src.split('\n').forEach(line => {
|
|
9871
|
+
if (!line.startsWith('Dialogue:')) return;
|
|
9872
|
+
const parts = line.slice(9).split(',');
|
|
9873
|
+
const textPart = parts.slice(iT).join(',').replace(/\\N/gi, '\n');
|
|
9874
|
+
const s = assTs(parts[iS] || ''), e = assTs(parts[iE] || '');
|
|
9875
|
+
if (Number.isFinite(s) && Number.isFinite(e)) out.push({ s, e, text: this._clean(textPart) });
|
|
9876
|
+
});
|
|
9877
|
+
return out;
|
|
9878
|
+
}
|
|
9879
|
+
src.split(/\n{2,}/).forEach(block => {
|
|
9880
|
+
const lines = block.split('\n').filter(l => l.trim() !== '');
|
|
9881
|
+
const k = lines.findIndex(l => l.includes('-->'));
|
|
9882
|
+
if (k < 0) return;
|
|
9883
|
+
const [a, b] = lines[k].split('-->');
|
|
9884
|
+
const s = ts(a), e = ts(b);
|
|
9885
|
+
const body = this._clean(lines.slice(k + 1).join('\n'));
|
|
9886
|
+
if (Number.isFinite(s) && Number.isFinite(e) && body) out.push({ s, e, text: body });
|
|
9887
|
+
});
|
|
9888
|
+
return out;
|
|
9889
|
+
},
|
|
9890
|
+
async openFile() {
|
|
9891
|
+
const input = document.createElement('input');
|
|
9892
|
+
input.type = 'file'; input.accept = '.srt,.vtt,.ass,.ssa,.sub,text/plain';
|
|
9893
|
+
input.onchange = async () => {
|
|
9894
|
+
const f = input.files?.[0];
|
|
9895
|
+
if (!f) return;
|
|
9896
|
+
const cues = this.parse(await f.text());
|
|
9897
|
+
if (cues.length) this.useCues(cues, f.name.replace(/\.[^.]+$/, '')); else showToast(t('subLoadFail'));
|
|
9898
|
+
};
|
|
9899
|
+
input.click();
|
|
9900
|
+
},
|
|
9901
|
+
// A gentle offer when cinema has nothing to read: once per page.
|
|
9902
|
+
maybeSuggest() {
|
|
9903
|
+
if (!IS_TOP || !STATE.isCinema || this.active() || DOM_SUBS._src || this._suggested === location.href) return;
|
|
9904
|
+
if (this.tracks().length || (CUE_MIRROR.box?.textContent || '').trim() || TRANSLATOR.active) return;
|
|
9905
|
+
const info = currentMediaInfo();
|
|
9906
|
+
if (!info || info.live || info.paused) return;
|
|
9907
|
+
this._suggested = location.href;
|
|
9908
|
+
const c = getContainer();
|
|
9909
|
+
if (!c) return;
|
|
9910
|
+
const chip = createEl('button', 'nx-sub-suggest', t('subSuggest'), { type: 'button' });
|
|
9911
|
+
chip.onclick = (e) => { e.stopPropagation(); chip.remove(); OPENSUBS.open(); };
|
|
9912
|
+
c.appendChild(chip);
|
|
9913
|
+
setTimeout(() => chip.classList.add('in'), 30);
|
|
9914
|
+
setTimeout(() => { chip.classList.remove('in'); setTimeout(() => chip.remove(), 400); }, 12000);
|
|
9915
|
+
}
|
|
9916
|
+
};
|
|
9917
|
+
|
|
9918
|
+
// The site's own subtitles drawn as page text (a separate subtitle file the site renders
|
|
9919
|
+
// itself, not a track of the video). With the NexusSync controls the player box is
|
|
9920
|
+
// stretched to the screen, and those lines kept their old position — often below the
|
|
9921
|
+
// visible screen on phones. Text in the player that keeps changing is recognised as
|
|
9922
|
+
// subtitles, hidden in place and shown in NexusSync's subtitle layer instead, which
|
|
9923
|
+
// always stays inside the visible screen and above the controls.
|
|
9924
|
+
const DOM_SUBS = {
|
|
9925
|
+
_obs: null, _root: null, _cands: new Map(), _src: null, _timer: 0,
|
|
9926
|
+
SEL: '[class*="caption" i], [class*="subtitle" i], [class*="cue" i], [class*="text-track" i], [class*="subs" i], [id*="subtitle" i], [id*="caption" i]',
|
|
9927
|
+
sync() {
|
|
9928
|
+
const root = STATE.isCinema && CINEMA.nexusControls() && CINEMA.applied?.chain?.[0]?.root;
|
|
9929
|
+
const v = CINEMA.applied?.video;
|
|
9930
|
+
if (!root || !v || root === v || root.ownerDocument !== document) { this.stop(); return; }
|
|
9931
|
+
if (this._root === root) return;
|
|
9932
|
+
this.stop();
|
|
9933
|
+
this._root = root;
|
|
9934
|
+
this._obs = new MutationObserver(() => { if (!this._timer) this._timer = setTimeout(() => { this._timer = 0; this.scan(); }, 80); });
|
|
9935
|
+
this._obs.observe(root, { childList: true, subtree: true, characterData: true });
|
|
9936
|
+
this.scan();
|
|
9937
|
+
},
|
|
9938
|
+
stop() {
|
|
9939
|
+
this._obs?.disconnect(); this._obs = null; this._root = null;
|
|
9940
|
+
clearTimeout(this._timer); this._timer = 0;
|
|
9941
|
+
document.querySelectorAll('.nxu-dsub-src').forEach(n => n.classList.remove('nxu-dsub-src'));
|
|
9942
|
+
if (this._src && !SUBS.active()) SUBS._render('');
|
|
9943
|
+
this._src = null; this._cands.clear();
|
|
9944
|
+
},
|
|
9945
|
+
_text(el) { return String(el.innerText || el.textContent || '').replace(/[ \t]+/g, ' ').replace(/\n{2,}/g, '\n').trim().slice(0, 300); },
|
|
9946
|
+
scan() {
|
|
9947
|
+
const root = this._root;
|
|
9948
|
+
if (!root || !root.isConnected) { this.stop(); return; }
|
|
9949
|
+
if (this._src && this._src.isConnected) { this._show(); return; }
|
|
9950
|
+
const v = CINEMA.applied?.video;
|
|
9951
|
+
const cands = new Set();
|
|
9952
|
+
try { root.querySelectorAll(this.SEL).forEach(el => cands.add(el)); } catch (_) { }
|
|
9953
|
+
(CINEMA._textLayers || []).forEach(el => cands.add(el));
|
|
9954
|
+
const now = Date.now();
|
|
9955
|
+
for (const el of cands) {
|
|
9956
|
+
if (!el.isConnected || el.contains(v) || el.closest('.nxu-cue-mirror') || el.querySelector('button, input, svg, [role="slider"]')) continue;
|
|
9957
|
+
const txt = this._text(el);
|
|
9958
|
+
const c = this._cands.get(el) || { last: null, changes: [], };
|
|
9959
|
+
if (txt !== c.last) { if (c.last !== null) c.changes.push(now); c.last = txt; }
|
|
9960
|
+
c.changes = c.changes.filter(ts => now - ts < 30000);
|
|
9961
|
+
this._cands.set(el, c);
|
|
9962
|
+
// Two changes of its text within half a minute: subtitles, not a title.
|
|
9963
|
+
if (c.changes.length >= 2) { this._src = el; el.classList.add('nxu-dsub-src'); logDebug('Site subtitles shown in the NexusSync layer.', 'info'); this._show(); return; }
|
|
9964
|
+
}
|
|
9965
|
+
},
|
|
9966
|
+
_show() {
|
|
9967
|
+
if (SUBS.active()) return; // the user picked other subtitles
|
|
9968
|
+
SUBS._render(this._text(this._src));
|
|
9969
|
+
}
|
|
9970
|
+
};
|
|
9971
|
+
setInterval(() => { try { DOM_SUBS.sync(); } catch (_) { } }, 1000);
|
|
9972
|
+
|
|
9973
|
+
// OpenSubtitles.org search (its public REST interface: no account needed).
|
|
9974
|
+
const OPENSUBS = {
|
|
9975
|
+
LANG3: { ko: 'kor', en: 'eng', ja: 'jpn', zh: 'chi', es: 'spa', fr: 'fre', de: 'ger', it: 'ita', pt: 'por', ru: 'rus', vi: 'vie', th: 'tha', id: 'ind', tr: 'tur', ar: 'ara', hi: 'hin', nl: 'dut', pl: 'pol', sv: 'swe', uk: 'ukr', ms: 'may', tl: 'tgl' },
|
|
9976
|
+
lang() { return STORE.get('nxu_os_lang', '') || baseLang(STORE.get('nxu_subtitle_language', '') || navigator.language || 'en'); },
|
|
9977
|
+
// Title, year and episode from the page (site names and "watch online" words removed).
|
|
9978
|
+
guess() {
|
|
9979
|
+
const og = document.querySelector('meta[property="og:title"]')?.content || '';
|
|
9980
|
+
let s = (og || document.title || '').replace(/\s+/g, ' ');
|
|
9981
|
+
let season = 0, episode = 0;
|
|
9982
|
+
let m = s.match(/S(\d{1,2})\s*E(\d{1,3})/i) || s.match(/시즌\s*(\d{1,2})\D{0,4}(\d{1,3})\s*화/);
|
|
9983
|
+
if (m) { season = +m[1]; episode = +m[2]; }
|
|
9984
|
+
else if ((m = s.match(/(\d{1,3})\s*(화|회|episode|ep\.?)/i))) { episode = +m[1]; season = 1; }
|
|
9985
|
+
const year = (s.match(/\b(19[3-9]\d|20[0-4]\d)\b/) || [])[1] || '';
|
|
9986
|
+
s = s.split(/\s[|\-–—:]\s|\s?\|\s?/)[0];
|
|
9987
|
+
s = s.replace(/S\d{1,2}\s*E\d{1,3}/ig, '').replace(/시즌\s*\d+|\d+\s*(화|회)|다시보기|무료|보기|스트리밍|영화|드라마|watch|online|free|full\s*movie|hd|1080p|720p|streaming/ig, ' ')
|
|
9988
|
+
.replace(/[\[\](){}]/g, ' ').replace(/\b(19|20)\d{2}\b/g, ' ').replace(/\s+/g, ' ').trim();
|
|
9989
|
+
return { query: s, year, season, episode };
|
|
9990
|
+
},
|
|
9991
|
+
// OpenSubtitles knows films by their English titles; a Korean (or other) page title is
|
|
9992
|
+
// looked up on TMDB first, and its English titles are offered (the first one is used).
|
|
9993
|
+
async tmdb(query, year) {
|
|
9994
|
+
const url = 'https://www.themoviedb.org/search?query=' + encodeURIComponent(query) + '&language=en-US';
|
|
9995
|
+
const res = await httpRequest({ url, headers: { 'Accept-Language': 'en-US,en;q=0.9' }, timeout: 12000 });
|
|
9996
|
+
if (res.status !== 200) throw new Error('HTTP ' + res.status);
|
|
9997
|
+
const doc = new DOMParser().parseFromString(res.text || '', 'text/html');
|
|
9998
|
+
const out = [];
|
|
9999
|
+
doc.querySelectorAll('a[data-media-type] h2').forEach(h2 => {
|
|
10000
|
+
const a = h2.closest('a');
|
|
10001
|
+
const title = (h2.querySelector('span')?.textContent || h2.textContent || '').trim();
|
|
10002
|
+
if (!title || out.some(x => x.title === title)) return;
|
|
10003
|
+
const card = a.closest('[class*="media-card"]') || a.parentElement?.parentElement;
|
|
10004
|
+
const date = card?.querySelector('.release_date')?.textContent || '';
|
|
10005
|
+
const y = (date.match(/(19|20)\d{2}/) || [])[0] || '';
|
|
10006
|
+
out.push({ title, year: y, type: a.getAttribute('data-media-type') === 'tv' ? 'tv' : 'movie' });
|
|
10007
|
+
});
|
|
10008
|
+
// The page's year (if any) decides between same-named films.
|
|
10009
|
+
if (year) out.sort((p, q) => (q.year === year) - (p.year === year));
|
|
10010
|
+
return out.slice(0, 6);
|
|
10011
|
+
},
|
|
10012
|
+
async search({ query, season, episode, lang }) {
|
|
10013
|
+
const l3 = this.LANG3[lang] || 'eng';
|
|
10014
|
+
const parts = [];
|
|
10015
|
+
if (episode) parts.push('episode-' + episode);
|
|
10016
|
+
parts.push('query-' + encodeURIComponent(query.toLowerCase()));
|
|
10017
|
+
if (season && episode) parts.push('season-' + season);
|
|
10018
|
+
parts.push('sublanguageid-' + l3);
|
|
10019
|
+
const res = await httpRequest({ url: 'https://rest.opensubtitles.org/search/' + parts.join('/'), headers: { 'X-User-Agent': 'TemporaryUserAgent' }, timeout: 15000 });
|
|
10020
|
+
if (res.status !== 200) throw new Error('HTTP ' + res.status);
|
|
10021
|
+
const list = JSON.parse(res.text || '[]');
|
|
10022
|
+
return (Array.isArray(list) ? list : []).filter(x => x && /^https:\/\/dl\.opensubtitles\.org\//.test(String(x.SubDownloadLink || '')))
|
|
10023
|
+
.sort((a, b) => (+b.SubDownloadsCnt || 0) - (+a.SubDownloadsCnt || 0)).slice(0, 40);
|
|
10024
|
+
},
|
|
10025
|
+
_binary(url) {
|
|
10026
|
+
return new Promise((resolve, reject) => {
|
|
10027
|
+
const gm = typeof GM_xmlhttpRequest === 'function' ? GM_xmlhttpRequest : (typeof GM !== 'undefined' && GM?.xmlHttpRequest ? GM.xmlHttpRequest.bind(GM) : null);
|
|
10028
|
+
if (gm) {
|
|
10029
|
+
const viaFetch = () => fetch(url).then(r => (r.ok ? r.arrayBuffer() : Promise.reject(new Error('HTTP ' + r.status)))).then(resolve, reject);
|
|
10030
|
+
try {
|
|
10031
|
+
gm({ method: 'GET', url, responseType: 'arraybuffer', timeout: 20000,
|
|
10032
|
+
// Some managers return no binary body: fall back to a plain request.
|
|
10033
|
+
onload: r => (r.status === 200 && r.response instanceof ArrayBuffer ? resolve(r.response) : r.status === 200 ? viaFetch() : reject(new Error('HTTP ' + r.status))),
|
|
10034
|
+
onerror: () => viaFetch(), ontimeout: () => reject(new Error('timeout')) });
|
|
10035
|
+
return;
|
|
10036
|
+
} catch (_) { }
|
|
10037
|
+
}
|
|
10038
|
+
fetch(url).then(r => (r.ok ? r.arrayBuffer() : Promise.reject(new Error('HTTP ' + r.status)))).then(resolve, reject);
|
|
10039
|
+
});
|
|
10040
|
+
},
|
|
10041
|
+
async download(item) {
|
|
10042
|
+
let buf = await this._binary(item.SubDownloadLink);
|
|
10043
|
+
const head = new Uint8Array(buf.slice(0, 2));
|
|
10044
|
+
if (head[0] === 0x1f && head[1] === 0x8b) {
|
|
10045
|
+
if (typeof DecompressionStream === 'undefined') throw new Error('gzip unsupported');
|
|
10046
|
+
buf = await new Response(new Blob([buf]).stream().pipeThrough(new DecompressionStream('gzip'))).arrayBuffer();
|
|
10047
|
+
}
|
|
10048
|
+
const enc = String(item.SubEncoding || 'UTF-8').toLowerCase().replace(/^cp(949|936|950)$/, (m, n) => ({ 949: 'euc-kr', 936: 'gbk', 950: 'big5' })[n]).replace(/^cp(\d+)$/, 'windows-$1');
|
|
10049
|
+
let text;
|
|
10050
|
+
try { text = new TextDecoder(enc).decode(buf); } catch (_) { text = new TextDecoder('utf-8').decode(buf); }
|
|
10051
|
+
return SUBS.parse(text);
|
|
10052
|
+
},
|
|
10053
|
+
open() {
|
|
10054
|
+
const panel = shadow?.getElementById('os-panel');
|
|
10055
|
+
if (!panel) return;
|
|
10056
|
+
const g = this.guess();
|
|
10057
|
+
const q = panel.querySelector('.os-q'), se = panel.querySelector('.os-season'), ep = panel.querySelector('.os-episode'), lg = panel.querySelector('.os-lang');
|
|
10058
|
+
if (!q.value || q.dataset.page !== location.href) { q.value = g.query; se.value = g.season || ''; ep.value = g.episode || ''; q.dataset.page = location.href; }
|
|
10059
|
+
lg.value = this.LANG3[this.lang()] ? this.lang() : 'en';
|
|
10060
|
+
// Opened again after picking one: start at the top (it used to keep the old scroll
|
|
10061
|
+
// position past the end of a shorter list, which looked like an empty window).
|
|
10062
|
+
panel.scrollTop = 0;
|
|
10063
|
+
const body = panel.querySelector('.os-body'); if (body) body.scrollTop = 0;
|
|
10064
|
+
panel.querySelectorAll('.os-item.busy').forEach(b => b.classList.remove('busy'));
|
|
10065
|
+
openPanel(panel);
|
|
10066
|
+
if (q.value && !panel.querySelector('.os-item')) this.prepare(panel, g);
|
|
10067
|
+
},
|
|
10068
|
+
// Non-Latin titles: English title from TMDB first, offered as one-tap choices.
|
|
10069
|
+
async prepare(panel, g) {
|
|
10070
|
+
const q = panel.querySelector('.os-q'), chips = panel.querySelector('.os-tmdb');
|
|
10071
|
+
chips.replaceChildren();
|
|
10072
|
+
if (/[^\u0000-\u024f\s\d\p{P}]/u.test(q.value)) {
|
|
10073
|
+
chips.append(createEl('span', 'trans-help', t('osTmdbLooking')));
|
|
10074
|
+
try {
|
|
10075
|
+
let list = await this.tmdb(q.value, g?.year || '');
|
|
10076
|
+
// Nothing for the whole title: try the part before a colon ("Title: Subtitle").
|
|
10077
|
+
if (!list.length && /[::]/.test(q.value)) list = await this.tmdb(q.value.split(/[::]/)[0].trim(), g?.year || '');
|
|
10078
|
+
chips.replaceChildren();
|
|
10079
|
+
if (list.length) {
|
|
10080
|
+
chips.append(createEl('span', 'os-tmdb-label', 'TMDB'));
|
|
10081
|
+
list.forEach((m, i) => {
|
|
10082
|
+
const b = createEl('button', 'os-chip' + (i === 0 ? ' on' : ''), m.title + (m.year ? ' (' + m.year + ')' : ''), { type: 'button' });
|
|
10083
|
+
b.onclick = () => { chips.querySelectorAll('.os-chip').forEach(c => c.classList.toggle('on', c === b)); q.value = m.title; this.run(panel); };
|
|
10084
|
+
chips.appendChild(b);
|
|
10085
|
+
});
|
|
10086
|
+
q.dataset.original = q.value;
|
|
10087
|
+
q.value = list[0].title;
|
|
10088
|
+
} else chips.append(createEl('span', 'trans-help', t('osTmdbNone')));
|
|
10089
|
+
} catch (err) { chips.replaceChildren(); logDebug('TMDB lookup failed: ' + (err.message || err), 'warn'); }
|
|
10090
|
+
}
|
|
10091
|
+
this.run(panel);
|
|
10092
|
+
},
|
|
10093
|
+
async run(panel) {
|
|
10094
|
+
const q = panel.querySelector('.os-q').value.trim();
|
|
10095
|
+
const out = panel.querySelector('.os-results');
|
|
10096
|
+
if (!q) return;
|
|
10097
|
+
const lang = panel.querySelector('.os-lang').value;
|
|
10098
|
+
STORE.set('nxu_os_lang', lang);
|
|
10099
|
+
out.replaceChildren(createEl('div', 'trans-help', t('osSearching')));
|
|
10100
|
+
try {
|
|
10101
|
+
const list = await this.search({ query: q, season: +panel.querySelector('.os-season').value || 0, episode: +panel.querySelector('.os-episode').value || 0, lang });
|
|
10102
|
+
if (!list.length) { out.replaceChildren(createEl('div', 'trans-help', t('osNone'))); return; }
|
|
10103
|
+
out.replaceChildren(...list.map(item => {
|
|
10104
|
+
const b = createEl('button', 'os-item', '', { type: 'button' });
|
|
10105
|
+
b.append(createEl('span', 'os-name', String(item.MovieReleaseName || item.SubFileName || item.MovieName || '').slice(0, 140)),
|
|
10106
|
+
createEl('span', 'os-meta', [item.MovieName, item.MovieYear, item.LanguageName, String(item.SubFormat || '').toUpperCase(), t('osDownloads', { n: item.SubDownloadsCnt || 0 })].filter(Boolean).join(' · ')));
|
|
10107
|
+
b.onclick = async () => {
|
|
10108
|
+
b.classList.add('busy'); b.querySelector('.os-meta').textContent = t('osLoading');
|
|
10109
|
+
try {
|
|
10110
|
+
const cues = await this.download(item);
|
|
10111
|
+
if (!cues.length) throw new Error('empty');
|
|
10112
|
+
SUBS.useCues(cues, String(item.MovieName || q).slice(0, 60) + ' · ' + (item.LanguageName || lang));
|
|
10113
|
+
closePanel(panel);
|
|
10114
|
+
} catch (err) { logDebug('Subtitles download failed: ' + (err.message || err), 'warn'); showToast(t('subLoadFail')); b.classList.remove('busy'); }
|
|
10115
|
+
};
|
|
10116
|
+
return b;
|
|
10117
|
+
}));
|
|
10118
|
+
} catch (err) {
|
|
10119
|
+
logDebug('OpenSubtitles search failed: ' + (err.message || err), 'warn');
|
|
10120
|
+
out.replaceChildren(createEl('div', 'trans-help', t('osError')));
|
|
10121
|
+
}
|
|
10122
|
+
},
|
|
10123
|
+
build() {
|
|
10124
|
+
const body = createEl('div', 'manual-body os-body');
|
|
10125
|
+
const q = createEl('input', 'nx-compose-input os-q', '', { type: 'search', placeholder: t('osQuery'), autocomplete: 'off' });
|
|
10126
|
+
const row = createEl('div', 'os-row');
|
|
10127
|
+
const se = createEl('input', 'nx-compose-input os-season', '', { type: 'number', min: '0', max: '99', placeholder: t('osSeason') });
|
|
10128
|
+
const ep = createEl('input', 'nx-compose-input os-episode', '', { type: 'number', min: '0', max: '999', placeholder: t('osEpisode') });
|
|
10129
|
+
const lg = createSelect('', Object.keys(this.LANG3).map(c => ({ value: c, label: LANG_BY_CODE.get(c)?.label || c })));
|
|
10130
|
+
lg.classList.add('os-lang');
|
|
10131
|
+
row.append(se, ep, lg);
|
|
10132
|
+
const go = createEl('button', 'btn primary', '🔎 ' + t('osSearch'), { type: 'button' });
|
|
10133
|
+
const out = createEl('div', 'os-results');
|
|
10134
|
+
go.onclick = () => this.run(body);
|
|
10135
|
+
[q, se, ep].forEach(i => i.addEventListener('keydown', (ev) => { ev.stopPropagation(); if (ev.key === 'Enter') this.run(body); }));
|
|
10136
|
+
const tm = createEl('div', 'os-tmdb');
|
|
10137
|
+
body.append(q, tm, row, go, out, createEl('div', 'trans-help', t('osHint')));
|
|
10138
|
+
return body;
|
|
8663
10139
|
}
|
|
8664
10140
|
};
|
|
8665
10141
|
|
|
@@ -8695,23 +10171,31 @@
|
|
|
8695
10171
|
const r = v.getBoundingClientRect();
|
|
8696
10172
|
if (r.width < 240 || r.height < 135) return;
|
|
8697
10173
|
const seen = new Set();
|
|
10174
|
+
// "Holds the video" across shadow roots (players often keep the <video> inside one:
|
|
10175
|
+
// a plain contains() said no, and a whole page section got hidden — black screen).
|
|
10176
|
+
const holds = (el) => { for (let n = v; n; n = n.parentNode || n.host) { if (n === el) return true; } return false; };
|
|
10177
|
+
const area = r.width * r.height;
|
|
8698
10178
|
for (const fx of [0.15, 0.5, 0.85]) for (const fy of [0.15, 0.5, 0.85]) {
|
|
8699
10179
|
const x = r.left + r.width * fx, y = r.top + r.height * fy;
|
|
8700
10180
|
if (x < 0 || y < 0 || x > innerWidth || y > innerHeight) continue;
|
|
8701
10181
|
let stack;
|
|
8702
10182
|
try { stack = document.elementsFromPoint(x, y); } catch (_) { continue; }
|
|
8703
10183
|
for (const el of stack) {
|
|
8704
|
-
if (el === v || el
|
|
10184
|
+
if (el === v || holds(el)) break; // reached the picture
|
|
8705
10185
|
if (seen.has(el) || this.hidden.has(el) || el.closest('#nxu-host') || el.id === 'nxu-host') continue;
|
|
8706
10186
|
seen.add(el);
|
|
8707
10187
|
// Climb to the whole overlay box (but never to something holding the video).
|
|
8708
10188
|
let box = el;
|
|
8709
|
-
while (box.parentElement && !box.parentElement
|
|
8710
|
-
if (this.hidden.has(box)) continue;
|
|
10189
|
+
while (box.parentElement && !holds(box.parentElement) && box.parentElement !== document.body) box = box.parentElement;
|
|
10190
|
+
if (this.hidden.has(box) || holds(box) || box.querySelector?.('video')) continue;
|
|
8711
10191
|
const sig = `${box.id} ${typeof box.className === 'string' ? box.className : ''}`;
|
|
8712
10192
|
if (this.RX_CONTROL.test(sig)) continue;
|
|
8713
10193
|
const br = box.getBoundingClientRect();
|
|
8714
|
-
if (br.width * br.height >
|
|
10194
|
+
if (br.width * br.height > area * 0.92 && !box.querySelector?.('a[href], iframe')) continue; // likely the player's own click layer
|
|
10195
|
+
// Only boxes laid over the picture: never a page section much larger than
|
|
10196
|
+
// the video, never something in the normal flow of the page.
|
|
10197
|
+
if (br.width * br.height > area * 1.6) continue;
|
|
10198
|
+
try { if (getComputedStyle(box).position === 'static' && getComputedStyle(el).position === 'static') continue; } catch (_) { }
|
|
8715
10199
|
if (!this._adLike(box) && !this._adLike(el)) continue;
|
|
8716
10200
|
this.hide(box);
|
|
8717
10201
|
}
|
|
@@ -8822,6 +10306,7 @@
|
|
|
8822
10306
|
if (!STATE.isCinema) { this._auto = false; STATE.controlsOverride = null; }
|
|
8823
10307
|
},
|
|
8824
10308
|
onEnter() {
|
|
10309
|
+
try { BRIGHTNESS.restore(); } catch (_) { }
|
|
8825
10310
|
const auto = this._auto;
|
|
8826
10311
|
this._auto = false;
|
|
8827
10312
|
setTimeout(() => this._showCard(auto), 400);
|
|
@@ -8875,7 +10360,13 @@
|
|
|
8875
10360
|
resetIdleTimer(true);
|
|
8876
10361
|
}
|
|
8877
10362
|
};
|
|
8878
|
-
setInterval(() => {
|
|
10363
|
+
setInterval(() => {
|
|
10364
|
+
try { AUTO_CINEMA.tick(); } catch (_) { }
|
|
10365
|
+
try {
|
|
10366
|
+
if (STATE.isCinema) { SUBS._cinemaSince = SUBS._cinemaSince || Date.now(); if (Date.now() - SUBS._cinemaSince > 6000) SUBS.maybeSuggest(); }
|
|
10367
|
+
else SUBS._cinemaSince = 0;
|
|
10368
|
+
} catch (_) { }
|
|
10369
|
+
}, 1200);
|
|
8879
10370
|
|
|
8880
10371
|
// ───────────────────────── Next episode
|
|
8881
10372
|
// On series pages (drama/anime sites) the page usually has a "next episode" link or
|
|
@@ -9186,7 +10677,7 @@
|
|
|
9186
10677
|
_typing: new Map(),
|
|
9187
10678
|
_connectedAt: 0,
|
|
9188
10679
|
_lastCanvasBubble: 0,
|
|
9189
|
-
TYPES: ['nudge', 'pointer', 'countdown', 'typing', 'ink', 'cover', 'goto'],
|
|
10680
|
+
TYPES: ['nudge', 'pointer', 'countdown', 'typing', 'ink', 'cover', 'goto', 'tune', 'avatar'],
|
|
9190
10681
|
live() { return STATE.handshakeVerified && !STATE.isReadOnly && STATE.role !== 'IDLE'; },
|
|
9191
10682
|
send(type, data = {}) {
|
|
9192
10683
|
if (!this.live()) return false;
|
|
@@ -9197,6 +10688,11 @@
|
|
|
9197
10688
|
},
|
|
9198
10689
|
receive(type, d) {
|
|
9199
10690
|
if (!d || typeof d !== 'object' || d.uid === STATE.userId || !this.live()) return;
|
|
10691
|
+
if (type !== 'typing' && type !== 'avatar') try { HEAL.heard(d.uid); } catch (_) { }
|
|
10692
|
+
// Muted people and switched-off kinds (the cover, countdowns and "go together"
|
|
10693
|
+
// always come through: they keep everyone watching the same thing).
|
|
10694
|
+
const kind = { nudge: 'nudge', ink: 'ink', pointer: 'ping', typing: 'chat' }[type];
|
|
10695
|
+
if (!SAFETY.allows(typeof d.uid === 'string' ? d.uid : '', kind)) return;
|
|
9200
10696
|
if (typeof d.id === 'string') {
|
|
9201
10697
|
if (this._seen.has(d.id)) return;
|
|
9202
10698
|
this._seen.add(d.id);
|
|
@@ -9211,6 +10707,8 @@
|
|
|
9211
10707
|
else if (type === 'ink') INK.onRemote(who, d);
|
|
9212
10708
|
else if (type === 'cover') COVER.onRemote(who, d);
|
|
9213
10709
|
else if (type === 'goto') TRAVEL.onRemote(who, d);
|
|
10710
|
+
else if (type === 'tune') TUNE.onRemote(who, d);
|
|
10711
|
+
else if (type === 'avatar') AVATAR_IMG.onRemote(d);
|
|
9214
10712
|
},
|
|
9215
10713
|
// Fresh events only: the history a newcomer downloads must not pop up as notifications.
|
|
9216
10714
|
isFresh(ts) {
|
|
@@ -9416,8 +10914,6 @@
|
|
|
9416
10914
|
// Remote chat message → bubble (unless the chat is already open).
|
|
9417
10915
|
onChat(msg) {
|
|
9418
10916
|
if (!msg || msg.sender === STATE.userId || !this.isFresh(msg.ts)) return;
|
|
9419
|
-
const chatOpen = uiElements.chatPanel && uiElements.chatPanel.style.display === 'flex';
|
|
9420
|
-
if (chatOpen && !document.hidden) return;
|
|
9421
10917
|
TALK.say(msg);
|
|
9422
10918
|
},
|
|
9423
10919
|
// Remote drawing → shown on screen right away (view only) + bubble to join in.
|
|
@@ -9655,7 +11151,7 @@
|
|
|
9655
11151
|
const PRESS_COLORS = { '😂': '#ffd54f', '😭': '#82b1ff', '😡': '#ff5252', '💦': '#4fc3f7', '🍪': '#d7a86e', '☕': '#bcaaa4', '😘': '#ff6fae', '🖕': '#ffb74d' };
|
|
9656
11152
|
function pressFx(btn, emoji) {
|
|
9657
11153
|
if (!btn) return;
|
|
9658
|
-
btn.style.setProperty('--pop',
|
|
11154
|
+
btn.style.setProperty('--pop', '#69f0ae');
|
|
9659
11155
|
btn.classList.remove('pop');
|
|
9660
11156
|
void btn.offsetWidth;
|
|
9661
11157
|
btn.classList.add('pop');
|
|
@@ -9746,7 +11242,9 @@
|
|
|
9746
11242
|
const sway = (Math.random() < 0.5 ? -1 : 1) * (10 + Math.random() * 14);
|
|
9747
11243
|
const d = 1700 + Math.random() * 500;
|
|
9748
11244
|
const base = { duration: d, delay };
|
|
9749
|
-
|
|
11245
|
+
// Every reaction moves the same way now that anyone can pick any emoji (only the
|
|
11246
|
+
// nudge's 💗 keeps its heartbeat).
|
|
11247
|
+
const kind = e === '💗' ? 'heart' : 'float';
|
|
9750
11248
|
if (this.reduced()) { this._run(el, [{ opacity: 0 }, { opacity: 1, offset: 0.2 }, { opacity: 0, transform: `translateY(${-R * 0.4}px)` }], base); return; }
|
|
9751
11249
|
switch (kind) {
|
|
9752
11250
|
case 'heart':
|
|
@@ -10008,6 +11506,8 @@
|
|
|
10008
11506
|
function onRemoteReaction(d) {
|
|
10009
11507
|
if (!d || typeof d.emoji !== 'string' || d.emoji.length > 8) return;
|
|
10010
11508
|
const uid = typeof d.uid === 'string' ? d.uid.slice(0, 40) : 'peer';
|
|
11509
|
+
try { HEAL.heard(uid); } catch (_) { }
|
|
11510
|
+
if (!SAFETY.allows(uid, 'react') || SAFETY.flood(uid)) return;
|
|
10011
11511
|
const color = typeof d.color === 'string' && /^(#[0-9a-f]{3,8}|hsl\([\d., %]+\))$/i.test(d.color) ? d.color : '#82b1ff';
|
|
10012
11512
|
const name = (typeof d.nick === 'string' && d.nick.trim().slice(0, 16)) || participantName(uid);
|
|
10013
11513
|
const now = Date.now();
|
|
@@ -10175,6 +11675,7 @@
|
|
|
10175
11675
|
fitCover: 'M3 5v4h2V5h4V3H5a2 2 0 0 0-2 2zm2 10H3v4a2 2 0 0 0 2 2h4v-2H5v-4zm14 4h-4v2h4a2 2 0 0 0 2-2v-4h-2v4zm0-16h-4v2h4v4h2V5a2 2 0 0 0-2-2zM7 7h10v10H7z',
|
|
10176
11676
|
close: 'M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z',
|
|
10177
11677
|
rotate: 'M16.48 2.52c3.27 1.55 5.61 4.72 5.97 8.48h1.5C23.44 4.84 18.29 0 12 0l-.66.03 3.81 3.81 1.33-1.32zm-6.25-.77a1.49 1.49 0 0 0-2.12 0L1.75 8.11a1.49 1.49 0 0 0 0 2.12l12.02 12.02c.59.59 1.54.59 2.12 0l6.36-6.36c.59-.59.59-1.54 0-2.12L10.23 1.75zm4.6 19.44L2.81 9.17l6.36-6.36 12.02 12.02-6.36 6.36zm-7.31.29A10.49 10.49 0 0 1 1.55 13H.05C.56 19.16 5.71 24 12 24l.66-.03-3.81-3.81-1.33 1.32z',
|
|
11678
|
+
view: 'M20 15.31 23.31 12 20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69zM12 18V6c3.31 0 6 2.69 6 6s-2.69 6-6 6z',
|
|
10178
11679
|
tune: 'M3 17v2h6v-2H3zM3 5v2h10V5H3zm10 16v-2h8v-2h-8v-2h-2v6h2zM7 9v2H3v2h4v2h2V9H7zm14 4v-2H11v2h10zm-6-4h2V7h4V5h-4V3h-2v6z',
|
|
10179
11680
|
film: 'M18 3v2h-2V3H8v2H6V3H4v18h2v-2h2v2h8v-2h2v2h2V3h-2zM8 17H6v-2h2v2zm0-4H6v-2h2v2zm0-4H6V7h2v2zm10 8h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V7h2v2z',
|
|
10180
11681
|
keyboard: 'M20 5H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2zm-9 3h2v2h-2V8zm0 3h2v2h-2v-2zM8 8h2v2H8V8zm0 3h2v2H8v-2zm-1 2H5v-2h2v2zm0-3H5V8h2v2zm9 7H8v-2h8v2zm0-4h-2v-2h2v2zm0-3h-2V8h2v2zm3 3h-2v-2h2v2zm0-3h-2V8h2v2z'
|
|
@@ -10294,9 +11795,10 @@
|
|
|
10294
11795
|
const subBtn = btn('cc-sub', 'cc', t('aiSubTitle'));
|
|
10295
11796
|
const fitBtn = btn('cc-fit', 'fit', t('ccFit'));
|
|
10296
11797
|
const ambientBtn = btn('cc-ambient', 'ambient', t('ccAmbient'));
|
|
11798
|
+
const viewBtn = btn('cc-view', 'view', t('viewMenu'));
|
|
10297
11799
|
const pipBtn = btn('cc-pip', 'pip', t('ccPip'));
|
|
10298
11800
|
const fsBtn = btn('cc-fs', 'fullscreen', t('ccFullscreen'));
|
|
10299
|
-
row.append(playBtn, backBtn, fwdBtn, vol, time, live, spacer, rateBtn, subBtn, fitBtn, ambientBtn, pipBtn, fsBtn);
|
|
11801
|
+
row.append(playBtn, backBtn, fwdBtn, vol, time, live, spacer, rateBtn, subBtn, viewBtn, fitBtn, ambientBtn, pipBtn, fsBtn);
|
|
10300
11802
|
bottom.append(seek, row);
|
|
10301
11803
|
|
|
10302
11804
|
const menu = createEl('div', 'cc-menu', '', { role: 'menu' });
|
|
@@ -10305,7 +11807,7 @@
|
|
|
10305
11807
|
root.append(gesture, scrim, rippleL, rippleR, spinner, center, flash, scrub, top, bottom, menu, help);
|
|
10306
11808
|
container.appendChild(root);
|
|
10307
11809
|
this.root = root;
|
|
10308
|
-
this.els = { gesture, scrim, rippleL, rippleR, flash, spinner, spinnerLabel, scrub, title, room, helpBtn, rotateBtn, modeBtn, exitBtn, center, cBack, cPlay, cFwd, bottom, seek, track, bufferBar, progress, pins, thumb, range, hover, playBtn, backBtn, fwdBtn, vol, muteBtn, volume, time, live, rateBtn, subBtn, fitBtn, ambientBtn, pipBtn, fsBtn, menu, help };
|
|
11810
|
+
this.els = { gesture, scrim, rippleL, rippleR, flash, spinner, spinnerLabel, scrub, title, room, helpBtn, rotateBtn, modeBtn, exitBtn, center, cBack, cPlay, cFwd, bottom, seek, track, bufferBar, progress, pins, thumb, range, hover, playBtn, backBtn, fwdBtn, vol, muteBtn, volume, time, live, rateBtn, subBtn, viewBtn, fitBtn, ambientBtn, pipBtn, fsBtn, menu, help };
|
|
10309
11811
|
|
|
10310
11812
|
const stop = (e) => e.stopPropagation();
|
|
10311
11813
|
[top, bottom, menu, help, center].forEach(el => el.addEventListener('pointerdown', stop));
|
|
@@ -10344,7 +11846,8 @@
|
|
|
10344
11846
|
volume.addEventListener('input', () => PLAYER.setVolume(volume.value / 100));
|
|
10345
11847
|
time.onclick = () => { STORE.set('nxu_cc_remaining', !STORE.get('nxu_cc_remaining', false)); this.update(); };
|
|
10346
11848
|
rateBtn.onclick = () => this.toggleRateMenu();
|
|
10347
|
-
subBtn.onclick = () =>
|
|
11849
|
+
subBtn.onclick = () => this.toggleSubMenu();
|
|
11850
|
+
viewBtn.onclick = () => this.toggleViewMenu();
|
|
10348
11851
|
fitBtn.onclick = () => this.cycleFit();
|
|
10349
11852
|
ambientBtn.onclick = () => {
|
|
10350
11853
|
const on = !CINEMA.ambientEnabled();
|
|
@@ -10619,6 +12122,7 @@
|
|
|
10619
12122
|
this.els.help.classList.remove('open');
|
|
10620
12123
|
menu.classList.toggle('open', open);
|
|
10621
12124
|
this.els.rateBtn.setAttribute('aria-expanded', String(open));
|
|
12125
|
+
menu.dataset.kind = 'rate';
|
|
10622
12126
|
if (!open) return;
|
|
10623
12127
|
const current = currentPlaybackRate();
|
|
10624
12128
|
menu.replaceChildren(createEl('div', 'cc-menu-title', t('ccSpeed')), ...[0.5, 0.75, 1, 1.25, 1.5, 1.75, 2].map(r => {
|
|
@@ -10629,6 +12133,81 @@
|
|
|
10629
12133
|
resetIdleTimer(true);
|
|
10630
12134
|
},
|
|
10631
12135
|
|
|
12136
|
+
// Subtitles: the video's own tracks, a file, OpenSubtitles, AI live subtitles; timing and size.
|
|
12137
|
+
toggleSubMenu(force) {
|
|
12138
|
+
const menu = this.els.menu;
|
|
12139
|
+
if (!menu) return;
|
|
12140
|
+
const open = force ?? !(menu.classList.contains('open') && menu.dataset.kind === 'sub');
|
|
12141
|
+
this.els.help.classList.remove('open');
|
|
12142
|
+
menu.classList.toggle('open', open);
|
|
12143
|
+
menu.dataset.kind = 'sub';
|
|
12144
|
+
if (!open) return;
|
|
12145
|
+
const item = (label, sel, fn) => { const b = createEl('button', sel ? 'sel' : '', label, { type: 'button', role: 'menuitemradio' }); b.onclick = (ev) => { ev.stopPropagation(); fn(); }; return b; };
|
|
12146
|
+
const tracks = SUBS.tracks();
|
|
12147
|
+
const nothing = !SUBS.active() && !TRANSLATOR.active && !DOM_SUBS._src;
|
|
12148
|
+
const kids = [createEl('div', 'cc-menu-title', t('subMenu')),
|
|
12149
|
+
item(t('xsubOff'), nothing, () => { SUBS.off(); if (TRANSLATOR.active) TRANSLATOR.stop(t('subOff')); this.toggleSubMenu(false); })];
|
|
12150
|
+
// Several can be on at once (up to three): tap to add, tap again to take away.
|
|
12151
|
+
tracks.forEach((tr, i) => kids.push(item('🎞 ' + (tr.label || tr.language || t('subTrack') + ' ' + (i + 1)), SUBS.hasTrack(tr), () => { SUBS.useTrack(tr); this.toggleSubMenu(true); })));
|
|
12152
|
+
SUBS.layers.filter(l => l.kind === 'cues').forEach(l => kids.push(item('💬 ' + l.label, true, () => { SUBS.remove(l.id); this.toggleSubMenu(true); })));
|
|
12153
|
+
if (SUBS.layers.length > 1) kids.push(createEl('div', 'cc-menu-note', t('subMulti')));
|
|
12154
|
+
kids.push(item(t('subSearch'), false, () => { this.toggleSubMenu(false); OPENSUBS.open(); }));
|
|
12155
|
+
kids.push(item(t('subFile'), false, () => { this.toggleSubMenu(false); SUBS.openFile(); }));
|
|
12156
|
+
kids.push(item(t('subAi'), !!TRANSLATOR.active, () => { this.toggleSubMenu(false); TRANSLATOR.toggle(); }));
|
|
12157
|
+
if (SUBS.active()) {
|
|
12158
|
+
const d = createEl('div', 'cc-menu-adjust');
|
|
12159
|
+
const val = createEl('span', 'cc-adj-val', (SUBS.delay > 0 ? '+' : '') + SUBS.delay.toFixed(1) + 's');
|
|
12160
|
+
const step = (x) => { SUBS.setDelay(SUBS.delay + x); val.textContent = (SUBS.delay > 0 ? '+' : '') + SUBS.delay.toFixed(1) + 's'; };
|
|
12161
|
+
const mkb = (txt, x) => { const b = createEl('button', 'cc-adj', txt, { type: 'button' }); b.onclick = (ev) => { ev.stopPropagation(); step(x); }; return b; };
|
|
12162
|
+
d.append(createEl('span', 'cc-adj-label', t('subDelay')), mkb('−0.5', -0.5), val, mkb('+0.5', 0.5));
|
|
12163
|
+
const z = createEl('div', 'cc-menu-adjust');
|
|
12164
|
+
const sz = (x) => { STORE.set('nxu_xsub_size', Math.round(Math.max(0.7, Math.min(1.8, SUBS.size() + x)) * 10) / 10); SUBS._box?.style.setProperty('--xs', String(SUBS.size())); szv.textContent = Math.round(SUBS.size() * 100) + '%'; };
|
|
12165
|
+
const szv = createEl('span', 'cc-adj-val', Math.round(SUBS.size() * 100) + '%');
|
|
12166
|
+
const mz = (txt, x) => { const b = createEl('button', 'cc-adj', txt, { type: 'button' }); b.onclick = (ev) => { ev.stopPropagation(); sz(x); }; return b; };
|
|
12167
|
+
z.append(createEl('span', 'cc-adj-label', t('xsubSize')), mz('A−', -0.1), szv, mz('A+', 0.1));
|
|
12168
|
+
kids.push(d, z);
|
|
12169
|
+
} else if (!tracks.length) kids.push(createEl('div', 'cc-menu-note', t('subNone')));
|
|
12170
|
+
menu.replaceChildren(...kids);
|
|
12171
|
+
resetIdleTimer(true);
|
|
12172
|
+
},
|
|
12173
|
+
// Picture & sound: brightness for dark films, volume above 100 %.
|
|
12174
|
+
toggleViewMenu(force) {
|
|
12175
|
+
const menu = this.els.menu;
|
|
12176
|
+
if (!menu) return;
|
|
12177
|
+
const open = force ?? !(menu.classList.contains('open') && menu.dataset.kind === 'view');
|
|
12178
|
+
this.els.help.classList.remove('open');
|
|
12179
|
+
menu.classList.toggle('open', open);
|
|
12180
|
+
menu.dataset.kind = 'view';
|
|
12181
|
+
if (!open) return;
|
|
12182
|
+
const slider = (label, min, max, value, fmt, on) => {
|
|
12183
|
+
const row = createEl('label', 'cc-slider');
|
|
12184
|
+
const out = createEl('span', 'cc-adj-val', fmt(value));
|
|
12185
|
+
const r = createEl('input', '', '', { type: 'range', min: String(min), max: String(max), step: '5', value: String(Math.round(value * 100)) });
|
|
12186
|
+
r.addEventListener('input', () => { const v = +r.value / 100; if (on(v) === false) { r.value = '100'; out.textContent = fmt(1); return; } out.textContent = fmt(v); });
|
|
12187
|
+
r.addEventListener('pointerdown', (ev) => ev.stopPropagation());
|
|
12188
|
+
row.append(createEl('span', 'cc-adj-label', label), r, out);
|
|
12189
|
+
return { row, r, out };
|
|
12190
|
+
};
|
|
12191
|
+
const pct = v => Math.round(v * 100) + '%';
|
|
12192
|
+
const b = slider('☀️ ' + t('viewBright'), 30, 200, BRIGHTNESS.level, pct, v => { BRIGHTNESS.set(v); this.update(); });
|
|
12193
|
+
const reset = createEl('button', '', '↺ ' + t('viewReset'), { type: 'button' });
|
|
12194
|
+
reset.onclick = (ev) => { ev.stopPropagation(); BRIGHTNESS.set(1); b.r.value = '100'; b.out.textContent = '100%'; this.update(); };
|
|
12195
|
+
const kids = [createEl('div', 'cc-menu-title', t('viewMenu')), b.row, reset];
|
|
12196
|
+
// Several soundtracks in the file (dubbed / original / commentary): pick one.
|
|
12197
|
+
const at = STATE.video?.audioTracks;
|
|
12198
|
+
if (at && at.length > 1) {
|
|
12199
|
+
kids.push(createEl('div', 'cc-menu-title', t('viewAudio')));
|
|
12200
|
+
for (let i = 0; i < at.length; i++) {
|
|
12201
|
+
const tr = at[i];
|
|
12202
|
+
const btn = createEl('button', tr.enabled ? 'sel' : '', '🔊 ' + (tr.label || tr.language || t('viewAudio') + ' ' + (i + 1)), { type: 'button', role: 'menuitemradio' });
|
|
12203
|
+
btn.onclick = (ev) => { ev.stopPropagation(); for (let j = 0; j < at.length; j++) at[j].enabled = j === i; this.toggleViewMenu(true); };
|
|
12204
|
+
kids.push(btn);
|
|
12205
|
+
}
|
|
12206
|
+
}
|
|
12207
|
+
menu.replaceChildren(...kids);
|
|
12208
|
+
resetIdleTimer(true);
|
|
12209
|
+
},
|
|
12210
|
+
|
|
10632
12211
|
stepRate(dir) {
|
|
10633
12212
|
const current = currentPlaybackRate();
|
|
10634
12213
|
let i = RATE_STEPS.findIndex(r => r >= current - 0.01);
|
|
@@ -10756,7 +12335,11 @@
|
|
|
10756
12335
|
const rate = +info.rate.toFixed(2);
|
|
10757
12336
|
e.rateBtn.textContent = `${rate}x`;
|
|
10758
12337
|
e.rateBtn.classList.toggle('on', Math.abs(rate - 1) > 0.01);
|
|
10759
|
-
e.subBtn.classList.toggle('on', TRANSLATOR.state !== 'idle');
|
|
12338
|
+
e.subBtn.classList.toggle('on', TRANSLATOR.state !== 'idle' || SUBS.active());
|
|
12339
|
+
e.viewBtn?.classList.toggle('on', Math.abs(BRIGHTNESS.level - 1) > 0.01);
|
|
12340
|
+
e.pipBtn.classList.toggle('on', !!document.pictureInPictureElement);
|
|
12341
|
+
e.fsBtn.classList.toggle('on', fullscreenActive());
|
|
12342
|
+
[e.rateBtn, e.subBtn, e.viewBtn, e.ambientBtn, e.fitBtn, e.pipBtn, e.fsBtn, this.els.rotateBtn].forEach(b => b && b.setAttribute('aria-pressed', String(b.classList.contains('on'))));
|
|
10760
12343
|
const canStyle = info.kind === 'video' || !!STATE.cinemaIframe;
|
|
10761
12344
|
e.ambientBtn.classList.toggle('on', CINEMA.ambientEnabled());
|
|
10762
12345
|
e.ambientBtn.style.display = canStyle ? '' : 'none';
|
|
@@ -10932,7 +12515,13 @@
|
|
|
10932
12515
|
}
|
|
10933
12516
|
stopPauseEnforcement();
|
|
10934
12517
|
}
|
|
10935
|
-
|
|
12518
|
+
// The hold before a shared start (countdown) is ours. The tap that started the
|
|
12519
|
+
// countdown is still a "recent gesture" when the hold's pause event arrives, which
|
|
12520
|
+
// used to cancel the start and send a pause to everyone (intermittently, depending
|
|
12521
|
+
// on how late the event came). Only a tap made after the hold began counts.
|
|
12522
|
+
const freshTap = (STATE._lastUserGestureTs || 0) > (video._nxuOwnPauseSince || 0) + 30;
|
|
12523
|
+
if ((e.type === 'pause' || e.type === 'seeked') && Date.now() < (video._nxuOwnPauseUntil || 0) && !freshTap) return;
|
|
12524
|
+
if ((e.type === 'play' || e.type === 'pause' || e.type === 'seeked') && gesture && (freshTap || !STATE._scheduledPlay)) { clearTimeout(STATE._scheduledPlay); STATE._scheduledPlay = null; }
|
|
10936
12525
|
const isPause = e.type === 'pause';
|
|
10937
12526
|
if (isPause && document.hidden) return;
|
|
10938
12527
|
// A click or key that slipped through the NexusSync UI to the site's player.
|
|
@@ -11408,9 +12997,12 @@
|
|
|
11408
12997
|
// Events this command causes are tagged so they are not sent back as decisions.
|
|
11409
12998
|
// A heartbeat usually changes nothing, so it only tags when it actually seeks or
|
|
11410
12999
|
// pauses — otherwise a real pause right after a heartbeat would be swallowed.
|
|
11411
|
-
const mark = (kinds) => { video._nxuRemoteEventId = data.eventId || null; video._nxuRemoteUntil = Date.now() +
|
|
13000
|
+
const mark = (kinds, ms = 700) => { video._nxuRemoteEventId = data.eventId || null; video._nxuRemoteUntil = Date.now() + ms; video._nxuRemoteKinds = kinds; };
|
|
13001
|
+
// A shared start is waiting (countdown): heartbeats meanwhile must not cancel it.
|
|
13002
|
+
if (heartbeat && video._nxuStartTimer && Date.now() < (video._nxuStartAt || 0) + 500) return;
|
|
11412
13003
|
if (!heartbeat) mark(data.cmd === 'play' ? 'play seeked ratechange' : data.cmd === 'rate' ? 'ratechange' : 'pause seeked ratechange');
|
|
11413
13004
|
clearTimeout(video._nxuStartTimer);
|
|
13005
|
+
video._nxuStartTimer = null;
|
|
11414
13006
|
if (data.cmd === 'rate') {
|
|
11415
13007
|
RATE.apply(video, rate);
|
|
11416
13008
|
return;
|
|
@@ -11423,15 +13015,22 @@
|
|
|
11423
13015
|
const changes = !heartbeat || video.paused || Math.abs(hbDrift) > CONFIG.hardSyncTolerance;
|
|
11424
13016
|
if (changes) STATE._remoteApplying = true;
|
|
11425
13017
|
if (data.startIn > 40) {
|
|
11426
|
-
// Synchronized start shared with the other devices.
|
|
13018
|
+
// Synchronized start shared with the other devices. The hold's own pause
|
|
13019
|
+
// and seek are tagged as caused by the room for the whole wait (they used
|
|
13020
|
+
// to go back up as someone pausing, which stopped the countdown).
|
|
13021
|
+
const waitMs = Math.min(data.startIn, 10000);
|
|
13022
|
+
mark('pause play seeked ratechange', waitMs + 1500);
|
|
11427
13023
|
if (!video.paused) { try { video.pause(); } catch (_) { } }
|
|
11428
13024
|
if (Number.isFinite(data.time) && Math.abs(video.currentTime - data.time) > 0.25) MEDIA_SAFE.seek(video, data.time);
|
|
11429
13025
|
RATE.apply(video, rate);
|
|
13026
|
+
video._nxuStartAt = Date.now() + waitMs;
|
|
11430
13027
|
video._nxuStartTimer = setTimeout(() => {
|
|
13028
|
+
video._nxuStartTimer = null;
|
|
11431
13029
|
STATE._remoteApplying = true;
|
|
11432
13030
|
MEDIA_SAFE.play(video);
|
|
11433
13031
|
setTimeout(() => { STATE._remoteApplying = false; }, 150);
|
|
11434
|
-
|
|
13032
|
+
setTimeout(() => { if (video.paused) MEDIA_SAFE.play(video); }, 900);
|
|
13033
|
+
}, waitMs);
|
|
11435
13034
|
setTimeout(() => { STATE._remoteApplying = false; }, 150);
|
|
11436
13035
|
return;
|
|
11437
13036
|
}
|
|
@@ -11462,6 +13061,10 @@
|
|
|
11462
13061
|
_onChildMessage(ifr, data) {
|
|
11463
13062
|
const isTarget = STATE.cinemaIframe === ifr;
|
|
11464
13063
|
switch (data.type) {
|
|
13064
|
+
case 'NXU_TUNE_DATA':
|
|
13065
|
+
if (!isTarget) break;
|
|
13066
|
+
if (IS_TOP) TUNE.onFrameData(data); else FRAME.postToParent(data);
|
|
13067
|
+
break;
|
|
11465
13068
|
case 'NXU_VIDEO_FOUND':
|
|
11466
13069
|
this._watchFrameBox(ifr);
|
|
11467
13070
|
this.frameReports.set(ifr, {
|
|
@@ -11544,6 +13147,10 @@
|
|
|
11544
13147
|
this._reportUp(true);
|
|
11545
13148
|
this.probeFrames();
|
|
11546
13149
|
break;
|
|
13150
|
+
case 'NXU_TUNE':
|
|
13151
|
+
if (STATE.video) TUNE.onFrameRequest(data);
|
|
13152
|
+
else if (STATE.cinemaIframe) FRAME.postToFrame(STATE.cinemaIframe, data);
|
|
13153
|
+
break;
|
|
11547
13154
|
}
|
|
11548
13155
|
},
|
|
11549
13156
|
|
|
@@ -11551,7 +13158,7 @@
|
|
|
11551
13158
|
window.addEventListener('message', (e) => {
|
|
11552
13159
|
const data = e.data;
|
|
11553
13160
|
if (!FRAME.isValid(data)) return;
|
|
11554
|
-
if (['NXU_CINEMA', 'NXU_SYNC_CMD', 'NXU_CAPTION', 'NXU_PROBE', 'NXU_MEDIA_CMD'].includes(data.type)) {
|
|
13161
|
+
if (['NXU_CINEMA', 'NXU_SYNC_CMD', 'NXU_CAPTION', 'NXU_PROBE', 'NXU_MEDIA_CMD', 'NXU_TUNE'].includes(data.type)) {
|
|
11555
13162
|
if (FRAME.isFromParent(e)) this._onParentMessage(data);
|
|
11556
13163
|
return;
|
|
11557
13164
|
}
|
|
@@ -11634,7 +13241,7 @@
|
|
|
11634
13241
|
updateRateButton();
|
|
11635
13242
|
if (uiElements.btnCinema) uiElements.btnCinema.style.display = hasMedia || STATE.isCinema ? '' : 'none';
|
|
11636
13243
|
if (uiElements.btnAutoCinema) { uiElements.btnAutoCinema.style.display = hasMedia || STATE.isCinema ? '' : 'none'; AUTO_CINEMA.paintButton(); }
|
|
11637
|
-
if (uiElements.btnBookmark) uiElements.btnBookmark.style.display =
|
|
13244
|
+
if (uiElements.btnBookmark) uiElements.btnBookmark.style.display = 'none';
|
|
11638
13245
|
if (uiElements.btnFindMedia) uiElements.btnFindMedia.style.display = hasMedia ? 'none' : '';
|
|
11639
13246
|
if (uiElements.btnLink) uiElements.btnLink.style.display = hasMedia || connected ? '' : 'none';
|
|
11640
13247
|
updateDockMenuState();
|
|
@@ -11645,7 +13252,7 @@
|
|
|
11645
13252
|
const show = connected ? '' : 'none';
|
|
11646
13253
|
const hasHistory = !!uiElements.subLogMessages?.childElementCount;
|
|
11647
13254
|
const showSubLog = connected || TRANSLATOR.active || hasHistory;
|
|
11648
|
-
['btnSyncStatus', 'btnDraw', 'btnChat', 'btnInvite'].forEach(key => { if (uiElements[key]) uiElements[key].style.display = show; });
|
|
13255
|
+
['btnSyncStatus', 'btnDraw', 'btnChat', 'btnInvite', 'btnTune'].forEach(key => { if (uiElements[key]) uiElements[key].style.display = show; });
|
|
11649
13256
|
if (uiElements.btnSubLog) uiElements.btnSubLog.style.display = showSubLog ? '' : 'none';
|
|
11650
13257
|
if (!connected) {
|
|
11651
13258
|
if (STATE.chatActive) {
|
|
@@ -11686,6 +13293,11 @@
|
|
|
11686
13293
|
if (STATE.handshakeVerified) {
|
|
11687
13294
|
try { if (ydoc && yPresence) ydoc.transact(() => yPresence.set(STATE.userId, { ts: Date.now(), color: STATE.color, viewer: !!STATE.isViewer, nick: STATE.nickname || '', v: NXU_VERSION, r: NXU_RANK, sess: NXU_SESSION, hid: !!document.hidden }), 'local'); } catch (_) { }
|
|
11688
13295
|
sendFirebaseCmd('heartbeat', { ts: Date.now() }, 'nexus_rooms');
|
|
13296
|
+
// What this device sent while falling asleep may have been lost: resend everything,
|
|
13297
|
+
// and fetch what the others did meanwhile.
|
|
13298
|
+
HEAL._pushAt = 0; HEAL._askAt = 0;
|
|
13299
|
+
HEAL.pushFull('woke up');
|
|
13300
|
+
HEAL.ask('woke up');
|
|
11689
13301
|
syncServerClock();
|
|
11690
13302
|
if (RTC.isHost && STATE.connectionMode === 'HTTP_RELAY') RTC.init();
|
|
11691
13303
|
}
|