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