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