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'
36 selector: 'my-video-watch',
37 templateUrl: './video-watch.component.html',
38 styleUrls: [ './video-watch.component.scss' ]
40 export class VideoWatchComponent implements OnInit, OnDestroy {
41 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
43 @ViewChild('videoWatchPlaylist') videoWatchPlaylist: VideoWatchPlaylistComponent
44 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
45 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
46 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
49 playerElement: HTMLVideoElement
50 theaterEnabled = false
51 userRating: UserVideoRateType = null
52 video: VideoDetails = null
53 descriptionLoading = false
55 playlist: VideoPlaylist = null
57 completeDescriptionShown = false
58 completeVideoDescription: string
59 shortVideoDescription: string
60 videoHTMLDescription = ''
61 likesBarTooltipText = ''
62 hasAlreadyAcceptedPrivacyConcern = false
63 remoteServerDown = false
66 private currentTime: number
67 private paramsSub: Subscription
68 private queryParamsSub: Subscription
69 private configSub: Subscription
72 private elementRef: ElementRef,
73 private changeDetector: ChangeDetectorRef,
74 private route: ActivatedRoute,
75 private router: Router,
76 private videoService: VideoService,
77 private playlistService: VideoPlaylistService,
78 private videoBlacklistService: VideoBlacklistService,
79 private confirmService: ConfirmService,
80 private metaService: MetaService,
81 private authService: AuthService,
82 private serverService: ServerService,
83 private restExtractor: RestExtractor,
84 private notifier: Notifier,
85 private markdownService: MarkdownService,
87 private redirectService: RedirectService,
88 private videoCaptionService: VideoCaptionService,
90 private hotkeysService: HotkeysService,
91 @Inject(LOCALE_ID) private localeId: string
95 return this.authService.getUser()
99 this.configSub = this.serverService.configLoaded
102 isWebRTCDisabled() ||
103 this.serverService.getConfig().tracker.enabled === false ||
104 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
106 this.hasAlreadyAcceptedPrivacyConcern = true
110 this.paramsSub = this.route.params.subscribe(routeParams => {
111 const videoId = routeParams[ 'videoId' ]
112 if (videoId) this.loadVideo(videoId)
114 const playlistId = routeParams[ 'playlistId' ]
115 if (playlistId) this.loadPlaylist(playlistId)
118 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
119 const videoId = queryParams[ 'videoId' ]
120 if (videoId) this.loadVideo(videoId)
129 // Unsubscribe subscriptions
130 if (this.paramsSub) this.paramsSub.unsubscribe()
131 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
134 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
138 if (this.isUserLoggedIn() === false) return
140 // Already liked this video
141 if (this.userRating === 'like') this.setRating('none')
142 else this.setRating('like')
146 if (this.isUserLoggedIn() === false) return
148 // Already disliked this video
149 if (this.userRating === 'dislike') this.setRating('none')
150 else this.setRating('dislike')
153 showMoreDescription () {
154 if (this.completeVideoDescription === undefined) {
155 return this.loadCompleteDescription()
158 this.updateVideoDescription(this.completeVideoDescription)
159 this.completeDescriptionShown = true
162 showLessDescription () {
163 this.updateVideoDescription(this.shortVideoDescription)
164 this.completeDescriptionShown = false
167 loadCompleteDescription () {
168 this.descriptionLoading = true
170 this.videoService.loadCompleteDescription(this.video.descriptionPath)
173 this.completeDescriptionShown = true
174 this.descriptionLoading = false
176 this.shortVideoDescription = this.video.description
177 this.completeVideoDescription = description
179 this.updateVideoDescription(this.completeVideoDescription)
183 this.descriptionLoading = false
184 this.notifier.error(error.message)
189 showSupportModal () {
190 this.videoSupportModal.show()
194 this.videoShareModal.show(this.currentTime)
198 return this.authService.isLoggedIn()
202 if (!this.video || Array.isArray(this.video.tags) === false) return []
204 return this.video.tags
208 this.redirectService.redirectToHomepage()
211 acceptedPrivacyConcern () {
212 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
213 this.hasAlreadyAcceptedPrivacyConcern = true
216 isVideoToTranscode () {
217 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
221 return this.video && this.video.state.id === VideoState.TO_IMPORT
224 hasVideoScheduledPublication () {
225 return this.video && this.video.scheduledUpdate !== undefined
228 isVideoBlur (video: Video) {
229 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
232 private loadVideo (videoId: string) {
233 // Video did not change
234 if (this.video && this.video.uuid === videoId) return
236 if (this.player) this.player.pause()
240 this.videoService.getVideo(videoId),
241 this.videoCaptionService.listCaptions(videoId)
244 // If 401, the video is private or blacklisted so redirect to 404
245 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
247 .subscribe(([ video, captionsResult ]) => {
248 const queryParams = this.route.snapshot.queryParams
251 startTime: queryParams.start,
252 stopTime: queryParams.stop,
254 muted: queryParams.muted,
255 loop: queryParams.loop,
256 subtitle: queryParams.subtitle,
258 playerMode: queryParams.mode,
262 this.onVideoFetched(video, captionsResult.data, urlOptions)
263 .catch(err => this.handleError(err))
267 private loadPlaylist (playlistId: string) {
268 // Playlist did not change
269 if (this.playlist && this.playlist.uuid === playlistId) return
271 this.playlistService.getVideoPlaylist(playlistId)
273 // If 401, the video is private or blacklisted so redirect to 404
274 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
276 .subscribe(playlist => {
277 this.playlist = playlist
279 const videoId = this.route.snapshot.queryParams['videoId']
280 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
284 private updateVideoDescription (description: string) {
285 this.video.description = description
286 this.setVideoDescriptionHTML()
287 .catch(err => console.error(err))
290 private async setVideoDescriptionHTML () {
291 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
294 private setVideoLikesBarTooltipText () {
295 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
296 likesNumber: this.video.likes,
297 dislikesNumber: this.video.dislikes
301 private handleError (err: any) {
302 const errorMessage: string = typeof err === 'string' ? err : err.message
303 if (!errorMessage) return
305 // Display a message in the video player instead of a notification
306 if (errorMessage.indexOf('from xs param') !== -1) {
308 this.remoteServerDown = true
309 this.changeDetector.detectChanges()
314 this.notifier.error(errorMessage)
317 private checkUserRating () {
318 // Unlogged users do not have ratings
319 if (this.isUserLoggedIn() === false) return
321 this.videoService.getUserVideoRating(this.video.id)
325 this.userRating = ratingObject.rating
329 err => this.notifier.error(err.message)
333 private async onVideoFetched (
335 videoCaptions: VideoCaption[],
336 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
340 // Re init attributes
341 this.descriptionLoading = false
342 this.completeDescriptionShown = false
343 this.remoteServerDown = false
344 this.currentTime = undefined
346 this.videoWatchPlaylist.updatePlaylistIndex(video)
348 let startTime = timeToInt(urlOptions.startTime) || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
349 // If we are at the end of the video, reset the timer
350 if (this.video.duration - startTime <= 1) startTime = 0
352 if (this.isVideoBlur(this.video)) {
353 const res = await this.confirmService.confirm(
354 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
355 this.i18n('Mature or explicit content')
357 if (res === false) return this.redirectService.redirectToHomepage()
360 // Flush old player if needed
363 // Build video element, because videojs remove it on dispose
364 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
365 this.playerElement = document.createElement('video')
366 this.playerElement.className = 'video-js vjs-peertube-skin'
367 this.playerElement.setAttribute('playsinline', 'true')
368 playerElementWrapper.appendChild(this.playerElement)
370 const playerCaptions = videoCaptions.map(c => ({
371 label: c.language.label,
372 language: c.language.id,
373 src: environment.apiUrl + c.captionPath
376 const options: PeertubePlayerManagerOptions = {
378 autoplay: this.isAutoplay(),
380 playerElement: this.playerElement,
381 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
383 videoDuration: this.video.duration,
385 inactivityTimeout: 2500,
386 poster: this.video.previewUrl,
389 stopTime: urlOptions.stopTime,
390 controls: urlOptions.controls,
391 muted: urlOptions.muted,
392 loop: urlOptions.loop,
393 subtitle: urlOptions.subtitle,
395 peertubeLink: urlOptions.peertubeLink,
398 captions: videoCaptions.length !== 0,
400 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE
401 ? this.videoService.getVideoViewUrl(this.video.uuid)
403 embedUrl: this.video.embedUrl,
405 language: this.localeId,
407 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
408 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
409 authorizationHeader: this.authService.getRequestHeaderValue()
412 serverUrl: environment.apiUrl,
414 videoCaptions: playerCaptions
418 videoFiles: this.video.files
424 if (urlOptions.playerMode) {
425 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
426 else mode = 'webtorrent'
428 if (this.video.hasHlsPlaylist()) mode = 'p2p-media-loader'
429 else mode = 'webtorrent'
432 if (mode === 'p2p-media-loader') {
433 const hlsPlaylist = this.video.getHlsPlaylist()
435 const p2pMediaLoader = {
436 playlistUrl: hlsPlaylist.playlistUrl,
437 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
438 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
439 trackerAnnounce: this.video.trackerUrls,
440 videoFiles: this.video.files
441 } as P2PMediaLoaderOptions
443 Object.assign(options, { p2pMediaLoader })
446 this.zone.runOutsideAngular(async () => {
447 this.player = await PeertubePlayerManager.initialize(mode, options)
448 this.theaterEnabled = this.player.theaterEnabled
450 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
452 this.player.on('timeupdate', () => {
453 this.currentTime = Math.floor(this.player.currentTime())
456 this.player.one('ended', () => {
458 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
462 this.player.one('stopped', () => {
464 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
468 this.player.on('theaterChange', (_: any, enabled: boolean) => {
469 this.zone.run(() => this.theaterEnabled = enabled)
473 this.setVideoDescriptionHTML()
474 this.setVideoLikesBarTooltipText()
476 this.setOpenGraphTags()
477 this.checkUserRating()
480 private setRating (nextRating: UserVideoRateType) {
481 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
482 like: this.videoService.setVideoLike,
483 dislike: this.videoService.setVideoDislike,
484 none: this.videoService.unsetVideoLike
487 ratingMethods[nextRating].call(this.videoService, this.video.id)
490 // Update the video like attribute
491 this.updateVideoRating(this.userRating, nextRating)
492 this.userRating = nextRating
495 (err: { message: string }) => this.notifier.error(err.message)
499 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
500 let likesToIncrement = 0
501 let dislikesToIncrement = 0
504 if (oldRating === 'like') likesToIncrement--
505 if (oldRating === 'dislike') dislikesToIncrement--
508 if (newRating === 'like') likesToIncrement++
509 if (newRating === 'dislike') dislikesToIncrement++
511 this.video.likes += likesToIncrement
512 this.video.dislikes += dislikesToIncrement
514 this.video.buildLikeAndDislikePercents()
515 this.setVideoLikesBarTooltipText()
518 private setOpenGraphTags () {
519 this.metaService.setTitle(this.video.name)
521 this.metaService.setTag('og:type', 'video')
523 this.metaService.setTag('og:title', this.video.name)
524 this.metaService.setTag('name', this.video.name)
526 this.metaService.setTag('og:description', this.video.description)
527 this.metaService.setTag('description', this.video.description)
529 this.metaService.setTag('og:image', this.video.previewPath)
531 this.metaService.setTag('og:duration', this.video.duration.toString())
533 this.metaService.setTag('og:site_name', 'PeerTube')
535 this.metaService.setTag('og:url', window.location.href)
536 this.metaService.setTag('url', window.location.href)
539 private isAutoplay () {
540 // We'll jump to the thread id, so do not play the video
541 if (this.route.snapshot.params['threadId']) return false
543 // Otherwise true by default
544 if (!this.user) return true
546 // Be sure the autoPlay is set to false
547 return this.user.autoPlayVideo !== false
550 private flushPlayer () {
551 // Remove player if it exists
554 this.player.dispose()
555 this.player = undefined
557 console.error('Cannot dispose player.', err)
562 private initHotkeys () {
564 new Hotkey('shift+l', () => {
567 }, undefined, this.i18n('Like the video')),
569 new Hotkey('shift+d', () => {
572 }, undefined, this.i18n('Dislike the video')),
574 new Hotkey('shift+s', () => {
575 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
577 }, undefined, this.i18n('Subscribe to the account'))
579 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)