-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththeater_debug.html
More file actions
869 lines (734 loc) · 32.7 KB
/
theater_debug.html
File metadata and controls
869 lines (734 loc) · 32.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Theater Debug</title>
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
overflow: hidden;
font-family: system-ui, -apple-system, Segoe UI, Roboto, "Helvetica Neue", Arial, "Noto Sans", "Apple Color Emoji", "Segoe UI Emoji";
}
#layout {
display: grid;
grid-template-rows: auto 1fr;
height: 100%;
}
#header {
padding: 10px 12px;
background: #111;
color: #fff;
font-size: 13px;
line-height: 1.4;
}
#content {
display: grid;
grid-template-columns: 1fr 420px;
height: 100%;
min-height: 0;
}
#player {
display: grid;
place-items: center;
background: #000;
color: rgba(255, 255, 255, 0.75);
font-size: 14px;
}
#debugPanel {
border-left: 1px solid #ddd;
background: #fafafa;
min-width: 280px;
min-height: 0;
display: grid;
grid-template-rows: auto 1fr;
}
#debugTitle {
padding: 10px 12px;
border-bottom: 1px solid #ddd;
font-weight: 600;
font-size: 13px;
}
#callLog {
margin: 0;
padding: 10px 12px;
overflow: auto;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
font-size: 12px;
white-space: pre-wrap;
word-break: break-word;
}
.muted {
opacity: 0.8;
}
</style>
</head>
<body>
<div id="layout">
<div id="header">
<div><b>Theater Debug</b> — 실제 YouTube는 로드/재생하지 않습니다.</div>
<div class="muted">외부에서 기존과 동일하게 <code>player.*</code> API를 호출하면, 호출된 함수명/인자를 오른쪽 패널에 표시합니다.</div>
</div>
<div id="content">
<div id="player">(YouTube disabled in debug)</div>
<div id="debugPanel">
<div id="debugTitle">API Call Log</div>
<pre id="callLog"></pre>
</div>
</div>
</div>
<script>
var playerObjectIsValid = false;
// Vuplex WebView 글로벌 상태 관리 (페이지 로딩 즉시 등록)
var __vuplexReady = !!window.vuplex;
var __pendingVuplexMessages = [];
if (!__vuplexReady) {
window.addEventListener('vuplexready', function __onVuplexReady() {
console.log("[Global] Vuplex WebView is now ready");
__vuplexReady = true;
// 펜딩된 메시지 모두 전송
while (__pendingVuplexMessages.length > 0) {
var message = __pendingVuplexMessages.shift();
window.vuplex.postMessage(message);
}
});
}
function _safeJson(value) {
try {
return JSON.stringify(value);
} catch {
return '"[unserializable]"';
}
}
function _renderArg(value) {
if (value instanceof Error) {
return _safeJson({ name: value.name, message: value.message, stack: value.stack });
}
// Promise rejection reason 등이 문자열/객체/기타일 수 있어 방어적으로 처리
const t = typeof value;
if (value == null || t === 'number' || t === 'boolean') return String(value);
if (t === 'string') return value;
return _safeJson(value);
}
function _nowTime() {
const d = new Date();
return d.toISOString().slice(11, 23);
}
function logCall(name, args) {
const el = document.getElementById('callLog');
if (!el) return;
const renderedArgs = args && args.length
? args.map(a => _renderArg(a)).join(', ')
: '';
el.textContent += `[${_nowTime()}] ${name}(${renderedArgs})\n`;
el.scrollTop = el.scrollHeight;
}
// console.* 로 찍히는 로그/에러를 가로채서 패널에 표시 (원래 콘솔 출력은 유지)
(function interceptConsole() {
const methods = ['log', 'info', 'warn', 'error', 'debug'];
const original = {};
for (const m of methods) {
if (typeof console[m] !== 'function') continue;
original[m] = console[m].bind(console);
console[m] = (...args) => {
try {
logCall(`console.${m}`, args);
} catch {
// 로깅 자체 실패 시 콘솔 기능을 깨지 않음
}
return original[m](...args);
};
}
})();
// 콘솔에 찍히지 않을 수도 있는 런타임 에러/리젝션도 패널에 남김
window.addEventListener('error', (event) => {
// event.error 가 Error 인스턴스일 수 있음
logCall('window.error', [event && event.message, (event && event.error) || null, event && event.filename, event && event.lineno, event && event.colno]);
});
window.addEventListener('unhandledrejection', (event) => {
logCall('window.unhandledrejection', [event && event.reason]);
});
// Debug 환경에서 vuplex가 없더라도 postMessage 호출을 확인할 수 있게 스텁 제공
if (!window.vuplex) {
window.vuplex = {
postMessage: (message) => {
logCall('vuplex.postMessage', [message]);
}
};
}
// 실제 YouTube IFrame API 대신, 최소 동작만 하는 YT 스텁 제공
(function installYTStub() {
const PlayerState = {
UNSTARTED: -1,
ENDED: 0,
PLAYING: 1,
PAUSED: 2,
BUFFERING: 3,
CUED: 5
};
class StubPlayer {
constructor(elementId, config) {
this._elementId = elementId;
this._config = config || {};
this._videoId = (config && config.videoId) || '';
this._width = (config && config.width) || '640';
this._height = (config && config.height) || '480';
this._muted = false;
this._volume = 100;
this._state = PlayerState.UNSTARTED;
this._currentTime = 0;
this._duration = 0;
window.setTimeout(() => {
const onReady = this._config && this._config.events && this._config.events.onReady;
if (typeof onReady === 'function') onReady({ target: this });
}, 0);
}
_emitStateChange(state) {
this._state = state;
const onStateChange = this._config && this._config.events && this._config.events.onStateChange;
if (typeof onStateChange === 'function') onStateChange({ data: state, target: this });
}
playVideo() {
this._emitStateChange(PlayerState.PLAYING);
}
pauseVideo() {
this._emitStateChange(PlayerState.PAUSED);
}
stopVideo() {
this._currentTime = 0;
this._emitStateChange(PlayerState.UNSTARTED);
}
seekTo(seconds, allowSeekAhead) {
this._currentTime = Number(seconds) || 0;
}
mute() {
this._muted = true;
}
unMute() {
this._muted = false;
}
isMuted() {
return this._muted;
}
setVolume(volume) {
const v = Number(volume);
this._volume = Number.isFinite(v) ? Math.max(0, Math.min(100, v)) : this._volume;
}
getVolume() {
return this._volume;
}
getDuration() {
return this._duration;
}
getCurrentTime() {
return this._currentTime;
}
getPlayerState() {
return this._state;
}
getVideoUrl() {
return this._videoId ? `https://www.youtube.com/watch?v=${this._videoId}` : '';
}
getVideoEmbedCode() {
return '';
}
loadVideoById(videoId, startSeconds) {
this._videoId = videoId || '';
this._currentTime = Number(startSeconds) || 0;
this._emitStateChange(PlayerState.CUED);
}
cueVideoById(videoId, startSeconds) {
this._videoId = videoId || '';
this._currentTime = Number(startSeconds) || 0;
this._emitStateChange(PlayerState.CUED);
}
setSize(width, height) {
this._width = width;
this._height = height;
}
}
window.YT = {
PlayerState,
Player: StubPlayer
};
})();
// PlayerWrapper 클래스 선언 - (디버그) YouTube 대신 YT 스텁으로 연결
class PlayerWrapper {
constructor(elementId, options = {}) {
this._player = null;
this._ready = false;
this._elementId = elementId;
this._options = options;
this._onReadyCallbacks = [];
this._onStateChangeCallbacks = [];
this._pendingLoadVideo = null;
this._pendingPlay = false;
this._playRequestId = 0;
this._playRequested = false; // playVideo 요청이 왔는지 여부 (pause 시 자동 재생용)
// Suspend 감지용 변수
this._suspendCheckInterval = null;
this._lastCheckTime = null;
this._suspendThresholdMs = 2000; // 2초 이상 차이나면 suspend로 간주
this._checkIntervalMs = 1000; // 1초마다 체크
this._installDebugMethodWrappers();
}
_installDebugMethodWrappers() {
const methodsToLog = [
'initPlayer',
'onReady',
'onStateChange',
'playVideo',
'pauseVideo',
'stopVideo',
'seekTo',
'mute',
'unMute',
'isMuted',
'setVolume',
'getVolume',
'getDuration',
'getCurrentTime',
'getPlayerState',
'getVideoUrl',
'getVideoEmbedCode',
'loadVideoById',
'cueVideoById',
'setSize',
'clickSkipAdButton',
'isReady',
'getInternalPlayer',
'postMessageToNative',
'postJsonToNative'
];
for (const name of methodsToLog) {
const original = this[name];
if (typeof original !== 'function') continue;
this[name] = (...args) => {
logCall(`player.${name}`, args);
return original.apply(this, args);
};
}
}
// 내부 플레이어 초기화 (실제 YouTube 아님)
initPlayer() {
this._player = new YT.Player(this._elementId, {
height: this._options.height || '480',
width: this._options.width || '640',
videoId: this._options.videoId || '',
playerVars: {
'playsinline': 1,
'autoplay': 0,
...this._options.playerVars
},
events: {
'onReady': (event) => this._handleReady(event),
'onStateChange': (event) => this._handleStateChange(event),
'onError': (event) => this._handleError(event),
'onAutoplayBlocked': (event) => this._handleAutoplayBlocked(event)
}
});
}
// 내부 이벤트 핸들러
_handleReady(event) {
this._ready = true;
// 네이티브에 플레이어 준비 완료 알림
this._notifyPlayerIsReady();
// 펜딩된 loadVideoById 호출 실행
if (this._pendingLoadVideo) {
const { videoId, startSeconds } = this._pendingLoadVideo;
this._pendingLoadVideo = null;
this._player.loadVideoById(videoId, startSeconds);
}
// 펜딩된 playVideo 호출 실행
if (this._pendingPlay) {
this._pendingPlay = false;
this.playVideo();
}
this._onReadyCallbacks.forEach(cb => cb(event));
}
_handleStateChange(event) {
console.log("Player state changed to: " + event.data);
// PLAYING (1) 상태면 suspend 감지 시작
if (event.data === YT.PlayerState.PLAYING) {
this._startSuspendCheck();
}
// PAUSED (2) 상태이고 playVideo 요청이 있었다면 자동 재생 시도
if (event.data === YT.PlayerState.PAUSED && this._playRequested) {
console.log("Video paused but playRequested is true, attempting to resume");
this._player.playVideo();
} else if (event.data === YT.PlayerState.PAUSED) {
// 명시적 pause면 suspend 감지 중지
this._stopSuspendCheck();
}
// ENDED (0) 상태면 검은 암막 표시 (추천 영상 가리기)
if (event.data === YT.PlayerState.ENDED) {
console.log("Video ended, showing black overlay");
this._playRequested = false; // 영상이 끝났으므로 플래그 리셋
this._stopSuspendCheck(); // suspend 감지 중지
this._showEndOverlay();
}
this._onStateChangeCallbacks.forEach(cb => cb(event));
}
_showEndOverlay() {
let overlay = document.getElementById('end-overlay');
if (!overlay) {
overlay = document.createElement('div');
overlay.id = 'end-overlay';
overlay.style.cssText = 'display:none;position:absolute;top:0;left:0;width:100%;height:100%;background-color:#000;z-index:9999;color:#fff;font-size:18px;justify-content:center;align-items:center;';
overlay.textContent = '영상 종료됨';
// player 영역에 추가
const playerEl = document.getElementById('player');
if (playerEl) {
playerEl.style.position = 'relative';
playerEl.appendChild(overlay);
} else {
document.body.appendChild(overlay);
}
}
overlay.style.display = 'flex';
}
_hideEndOverlay() {
const overlay = document.getElementById('end-overlay');
if (overlay) {
overlay.style.display = 'none';
}
}
// Suspend 감지 시작
_startSuspendCheck() {
if (this._suspendCheckInterval) return; // 이미 실행 중
this._lastCheckTime = Date.now();
console.log("Starting suspend detection");
this._suspendCheckInterval = window.setInterval(() => {
const now = Date.now();
const elapsed = now - this._lastCheckTime;
const expectedElapsed = this._checkIntervalMs;
// 예상보다 훨씬 긴 시간이 지났다면 suspend 상태였던 것
if (elapsed > expectedElapsed + this._suspendThresholdMs) {
const suspendDuration = (elapsed - expectedElapsed) / 1000; // 초 단위
console.log("Browser suspend detected! Duration:", suspendDuration.toFixed(2), "seconds");
this._handleSuspendResume(suspendDuration);
}
this._lastCheckTime = now;
}, this._checkIntervalMs);
}
// Suspend 감지 중지
_stopSuspendCheck() {
if (this._suspendCheckInterval) {
console.log("Stopping suspend detection");
window.clearInterval(this._suspendCheckInterval);
this._suspendCheckInterval = null;
this._lastCheckTime = null;
}
}
// Suspend에서 복귀했을 때 처리
_handleSuspendResume(suspendDurationSeconds) {
if (!this._player || !this._ready) return;
const currentTime = this._player.getCurrentTime();
const duration = this._player.getDuration();
const newTime = currentTime + suspendDurationSeconds;
// 영상 끝을 넘어가지 않도록 처리
if (newTime >= duration) {
console.log("Suspend skip would exceed video duration, seeking to end");
this._player.seekTo(duration - 0.5, true);
} else {
console.log("Seeking forward by", suspendDurationSeconds.toFixed(2), "seconds to", newTime.toFixed(2));
this._player.seekTo(newTime, true);
}
// 네이티브에 suspend 복귀 알림
this.postJsonToNative({
Type: 'suspendResume',
SuspendDuration: suspendDurationSeconds,
SkippedTo: Math.min(newTime, duration - 0.5)
});
}
_handleError(event) {
// 모바일/웹뷰 환경에서 사용자 제스처 없이 재생 시도가 막힐 때 error 콜백이 오거나,
// state가 PLAYING으로 전환되지 않는 경우가 있어, 네이티브에 안내할 수 있게 한다.
logCall('player._handleError', [event && event.data]);
}
_handleAutoplayBlocked(event) {
console.log("Autoplay blocked event:", event);
console.log("Autoplay blocked event.data:", event && event.data);
console.log("Autoplay blocked event.target:", event && event.target);
logCall('player._handleAutoplayBlocked [event]', [event]);
logCall('player._handleAutoplayBlocked [event.data]', [event && event.data]);
logCall('player._handleAutoplayBlocked [event.target]', [event && event.target]);
try {
const eventJson = JSON.stringify(event, null, 2);
console.log("Autoplay blocked event (JSON):", eventJson);
logCall('player._handleAutoplayBlocked [JSON]', [eventJson]);
} catch (e) {
console.log("Autoplay blocked event serialization error:", e.message);
logCall('player._handleAutoplayBlocked [serialization error]', [e.message]);
}
// 0.5초 대기 후 플레이어 상태 확인
window.setTimeout(() => {
const state = this.getPlayerState();
const isPlaying = state === YT.PlayerState.PLAYING;
const isBuffering = state === YT.PlayerState.BUFFERING;
console.log("Autoplay blocked check after 500ms: state =", state, "playing =", isPlaying, "buffering =", isBuffering);
logCall('player._handleAutoplayBlocked [state check]', [state, isPlaying, isBuffering]);
// 재생 중이거나 버퍼링 중이면 클릭 요청 안함
if (isPlaying || isBuffering) {
console.log("Player is playing or buffering, no user gesture needed");
logCall('player._handleAutoplayBlocked [no gesture needed]', []);
return;
}
// 재생이 시작되지 않았으면 클릭 요청
logCall('player._handleAutoplayBlocked [requesting gesture]', [state]);
this._notifyUserGestureRequired('autoplayBlocked', {
source: 'onAutoplayBlocked',
data: event && event.data,
state: state
});
}, 500);
}
_notifyUserGestureRequired(reason, extra = {}, x = 0.25, y = 0.25) {
this.postJsonToNative({
Type: 'userGestureRequired',
Action: 'clickToPlay',
X: x,
Y: y,
Reason: reason,
...extra
});
}
_notifyPlayerIsReady() {
console.log("Notifying native that player is ready");
this.postJsonToNative({
Type: 'playerReady'
});
}
// 이벤트 콜백 등록
onReady(callback) {
this._onReadyCallbacks.push(callback);
if (this._ready) callback({ target: this._player });
}
onStateChange(callback) {
this._onStateChangeCallbacks.push(callback);
}
// 프록시 메서드들 - 재생 제어
playVideo() {
// playVideo 요청이 왔음을 기록 (pause 시 자동 재생용)
this._playRequested = true;
if (!(this._player && this._ready)) {
console.log("Player not ready, deferring playVideo");
this._pendingPlay = true;
return;
}
// play 지시 후 실제로 재생이 시작되지 않으면(모바일 자동재생 제한 등)
// 네이티브에 사용자 클릭 유도를 요청한다.
const requestId = ++this._playRequestId;
this._player.playVideo();
// const checkPlayback = (delayMs) => {
// window.setTimeout(() => {
// if (requestId !== this._playRequestId) return; // 최신 요청만 처리
// const state = this.getPlayerState();
// const isPlaying = state === YT.PlayerState.PLAYING;
// const isBuffering = state === YT.PlayerState.BUFFERING;
// if (isPlaying) return;
// // BUFFERING이면 조금 더 기다렸다가 최종 확인
// if (isBuffering && delayMs < 2000) {
// checkPlayback(2500);
// return;
// }
// // print state for debugging
// console.log("Playback check: state =", state);
// this._notifyUserGestureRequired('autoplayBlocked', {
// state
// });
// }, delayMs);
// };
// checkPlayback(1500);
}
pauseVideo() {
console.log("Pausing video");
if (this._player && this._ready) this._player.pauseVideo();
}
stopVideo() {
console.log("Stopping video");
this._stopSuspendCheck(); // suspend 감지 중지
if (this._player && this._ready) this._player.stopVideo();
}
seekTo(seconds, allowSeekAhead = true) {
if (this._player && this._ready) this._player.seekTo(seconds, allowSeekAhead);
}
// 프록시 메서드들 - 볼륨 제어
mute() {
if (this._player && this._ready) this._player.mute();
}
unMute() {
if (this._player && this._ready) this._player.unMute();
}
isMuted() {
const result = this._player && this._ready ? this._player.isMuted() : false;
this.postJsonToNative({
Type: 'isMuted',
Data: result
});
return result;
}
setVolume(volume) {
if (this._player && this._ready) this._player.setVolume(volume);
}
getVolume() {
const result = this._player && this._ready ? this._player.getVolume() : 0;
this.postJsonToNative({
Type: 'getVolume',
Data: result
});
return result;
}
// 프록시 메서드들 - 영상 정보
getDuration() {
const result = this._player && this._ready ? this._player.getDuration() : 0;
this.postJsonToNative({
Type: 'getDuration',
Data: result
});
return result;
}
getCurrentTime() {
const result = this._player && this._ready ? this._player.getCurrentTime() : 0;
this.postJsonToNative({
Type: 'getCurrentTime',
Data: result
});
return result;
}
getPlayerState() {
const result = this._player && this._ready ? this._player.getPlayerState() : -1;
this.postJsonToNative({
Type: 'getPlayerState',
Data: result
});
return result;
}
getVideoUrl() {
const result = this._player && this._ready ? this._player.getVideoUrl() : '';
this.postJsonToNative({
Type: 'getVideoUrl',
Data: result
});
return result;
}
getVideoEmbedCode() {
const result = this._player && this._ready ? this._player.getVideoEmbedCode() : '';
this.postJsonToNative({
Type: 'getVideoEmbedCode',
Data: result
});
return result;
}
// 프록시 메서드들 - 영상 로드
loadVideoById(videoId, startSeconds = 0, debugString = '') {
console.log("Loading video by ID:", videoId, "at", startSeconds, "Debug:", debugString);
logCall('player.loadVideoById debug', [videoId, startSeconds, debugString]);
// 새 영상 로드 시 암막 숨기기
this._hideEndOverlay();
this._playRequested = false; // 새 영상이므로 플래그 리셋
this._stopSuspendCheck(); // suspend 감지 초기화
if (this._player && this._ready) {
console.log("Loading video by ID:", videoId, "at", startSeconds);
this._player.loadVideoById(videoId, startSeconds);
} else {
// 플레이어가 준비되지 않았으면 나중에 실행하도록 저장
console.log("Player not ready, deferring loadVideoById:", videoId, "at", startSeconds);
this._pendingLoadVideo = { videoId, startSeconds };
}
}
cueVideoById(videoId, startSeconds = 0) {
console.log("Cueing video by ID:", videoId, "at", startSeconds);
// 새 영상 로드 시 암막 숨기기
this._hideEndOverlay();
this._playRequested = false; // 새 영상이므로 플래그 리셋
this._stopSuspendCheck(); // suspend 감지 초기화
if (this._player && this._ready) this._player.cueVideoById(videoId, startSeconds);
}
// 프록시 메서드들 - 플레이어 크기
setSize(width, height) {
console.log("Setting player size to:", width, height);
if (this._player && this._ready) this._player.setSize(width, height);
}
// 광고 스킵 버튼 클릭 요청
clickSkipAdButton() {
console.log("Requesting native to click skip ad button");
// YouTube 광고 스킵 버튼 선택자들 (우선순위 순)
const selectors = [
'.ytp-skip-ad-button',
'.ytp-ad-skip-button',
'.ytp-ad-skip-button-modern',
'button.ytp-ad-skip-button',
'.ytp-ad-skip-button-container button'
];
this.postJsonToNative({
Type: 'userGestureRequired',
Action: 'clickSkipAd',
Reason: 'skipAdButton',
Selectors: selectors,
// 기본 fallback 좌표 (오른쪽 하단, 버튼 일반 위치)
DefaultX: 0.9,
DefaultY: 0.87
});
}
// 상태 확인
isReady() {
return this._ready;
}
// 내부 플레이어 직접 접근 (필요시)
getInternalPlayer() {
return this._player;
}
// Vuplex WebView 네이티브 메시지 전송
postMessageToNative(message) {
if (__vuplexReady && window.vuplex) {
window.vuplex.postMessage(message);
} else {
console.log("Vuplex not ready, queueing message");
__pendingVuplexMessages.push(message);
}
}
// JSON 객체를 네이티브로 전송
postJsonToNative(obj) {
this.postMessageToNative(JSON.stringify(obj));
}
}
// URL에서 파라미터 가져오기 (기본값 설정)
var urlParams = new URLSearchParams(window.location.search);
var videoId = urlParams.get('videoId') || '';
var width = urlParams.get('width') || '640';
var height = urlParams.get('height') || '480';
// HTML 로드하자마자 PlayerWrapper 인스턴스 생성
var player = new PlayerWrapper('player', {
videoId: videoId,
width: width,
height: height
});
// 디버그 페이지에서는 즉시 초기화한다 (실제 YouTube 로딩 없음)
player.initPlayer();
// 외부가 기존처럼 이 함수를 기대할 수 있어 유지
function onYouTubeIframeAPIReady() {
player.initPlayer();
}
playerObjectIsValid = true;
// C#에서 호출하여 플레이어 준비 상태를 확인하는 전역 함수
function checkPlayerReady() {
var isReady = !!(player && typeof player.isReady === 'function' && player.isReady());
if (!isReady) return;
// 기존 ready notify와 동일한 메시지로 통일
if (player && typeof player._notifyPlayerIsReady === 'function') {
player._notifyPlayerIsReady();
return;
}
// fallback
var message = JSON.stringify({ Type: 'playerReady' });
if (__vuplexReady && window.vuplex) window.vuplex.postMessage(message);
else __pendingVuplexMessages.push(message);
}
</script>
</body>
</html>