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