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'
25 P2PMediaLoaderOptions,
26 PeertubePlayerManager,
27 PeertubePlayerManagerOptions,
29 } from '../../../assets/player/peertube-player-manager'
30 import { VideoPlaylist } from '@app/shared/video-playlist/video-playlist.model'
31 import { VideoPlaylistService } from '@app/shared/video-playlist/video-playlist.service'
32 import { Video } from '@app/shared/video/video.model'
33 import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils'
34 import { VideoWatchPlaylistComponent } from '@app/videos/+video-watch/video-watch-playlist.component'
35 import { getStoredTheater } from '../../../assets/player/peertube-player-local-storage'
36 import { PluginService } from '@app/core/plugins/plugin.service'
37 import { HooksService } from '@app/core/plugins/hooks.service'
38 import { PlatformLocation } from '@angular/common'
39 import { randomInt } from '@shared/core-utils/miscs/miscs'
42 selector: 'my-video-watch',
43 templateUrl: './video-watch.component.html',
44 styleUrls: [ './video-watch.component.scss' ]
46 export class VideoWatchComponent implements OnInit, OnDestroy {
47 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
49 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
50 @ViewChild('videoShareModal', { static: false }) videoShareModal: VideoShareComponent
51 @ViewChild('videoSupportModal', { static: false }) videoSupportModal: VideoSupportComponent
52 @ViewChild('subscribeButton', { static: false }) subscribeButton: SubscribeButtonComponent
55 playerElement: HTMLVideoElement
56 theaterEnabled = false
57 userRating: UserVideoRateType = null
58 descriptionLoading = false
60 video: VideoDetails = null
61 videoCaptions: VideoCaption[] = []
63 playlist: VideoPlaylist = null
65 completeDescriptionShown = false
66 completeVideoDescription: string
67 shortVideoDescription: string
68 videoHTMLDescription = ''
69 likesBarTooltipText = ''
70 hasAlreadyAcceptedPrivacyConcern = false
71 remoteServerDown = false
74 private nextVideoUuid = ''
75 private currentTime: number
76 private paramsSub: Subscription
77 private queryParamsSub: Subscription
78 private configSub: Subscription
81 private elementRef: ElementRef,
82 private changeDetector: ChangeDetectorRef,
83 private route: ActivatedRoute,
84 private router: Router,
85 private videoService: VideoService,
86 private playlistService: VideoPlaylistService,
87 private videoBlacklistService: VideoBlacklistService,
88 private confirmService: ConfirmService,
89 private metaService: MetaService,
90 private authService: AuthService,
91 private serverService: ServerService,
92 private restExtractor: RestExtractor,
93 private notifier: Notifier,
94 private pluginService: PluginService,
95 private markdownService: MarkdownService,
97 private redirectService: RedirectService,
98 private videoCaptionService: VideoCaptionService,
100 private hotkeysService: HotkeysService,
101 private hooks: HooksService,
102 private location: PlatformLocation,
103 @Inject(LOCALE_ID) private localeId: string
107 return this.authService.getUser()
111 this.configSub = this.serverService.configLoaded
114 isWebRTCDisabled() ||
115 this.serverService.getConfig().tracker.enabled === false ||
116 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
118 this.hasAlreadyAcceptedPrivacyConcern = true
122 this.paramsSub = this.route.params.subscribe(routeParams => {
123 const videoId = routeParams[ 'videoId' ]
124 if (videoId) this.loadVideo(videoId)
126 const playlistId = routeParams[ 'playlistId' ]
127 if (playlistId) this.loadPlaylist(playlistId)
130 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
131 const videoId = queryParams[ 'videoId' ]
132 if (videoId) this.loadVideo(videoId)
137 this.theaterEnabled = getStoredTheater()
139 this.hooks.runAction('action:video-watch.init', 'video-watch')
145 // Unsubscribe subscriptions
146 if (this.paramsSub) this.paramsSub.unsubscribe()
147 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
150 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
154 if (this.isUserLoggedIn() === false) return
156 // Already liked this video
157 if (this.userRating === 'like') this.setRating('none')
158 else this.setRating('like')
162 if (this.isUserLoggedIn() === false) return
164 // Already disliked this video
165 if (this.userRating === 'dislike') this.setRating('none')
166 else this.setRating('dislike')
169 showMoreDescription () {
170 if (this.completeVideoDescription === undefined) {
171 return this.loadCompleteDescription()
174 this.updateVideoDescription(this.completeVideoDescription)
175 this.completeDescriptionShown = true
178 showLessDescription () {
179 this.updateVideoDescription(this.shortVideoDescription)
180 this.completeDescriptionShown = false
183 loadCompleteDescription () {
184 this.descriptionLoading = true
186 this.videoService.loadCompleteDescription(this.video.descriptionPath)
189 this.completeDescriptionShown = true
190 this.descriptionLoading = false
192 this.shortVideoDescription = this.video.description
193 this.completeVideoDescription = description
195 this.updateVideoDescription(this.completeVideoDescription)
199 this.descriptionLoading = false
200 this.notifier.error(error.message)
205 showSupportModal () {
206 this.videoSupportModal.show()
210 this.videoShareModal.show(this.currentTime)
214 return this.authService.isLoggedIn()
218 if (!this.video || Array.isArray(this.video.tags) === false) return []
220 return this.video.tags
223 onRecommendations (videos: Video[]) {
224 if (videos.length > 0) {
225 // Pick a random video until the recommendations are improved
226 this.nextVideoUuid = videos[randomInt(0,videos.length - 1)].uuid
231 this.redirectService.redirectToHomepage()
234 acceptedPrivacyConcern () {
235 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
236 this.hasAlreadyAcceptedPrivacyConcern = true
239 isVideoToTranscode () {
240 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
244 return this.video && this.video.state.id === VideoState.TO_IMPORT
247 hasVideoScheduledPublication () {
248 return this.video && this.video.scheduledUpdate !== undefined
251 isVideoBlur (video: Video) {
252 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
255 private loadVideo (videoId: string) {
256 // Video did not change
257 if (this.video && this.video.uuid === videoId) return
259 if (this.player) this.player.pause()
261 const videoObs = this.hooks.wrapObsFun(
262 this.videoService.getVideo.bind(this.videoService),
265 'filter:api.video-watch.video.get.params',
266 'filter:api.video-watch.video.get.result'
272 this.videoCaptionService.listCaptions(videoId)
275 // If 401, the video is private or blacklisted so redirect to 404
276 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
278 .subscribe(([ video, captionsResult ]) => {
279 const queryParams = this.route.snapshot.queryParams
282 startTime: queryParams.start,
283 stopTime: queryParams.stop,
285 muted: queryParams.muted,
286 loop: queryParams.loop,
287 subtitle: queryParams.subtitle,
289 playerMode: queryParams.mode,
293 this.onVideoFetched(video, captionsResult.data, urlOptions)
294 .catch(err => this.handleError(err))
298 private loadPlaylist (playlistId: string) {
299 // Playlist did not change
300 if (this.playlist && this.playlist.uuid === playlistId) return
302 this.playlistService.getVideoPlaylist(playlistId)
304 // If 401, the video is private or blacklisted so redirect to 404
305 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
307 .subscribe(playlist => {
308 this.playlist = playlist
310 const videoId = this.route.snapshot.queryParams['videoId']
311 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
315 private updateVideoDescription (description: string) {
316 this.video.description = description
317 this.setVideoDescriptionHTML()
318 .catch(err => console.error(err))
321 private async setVideoDescriptionHTML () {
322 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
325 private setVideoLikesBarTooltipText () {
326 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
327 likesNumber: this.video.likes,
328 dislikesNumber: this.video.dislikes
332 private handleError (err: any) {
333 const errorMessage: string = typeof err === 'string' ? err : err.message
334 if (!errorMessage) return
336 // Display a message in the video player instead of a notification
337 if (errorMessage.indexOf('from xs param') !== -1) {
339 this.remoteServerDown = true
340 this.changeDetector.detectChanges()
345 this.notifier.error(errorMessage)
348 private checkUserRating () {
349 // Unlogged users do not have ratings
350 if (this.isUserLoggedIn() === false) return
352 this.videoService.getUserVideoRating(this.video.id)
356 this.userRating = ratingObject.rating
360 err => this.notifier.error(err.message)
364 private async onVideoFetched (
366 videoCaptions: VideoCaption[],
367 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
370 this.videoCaptions = videoCaptions
372 // Re init attributes
373 this.descriptionLoading = false
374 this.completeDescriptionShown = false
375 this.remoteServerDown = false
376 this.currentTime = undefined
378 this.videoWatchPlaylist.updatePlaylistIndex(video)
380 let startTime = timeToInt(urlOptions.startTime) || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
381 // If we are at the end of the video, reset the timer
382 if (this.video.duration - startTime <= 1) startTime = 0
384 if (this.isVideoBlur(this.video)) {
385 const res = await this.confirmService.confirm(
386 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
387 this.i18n('Mature or explicit content')
389 if (res === false) return this.location.back()
392 // Flush old player if needed
395 // Build video element, because videojs removes it on dispose
396 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
397 this.playerElement = document.createElement('video')
398 this.playerElement.className = 'video-js vjs-peertube-skin'
399 this.playerElement.setAttribute('playsinline', 'true')
400 playerElementWrapper.appendChild(this.playerElement)
402 const playerCaptions = videoCaptions.map(c => ({
403 label: c.language.label,
404 language: c.language.id,
405 src: environment.apiUrl + c.captionPath
408 const options: PeertubePlayerManagerOptions = {
410 autoplay: this.isAutoplay(),
412 playerElement: this.playerElement,
413 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
415 videoDuration: this.video.duration,
417 inactivityTimeout: 2500,
418 poster: this.video.previewUrl,
421 stopTime: urlOptions.stopTime,
422 controls: urlOptions.controls,
423 muted: urlOptions.muted,
424 loop: urlOptions.loop,
425 subtitle: urlOptions.subtitle,
427 peertubeLink: urlOptions.peertubeLink,
430 captions: videoCaptions.length !== 0,
432 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE
433 ? this.videoService.getVideoViewUrl(this.video.uuid)
435 embedUrl: this.video.embedUrl,
437 language: this.localeId,
439 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
440 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
441 authorizationHeader: this.authService.getRequestHeaderValue()
444 serverUrl: environment.apiUrl,
446 videoCaptions: playerCaptions
450 videoFiles: this.video.files
456 if (urlOptions.playerMode) {
457 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
458 else mode = 'webtorrent'
460 if (this.video.hasHlsPlaylist()) mode = 'p2p-media-loader'
461 else mode = 'webtorrent'
464 if (mode === 'p2p-media-loader') {
465 const hlsPlaylist = this.video.getHlsPlaylist()
467 const p2pMediaLoader = {
468 playlistUrl: hlsPlaylist.playlistUrl,
469 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
470 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
471 trackerAnnounce: this.video.trackerUrls,
472 videoFiles: hlsPlaylist.files
473 } as P2PMediaLoaderOptions
475 Object.assign(options, { p2pMediaLoader })
478 this.zone.runOutsideAngular(async () => {
479 this.player = await PeertubePlayerManager.initialize(mode, options, player => this.player = player)
482 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
484 this.player.on('timeupdate', () => {
485 this.currentTime = Math.floor(this.player.currentTime())
488 this.player.one('ended', () => {
490 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
491 } else if (this.user && this.user.autoPlayNextVideo) {
492 this.zone.run(() => this.autoplayNext())
496 this.player.one('stopped', () => {
498 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
502 this.player.on('theaterChange', (_: any, enabled: boolean) => {
503 this.zone.run(() => this.theaterEnabled = enabled)
506 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
509 this.setVideoDescriptionHTML()
510 this.setVideoLikesBarTooltipText()
512 this.setOpenGraphTags()
513 this.checkUserRating()
515 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
518 private autoplayNext () {
519 if (this.nextVideoUuid) {
520 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
524 private setRating (nextRating: UserVideoRateType) {
525 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
526 like: this.videoService.setVideoLike,
527 dislike: this.videoService.setVideoDislike,
528 none: this.videoService.unsetVideoLike
531 ratingMethods[nextRating].call(this.videoService, this.video.id)
534 // Update the video like attribute
535 this.updateVideoRating(this.userRating, nextRating)
536 this.userRating = nextRating
539 (err: { message: string }) => this.notifier.error(err.message)
543 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
544 let likesToIncrement = 0
545 let dislikesToIncrement = 0
548 if (oldRating === 'like') likesToIncrement--
549 if (oldRating === 'dislike') dislikesToIncrement--
552 if (newRating === 'like') likesToIncrement++
553 if (newRating === 'dislike') dislikesToIncrement++
555 this.video.likes += likesToIncrement
556 this.video.dislikes += dislikesToIncrement
558 this.video.buildLikeAndDislikePercents()
559 this.setVideoLikesBarTooltipText()
562 private setOpenGraphTags () {
563 this.metaService.setTitle(this.video.name)
565 this.metaService.setTag('og:type', 'video')
567 this.metaService.setTag('og:title', this.video.name)
568 this.metaService.setTag('name', this.video.name)
570 this.metaService.setTag('og:description', this.video.description)
571 this.metaService.setTag('description', this.video.description)
573 this.metaService.setTag('og:image', this.video.previewPath)
575 this.metaService.setTag('og:duration', this.video.duration.toString())
577 this.metaService.setTag('og:site_name', 'PeerTube')
579 this.metaService.setTag('og:url', window.location.href)
580 this.metaService.setTag('url', window.location.href)
583 private isAutoplay () {
584 // We'll jump to the thread id, so do not play the video
585 if (this.route.snapshot.params['threadId']) return false
587 // Otherwise true by default
588 if (!this.user) return true
590 // Be sure the autoPlay is set to false
591 return this.user.autoPlayVideo !== false
594 private flushPlayer () {
595 // Remove player if it exists
598 this.player.dispose()
599 this.player = undefined
601 console.error('Cannot dispose player.', err)
606 private initHotkeys () {
608 new Hotkey('shift+l', () => {
611 }, undefined, this.i18n('Like the video')),
613 new Hotkey('shift+d', () => {
616 }, undefined, this.i18n('Dislike the video')),
618 new Hotkey('shift+s', () => {
619 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
621 }, undefined, this.i18n('Subscribe to the account'))
623 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)