-
Notifications
You must be signed in to change notification settings - Fork 195
Expand file tree
/
Copy pathguacamole.component.ts
More file actions
477 lines (405 loc) · 11.8 KB
/
Copy pathguacamole.component.ts
File metadata and controls
477 lines (405 loc) · 11.8 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
import {
Component,
Input,
OnChanges,
OnInit,
AfterViewInit,
SimpleChanges,
ViewEncapsulation
} from '@angular/core';
import Guacamole from 'guacamole-common-js';
import { Command, Replay } from '@app/model';
import { HttpService } from '@app/services';
import { formatTime } from '@app/utils/common';
import { TranslateService } from '@ngx-translate/core';
import { fromEvent, Observable, Subscription } from 'rxjs';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
@Component({
standalone: false,
selector: 'elements-replay-guacamole',
templateUrl: 'guacamole.component.html',
styleUrls: ['guacamole.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class ElementReplayGuacamoleComponent implements OnInit, OnChanges, AfterViewInit {
isPlaying = false;
isSeeking = false;
recording: any;
playerRef: any;
displayRef: any;
screenRef: any;
recordingDisplay: any;
max = 100;
percent = 0;
duration = '00:00';
position = '00:00';
@Input() replay: Replay;
startTime = null;
startTimeStamp = null;
commands: Command[] = [];
page = 0;
leftInfo = null;
winSizeChange$: Observable<any>;
winSizeSub: Subscription;
firstLoad = true;
rangeHideClass = 'hideCursor';
lastDuration: number = 0;
interval: number;
initializedCommand: boolean = false;
commandsCollapsed: boolean = false;
constructor(
private _http: HttpService,
private _translate: TranslateService
) {}
ngOnInit() {
this.initialize();
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['replay'] && changes['replay'].currentValue) {
this.destroy();
setTimeout(() => {
this.initialize();
}, 50);
}
}
ngAfterViewInit() {
this.applyScaleWithRetry(500);
}
initialize() {
if (!this.replay || !this.replay.src) {
return alert('Not found replay');
}
this.commands = [];
const date = new Date(Date.parse(this.replay.date_start));
this.startTime = this.toSafeLocalDateStr(date);
this.startTimeStamp = Date.parse(this.replay.date_start);
this.playerRef = document.getElementById('player');
this.displayRef = document.getElementById('display');
this.screenRef = document.getElementById('screen');
if (!this.screenRef) {
return;
}
try {
const tunnel = new Guacamole.StaticHTTPTunnel(this.replay.src);
this.recording = new Guacamole.SessionRecording(tunnel);
this.recordingDisplay = this.recording.getDisplay();
const recordingElement = this.recordingDisplay.getElement();
recordingElement.style.margin = '0 auto';
this.screenRef.appendChild(recordingElement);
this.initRecording();
if (!this.initializedCommand) {
this.getCommands(this.page);
this.initializedCommand = true;
}
this._translate.get('LeftInfo').subscribe((res: string) => {
this.leftInfo = res;
});
this.winSizeChange$ = fromEvent(window, 'resize').pipe(
debounceTime(300),
distinctUntilChanged()
);
this.winSizeSub = this.winSizeChange$.subscribe(() => {
if (this.recordingDisplay && this.screenRef) {
this.applyScaleWithRetry(300);
}
});
if (this.isMobile()) {
this.initTouchEvents();
}
} catch (error) {
throw new Error(error);
}
}
initRecording() {
// 先注册事件,避免在 connect 之后事件被瞬间触发而丢失
this.recording.onload = () => {
this.applyScaleWithRetry(200);
};
this.recording.onplay = () => {
this.isPlaying = true;
this.applyScaleWithRetry(100);
};
this.recording.onseek = millis => {
this.position = formatTime(millis);
this.percent = millis;
};
this.recording.onprogress = millis => {
if (millis >= this.max) {
this.duration = formatTime(millis);
this.max = millis;
}
if (this.firstLoad) {
this.recording.play();
this.firstLoad = false;
this.applyScaleWithRetry(300);
}
};
this.recording.onpause = () => {
this.isPlaying = false;
};
this.recordingDisplay.onresize = (width, height) => {
// Do not scale if displayRef has no width
if (!height) {
return;
}
this.applyScaleWithRetry(100);
};
clearInterval(this.interval);
// @ts-ignore
this.interval = setInterval(() => {
if (this.lastDuration === this.max) {
clearInterval(this.interval);
this.rangeHideClass = '';
} else {
this.lastDuration = this.max;
}
}, 1000);
// 连接录制流
this.recording.connect('');
// 立即尝试播放,不等待 onload,增强大文件/慢速网络下的起播速度
this.safeAutoplayWithRetry();
}
private safeAutoplayWithRetry(maxRetry: number = 5, delayMs: number = 500) {
let attempts = 0;
const tryPlay = () => {
if (!this.recording) {
return;
}
try {
if (!this.recording.isPlaying()) {
this.recording.play();
}
} catch (e) {
console.error(e)
}
if (this.recording && !this.recording.isPlaying() && attempts < maxRetry) {
attempts++;
setTimeout(tryPlay, delayMs);
}
};
tryPlay();
}
private applyScaleWithRetry(delay: number = 100, maxRetries: number = 5) {
let retryCount = 0;
const tryApplyScale = () => {
if (this.recordingDisplay && this.screenRef) {
const width = this.recordingDisplay.getWidth();
const height = this.recordingDisplay.getHeight();
if (width > 0 && height > 0) {
const scale = this.getPropScale();
this.recordingDisplay.scale(scale);
return true;
} else if (retryCount < maxRetries) {
retryCount++;
setTimeout(tryApplyScale, delay);
return false;
} else {
return false;
}
}
return false;
};
setTimeout(tryApplyScale, delay);
}
destroy() {
if (this.recording) {
this.recording.onplay = null;
this.recording.onseek = null;
this.recording.onprogress = null;
this.recording.onpause = null;
this.recordingDisplay.onresize = null;
this.recording.disconnect();
this.recording = null;
}
if (this.recordingDisplay) {
const recordingElement = this.recordingDisplay.getElement();
if (recordingElement && recordingElement.parentNode) {
recordingElement.parentNode.removeChild(recordingElement);
}
this.recordingDisplay = null;
}
if (this.winSizeSub) {
this.winSizeSub.unsubscribe();
this.winSizeSub = null;
}
if (this.interval) {
clearInterval(this.interval);
}
this.interval = null;
this.playerRef = null;
this.displayRef = null;
this.screenRef = null;
this.isPlaying = false;
this.isSeeking = false;
this.max = 100;
this.percent = 0;
this.duration = '00:00';
this.position = '00:00';
this.startTime = null;
this.startTimeStamp = null;
this.commands = [];
this.page = 0;
this.leftInfo = null;
this.firstLoad = true;
this.rangeHideClass = 'hideCursor';
this.lastDuration = 0;
this.initializedCommand = false;
}
getPropScale() {
let scale = 1;
if (this.recordingDisplay && this.screenRef) {
const width = this.recordingDisplay.getWidth();
const height = this.recordingDisplay.getHeight();
if (!width || !height) {
return scale;
}
const containerRect = this.screenRef.getBoundingClientRect();
const availableWidth = containerRect.width - 32; // 减去padding
const availableHeight = containerRect.height - 32;
if (availableWidth <= 0 || availableHeight <= 0) {
return scale;
}
const widthScale = availableWidth / width;
const heightScale = availableHeight / height;
scale = Math.min(widthScale, heightScale, 1);
}
return scale;
}
restart() {
this.percent = 0;
this.runFrom();
}
getUserLang() {
const userLangEN = document.cookie.indexOf('django_language=en');
if (userLangEN === -1) {
return 'zh-CN';
} else {
return 'en-US';
}
}
toSafeLocalDateStr(d) {
const date_s = d.toLocaleString(this.getUserLang(), { hour12: false });
return date_s.split('/').join('-');
}
setDisableStatusSiderElement(disable: boolean) {
const sliderElement = document.getElementById('position-slider') as HTMLInputElement;
sliderElement.disabled = disable;
}
runFrom() {
this.setDisableStatusSiderElement(true);
this.isSeeking = true;
this.recording.seek(this.percent, () => {
this.playerRef.classList.remove('seeking');
this.isSeeking = false;
this.setDisableStatusSiderElement(false);
});
// Seek is in progress
this.playerRef.classList.add('seeking');
}
cancelSeek(e) {
this.recording.play();
this.playerRef.classList.remove('seeking');
this.isSeeking = false;
e.stopPropagation();
this.setDisableStatusSiderElement(false);
}
play() {
if (!this.recording.isPlaying()) {
this.recording.play();
this.isPlaying = true;
// 延迟应用缩放,确保播放状态已更新
this.applyScaleWithRetry(100);
}
}
pause() {
if (this.recording.isPlaying()) {
this.recording.pause();
this.isPlaying = false;
}
}
toggle() {
if (!this.recording.isPlaying()) {
this.play();
} else {
this.pause();
}
}
getCommands(page: number) {
if (!this.startTimeStamp) {
return;
}
this._http.getCommandsData(this.replay.id, page).subscribe(
data => {
const results = data.results;
results.forEach((element: any) => {
element.atime = formatTime(element.timestamp * 1000 - this.startTimeStamp);
});
this.commands = this.commands.concat(results);
},
err => {
alert('没找到命令记录');
}
);
}
onScroll() {
this.getCommands(++this.page);
}
commandClick(item: Command) {
const time = (item.timestamp - 10) * 1000 - this.startTimeStamp;
this.percent = time <= 0 ? 0 : time;
this.runFrom();
}
trackByCommand(index: number, item: Command): any {
return item.timestamp || index;
}
private isMobile(): boolean {
return window.innerWidth < 768;
}
private initTouchEvents() {
const screen = document.getElementById('screen');
if (!screen) {
return;
}
let touchStartX = 0;
let touchStartY = 0;
let touchStartTime = 0;
screen.addEventListener('touchstart', (e: TouchEvent) => {
touchStartX = e.touches[0].clientX;
touchStartY = e.touches[0].clientY;
touchStartTime = Date.now();
});
screen.addEventListener('touchmove', (e: TouchEvent) => {
// 防止页面滚动
if (Math.abs(e.touches[0].clientY - touchStartY) > 10) {
e.preventDefault();
}
});
screen.addEventListener('touchend', (e: TouchEvent) => {
const touchEndX = e.changedTouches[0].clientX;
const touchEndY = e.changedTouches[0].clientY;
const touchEndTime = Date.now();
const deltaX = touchEndX - touchStartX;
const deltaY = touchEndY - touchStartY;
const deltaTime = touchEndTime - touchStartTime;
// 点击判定
if (Math.abs(deltaX) < 10 && Math.abs(deltaY) < 10 && deltaTime < 200) {
this.toggle();
}
// 左右滑动判定
if (Math.abs(deltaX) > 50 && Math.abs(deltaY) < 30) {
const seekTime = 5000; // 5秒
if (deltaX > 0) {
// 向右滑动,前进
this.percent = Math.min(this.percent + seekTime, this.max);
} else {
// 向左滑动,后退
this.percent = Math.max(this.percent - seekTime, 0);
}
this.runFrom();
}
});
}
toggleCommands() {
this.commandsCollapsed = !this.commandsCollapsed;
}
}