1 import { catchError } from 'rxjs/operators'
2 import { ChangeDetectorRef, Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
3 import { ActivatedRoute, Router } from '@angular/router'
4 import { RedirectService } from '@app/core/routing/redirect.service'
5 import { peertubeLocalStorage } from '@app/shared/misc/peertube-local-storage'
6 import { VideoSupportComponent } from '@app/videos/+video-watch/modal/video-support.component'
7 import { MetaService } from '@ngx-meta/core'
8 import { Notifier, ServerService } from '@app/core'
9 import { forkJoin, Observable, Subscription } from 'rxjs'
10 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
11 import { UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '../../../../../shared'
12 import { AuthService, ConfirmService } from '../../core'
13 import { RestExtractor, VideoBlacklistService } from '../../shared'
14 import { VideoDetails } from '../../shared/video/video-details.model'
15 import { VideoService } from '../../shared/video/video.service'
16 import { VideoShareComponent } from './modal/video-share.component'
17 import { SubscribeButtonComponent } from '@app/shared/user-subscription/subscribe-button.component'
18 import { I18n } from '@ngx-translate/i18n-polyfill'
19 import { environment } from '../../../environments/environment'
20 import { VideoCaptionService } from '@app/shared/video-caption'
21 import { MarkdownService } from '@app/shared/renderer'
24 P2PMediaLoaderOptions,
25 PeertubePlayerManager,
26 PeertubePlayerManagerOptions,
28 } from '../../../assets/player/peertube-player-manager'
29 import { VideoPlaylist } from '@app/shared/video-playlist/video-playlist.model'
30 import { VideoPlaylistService } from '@app/shared/video-playlist/video-playlist.service'
31 import { Video } from '@app/shared/video/video.model'
32 import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils'
33 import { VideoWatchPlaylistComponent } from '@app/videos/+video-watch/video-watch-playlist.component'
34 import { getStoredTheater } from '../../../assets/player/peertube-player-local-storage'
35 import { PluginService } from '@app/core/plugins/plugin.service'
36 import { HooksService } from '@app/core/plugins/hooks.service'
39 selector: 'my-video-watch',
40 templateUrl: './video-watch.component.html',
41 styleUrls: [ './video-watch.component.scss' ]
43 export class VideoWatchComponent implements OnInit, OnDestroy {
44 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
46 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
47 @ViewChild('videoShareModal', { static: false }) videoShareModal: VideoShareComponent
48 @ViewChild('videoSupportModal', { static: false }) videoSupportModal: VideoSupportComponent
49 @ViewChild('subscribeButton', { static: false }) subscribeButton: SubscribeButtonComponent
52 playerElement: HTMLVideoElement
53 theaterEnabled = false
54 userRating: UserVideoRateType = null
55 descriptionLoading = false
57 video: VideoDetails = null
58 videoCaptions: VideoCaption[] = []
60 playlist: VideoPlaylist = null
62 completeDescriptionShown = false
63 completeVideoDescription: string
64 shortVideoDescription: string
65 videoHTMLDescription = ''
66 likesBarTooltipText = ''
67 hasAlreadyAcceptedPrivacyConcern = false
68 remoteServerDown = false
71 private currentTime: number
72 private paramsSub: Subscription
73 private queryParamsSub: Subscription
74 private configSub: Subscription
77 private elementRef: ElementRef,
78 private changeDetector: ChangeDetectorRef,
79 private route: ActivatedRoute,
80 private router: Router,
81 private videoService: VideoService,
82 private playlistService: VideoPlaylistService,
83 private videoBlacklistService: VideoBlacklistService,
84 private confirmService: ConfirmService,
85 private metaService: MetaService,
86 private authService: AuthService,
87 private serverService: ServerService,
88 private restExtractor: RestExtractor,
89 private notifier: Notifier,
90 private pluginService: PluginService,
91 private markdownService: MarkdownService,
93 private redirectService: RedirectService,
94 private videoCaptionService: VideoCaptionService,
96 private hotkeysService: HotkeysService,
97 private hooks: HooksService,
98 @Inject(LOCALE_ID) private localeId: string
102 return this.authService.getUser()
106 this.configSub = this.serverService.configLoaded
109 isWebRTCDisabled() ||
110 this.serverService.getConfig().tracker.enabled === false ||
111 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
113 this.hasAlreadyAcceptedPrivacyConcern = true
117 this.paramsSub = this.route.params.subscribe(routeParams => {
118 const videoId = routeParams[ 'videoId' ]
119 if (videoId) this.loadVideo(videoId)
121 const playlistId = routeParams[ 'playlistId' ]
122 if (playlistId) this.loadPlaylist(playlistId)
125 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
126 const videoId = queryParams[ 'videoId' ]
127 if (videoId) this.loadVideo(videoId)
132 this.theaterEnabled = getStoredTheater()
134 this.hooks.runAction('action:video-watch.init', 'video-watch')
140 // Unsubscribe subscriptions
141 if (this.paramsSub) this.paramsSub.unsubscribe()
142 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
145 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
149 if (this.isUserLoggedIn() === false) return
151 // Already liked this video
152 if (this.userRating === 'like') this.setRating('none')
153 else this.setRating('like')
157 if (this.isUserLoggedIn() === false) return
159 // Already disliked this video
160 if (this.userRating === 'dislike') this.setRating('none')
161 else this.setRating('dislike')
164 showMoreDescription () {
165 if (this.completeVideoDescription === undefined) {
166 return this.loadCompleteDescription()
169 this.updateVideoDescription(this.completeVideoDescription)
170 this.completeDescriptionShown = true
173 showLessDescription () {
174 this.updateVideoDescription(this.shortVideoDescription)
175 this.completeDescriptionShown = false
178 loadCompleteDescription () {
179 this.descriptionLoading = true
181 this.videoService.loadCompleteDescription(this.video.descriptionPath)
184 this.completeDescriptionShown = true
185 this.descriptionLoading = false
187 this.shortVideoDescription = this.video.description
188 this.completeVideoDescription = description
190 this.updateVideoDescription(this.completeVideoDescription)
194 this.descriptionLoading = false
195 this.notifier.error(error.message)
200 showSupportModal () {
201 this.videoSupportModal.show()
205 this.videoShareModal.show(this.currentTime)
209 return this.authService.isLoggedIn()
213 if (!this.video || Array.isArray(this.video.tags) === false) return []
215 return this.video.tags
219 this.redirectService.redirectToHomepage()
222 acceptedPrivacyConcern () {
223 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
224 this.hasAlreadyAcceptedPrivacyConcern = true
227 isVideoToTranscode () {
228 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
232 return this.video && this.video.state.id === VideoState.TO_IMPORT
235 hasVideoScheduledPublication () {
236 return this.video && this.video.scheduledUpdate !== undefined
239 isVideoBlur (video: Video) {
240 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
243 private loadVideo (videoId: string) {
244 // Video did not change
245 if (this.video && this.video.uuid === videoId) return
247 if (this.player) this.player.pause()
249 const videoObs = this.hooks.wrapObsFun(
250 this.videoService.getVideo.bind(this.videoService),
253 'filter:api.video-watch.video.get.params',
254 'filter:api.video-watch.video.get.result'
260 this.videoCaptionService.listCaptions(videoId)
263 // If 401, the video is private or blacklisted so redirect to 404
264 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
266 .subscribe(([ video, captionsResult ]) => {
267 const queryParams = this.route.snapshot.queryParams
270 startTime: queryParams.start,
271 stopTime: queryParams.stop,
273 muted: queryParams.muted,
274 loop: queryParams.loop,
275 subtitle: queryParams.subtitle,
277 playerMode: queryParams.mode,
281 this.onVideoFetched(video, captionsResult.data, urlOptions)
282 .catch(err => this.handleError(err))
286 private loadPlaylist (playlistId: string) {
287 // Playlist did not change
288 if (this.playlist && this.playlist.uuid === playlistId) return
290 this.playlistService.getVideoPlaylist(playlistId)
292 // If 401, the video is private or blacklisted so redirect to 404
293 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
295 .subscribe(playlist => {
296 this.playlist = playlist
298 const videoId = this.route.snapshot.queryParams['videoId']
299 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
303 private updateVideoDescription (description: string) {
304 this.video.description = description
305 this.setVideoDescriptionHTML()
306 .catch(err => console.error(err))
309 private async setVideoDescriptionHTML () {
310 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
313 private setVideoLikesBarTooltipText () {
314 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
315 likesNumber: this.video.likes,
316 dislikesNumber: this.video.dislikes
320 private handleError (err: any) {
321 const errorMessage: string = typeof err === 'string' ? err : err.message
322 if (!errorMessage) return
324 // Display a message in the video player instead of a notification
325 if (errorMessage.indexOf('from xs param') !== -1) {
327 this.remoteServerDown = true
328 this.changeDetector.detectChanges()
333 this.notifier.error(errorMessage)
336 private checkUserRating () {
337 // Unlogged users do not have ratings
338 if (this.isUserLoggedIn() === false) return
340 this.videoService.getUserVideoRating(this.video.id)
344 this.userRating = ratingObject.rating
348 err => this.notifier.error(err.message)
352 private async onVideoFetched (
354 videoCaptions: VideoCaption[],
355 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
358 this.videoCaptions = videoCaptions
360 // Re init attributes
361 this.descriptionLoading = false
362 this.completeDescriptionShown = false
363 this.remoteServerDown = false
364 this.currentTime = undefined
366 this.videoWatchPlaylist.updatePlaylistIndex(video)
368 let startTime = timeToInt(urlOptions.startTime) || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
369 // If we are at the end of the video, reset the timer
370 if (this.video.duration - startTime <= 1) startTime = 0
372 if (this.isVideoBlur(this.video)) {
373 const res = await this.confirmService.confirm(
374 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
375 this.i18n('Mature or explicit content')
377 if (res === false) return this.redirectService.redirectToHomepage()
380 // Flush old player if needed
383 // Build video element, because videojs remove it on dispose
384 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
385 this.playerElement = document.createElement('video')
386 this.playerElement.className = 'video-js vjs-peertube-skin'
387 this.playerElement.setAttribute('playsinline', 'true')
388 playerElementWrapper.appendChild(this.playerElement)
390 const playerCaptions = videoCaptions.map(c => ({
391 label: c.language.label,
392 language: c.language.id,
393 src: environment.apiUrl + c.captionPath
396 const options: PeertubePlayerManagerOptions = {
398 autoplay: this.isAutoplay(),
400 playerElement: this.playerElement,
401 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
403 videoDuration: this.video.duration,
405 inactivityTimeout: 2500,
406 poster: this.video.previewUrl,
409 stopTime: urlOptions.stopTime,
410 controls: urlOptions.controls,
411 muted: urlOptions.muted,
412 loop: urlOptions.loop,
413 subtitle: urlOptions.subtitle,
415 peertubeLink: urlOptions.peertubeLink,
418 captions: videoCaptions.length !== 0,
420 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE
421 ? this.videoService.getVideoViewUrl(this.video.uuid)
423 embedUrl: this.video.embedUrl,
425 language: this.localeId,
427 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
428 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
429 authorizationHeader: this.authService.getRequestHeaderValue()
432 serverUrl: environment.apiUrl,
434 videoCaptions: playerCaptions
438 videoFiles: this.video.files
444 if (urlOptions.playerMode) {
445 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
446 else mode = 'webtorrent'
448 if (this.video.hasHlsPlaylist()) mode = 'p2p-media-loader'
449 else mode = 'webtorrent'
452 if (mode === 'p2p-media-loader') {
453 const hlsPlaylist = this.video.getHlsPlaylist()
455 const p2pMediaLoader = {
456 playlistUrl: hlsPlaylist.playlistUrl,
457 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
458 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
459 trackerAnnounce: this.video.trackerUrls,
460 videoFiles: this.video.files
461 } as P2PMediaLoaderOptions
463 Object.assign(options, { p2pMediaLoader })
466 this.zone.runOutsideAngular(async () => {
467 this.player = await PeertubePlayerManager.initialize(mode, options, player => this.player = player)
469 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
471 this.player.on('timeupdate', () => {
472 this.currentTime = Math.floor(this.player.currentTime())
475 this.player.one('ended', () => {
477 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
481 this.player.one('stopped', () => {
483 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
487 this.player.on('theaterChange', (_: any, enabled: boolean) => {
488 this.zone.run(() => this.theaterEnabled = enabled)
492 this.setVideoDescriptionHTML()
493 this.setVideoLikesBarTooltipText()
495 this.setOpenGraphTags()
496 this.checkUserRating()
498 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch')
501 private setRating (nextRating: UserVideoRateType) {
502 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
503 like: this.videoService.setVideoLike,
504 dislike: this.videoService.setVideoDislike,
505 none: this.videoService.unsetVideoLike
508 ratingMethods[nextRating].call(this.videoService, this.video.id)
511 // Update the video like attribute
512 this.updateVideoRating(this.userRating, nextRating)
513 this.userRating = nextRating
516 (err: { message: string }) => this.notifier.error(err.message)
520 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
521 let likesToIncrement = 0
522 let dislikesToIncrement = 0
525 if (oldRating === 'like') likesToIncrement--
526 if (oldRating === 'dislike') dislikesToIncrement--
529 if (newRating === 'like') likesToIncrement++
530 if (newRating === 'dislike') dislikesToIncrement++
532 this.video.likes += likesToIncrement
533 this.video.dislikes += dislikesToIncrement
535 this.video.buildLikeAndDislikePercents()
536 this.setVideoLikesBarTooltipText()
539 private setOpenGraphTags () {
540 this.metaService.setTitle(this.video.name)
542 this.metaService.setTag('og:type', 'video')
544 this.metaService.setTag('og:title', this.video.name)
545 this.metaService.setTag('name', this.video.name)
547 this.metaService.setTag('og:description', this.video.description)
548 this.metaService.setTag('description', this.video.description)
550 this.metaService.setTag('og:image', this.video.previewPath)
552 this.metaService.setTag('og:duration', this.video.duration.toString())
554 this.metaService.setTag('og:site_name', 'PeerTube')
556 this.metaService.setTag('og:url', window.location.href)
557 this.metaService.setTag('url', window.location.href)
560 private isAutoplay () {
561 // We'll jump to the thread id, so do not play the video
562 if (this.route.snapshot.params['threadId']) return false
564 // Otherwise true by default
565 if (!this.user) return true
567 // Be sure the autoPlay is set to false
568 return this.user.autoPlayVideo !== false
571 private flushPlayer () {
572 // Remove player if it exists
575 this.player.dispose()
576 this.player = undefined
578 console.error('Cannot dispose player.', err)
583 private initHotkeys () {
585 new Hotkey('shift+l', () => {
588 }, undefined, this.i18n('Like the video')),
590 new Hotkey('shift+d', () => {
593 }, undefined, this.i18n('Dislike the video')),
595 new Hotkey('shift+s', () => {
596 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
598 }, undefined, this.i18n('Subscribe to the account'))
600 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)