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'
38 selector: 'my-video-watch',
39 templateUrl: './video-watch.component.html',
40 styleUrls: [ './video-watch.component.scss' ]
42 export class VideoWatchComponent implements OnInit, OnDestroy {
43 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
45 @ViewChild('videoWatchPlaylist') videoWatchPlaylist: VideoWatchPlaylistComponent
46 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
47 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
48 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
51 playerElement: HTMLVideoElement
52 theaterEnabled = false
53 userRating: UserVideoRateType = null
54 descriptionLoading = false
56 video: VideoDetails = null
57 videoCaptions: VideoCaption[] = []
59 playlist: VideoPlaylist = null
61 completeDescriptionShown = false
62 completeVideoDescription: string
63 shortVideoDescription: string
64 videoHTMLDescription = ''
65 likesBarTooltipText = ''
66 hasAlreadyAcceptedPrivacyConcern = false
67 remoteServerDown = false
70 private currentTime: number
71 private paramsSub: Subscription
72 private queryParamsSub: Subscription
73 private configSub: Subscription
76 private elementRef: ElementRef,
77 private changeDetector: ChangeDetectorRef,
78 private route: ActivatedRoute,
79 private router: Router,
80 private videoService: VideoService,
81 private playlistService: VideoPlaylistService,
82 private videoBlacklistService: VideoBlacklistService,
83 private confirmService: ConfirmService,
84 private metaService: MetaService,
85 private authService: AuthService,
86 private serverService: ServerService,
87 private restExtractor: RestExtractor,
88 private notifier: Notifier,
89 private pluginService: PluginService,
90 private markdownService: MarkdownService,
92 private redirectService: RedirectService,
93 private videoCaptionService: VideoCaptionService,
95 private hotkeysService: HotkeysService,
96 @Inject(LOCALE_ID) private localeId: string
100 return this.authService.getUser()
104 await this.pluginService.loadPluginsByScope('video-watch')
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.pluginService.runHook('action:video-watch.loaded')
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()
251 this.videoService.getVideo(videoId),
252 this.videoCaptionService.listCaptions(videoId)
255 // If 401, the video is private or blacklisted so redirect to 404
256 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
258 .subscribe(([ video, captionsResult ]) => {
259 const queryParams = this.route.snapshot.queryParams
262 startTime: queryParams.start,
263 stopTime: queryParams.stop,
265 muted: queryParams.muted,
266 loop: queryParams.loop,
267 subtitle: queryParams.subtitle,
269 playerMode: queryParams.mode,
273 this.onVideoFetched(video, captionsResult.data, urlOptions)
274 .catch(err => this.handleError(err))
278 private loadPlaylist (playlistId: string) {
279 // Playlist did not change
280 if (this.playlist && this.playlist.uuid === playlistId) return
282 this.playlistService.getVideoPlaylist(playlistId)
284 // If 401, the video is private or blacklisted so redirect to 404
285 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
287 .subscribe(playlist => {
288 this.playlist = playlist
290 const videoId = this.route.snapshot.queryParams['videoId']
291 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
295 private updateVideoDescription (description: string) {
296 this.video.description = description
297 this.setVideoDescriptionHTML()
298 .catch(err => console.error(err))
301 private async setVideoDescriptionHTML () {
302 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
305 private setVideoLikesBarTooltipText () {
306 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
307 likesNumber: this.video.likes,
308 dislikesNumber: this.video.dislikes
312 private handleError (err: any) {
313 const errorMessage: string = typeof err === 'string' ? err : err.message
314 if (!errorMessage) return
316 // Display a message in the video player instead of a notification
317 if (errorMessage.indexOf('from xs param') !== -1) {
319 this.remoteServerDown = true
320 this.changeDetector.detectChanges()
325 this.notifier.error(errorMessage)
328 private checkUserRating () {
329 // Unlogged users do not have ratings
330 if (this.isUserLoggedIn() === false) return
332 this.videoService.getUserVideoRating(this.video.id)
336 this.userRating = ratingObject.rating
340 err => this.notifier.error(err.message)
344 private async onVideoFetched (
346 videoCaptions: VideoCaption[],
347 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
350 this.videoCaptions = videoCaptions
352 // Re init attributes
353 this.descriptionLoading = false
354 this.completeDescriptionShown = false
355 this.remoteServerDown = false
356 this.currentTime = undefined
358 this.videoWatchPlaylist.updatePlaylistIndex(video)
360 let startTime = timeToInt(urlOptions.startTime) || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
361 // If we are at the end of the video, reset the timer
362 if (this.video.duration - startTime <= 1) startTime = 0
364 if (this.isVideoBlur(this.video)) {
365 const res = await this.confirmService.confirm(
366 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
367 this.i18n('Mature or explicit content')
369 if (res === false) return this.redirectService.redirectToHomepage()
372 // Flush old player if needed
375 // Build video element, because videojs remove it on dispose
376 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
377 this.playerElement = document.createElement('video')
378 this.playerElement.className = 'video-js vjs-peertube-skin'
379 this.playerElement.setAttribute('playsinline', 'true')
380 playerElementWrapper.appendChild(this.playerElement)
382 const playerCaptions = videoCaptions.map(c => ({
383 label: c.language.label,
384 language: c.language.id,
385 src: environment.apiUrl + c.captionPath
388 const options: PeertubePlayerManagerOptions = {
390 autoplay: this.isAutoplay(),
392 playerElement: this.playerElement,
393 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
395 videoDuration: this.video.duration,
397 inactivityTimeout: 2500,
398 poster: this.video.previewUrl,
401 stopTime: urlOptions.stopTime,
402 controls: urlOptions.controls,
403 muted: urlOptions.muted,
404 loop: urlOptions.loop,
405 subtitle: urlOptions.subtitle,
407 peertubeLink: urlOptions.peertubeLink,
410 captions: videoCaptions.length !== 0,
412 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE
413 ? this.videoService.getVideoViewUrl(this.video.uuid)
415 embedUrl: this.video.embedUrl,
417 language: this.localeId,
419 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
420 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
421 authorizationHeader: this.authService.getRequestHeaderValue()
424 serverUrl: environment.apiUrl,
426 videoCaptions: playerCaptions
430 videoFiles: this.video.files
436 if (urlOptions.playerMode) {
437 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
438 else mode = 'webtorrent'
440 if (this.video.hasHlsPlaylist()) mode = 'p2p-media-loader'
441 else mode = 'webtorrent'
444 if (mode === 'p2p-media-loader') {
445 const hlsPlaylist = this.video.getHlsPlaylist()
447 const p2pMediaLoader = {
448 playlistUrl: hlsPlaylist.playlistUrl,
449 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
450 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
451 trackerAnnounce: this.video.trackerUrls,
452 videoFiles: this.video.files
453 } as P2PMediaLoaderOptions
455 Object.assign(options, { p2pMediaLoader })
458 this.zone.runOutsideAngular(async () => {
459 this.player = await PeertubePlayerManager.initialize(mode, options)
461 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
463 this.player.on('timeupdate', () => {
464 this.currentTime = Math.floor(this.player.currentTime())
467 this.player.one('ended', () => {
469 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
473 this.player.one('stopped', () => {
475 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
479 this.player.on('theaterChange', (_: any, enabled: boolean) => {
480 this.zone.run(() => this.theaterEnabled = enabled)
484 this.setVideoDescriptionHTML()
485 this.setVideoLikesBarTooltipText()
487 this.setOpenGraphTags()
488 this.checkUserRating()
491 private setRating (nextRating: UserVideoRateType) {
492 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
493 like: this.videoService.setVideoLike,
494 dislike: this.videoService.setVideoDislike,
495 none: this.videoService.unsetVideoLike
498 ratingMethods[nextRating].call(this.videoService, this.video.id)
501 // Update the video like attribute
502 this.updateVideoRating(this.userRating, nextRating)
503 this.userRating = nextRating
506 (err: { message: string }) => this.notifier.error(err.message)
510 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
511 let likesToIncrement = 0
512 let dislikesToIncrement = 0
515 if (oldRating === 'like') likesToIncrement--
516 if (oldRating === 'dislike') dislikesToIncrement--
519 if (newRating === 'like') likesToIncrement++
520 if (newRating === 'dislike') dislikesToIncrement++
522 this.video.likes += likesToIncrement
523 this.video.dislikes += dislikesToIncrement
525 this.video.buildLikeAndDislikePercents()
526 this.setVideoLikesBarTooltipText()
529 private setOpenGraphTags () {
530 this.metaService.setTitle(this.video.name)
532 this.metaService.setTag('og:type', 'video')
534 this.metaService.setTag('og:title', this.video.name)
535 this.metaService.setTag('name', this.video.name)
537 this.metaService.setTag('og:description', this.video.description)
538 this.metaService.setTag('description', this.video.description)
540 this.metaService.setTag('og:image', this.video.previewPath)
542 this.metaService.setTag('og:duration', this.video.duration.toString())
544 this.metaService.setTag('og:site_name', 'PeerTube')
546 this.metaService.setTag('og:url', window.location.href)
547 this.metaService.setTag('url', window.location.href)
550 private isAutoplay () {
551 // We'll jump to the thread id, so do not play the video
552 if (this.route.snapshot.params['threadId']) return false
554 // Otherwise true by default
555 if (!this.user) return true
557 // Be sure the autoPlay is set to false
558 return this.user.autoPlayVideo !== false
561 private flushPlayer () {
562 // Remove player if it exists
565 this.player.dispose()
566 this.player = undefined
568 console.error('Cannot dispose player.', err)
573 private initHotkeys () {
575 new Hotkey('shift+l', () => {
578 }, undefined, this.i18n('Like the video')),
580 new Hotkey('shift+d', () => {
583 }, undefined, this.i18n('Dislike the video')),
585 new Hotkey('shift+s', () => {
586 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
588 }, undefined, this.i18n('Subscribe to the account'))
590 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)