]>
Commit | Line | Data |
---|---|---|
1 | import { Hotkey, HotkeysService } from 'angular2-hotkeys' | |
2 | import { forkJoin, Subscription } from 'rxjs' | |
3 | import { catchError } from 'rxjs/operators' | |
4 | import { PlatformLocation } from '@angular/common' | |
5 | import { ChangeDetectorRef, Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core' | |
6 | import { ActivatedRoute, Router } from '@angular/router' | |
7 | import { | |
8 | AuthService, | |
9 | AuthUser, | |
10 | ConfirmService, | |
11 | MarkdownService, | |
12 | MetaService, | |
13 | Notifier, | |
14 | PeerTubeSocket, | |
15 | PluginService, | |
16 | RestExtractor, | |
17 | ScreenService, | |
18 | ServerService, | |
19 | UserService | |
20 | } from '@app/core' | |
21 | import { HooksService } from '@app/core/plugins/hooks.service' | |
22 | import { RedirectService } from '@app/core/routing/redirect.service' | |
23 | import { isXPercentInViewport, scrollToTop } from '@app/helpers' | |
24 | import { Video, VideoCaptionService, VideoDetails, VideoService } from '@app/shared/shared-main' | |
25 | import { VideoShareComponent } from '@app/shared/shared-share-modal' | |
26 | import { SupportModalComponent } from '@app/shared/shared-support-modal' | |
27 | import { SubscribeButtonComponent } from '@app/shared/shared-user-subscription' | |
28 | import { VideoActionsDisplayType, VideoDownloadComponent } from '@app/shared/shared-video-miniature' | |
29 | import { VideoPlaylist, VideoPlaylistService } from '@app/shared/shared-video-playlist' | |
30 | import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage' | |
31 | import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes' | |
32 | import { | |
33 | HTMLServerConfig, | |
34 | PeerTubeProblemDocument, | |
35 | ServerErrorCode, | |
36 | UserVideoRateType, | |
37 | VideoCaption, | |
38 | VideoPrivacy, | |
39 | VideoState | |
40 | } from '@shared/models' | |
41 | import { | |
42 | cleanupVideoWatch, | |
43 | getStoredP2PEnabled, | |
44 | getStoredTheater, | |
45 | getStoredVideoWatchHistory | |
46 | } from '../../../assets/player/peertube-player-local-storage' | |
47 | import { | |
48 | CustomizationOptions, | |
49 | P2PMediaLoaderOptions, | |
50 | PeertubePlayerManager, | |
51 | PeertubePlayerManagerOptions, | |
52 | PlayerMode, | |
53 | videojs | |
54 | } from '../../../assets/player/peertube-player-manager' | |
55 | import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils' | |
56 | import { environment } from '../../../environments/environment' | |
57 | import { VideoWatchPlaylistComponent } from './video-watch-playlist.component' | |
58 | ||
59 | type URLOptions = CustomizationOptions & { playerMode: PlayerMode } | |
60 | ||
61 | @Component({ | |
62 | selector: 'my-video-watch', | |
63 | templateUrl: './video-watch.component.html', | |
64 | styleUrls: [ './video-watch.component.scss' ] | |
65 | }) | |
66 | export class VideoWatchComponent implements OnInit, OnDestroy { | |
67 | private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern' | |
68 | ||
69 | @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent | |
70 | @ViewChild('videoShareModal') videoShareModal: VideoShareComponent | |
71 | @ViewChild('supportModal') supportModal: SupportModalComponent | |
72 | @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent | |
73 | @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent | |
74 | ||
75 | player: any | |
76 | playerElement: HTMLVideoElement | |
77 | ||
78 | theaterEnabled = false | |
79 | ||
80 | playerPlaceholderImgSrc: string | |
81 | ||
82 | video: VideoDetails = null | |
83 | videoCaptions: VideoCaption[] = [] | |
84 | ||
85 | playlistPosition: number | |
86 | playlist: VideoPlaylist = null | |
87 | ||
88 | descriptionLoading = false | |
89 | completeDescriptionShown = false | |
90 | completeVideoDescription: string | |
91 | shortVideoDescription: string | |
92 | videoHTMLDescription = '' | |
93 | ||
94 | likesBarTooltipText = '' | |
95 | ||
96 | hasAlreadyAcceptedPrivacyConcern = false | |
97 | remoteServerDown = false | |
98 | ||
99 | tooltipSupport = '' | |
100 | tooltipSaveToPlaylist = '' | |
101 | ||
102 | videoActionsOptions: VideoActionsDisplayType = { | |
103 | playlist: false, | |
104 | download: true, | |
105 | update: true, | |
106 | blacklist: true, | |
107 | delete: true, | |
108 | report: true, | |
109 | duplicate: true, | |
110 | mute: true, | |
111 | liveInfo: true | |
112 | } | |
113 | ||
114 | userRating: UserVideoRateType | |
115 | ||
116 | private nextVideoUuid = '' | |
117 | private nextVideoTitle = '' | |
118 | private currentTime: number | |
119 | private paramsSub: Subscription | |
120 | private queryParamsSub: Subscription | |
121 | private configSub: Subscription | |
122 | private liveVideosSub: Subscription | |
123 | ||
124 | private serverConfig: HTMLServerConfig | |
125 | ||
126 | private hotkeys: Hotkey[] = [] | |
127 | ||
128 | constructor ( | |
129 | private elementRef: ElementRef, | |
130 | private changeDetector: ChangeDetectorRef, | |
131 | private route: ActivatedRoute, | |
132 | private router: Router, | |
133 | private videoService: VideoService, | |
134 | private playlistService: VideoPlaylistService, | |
135 | private confirmService: ConfirmService, | |
136 | private metaService: MetaService, | |
137 | private authService: AuthService, | |
138 | private userService: UserService, | |
139 | private serverService: ServerService, | |
140 | private restExtractor: RestExtractor, | |
141 | private notifier: Notifier, | |
142 | private markdownService: MarkdownService, | |
143 | private zone: NgZone, | |
144 | private redirectService: RedirectService, | |
145 | private videoCaptionService: VideoCaptionService, | |
146 | private hotkeysService: HotkeysService, | |
147 | private hooks: HooksService, | |
148 | private pluginService: PluginService, | |
149 | private peertubeSocket: PeerTubeSocket, | |
150 | private screenService: ScreenService, | |
151 | private location: PlatformLocation, | |
152 | @Inject(LOCALE_ID) private localeId: string | |
153 | ) { } | |
154 | ||
155 | get user () { | |
156 | return this.authService.getUser() | |
157 | } | |
158 | ||
159 | get anonymousUser () { | |
160 | return this.userService.getAnonymousUser() | |
161 | } | |
162 | ||
163 | async ngOnInit () { | |
164 | // Hide the tooltips for unlogged users in mobile view, this adds confusion with the popover | |
165 | if (this.user || !this.screenService.isInMobileView()) { | |
166 | this.tooltipSupport = $localize`Support options for this video` | |
167 | this.tooltipSaveToPlaylist = $localize`Save to playlist` | |
168 | } | |
169 | ||
170 | PeertubePlayerManager.initState() | |
171 | ||
172 | this.serverConfig = this.serverService.getHTMLConfig() | |
173 | if ( | |
174 | isWebRTCDisabled() || | |
175 | this.serverConfig.tracker.enabled === false || | |
176 | getStoredP2PEnabled() === false || | |
177 | peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true' | |
178 | ) { | |
179 | this.hasAlreadyAcceptedPrivacyConcern = true | |
180 | } | |
181 | ||
182 | this.paramsSub = this.route.params.subscribe(routeParams => { | |
183 | const videoId = routeParams[ 'videoId' ] | |
184 | if (videoId) this.loadVideo(videoId) | |
185 | ||
186 | const playlistId = routeParams[ 'playlistId' ] | |
187 | if (playlistId) this.loadPlaylist(playlistId) | |
188 | }) | |
189 | ||
190 | this.queryParamsSub = this.route.queryParams.subscribe(queryParams => { | |
191 | // Handle the ?playlistPosition | |
192 | const positionParam = queryParams[ 'playlistPosition' ] ?? 1 | |
193 | ||
194 | this.playlistPosition = positionParam === 'last' | |
195 | ? -1 // Handle the "last" index | |
196 | : parseInt(positionParam + '', 10) | |
197 | ||
198 | if (isNaN(this.playlistPosition)) { | |
199 | console.error(`playlistPosition query param '${positionParam}' was parsed as NaN, defaulting to 1.`) | |
200 | this.playlistPosition = 1 | |
201 | } | |
202 | ||
203 | this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition) | |
204 | ||
205 | const start = queryParams[ 'start' ] | |
206 | if (this.player && start) this.player.currentTime(parseInt(start, 10)) | |
207 | }) | |
208 | ||
209 | this.initHotkeys() | |
210 | ||
211 | this.theaterEnabled = getStoredTheater() | |
212 | ||
213 | this.hooks.runAction('action:video-watch.init', 'video-watch') | |
214 | ||
215 | setTimeout(cleanupVideoWatch, 1500) // Run in timeout to ensure we're not blocking the UI | |
216 | } | |
217 | ||
218 | ngOnDestroy () { | |
219 | this.flushPlayer() | |
220 | ||
221 | // Unsubscribe subscriptions | |
222 | if (this.paramsSub) this.paramsSub.unsubscribe() | |
223 | if (this.queryParamsSub) this.queryParamsSub.unsubscribe() | |
224 | if (this.configSub) this.configSub.unsubscribe() | |
225 | if (this.liveVideosSub) this.liveVideosSub.unsubscribe() | |
226 | ||
227 | // Unbind hotkeys | |
228 | this.hotkeysService.remove(this.hotkeys) | |
229 | } | |
230 | ||
231 | showMoreDescription () { | |
232 | if (this.completeVideoDescription === undefined) { | |
233 | return this.loadCompleteDescription() | |
234 | } | |
235 | ||
236 | this.updateVideoDescription(this.completeVideoDescription) | |
237 | this.completeDescriptionShown = true | |
238 | } | |
239 | ||
240 | showLessDescription () { | |
241 | this.updateVideoDescription(this.shortVideoDescription) | |
242 | this.completeDescriptionShown = false | |
243 | } | |
244 | ||
245 | showDownloadModal () { | |
246 | this.videoDownloadModal.show(this.video, this.videoCaptions) | |
247 | } | |
248 | ||
249 | isVideoDownloadable () { | |
250 | return this.video && this.video instanceof VideoDetails && this.video.downloadEnabled && !this.video.isLive | |
251 | } | |
252 | ||
253 | loadCompleteDescription () { | |
254 | this.descriptionLoading = true | |
255 | ||
256 | this.videoService.loadCompleteDescription(this.video.descriptionPath) | |
257 | .subscribe( | |
258 | description => { | |
259 | this.completeDescriptionShown = true | |
260 | this.descriptionLoading = false | |
261 | ||
262 | this.shortVideoDescription = this.video.description | |
263 | this.completeVideoDescription = description | |
264 | ||
265 | this.updateVideoDescription(this.completeVideoDescription) | |
266 | }, | |
267 | ||
268 | error => { | |
269 | this.descriptionLoading = false | |
270 | this.notifier.error(error.message) | |
271 | } | |
272 | ) | |
273 | } | |
274 | ||
275 | showSupportModal () { | |
276 | this.supportModal.show() | |
277 | } | |
278 | ||
279 | showShareModal () { | |
280 | this.videoShareModal.show(this.currentTime, this.videoWatchPlaylist.currentPlaylistPosition) | |
281 | } | |
282 | ||
283 | isUserLoggedIn () { | |
284 | return this.authService.isLoggedIn() | |
285 | } | |
286 | ||
287 | getVideoUrl () { | |
288 | if (!this.video.url) { | |
289 | return this.video.originInstanceUrl + VideoDetails.buildWatchUrl(this.video) | |
290 | } | |
291 | return this.video.url | |
292 | } | |
293 | ||
294 | getVideoTags () { | |
295 | if (!this.video || Array.isArray(this.video.tags) === false) return [] | |
296 | ||
297 | return this.video.tags | |
298 | } | |
299 | ||
300 | onRecommendations (videos: Video[]) { | |
301 | if (videos.length > 0) { | |
302 | // The recommended videos's first element should be the next video | |
303 | const video = videos[0] | |
304 | this.nextVideoUuid = video.uuid | |
305 | this.nextVideoTitle = video.name | |
306 | } | |
307 | } | |
308 | ||
309 | onVideoRemoved () { | |
310 | this.redirectService.redirectToHomepage() | |
311 | } | |
312 | ||
313 | declinedPrivacyConcern () { | |
314 | peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false') | |
315 | this.hasAlreadyAcceptedPrivacyConcern = false | |
316 | } | |
317 | ||
318 | acceptedPrivacyConcern () { | |
319 | peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true') | |
320 | this.hasAlreadyAcceptedPrivacyConcern = true | |
321 | } | |
322 | ||
323 | isVideoToTranscode () { | |
324 | return this.video && this.video.state.id === VideoState.TO_TRANSCODE | |
325 | } | |
326 | ||
327 | isVideoToImport () { | |
328 | return this.video && this.video.state.id === VideoState.TO_IMPORT | |
329 | } | |
330 | ||
331 | hasVideoScheduledPublication () { | |
332 | return this.video && this.video.scheduledUpdate !== undefined | |
333 | } | |
334 | ||
335 | isLive () { | |
336 | return !!(this.video?.isLive) | |
337 | } | |
338 | ||
339 | isWaitingForLive () { | |
340 | return this.video?.state.id === VideoState.WAITING_FOR_LIVE | |
341 | } | |
342 | ||
343 | isLiveEnded () { | |
344 | return this.video?.state.id === VideoState.LIVE_ENDED | |
345 | } | |
346 | ||
347 | isVideoBlur (video: Video) { | |
348 | return video.isVideoNSFWForUser(this.user, this.serverConfig) | |
349 | } | |
350 | ||
351 | isAutoPlayEnabled () { | |
352 | return ( | |
353 | (this.user && this.user.autoPlayNextVideo) || | |
354 | this.anonymousUser.autoPlayNextVideo | |
355 | ) | |
356 | } | |
357 | ||
358 | handleTimestampClicked (timestamp: number) { | |
359 | if (!this.player || this.video.isLive) return | |
360 | ||
361 | this.player.currentTime(timestamp) | |
362 | scrollToTop() | |
363 | } | |
364 | ||
365 | isPlaylistAutoPlayEnabled () { | |
366 | return ( | |
367 | (this.user && this.user.autoPlayNextVideoPlaylist) || | |
368 | this.anonymousUser.autoPlayNextVideoPlaylist | |
369 | ) | |
370 | } | |
371 | ||
372 | isChannelDisplayNameGeneric () { | |
373 | const genericChannelDisplayName = [ | |
374 | `Main ${this.video.channel.ownerAccount.name} channel`, | |
375 | `Default ${this.video.channel.ownerAccount.name} channel` | |
376 | ] | |
377 | ||
378 | return genericChannelDisplayName.includes(this.video.channel.displayName) | |
379 | } | |
380 | ||
381 | onPlaylistVideoFound (videoId: string) { | |
382 | this.loadVideo(videoId) | |
383 | } | |
384 | ||
385 | onRateUpdated (userRating: UserVideoRateType) { | |
386 | this.userRating = userRating | |
387 | this.setVideoLikesBarTooltipText() | |
388 | } | |
389 | ||
390 | displayOtherVideosAsRow () { | |
391 | // Use the same value as in the SASS file | |
392 | return this.screenService.getWindowInnerWidth() <= 1100 | |
393 | } | |
394 | ||
395 | private loadVideo (videoId: string) { | |
396 | // Video did not change | |
397 | if ( | |
398 | this.video && | |
399 | (this.video.uuid === videoId || this.video.shortUUID === videoId) | |
400 | ) return | |
401 | ||
402 | if (this.player) this.player.pause() | |
403 | ||
404 | const videoObs = this.hooks.wrapObsFun( | |
405 | this.videoService.getVideo.bind(this.videoService), | |
406 | { videoId }, | |
407 | 'video-watch', | |
408 | 'filter:api.video-watch.video.get.params', | |
409 | 'filter:api.video-watch.video.get.result' | |
410 | ) | |
411 | ||
412 | // Video did change | |
413 | forkJoin([ | |
414 | videoObs, | |
415 | this.videoCaptionService.listCaptions(videoId) | |
416 | ]) | |
417 | .pipe( | |
418 | // If 400, 403 or 404, the video is private or blocked so redirect to 404 | |
419 | catchError(err => { | |
420 | const errorBody = err.body as PeerTubeProblemDocument | |
421 | ||
422 | if (errorBody.code === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && errorBody.originUrl) { | |
423 | const search = window.location.search | |
424 | let originUrl = errorBody.originUrl | |
425 | if (search) originUrl += search | |
426 | ||
427 | this.confirmService.confirm( | |
428 | $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`, | |
429 | $localize`Redirection` | |
430 | ).then(res => { | |
431 | if (res === false) { | |
432 | return this.restExtractor.redirectTo404IfNotFound(err, 'video', [ | |
433 | HttpStatusCode.BAD_REQUEST_400, | |
434 | HttpStatusCode.FORBIDDEN_403, | |
435 | HttpStatusCode.NOT_FOUND_404 | |
436 | ]) | |
437 | } | |
438 | ||
439 | return window.location.href = originUrl | |
440 | }) | |
441 | } | |
442 | ||
443 | return this.restExtractor.redirectTo404IfNotFound(err, 'video', [ | |
444 | HttpStatusCode.BAD_REQUEST_400, | |
445 | HttpStatusCode.FORBIDDEN_403, | |
446 | HttpStatusCode.NOT_FOUND_404 | |
447 | ]) | |
448 | }) | |
449 | ) | |
450 | .subscribe(([ video, captionsResult ]) => { | |
451 | const queryParams = this.route.snapshot.queryParams | |
452 | ||
453 | const urlOptions = { | |
454 | resume: queryParams.resume, | |
455 | ||
456 | startTime: queryParams.start, | |
457 | stopTime: queryParams.stop, | |
458 | ||
459 | muted: queryParams.muted, | |
460 | loop: queryParams.loop, | |
461 | subtitle: queryParams.subtitle, | |
462 | ||
463 | playerMode: queryParams.mode, | |
464 | peertubeLink: false | |
465 | } | |
466 | ||
467 | this.onVideoFetched(video, captionsResult.data, urlOptions) | |
468 | .catch(err => this.handleError(err)) | |
469 | }) | |
470 | } | |
471 | ||
472 | private loadPlaylist (playlistId: string) { | |
473 | // Playlist did not change | |
474 | if ( | |
475 | this.playlist && | |
476 | (this.playlist.uuid === playlistId || this.playlist.shortUUID === playlistId) | |
477 | ) return | |
478 | ||
479 | this.playlistService.getVideoPlaylist(playlistId) | |
480 | .pipe( | |
481 | // If 400 or 403, the video is private or blocked so redirect to 404 | |
482 | catchError(err => this.restExtractor.redirectTo404IfNotFound(err, 'video', [ | |
483 | HttpStatusCode.BAD_REQUEST_400, | |
484 | HttpStatusCode.FORBIDDEN_403, | |
485 | HttpStatusCode.NOT_FOUND_404 | |
486 | ])) | |
487 | ) | |
488 | .subscribe(playlist => { | |
489 | this.playlist = playlist | |
490 | ||
491 | this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition) | |
492 | }) | |
493 | } | |
494 | ||
495 | private updateVideoDescription (description: string) { | |
496 | this.video.description = description | |
497 | this.setVideoDescriptionHTML() | |
498 | .catch(err => console.error(err)) | |
499 | } | |
500 | ||
501 | private async setVideoDescriptionHTML () { | |
502 | const html = await this.markdownService.textMarkdownToHTML(this.video.description) | |
503 | this.videoHTMLDescription = this.markdownService.processVideoTimestamps(html) | |
504 | } | |
505 | ||
506 | private setVideoLikesBarTooltipText () { | |
507 | this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes` | |
508 | } | |
509 | ||
510 | private handleError (err: any) { | |
511 | const errorMessage: string = typeof err === 'string' ? err : err.message | |
512 | if (!errorMessage) return | |
513 | ||
514 | // Display a message in the video player instead of a notification | |
515 | if (errorMessage.indexOf('from xs param') !== -1) { | |
516 | this.flushPlayer() | |
517 | this.remoteServerDown = true | |
518 | this.changeDetector.detectChanges() | |
519 | ||
520 | return | |
521 | } | |
522 | ||
523 | this.notifier.error(errorMessage) | |
524 | } | |
525 | ||
526 | private async onVideoFetched ( | |
527 | video: VideoDetails, | |
528 | videoCaptions: VideoCaption[], | |
529 | urlOptions: URLOptions | |
530 | ) { | |
531 | this.subscribeToLiveEventsIfNeeded(this.video, video) | |
532 | ||
533 | this.video = video | |
534 | this.videoCaptions = videoCaptions | |
535 | ||
536 | // Re init attributes | |
537 | this.playerPlaceholderImgSrc = undefined | |
538 | this.descriptionLoading = false | |
539 | this.completeDescriptionShown = false | |
540 | this.completeVideoDescription = undefined | |
541 | this.remoteServerDown = false | |
542 | this.currentTime = undefined | |
543 | ||
544 | if (this.isVideoBlur(this.video)) { | |
545 | const res = await this.confirmService.confirm( | |
546 | $localize`This video contains mature or explicit content. Are you sure you want to watch it?`, | |
547 | $localize`Mature or explicit content` | |
548 | ) | |
549 | if (res === false) return this.location.back() | |
550 | } | |
551 | ||
552 | this.buildPlayer(urlOptions) | |
553 | .catch(err => console.error('Cannot build the player', err)) | |
554 | ||
555 | this.setVideoDescriptionHTML() | |
556 | this.setVideoLikesBarTooltipText() | |
557 | ||
558 | this.setOpenGraphTags() | |
559 | ||
560 | const hookOptions = { | |
561 | videojs, | |
562 | video: this.video, | |
563 | playlist: this.playlist | |
564 | } | |
565 | this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', hookOptions) | |
566 | } | |
567 | ||
568 | private async buildPlayer (urlOptions: URLOptions) { | |
569 | // Flush old player if needed | |
570 | this.flushPlayer() | |
571 | ||
572 | const videoState = this.video.state.id | |
573 | if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) { | |
574 | this.playerPlaceholderImgSrc = this.video.previewPath | |
575 | return | |
576 | } | |
577 | ||
578 | // Build video element, because videojs removes it on dispose | |
579 | const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper') | |
580 | this.playerElement = document.createElement('video') | |
581 | this.playerElement.className = 'video-js vjs-peertube-skin' | |
582 | this.playerElement.setAttribute('playsinline', 'true') | |
583 | playerElementWrapper.appendChild(this.playerElement) | |
584 | ||
585 | const params = { | |
586 | video: this.video, | |
587 | videoCaptions: this.videoCaptions, | |
588 | urlOptions, | |
589 | user: this.user | |
590 | } | |
591 | const { playerMode, playerOptions } = await this.hooks.wrapFun( | |
592 | this.buildPlayerManagerOptions.bind(this), | |
593 | params, | |
594 | 'video-watch', | |
595 | 'filter:internal.video-watch.player.build-options.params', | |
596 | 'filter:internal.video-watch.player.build-options.result' | |
597 | ) | |
598 | ||
599 | this.zone.runOutsideAngular(async () => { | |
600 | this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player) | |
601 | ||
602 | this.player.on('customError', ({ err }: { err: any }) => this.handleError(err)) | |
603 | ||
604 | this.player.on('timeupdate', () => { | |
605 | this.currentTime = Math.floor(this.player.currentTime()) | |
606 | }) | |
607 | ||
608 | /** | |
609 | * replaces this.player.one('ended') | |
610 | * 'condition()': true to make the upnext functionality trigger, | |
611 | * false to disable the upnext functionality | |
612 | * go to the next video in 'condition()' if you don't want of the timer. | |
613 | * 'next': function triggered at the end of the timer. | |
614 | * 'suspended': function used at each clic of the timer checking if we need | |
615 | * to reset progress and wait until 'suspended' becomes truthy again. | |
616 | */ | |
617 | this.player.upnext({ | |
618 | timeout: 10000, // 10s | |
619 | headText: $localize`Up Next`, | |
620 | cancelText: $localize`Cancel`, | |
621 | suspendedText: $localize`Autoplay is suspended`, | |
622 | getTitle: () => this.nextVideoTitle, | |
623 | next: () => this.zone.run(() => this.autoplayNext()), | |
624 | condition: () => { | |
625 | if (this.playlist) { | |
626 | if (this.isPlaylistAutoPlayEnabled()) { | |
627 | // upnext will not trigger, and instead the next video will play immediately | |
628 | this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo()) | |
629 | } | |
630 | } else if (this.isAutoPlayEnabled()) { | |
631 | return true // upnext will trigger | |
632 | } | |
633 | return false // upnext will not trigger, and instead leave the video stopping | |
634 | }, | |
635 | suspended: () => { | |
636 | return ( | |
637 | !isXPercentInViewport(this.player.el(), 80) || | |
638 | !document.getElementById('content').contains(document.activeElement) | |
639 | ) | |
640 | } | |
641 | }) | |
642 | ||
643 | this.player.one('stopped', () => { | |
644 | if (this.playlist) { | |
645 | if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo()) | |
646 | } | |
647 | }) | |
648 | ||
649 | this.player.one('ended', () => { | |
650 | if (this.video.isLive) { | |
651 | this.zone.run(() => this.video.state.id = VideoState.LIVE_ENDED) | |
652 | } | |
653 | }) | |
654 | ||
655 | this.player.on('theaterChange', (_: any, enabled: boolean) => { | |
656 | this.zone.run(() => this.theaterEnabled = enabled) | |
657 | }) | |
658 | ||
659 | this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player, videojs, video: this.video }) | |
660 | }) | |
661 | } | |
662 | ||
663 | private autoplayNext () { | |
664 | if (this.playlist) { | |
665 | this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo()) | |
666 | } else if (this.nextVideoUuid) { | |
667 | this.router.navigate([ '/w', this.nextVideoUuid ]) | |
668 | } | |
669 | } | |
670 | ||
671 | private setOpenGraphTags () { | |
672 | this.metaService.setTitle(this.video.name) | |
673 | ||
674 | this.metaService.setTag('og:type', 'video') | |
675 | ||
676 | this.metaService.setTag('og:title', this.video.name) | |
677 | this.metaService.setTag('name', this.video.name) | |
678 | ||
679 | this.metaService.setTag('og:description', this.video.description) | |
680 | this.metaService.setTag('description', this.video.description) | |
681 | ||
682 | this.metaService.setTag('og:image', this.video.previewPath) | |
683 | ||
684 | this.metaService.setTag('og:duration', this.video.duration.toString()) | |
685 | ||
686 | this.metaService.setTag('og:site_name', 'PeerTube') | |
687 | ||
688 | this.metaService.setTag('og:url', window.location.href) | |
689 | this.metaService.setTag('url', window.location.href) | |
690 | } | |
691 | ||
692 | private isAutoplay () { | |
693 | // We'll jump to the thread id, so do not play the video | |
694 | if (this.route.snapshot.params['threadId']) return false | |
695 | ||
696 | // Otherwise true by default | |
697 | if (!this.user) return true | |
698 | ||
699 | // Be sure the autoPlay is set to false | |
700 | return this.user.autoPlayVideo !== false | |
701 | } | |
702 | ||
703 | private flushPlayer () { | |
704 | // Remove player if it exists | |
705 | if (!this.player) return | |
706 | ||
707 | try { | |
708 | this.player.dispose() | |
709 | this.player = undefined | |
710 | } catch (err) { | |
711 | console.error('Cannot dispose player.', err) | |
712 | } | |
713 | } | |
714 | ||
715 | private buildPlayerManagerOptions (params: { | |
716 | video: VideoDetails, | |
717 | videoCaptions: VideoCaption[], | |
718 | urlOptions: CustomizationOptions & { playerMode: PlayerMode }, | |
719 | user?: AuthUser | |
720 | }) { | |
721 | const { video, videoCaptions, urlOptions, user } = params | |
722 | const getStartTime = () => { | |
723 | const byUrl = urlOptions.startTime !== undefined | |
724 | const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined) | |
725 | const byLocalStorage = getStoredVideoWatchHistory(video.uuid) | |
726 | ||
727 | if (byUrl) return timeToInt(urlOptions.startTime) | |
728 | if (byHistory) return video.userHistory.currentTime | |
729 | if (byLocalStorage) return byLocalStorage.duration | |
730 | ||
731 | return 0 | |
732 | } | |
733 | ||
734 | let startTime = getStartTime() | |
735 | ||
736 | // If we are at the end of the video, reset the timer | |
737 | if (video.duration - startTime <= 1) startTime = 0 | |
738 | ||
739 | const playerCaptions = videoCaptions.map(c => ({ | |
740 | label: c.language.label, | |
741 | language: c.language.id, | |
742 | src: environment.apiUrl + c.captionPath | |
743 | })) | |
744 | ||
745 | const options: PeertubePlayerManagerOptions = { | |
746 | common: { | |
747 | autoplay: this.isAutoplay(), | |
748 | nextVideo: () => this.zone.run(() => this.autoplayNext()), | |
749 | ||
750 | playerElement: this.playerElement, | |
751 | onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element, | |
752 | ||
753 | videoDuration: video.duration, | |
754 | enableHotkeys: true, | |
755 | inactivityTimeout: 2500, | |
756 | poster: video.previewUrl, | |
757 | ||
758 | startTime, | |
759 | stopTime: urlOptions.stopTime, | |
760 | controls: urlOptions.controls, | |
761 | muted: urlOptions.muted, | |
762 | loop: urlOptions.loop, | |
763 | subtitle: urlOptions.subtitle, | |
764 | ||
765 | peertubeLink: urlOptions.peertubeLink, | |
766 | ||
767 | theaterButton: true, | |
768 | captions: videoCaptions.length !== 0, | |
769 | ||
770 | videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE | |
771 | ? this.videoService.getVideoViewUrl(video.uuid) | |
772 | : null, | |
773 | embedUrl: video.embedUrl, | |
774 | embedTitle: video.name, | |
775 | ||
776 | isLive: video.isLive, | |
777 | ||
778 | language: this.localeId, | |
779 | ||
780 | userWatching: user && user.videosHistoryEnabled === true ? { | |
781 | url: this.videoService.getUserWatchingVideoUrl(video.uuid), | |
782 | authorizationHeader: this.authService.getRequestHeaderValue() | |
783 | } : undefined, | |
784 | ||
785 | serverUrl: environment.apiUrl, | |
786 | ||
787 | videoCaptions: playerCaptions, | |
788 | ||
789 | videoUUID: video.uuid | |
790 | }, | |
791 | ||
792 | webtorrent: { | |
793 | videoFiles: video.files | |
794 | }, | |
795 | ||
796 | pluginsManager: this.pluginService.getPluginsManager() | |
797 | } | |
798 | ||
799 | // Only set this if we're in a playlist | |
800 | if (this.playlist) { | |
801 | options.common.previousVideo = () => { | |
802 | this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo()) | |
803 | } | |
804 | } | |
805 | ||
806 | let mode: PlayerMode | |
807 | ||
808 | if (urlOptions.playerMode) { | |
809 | if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader' | |
810 | else mode = 'webtorrent' | |
811 | } else { | |
812 | if (video.hasHlsPlaylist()) mode = 'p2p-media-loader' | |
813 | else mode = 'webtorrent' | |
814 | } | |
815 | ||
816 | // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent | |
817 | if (typeof TextEncoder === 'undefined') { | |
818 | mode = 'webtorrent' | |
819 | } | |
820 | ||
821 | if (mode === 'p2p-media-loader') { | |
822 | const hlsPlaylist = video.getHlsPlaylist() | |
823 | ||
824 | const p2pMediaLoader = { | |
825 | playlistUrl: hlsPlaylist.playlistUrl, | |
826 | segmentsSha256Url: hlsPlaylist.segmentsSha256Url, | |
827 | redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl), | |
828 | trackerAnnounce: video.trackerUrls, | |
829 | videoFiles: hlsPlaylist.files | |
830 | } as P2PMediaLoaderOptions | |
831 | ||
832 | Object.assign(options, { p2pMediaLoader }) | |
833 | } | |
834 | ||
835 | return { playerMode: mode, playerOptions: options } | |
836 | } | |
837 | ||
838 | private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) { | |
839 | if (!this.liveVideosSub) { | |
840 | this.liveVideosSub = this.buildLiveEventsSubscription() | |
841 | } | |
842 | ||
843 | if (oldVideo && oldVideo.id !== newVideo.id) { | |
844 | await this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id) | |
845 | } | |
846 | ||
847 | if (!newVideo.isLive) return | |
848 | ||
849 | await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id) | |
850 | } | |
851 | ||
852 | private buildLiveEventsSubscription () { | |
853 | return this.peertubeSocket.getLiveVideosObservable() | |
854 | .subscribe(({ type, payload }) => { | |
855 | if (type === 'state-change') return this.handleLiveStateChange(payload.state) | |
856 | if (type === 'views-change') return this.handleLiveViewsChange(payload.views) | |
857 | }) | |
858 | } | |
859 | ||
860 | private handleLiveStateChange (newState: VideoState) { | |
861 | if (newState !== VideoState.PUBLISHED) return | |
862 | ||
863 | const videoState = this.video.state.id | |
864 | if (videoState !== VideoState.WAITING_FOR_LIVE && videoState !== VideoState.LIVE_ENDED) return | |
865 | ||
866 | console.log('Loading video after live update.') | |
867 | ||
868 | const videoUUID = this.video.uuid | |
869 | ||
870 | // Reset to refetch the video | |
871 | this.video = undefined | |
872 | this.loadVideo(videoUUID) | |
873 | } | |
874 | ||
875 | private handleLiveViewsChange (newViews: number) { | |
876 | if (!this.video) { | |
877 | console.error('Cannot update video live views because video is no defined.') | |
878 | return | |
879 | } | |
880 | ||
881 | console.log('Updating live views.') | |
882 | ||
883 | this.video.views = newViews | |
884 | } | |
885 | ||
886 | private initHotkeys () { | |
887 | this.hotkeys = [ | |
888 | // These hotkeys are managed by the player | |
889 | new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`), | |
890 | new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`), | |
891 | new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`), | |
892 | ||
893 | new Hotkey('0-9', e => e, undefined, $localize`Skip to a percentage of the video: 0 is 0% and 9 is 90% (requires player focus)`), | |
894 | ||
895 | new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`), | |
896 | new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`), | |
897 | ||
898 | new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`), | |
899 | new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`), | |
900 | ||
901 | new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`), | |
902 | new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`), | |
903 | ||
904 | new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`) | |
905 | ] | |
906 | ||
907 | if (this.isUserLoggedIn()) { | |
908 | this.hotkeys = this.hotkeys.concat([ | |
909 | new Hotkey('shift+s', () => { | |
910 | this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe() | |
911 | return false | |
912 | }, undefined, $localize`Subscribe to the account`) | |
913 | ]) | |
914 | } | |
915 | ||
916 | this.hotkeysService.add(this.hotkeys) | |
917 | } | |
918 | } |