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, 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'
23 P2PMediaLoaderOptions,
24 PeertubePlayerManager,
25 PeertubePlayerManagerOptions,
27 } from '../../../assets/player/peertube-player-manager'
28 import { VideoPlaylist } from '@app/shared/video-playlist/video-playlist.model'
29 import { VideoPlaylistService } from '@app/shared/video-playlist/video-playlist.service'
30 import { Video } from '@app/shared/video/video.model'
31 import { isWebRTCDisabled } from '../../../assets/player/utils'
32 import { VideoWatchPlaylistComponent } from '@app/videos/+video-watch/video-watch-playlist.component'
35 selector: 'my-video-watch',
36 templateUrl: './video-watch.component.html',
37 styleUrls: [ './video-watch.component.scss' ]
39 export class VideoWatchComponent implements OnInit, OnDestroy {
40 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
42 @ViewChild('videoWatchPlaylist') videoWatchPlaylist: VideoWatchPlaylistComponent
43 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
44 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
45 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
48 playerElement: HTMLVideoElement
49 theaterEnabled = false
50 userRating: UserVideoRateType = null
51 video: VideoDetails = null
52 descriptionLoading = false
54 playlist: VideoPlaylist = null
56 completeDescriptionShown = false
57 completeVideoDescription: string
58 shortVideoDescription: string
59 videoHTMLDescription = ''
60 likesBarTooltipText = ''
61 hasAlreadyAcceptedPrivacyConcern = false
62 remoteServerDown = false
65 private currentTime: number
66 private paramsSub: Subscription
67 private queryParamsSub: Subscription
68 private configSub: Subscription
71 private elementRef: ElementRef,
72 private changeDetector: ChangeDetectorRef,
73 private route: ActivatedRoute,
74 private router: Router,
75 private videoService: VideoService,
76 private playlistService: VideoPlaylistService,
77 private videoBlacklistService: VideoBlacklistService,
78 private confirmService: ConfirmService,
79 private metaService: MetaService,
80 private authService: AuthService,
81 private serverService: ServerService,
82 private restExtractor: RestExtractor,
83 private notifier: Notifier,
84 private markdownService: MarkdownService,
86 private redirectService: RedirectService,
87 private videoCaptionService: VideoCaptionService,
89 private hotkeysService: HotkeysService,
90 @Inject(LOCALE_ID) private localeId: string
94 return this.authService.getUser()
98 this.configSub = this.serverService.configLoaded
101 isWebRTCDisabled() ||
102 this.serverService.getConfig().tracker.enabled === false ||
103 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
105 this.hasAlreadyAcceptedPrivacyConcern = true
109 this.paramsSub = this.route.params.subscribe(routeParams => {
110 const videoId = routeParams[ 'videoId' ]
111 if (videoId) this.loadVideo(videoId)
113 const playlistId = routeParams[ 'playlistId' ]
114 if (playlistId) this.loadPlaylist(playlistId)
117 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
118 const videoId = queryParams[ 'videoId' ]
119 if (videoId) this.loadVideo(videoId)
128 // Unsubscribe subscriptions
129 if (this.paramsSub) this.paramsSub.unsubscribe()
130 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
133 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
137 if (this.isUserLoggedIn() === false) return
138 if (this.userRating === 'like') {
139 // Already liked this video
140 this.setRating('none')
142 this.setRating('like')
147 if (this.isUserLoggedIn() === false) return
148 if (this.userRating === 'dislike') {
149 // Already disliked this video
150 this.setRating('none')
152 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
252 const startTime = queryParams.start
253 const stopTime = queryParams.stop
254 const subtitle = queryParams.subtitle
255 const playerMode = queryParams.mode
257 this.onVideoFetched(video, captionsResult.data, { startTime, stopTime, subtitle, playerMode })
258 .catch(err => this.handleError(err))
262 private loadPlaylist (playlistId: string) {
263 // Playlist did not change
264 if (this.playlist && this.playlist.uuid === playlistId) return
266 this.playlistService.getVideoPlaylist(playlistId)
268 // If 401, the video is private or blacklisted so redirect to 404
269 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
271 .subscribe(playlist => {
272 this.playlist = playlist
274 const videoId = this.route.snapshot.queryParams['videoId']
275 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
279 private updateVideoDescription (description: string) {
280 this.video.description = description
281 this.setVideoDescriptionHTML()
284 private async setVideoDescriptionHTML () {
285 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
288 private setVideoLikesBarTooltipText () {
289 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
290 likesNumber: this.video.likes,
291 dislikesNumber: this.video.dislikes
295 private handleError (err: any) {
296 const errorMessage: string = typeof err === 'string' ? err : err.message
297 if (!errorMessage) return
299 // Display a message in the video player instead of a notification
300 if (errorMessage.indexOf('from xs param') !== -1) {
302 this.remoteServerDown = true
303 this.changeDetector.detectChanges()
308 this.notifier.error(errorMessage)
311 private checkUserRating () {
312 // Unlogged users do not have ratings
313 if (this.isUserLoggedIn() === false) return
315 this.videoService.getUserVideoRating(this.video.id)
319 this.userRating = ratingObject.rating
323 err => this.notifier.error(err.message)
327 private async onVideoFetched (
329 videoCaptions: VideoCaption[],
330 urlOptions: { startTime?: number, stopTime?: number, subtitle?: string, playerMode?: string }
334 // Re init attributes
335 this.descriptionLoading = false
336 this.completeDescriptionShown = false
337 this.remoteServerDown = false
338 this.currentTime = undefined
340 this.videoWatchPlaylist.updatePlaylistIndex(video)
342 let startTime = urlOptions.startTime || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
343 // If we are at the end of the video, reset the timer
344 if (this.video.duration - startTime <= 1) startTime = 0
346 if (this.isVideoBlur(this.video)) {
347 const res = await this.confirmService.confirm(
348 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
349 this.i18n('Mature or explicit content')
351 if (res === false) return this.redirectService.redirectToHomepage()
354 // Flush old player if needed
357 // Build video element, because videojs remove it on dispose
358 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
359 this.playerElement = document.createElement('video')
360 this.playerElement.className = 'video-js vjs-peertube-skin'
361 this.playerElement.setAttribute('playsinline', 'true')
362 playerElementWrapper.appendChild(this.playerElement)
364 const playerCaptions = videoCaptions.map(c => ({
365 label: c.language.label,
366 language: c.language.id,
367 src: environment.apiUrl + c.captionPath
370 const options: PeertubePlayerManagerOptions = {
372 autoplay: this.isAutoplay(),
374 playerElement: this.playerElement,
375 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
377 videoDuration: this.video.duration,
379 inactivityTimeout: 2500,
380 poster: this.video.previewUrl,
382 stopTime: urlOptions.stopTime,
385 captions: videoCaptions.length !== 0,
388 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
389 embedUrl: this.video.embedUrl,
391 language: this.localeId,
393 subtitle: urlOptions.subtitle,
395 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
396 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
397 authorizationHeader: this.authService.getRequestHeaderValue()
400 serverUrl: environment.apiUrl,
402 videoCaptions: playerCaptions
406 videoFiles: this.video.files
412 if (urlOptions.playerMode) {
413 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
414 else mode = 'webtorrent'
416 if (this.video.hasHlsPlaylist()) mode = 'p2p-media-loader'
417 else mode = 'webtorrent'
420 if (mode === 'p2p-media-loader') {
421 const hlsPlaylist = this.video.getHlsPlaylist()
423 const p2pMediaLoader = {
424 playlistUrl: hlsPlaylist.playlistUrl,
425 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
426 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
427 trackerAnnounce: this.video.trackerUrls,
428 videoFiles: this.video.files
429 } as P2PMediaLoaderOptions
431 Object.assign(options, { p2pMediaLoader })
434 this.zone.runOutsideAngular(async () => {
435 this.player = await PeertubePlayerManager.initialize(mode, options)
436 this.theaterEnabled = this.player.theaterEnabled
438 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
440 this.player.on('timeupdate', () => {
441 this.currentTime = Math.floor(this.player.currentTime())
444 this.player.one('ended', () => {
446 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
450 this.player.one('stopped', () => {
452 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
456 this.player.on('theaterChange', (_: any, enabled: boolean) => {
457 this.zone.run(() => this.theaterEnabled = enabled)
461 this.setVideoDescriptionHTML()
462 this.setVideoLikesBarTooltipText()
464 this.setOpenGraphTags()
465 this.checkUserRating()
468 private setRating (nextRating: UserVideoRateType) {
470 switch (nextRating) {
472 method = this.videoService.setVideoLike
475 method = this.videoService.setVideoDislike
478 method = this.videoService.unsetVideoLike
482 method.call(this.videoService, this.video.id)
485 // Update the video like attribute
486 this.updateVideoRating(this.userRating, nextRating)
487 this.userRating = nextRating
490 (err: { message: string }) => this.notifier.error(err.message)
494 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
495 let likesToIncrement = 0
496 let dislikesToIncrement = 0
499 if (oldRating === 'like') likesToIncrement--
500 if (oldRating === 'dislike') dislikesToIncrement--
503 if (newRating === 'like') likesToIncrement++
504 if (newRating === 'dislike') dislikesToIncrement++
506 this.video.likes += likesToIncrement
507 this.video.dislikes += dislikesToIncrement
509 this.video.buildLikeAndDislikePercents()
510 this.setVideoLikesBarTooltipText()
513 private setOpenGraphTags () {
514 this.metaService.setTitle(this.video.name)
516 this.metaService.setTag('og:type', 'video')
518 this.metaService.setTag('og:title', this.video.name)
519 this.metaService.setTag('name', this.video.name)
521 this.metaService.setTag('og:description', this.video.description)
522 this.metaService.setTag('description', this.video.description)
524 this.metaService.setTag('og:image', this.video.previewPath)
526 this.metaService.setTag('og:duration', this.video.duration.toString())
528 this.metaService.setTag('og:site_name', 'PeerTube')
530 this.metaService.setTag('og:url', window.location.href)
531 this.metaService.setTag('url', window.location.href)
534 private isAutoplay () {
535 // We'll jump to the thread id, so do not play the video
536 if (this.route.snapshot.params['threadId']) return false
538 // Otherwise true by default
539 if (!this.user) return true
541 // Be sure the autoPlay is set to false
542 return this.user.autoPlayVideo !== false
545 private flushPlayer () {
546 // Remove player if it exists
548 this.player.dispose()
549 this.player = undefined
553 private initHotkeys () {
555 new Hotkey('shift+l', (event: KeyboardEvent): boolean => {
558 }, undefined, this.i18n('Like the video')),
559 new Hotkey('shift+d', (event: KeyboardEvent): boolean => {
562 }, undefined, this.i18n('Dislike the video')),
563 new Hotkey('shift+s', (event: KeyboardEvent): boolean => {
564 this.subscribeButton.subscribed ?
565 this.subscribeButton.unsubscribe() :
566 this.subscribeButton.subscribe()
568 }, undefined, this.i18n('Subscribe to the account'))
570 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)