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 descriptionLoading = false
55 video: VideoDetails = null
56 videoCaptions: VideoCaption[] = []
58 playlist: VideoPlaylist = null
60 completeDescriptionShown = false
61 completeVideoDescription: string
62 shortVideoDescription: string
63 videoHTMLDescription = ''
64 likesBarTooltipText = ''
65 hasAlreadyAcceptedPrivacyConcern = false
66 remoteServerDown = false
69 private currentTime: number
70 private paramsSub: Subscription
71 private queryParamsSub: Subscription
72 private configSub: Subscription
75 private elementRef: ElementRef,
76 private changeDetector: ChangeDetectorRef,
77 private route: ActivatedRoute,
78 private router: Router,
79 private videoService: VideoService,
80 private playlistService: VideoPlaylistService,
81 private videoBlacklistService: VideoBlacklistService,
82 private confirmService: ConfirmService,
83 private metaService: MetaService,
84 private authService: AuthService,
85 private serverService: ServerService,
86 private restExtractor: RestExtractor,
87 private notifier: Notifier,
88 private markdownService: MarkdownService,
90 private redirectService: RedirectService,
91 private videoCaptionService: VideoCaptionService,
93 private hotkeysService: HotkeysService,
94 @Inject(LOCALE_ID) private localeId: string
98 return this.authService.getUser()
102 this.configSub = this.serverService.configLoaded
105 isWebRTCDisabled() ||
106 this.serverService.getConfig().tracker.enabled === false ||
107 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
109 this.hasAlreadyAcceptedPrivacyConcern = true
113 this.paramsSub = this.route.params.subscribe(routeParams => {
114 const videoId = routeParams[ 'videoId' ]
115 if (videoId) this.loadVideo(videoId)
117 const playlistId = routeParams[ 'playlistId' ]
118 if (playlistId) this.loadPlaylist(playlistId)
121 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
122 const videoId = queryParams[ 'videoId' ]
123 if (videoId) this.loadVideo(videoId)
128 this.theaterEnabled = getStoredTheater()
134 // Unsubscribe subscriptions
135 if (this.paramsSub) this.paramsSub.unsubscribe()
136 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
139 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
143 if (this.isUserLoggedIn() === false) return
145 // Already liked this video
146 if (this.userRating === 'like') this.setRating('none')
147 else this.setRating('like')
151 if (this.isUserLoggedIn() === false) return
153 // Already disliked this video
154 if (this.userRating === 'dislike') this.setRating('none')
155 else this.setRating('dislike')
158 showMoreDescription () {
159 if (this.completeVideoDescription === undefined) {
160 return this.loadCompleteDescription()
163 this.updateVideoDescription(this.completeVideoDescription)
164 this.completeDescriptionShown = true
167 showLessDescription () {
168 this.updateVideoDescription(this.shortVideoDescription)
169 this.completeDescriptionShown = false
172 loadCompleteDescription () {
173 this.descriptionLoading = true
175 this.videoService.loadCompleteDescription(this.video.descriptionPath)
178 this.completeDescriptionShown = true
179 this.descriptionLoading = false
181 this.shortVideoDescription = this.video.description
182 this.completeVideoDescription = description
184 this.updateVideoDescription(this.completeVideoDescription)
188 this.descriptionLoading = false
189 this.notifier.error(error.message)
194 showSupportModal () {
195 this.videoSupportModal.show()
199 this.videoShareModal.show(this.currentTime)
203 return this.authService.isLoggedIn()
207 if (!this.video || Array.isArray(this.video.tags) === false) return []
209 return this.video.tags
213 this.redirectService.redirectToHomepage()
216 acceptedPrivacyConcern () {
217 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
218 this.hasAlreadyAcceptedPrivacyConcern = true
221 isVideoToTranscode () {
222 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
226 return this.video && this.video.state.id === VideoState.TO_IMPORT
229 hasVideoScheduledPublication () {
230 return this.video && this.video.scheduledUpdate !== undefined
233 isVideoBlur (video: Video) {
234 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
237 private loadVideo (videoId: string) {
238 // Video did not change
239 if (this.video && this.video.uuid === videoId) return
241 if (this.player) this.player.pause()
245 this.videoService.getVideo(videoId),
246 this.videoCaptionService.listCaptions(videoId)
249 // If 401, the video is private or blacklisted so redirect to 404
250 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
252 .subscribe(([ video, captionsResult ]) => {
253 const queryParams = this.route.snapshot.queryParams
256 startTime: queryParams.start,
257 stopTime: queryParams.stop,
259 muted: queryParams.muted,
260 loop: queryParams.loop,
261 subtitle: queryParams.subtitle,
263 playerMode: queryParams.mode,
267 this.onVideoFetched(video, captionsResult.data, urlOptions)
268 .catch(err => this.handleError(err))
272 private loadPlaylist (playlistId: string) {
273 // Playlist did not change
274 if (this.playlist && this.playlist.uuid === playlistId) return
276 this.playlistService.getVideoPlaylist(playlistId)
278 // If 401, the video is private or blacklisted so redirect to 404
279 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
281 .subscribe(playlist => {
282 this.playlist = playlist
284 const videoId = this.route.snapshot.queryParams['videoId']
285 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
289 private updateVideoDescription (description: string) {
290 this.video.description = description
291 this.setVideoDescriptionHTML()
292 .catch(err => console.error(err))
295 private async setVideoDescriptionHTML () {
296 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
299 private setVideoLikesBarTooltipText () {
300 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
301 likesNumber: this.video.likes,
302 dislikesNumber: this.video.dislikes
306 private handleError (err: any) {
307 const errorMessage: string = typeof err === 'string' ? err : err.message
308 if (!errorMessage) return
310 // Display a message in the video player instead of a notification
311 if (errorMessage.indexOf('from xs param') !== -1) {
313 this.remoteServerDown = true
314 this.changeDetector.detectChanges()
319 this.notifier.error(errorMessage)
322 private checkUserRating () {
323 // Unlogged users do not have ratings
324 if (this.isUserLoggedIn() === false) return
326 this.videoService.getUserVideoRating(this.video.id)
330 this.userRating = ratingObject.rating
334 err => this.notifier.error(err.message)
338 private async onVideoFetched (
340 videoCaptions: VideoCaption[],
341 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
344 this.videoCaptions = videoCaptions
346 // Re init attributes
347 this.descriptionLoading = false
348 this.completeDescriptionShown = false
349 this.remoteServerDown = false
350 this.currentTime = undefined
352 this.videoWatchPlaylist.updatePlaylistIndex(video)
354 let startTime = timeToInt(urlOptions.startTime) || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
355 // If we are at the end of the video, reset the timer
356 if (this.video.duration - startTime <= 1) startTime = 0
358 if (this.isVideoBlur(this.video)) {
359 const res = await this.confirmService.confirm(
360 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
361 this.i18n('Mature or explicit content')
363 if (res === false) return this.redirectService.redirectToHomepage()
366 // Flush old player if needed
369 // Build video element, because videojs remove it on dispose
370 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
371 this.playerElement = document.createElement('video')
372 this.playerElement.className = 'video-js vjs-peertube-skin'
373 this.playerElement.setAttribute('playsinline', 'true')
374 playerElementWrapper.appendChild(this.playerElement)
376 const playerCaptions = videoCaptions.map(c => ({
377 label: c.language.label,
378 language: c.language.id,
379 src: environment.apiUrl + c.captionPath
382 const options: PeertubePlayerManagerOptions = {
384 autoplay: this.isAutoplay(),
386 playerElement: this.playerElement,
387 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
389 videoDuration: this.video.duration,
391 inactivityTimeout: 2500,
392 poster: this.video.previewUrl,
395 stopTime: urlOptions.stopTime,
396 controls: urlOptions.controls,
397 muted: urlOptions.muted,
398 loop: urlOptions.loop,
399 subtitle: urlOptions.subtitle,
401 peertubeLink: urlOptions.peertubeLink,
404 captions: videoCaptions.length !== 0,
406 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE
407 ? this.videoService.getVideoViewUrl(this.video.uuid)
409 embedUrl: this.video.embedUrl,
411 language: this.localeId,
413 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
414 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
415 authorizationHeader: this.authService.getRequestHeaderValue()
418 serverUrl: environment.apiUrl,
420 videoCaptions: playerCaptions
424 videoFiles: this.video.files
430 if (urlOptions.playerMode) {
431 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
432 else mode = 'webtorrent'
434 if (this.video.hasHlsPlaylist()) mode = 'p2p-media-loader'
435 else mode = 'webtorrent'
438 if (mode === 'p2p-media-loader') {
439 const hlsPlaylist = this.video.getHlsPlaylist()
441 const p2pMediaLoader = {
442 playlistUrl: hlsPlaylist.playlistUrl,
443 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
444 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
445 trackerAnnounce: this.video.trackerUrls,
446 videoFiles: this.video.files
447 } as P2PMediaLoaderOptions
449 Object.assign(options, { p2pMediaLoader })
452 this.zone.runOutsideAngular(async () => {
453 this.player = await PeertubePlayerManager.initialize(mode, options)
455 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
457 this.player.on('timeupdate', () => {
458 this.currentTime = Math.floor(this.player.currentTime())
461 this.player.one('ended', () => {
463 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
467 this.player.one('stopped', () => {
469 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
473 this.player.on('theaterChange', (_: any, enabled: boolean) => {
474 this.zone.run(() => this.theaterEnabled = enabled)
478 this.setVideoDescriptionHTML()
479 this.setVideoLikesBarTooltipText()
481 this.setOpenGraphTags()
482 this.checkUserRating()
485 private setRating (nextRating: UserVideoRateType) {
486 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
487 like: this.videoService.setVideoLike,
488 dislike: this.videoService.setVideoDislike,
489 none: this.videoService.unsetVideoLike
492 ratingMethods[nextRating].call(this.videoService, this.video.id)
495 // Update the video like attribute
496 this.updateVideoRating(this.userRating, nextRating)
497 this.userRating = nextRating
500 (err: { message: string }) => this.notifier.error(err.message)
504 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
505 let likesToIncrement = 0
506 let dislikesToIncrement = 0
509 if (oldRating === 'like') likesToIncrement--
510 if (oldRating === 'dislike') dislikesToIncrement--
513 if (newRating === 'like') likesToIncrement++
514 if (newRating === 'dislike') dislikesToIncrement++
516 this.video.likes += likesToIncrement
517 this.video.dislikes += dislikesToIncrement
519 this.video.buildLikeAndDislikePercents()
520 this.setVideoLikesBarTooltipText()
523 private setOpenGraphTags () {
524 this.metaService.setTitle(this.video.name)
526 this.metaService.setTag('og:type', 'video')
528 this.metaService.setTag('og:title', this.video.name)
529 this.metaService.setTag('name', this.video.name)
531 this.metaService.setTag('og:description', this.video.description)
532 this.metaService.setTag('description', this.video.description)
534 this.metaService.setTag('og:image', this.video.previewPath)
536 this.metaService.setTag('og:duration', this.video.duration.toString())
538 this.metaService.setTag('og:site_name', 'PeerTube')
540 this.metaService.setTag('og:url', window.location.href)
541 this.metaService.setTag('url', window.location.href)
544 private isAutoplay () {
545 // We'll jump to the thread id, so do not play the video
546 if (this.route.snapshot.params['threadId']) return false
548 // Otherwise true by default
549 if (!this.user) return true
551 // Be sure the autoPlay is set to false
552 return this.user.autoPlayVideo !== false
555 private flushPlayer () {
556 // Remove player if it exists
559 this.player.dispose()
560 this.player = undefined
562 console.error('Cannot dispose player.', err)
567 private initHotkeys () {
569 new Hotkey('shift+l', () => {
572 }, undefined, this.i18n('Like the video')),
574 new Hotkey('shift+d', () => {
577 }, undefined, this.i18n('Dislike the video')),
579 new Hotkey('shift+s', () => {
580 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
582 }, undefined, this.i18n('Subscribe to the account'))
584 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)