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'
37 selector: 'my-video-watch',
38 templateUrl: './video-watch.component.html',
39 styleUrls: [ './video-watch.component.scss' ]
41 export class VideoWatchComponent implements OnInit, OnDestroy {
42 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
44 @ViewChild('videoWatchPlaylist') videoWatchPlaylist: VideoWatchPlaylistComponent
45 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
46 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
47 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
50 playerElement: HTMLVideoElement
51 theaterEnabled = false
52 userRating: UserVideoRateType = null
53 video: VideoDetails = null
54 descriptionLoading = false
56 playlist: VideoPlaylist = null
58 completeDescriptionShown = false
59 completeVideoDescription: string
60 shortVideoDescription: string
61 videoHTMLDescription = ''
62 likesBarTooltipText = ''
63 hasAlreadyAcceptedPrivacyConcern = false
64 remoteServerDown = false
67 private currentTime: number
68 private paramsSub: Subscription
69 private queryParamsSub: Subscription
70 private configSub: Subscription
73 private elementRef: ElementRef,
74 private changeDetector: ChangeDetectorRef,
75 private route: ActivatedRoute,
76 private router: Router,
77 private videoService: VideoService,
78 private playlistService: VideoPlaylistService,
79 private videoBlacklistService: VideoBlacklistService,
80 private confirmService: ConfirmService,
81 private metaService: MetaService,
82 private authService: AuthService,
83 private serverService: ServerService,
84 private restExtractor: RestExtractor,
85 private notifier: Notifier,
86 private markdownService: MarkdownService,
88 private redirectService: RedirectService,
89 private videoCaptionService: VideoCaptionService,
91 private hotkeysService: HotkeysService,
92 @Inject(LOCALE_ID) private localeId: string
96 return this.authService.getUser()
100 this.configSub = this.serverService.configLoaded
103 isWebRTCDisabled() ||
104 this.serverService.getConfig().tracker.enabled === false ||
105 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
107 this.hasAlreadyAcceptedPrivacyConcern = true
111 this.paramsSub = this.route.params.subscribe(routeParams => {
112 const videoId = routeParams[ 'videoId' ]
113 if (videoId) this.loadVideo(videoId)
115 const playlistId = routeParams[ 'playlistId' ]
116 if (playlistId) this.loadPlaylist(playlistId)
119 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
120 const videoId = queryParams[ 'videoId' ]
121 if (videoId) this.loadVideo(videoId)
126 this.theaterEnabled = getStoredTheater()
132 // Unsubscribe subscriptions
133 if (this.paramsSub) this.paramsSub.unsubscribe()
134 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
137 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
141 if (this.isUserLoggedIn() === false) return
143 // Already liked this video
144 if (this.userRating === 'like') this.setRating('none')
145 else this.setRating('like')
149 if (this.isUserLoggedIn() === false) return
151 // Already disliked this video
152 if (this.userRating === 'dislike') this.setRating('none')
153 else this.setRating('dislike')
156 showMoreDescription () {
157 if (this.completeVideoDescription === undefined) {
158 return this.loadCompleteDescription()
161 this.updateVideoDescription(this.completeVideoDescription)
162 this.completeDescriptionShown = true
165 showLessDescription () {
166 this.updateVideoDescription(this.shortVideoDescription)
167 this.completeDescriptionShown = false
170 loadCompleteDescription () {
171 this.descriptionLoading = true
173 this.videoService.loadCompleteDescription(this.video.descriptionPath)
176 this.completeDescriptionShown = true
177 this.descriptionLoading = false
179 this.shortVideoDescription = this.video.description
180 this.completeVideoDescription = description
182 this.updateVideoDescription(this.completeVideoDescription)
186 this.descriptionLoading = false
187 this.notifier.error(error.message)
192 showSupportModal () {
193 this.videoSupportModal.show()
197 this.videoShareModal.show(this.currentTime)
201 return this.authService.isLoggedIn()
205 if (!this.video || Array.isArray(this.video.tags) === false) return []
207 return this.video.tags
211 this.redirectService.redirectToHomepage()
214 acceptedPrivacyConcern () {
215 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
216 this.hasAlreadyAcceptedPrivacyConcern = true
219 isVideoToTranscode () {
220 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
224 return this.video && this.video.state.id === VideoState.TO_IMPORT
227 hasVideoScheduledPublication () {
228 return this.video && this.video.scheduledUpdate !== undefined
231 isVideoBlur (video: Video) {
232 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
235 private loadVideo (videoId: string) {
236 // Video did not change
237 if (this.video && this.video.uuid === videoId) return
239 if (this.player) this.player.pause()
243 this.videoService.getVideo(videoId),
244 this.videoCaptionService.listCaptions(videoId)
247 // If 401, the video is private or blacklisted so redirect to 404
248 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
250 .subscribe(([ video, captionsResult ]) => {
251 const queryParams = this.route.snapshot.queryParams
254 startTime: queryParams.start,
255 stopTime: queryParams.stop,
257 muted: queryParams.muted,
258 loop: queryParams.loop,
259 subtitle: queryParams.subtitle,
261 playerMode: queryParams.mode,
265 this.onVideoFetched(video, captionsResult.data, urlOptions)
266 .catch(err => this.handleError(err))
270 private loadPlaylist (playlistId: string) {
271 // Playlist did not change
272 if (this.playlist && this.playlist.uuid === playlistId) return
274 this.playlistService.getVideoPlaylist(playlistId)
276 // If 401, the video is private or blacklisted so redirect to 404
277 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
279 .subscribe(playlist => {
280 this.playlist = playlist
282 const videoId = this.route.snapshot.queryParams['videoId']
283 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
287 private updateVideoDescription (description: string) {
288 this.video.description = description
289 this.setVideoDescriptionHTML()
290 .catch(err => console.error(err))
293 private async setVideoDescriptionHTML () {
294 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
297 private setVideoLikesBarTooltipText () {
298 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
299 likesNumber: this.video.likes,
300 dislikesNumber: this.video.dislikes
304 private handleError (err: any) {
305 const errorMessage: string = typeof err === 'string' ? err : err.message
306 if (!errorMessage) return
308 // Display a message in the video player instead of a notification
309 if (errorMessage.indexOf('from xs param') !== -1) {
311 this.remoteServerDown = true
312 this.changeDetector.detectChanges()
317 this.notifier.error(errorMessage)
320 private checkUserRating () {
321 // Unlogged users do not have ratings
322 if (this.isUserLoggedIn() === false) return
324 this.videoService.getUserVideoRating(this.video.id)
328 this.userRating = ratingObject.rating
332 err => this.notifier.error(err.message)
336 private async onVideoFetched (
338 videoCaptions: VideoCaption[],
339 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
343 // Re init attributes
344 this.descriptionLoading = false
345 this.completeDescriptionShown = false
346 this.remoteServerDown = false
347 this.currentTime = undefined
349 this.videoWatchPlaylist.updatePlaylistIndex(video)
351 let startTime = timeToInt(urlOptions.startTime) || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
352 // If we are at the end of the video, reset the timer
353 if (this.video.duration - startTime <= 1) startTime = 0
355 if (this.isVideoBlur(this.video)) {
356 const res = await this.confirmService.confirm(
357 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
358 this.i18n('Mature or explicit content')
360 if (res === false) return this.redirectService.redirectToHomepage()
363 // Flush old player if needed
366 // Build video element, because videojs remove it on dispose
367 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
368 this.playerElement = document.createElement('video')
369 this.playerElement.className = 'video-js vjs-peertube-skin'
370 this.playerElement.setAttribute('playsinline', 'true')
371 playerElementWrapper.appendChild(this.playerElement)
373 const playerCaptions = videoCaptions.map(c => ({
374 label: c.language.label,
375 language: c.language.id,
376 src: environment.apiUrl + c.captionPath
379 const options: PeertubePlayerManagerOptions = {
381 autoplay: this.isAutoplay(),
383 playerElement: this.playerElement,
384 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
386 videoDuration: this.video.duration,
388 inactivityTimeout: 2500,
389 poster: this.video.previewUrl,
392 stopTime: urlOptions.stopTime,
393 controls: urlOptions.controls,
394 muted: urlOptions.muted,
395 loop: urlOptions.loop,
396 subtitle: urlOptions.subtitle,
398 peertubeLink: urlOptions.peertubeLink,
401 captions: videoCaptions.length !== 0,
403 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE
404 ? this.videoService.getVideoViewUrl(this.video.uuid)
406 embedUrl: this.video.embedUrl,
408 language: this.localeId,
410 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
411 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
412 authorizationHeader: this.authService.getRequestHeaderValue()
415 serverUrl: environment.apiUrl,
417 videoCaptions: playerCaptions
421 videoFiles: this.video.files
427 if (urlOptions.playerMode) {
428 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
429 else mode = 'webtorrent'
431 if (this.video.hasHlsPlaylist()) mode = 'p2p-media-loader'
432 else mode = 'webtorrent'
435 if (mode === 'p2p-media-loader') {
436 const hlsPlaylist = this.video.getHlsPlaylist()
438 const p2pMediaLoader = {
439 playlistUrl: hlsPlaylist.playlistUrl,
440 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
441 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
442 trackerAnnounce: this.video.trackerUrls,
443 videoFiles: this.video.files
444 } as P2PMediaLoaderOptions
446 Object.assign(options, { p2pMediaLoader })
449 this.zone.runOutsideAngular(async () => {
450 this.player = await PeertubePlayerManager.initialize(mode, options)
452 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
454 this.player.on('timeupdate', () => {
455 this.currentTime = Math.floor(this.player.currentTime())
458 this.player.one('ended', () => {
460 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
464 this.player.one('stopped', () => {
466 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
470 this.player.on('theaterChange', (_: any, enabled: boolean) => {
471 this.zone.run(() => this.theaterEnabled = enabled)
475 this.setVideoDescriptionHTML()
476 this.setVideoLikesBarTooltipText()
478 this.setOpenGraphTags()
479 this.checkUserRating()
482 private setRating (nextRating: UserVideoRateType) {
483 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
484 like: this.videoService.setVideoLike,
485 dislike: this.videoService.setVideoDislike,
486 none: this.videoService.unsetVideoLike
489 ratingMethods[nextRating].call(this.videoService, this.video.id)
492 // Update the video like attribute
493 this.updateVideoRating(this.userRating, nextRating)
494 this.userRating = nextRating
497 (err: { message: string }) => this.notifier.error(err.message)
501 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
502 let likesToIncrement = 0
503 let dislikesToIncrement = 0
506 if (oldRating === 'like') likesToIncrement--
507 if (oldRating === 'dislike') dislikesToIncrement--
510 if (newRating === 'like') likesToIncrement++
511 if (newRating === 'dislike') dislikesToIncrement++
513 this.video.likes += likesToIncrement
514 this.video.dislikes += dislikesToIncrement
516 this.video.buildLikeAndDislikePercents()
517 this.setVideoLikesBarTooltipText()
520 private setOpenGraphTags () {
521 this.metaService.setTitle(this.video.name)
523 this.metaService.setTag('og:type', 'video')
525 this.metaService.setTag('og:title', this.video.name)
526 this.metaService.setTag('name', this.video.name)
528 this.metaService.setTag('og:description', this.video.description)
529 this.metaService.setTag('description', this.video.description)
531 this.metaService.setTag('og:image', this.video.previewPath)
533 this.metaService.setTag('og:duration', this.video.duration.toString())
535 this.metaService.setTag('og:site_name', 'PeerTube')
537 this.metaService.setTag('og:url', window.location.href)
538 this.metaService.setTag('url', window.location.href)
541 private isAutoplay () {
542 // We'll jump to the thread id, so do not play the video
543 if (this.route.snapshot.params['threadId']) return false
545 // Otherwise true by default
546 if (!this.user) return true
548 // Be sure the autoPlay is set to false
549 return this.user.autoPlayVideo !== false
552 private flushPlayer () {
553 // Remove player if it exists
556 this.player.dispose()
557 this.player = undefined
559 console.error('Cannot dispose player.', err)
564 private initHotkeys () {
566 new Hotkey('shift+l', () => {
569 }, undefined, this.i18n('Like the video')),
571 new Hotkey('shift+d', () => {
574 }, undefined, this.i18n('Dislike the video')),
576 new Hotkey('shift+s', () => {
577 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
579 }, undefined, this.i18n('Subscribe to the account'))
581 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)