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)
123 new Hotkey('shift+l', (event: KeyboardEvent): boolean => {
126 }, undefined, this.i18n('Like the video')),
127 new Hotkey('shift+d', (event: KeyboardEvent): boolean => {
130 }, undefined, this.i18n('Dislike the video')),
131 new Hotkey('shift+s', (event: KeyboardEvent): boolean => {
132 this.subscribeButton.subscribed ?
133 this.subscribeButton.unsubscribe() :
134 this.subscribeButton.subscribe()
136 }, undefined, this.i18n('Subscribe to the account'))
138 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
144 // Unsubscribe subscriptions
145 if (this.paramsSub) this.paramsSub.unsubscribe()
146 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
149 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
153 if (this.isUserLoggedIn() === false) return
154 if (this.userRating === 'like') {
155 // Already liked this video
156 this.setRating('none')
158 this.setRating('like')
163 if (this.isUserLoggedIn() === false) return
164 if (this.userRating === 'dislike') {
165 // Already disliked this video
166 this.setRating('none')
168 this.setRating('dislike')
172 showMoreDescription () {
173 if (this.completeVideoDescription === undefined) {
174 return this.loadCompleteDescription()
177 this.updateVideoDescription(this.completeVideoDescription)
178 this.completeDescriptionShown = true
181 showLessDescription () {
182 this.updateVideoDescription(this.shortVideoDescription)
183 this.completeDescriptionShown = false
186 loadCompleteDescription () {
187 this.descriptionLoading = true
189 this.videoService.loadCompleteDescription(this.video.descriptionPath)
192 this.completeDescriptionShown = true
193 this.descriptionLoading = false
195 this.shortVideoDescription = this.video.description
196 this.completeVideoDescription = description
198 this.updateVideoDescription(this.completeVideoDescription)
202 this.descriptionLoading = false
203 this.notifier.error(error.message)
208 showSupportModal () {
209 this.videoSupportModal.show()
213 this.videoShareModal.show(this.currentTime)
217 return this.authService.isLoggedIn()
221 if (!this.video || Array.isArray(this.video.tags) === false) return []
223 return this.video.tags
227 this.redirectService.redirectToHomepage()
230 acceptedPrivacyConcern () {
231 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
232 this.hasAlreadyAcceptedPrivacyConcern = true
235 isVideoToTranscode () {
236 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
240 return this.video && this.video.state.id === VideoState.TO_IMPORT
243 hasVideoScheduledPublication () {
244 return this.video && this.video.scheduledUpdate !== undefined
247 isVideoBlur (video: Video) {
248 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
251 private loadVideo (videoId: string) {
252 // Video did not change
253 if (this.video && this.video.uuid === videoId) return
255 if (this.player) this.player.pause()
259 this.videoService.getVideo(videoId),
260 this.videoCaptionService.listCaptions(videoId)
263 // If 401, the video is private or blacklisted so redirect to 404
264 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
266 .subscribe(([ video, captionsResult ]) => {
267 const queryParams = this.route.snapshot.queryParams
268 const startTime = queryParams.start
269 const stopTime = queryParams.stop
270 const subtitle = queryParams.subtitle
271 const playerMode = queryParams.mode
273 this.onVideoFetched(video, captionsResult.data, { startTime, stopTime, subtitle, playerMode })
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()
300 private async setVideoDescriptionHTML () {
301 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
304 private setVideoLikesBarTooltipText () {
305 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
306 likesNumber: this.video.likes,
307 dislikesNumber: this.video.dislikes
311 private handleError (err: any) {
312 const errorMessage: string = typeof err === 'string' ? err : err.message
313 if (!errorMessage) return
315 // Display a message in the video player instead of a notification
316 if (errorMessage.indexOf('from xs param') !== -1) {
318 this.remoteServerDown = true
319 this.changeDetector.detectChanges()
324 this.notifier.error(errorMessage)
327 private checkUserRating () {
328 // Unlogged users do not have ratings
329 if (this.isUserLoggedIn() === false) return
331 this.videoService.getUserVideoRating(this.video.id)
335 this.userRating = ratingObject.rating
339 err => this.notifier.error(err.message)
343 private async onVideoFetched (
345 videoCaptions: VideoCaption[],
346 urlOptions: { startTime?: number, stopTime?: number, subtitle?: string, playerMode?: string }
350 // Re init attributes
351 this.descriptionLoading = false
352 this.completeDescriptionShown = false
353 this.remoteServerDown = false
354 this.currentTime = undefined
356 this.videoWatchPlaylist.updatePlaylistIndex(video)
358 let startTime = urlOptions.startTime || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
359 // If we are at the end of the video, reset the timer
360 if (this.video.duration - startTime <= 1) startTime = 0
362 if (this.isVideoBlur(this.video)) {
363 const res = await this.confirmService.confirm(
364 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
365 this.i18n('Mature or explicit content')
367 if (res === false) return this.redirectService.redirectToHomepage()
370 // Flush old player if needed
373 // Build video element, because videojs remove it on dispose
374 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
375 this.playerElement = document.createElement('video')
376 this.playerElement.className = 'video-js vjs-peertube-skin'
377 this.playerElement.setAttribute('playsinline', 'true')
378 playerElementWrapper.appendChild(this.playerElement)
380 const playerCaptions = videoCaptions.map(c => ({
381 label: c.language.label,
382 language: c.language.id,
383 src: environment.apiUrl + c.captionPath
386 const options: PeertubePlayerManagerOptions = {
388 autoplay: this.isAutoplay(),
390 playerElement: this.playerElement,
391 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
393 videoDuration: this.video.duration,
395 inactivityTimeout: 2500,
396 poster: this.video.previewUrl,
398 stopTime: urlOptions.stopTime,
401 captions: videoCaptions.length !== 0,
404 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
405 embedUrl: this.video.embedUrl,
407 language: this.localeId,
409 subtitle: urlOptions.subtitle,
411 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
412 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
413 authorizationHeader: this.authService.getRequestHeaderValue()
416 serverUrl: environment.apiUrl,
418 videoCaptions: playerCaptions
422 videoFiles: this.video.files
426 const mode: PlayerMode = urlOptions.playerMode === 'p2p-media-loader' ? 'p2p-media-loader' : 'webtorrent'
428 if (mode === 'p2p-media-loader') {
429 const hlsPlaylist = this.video.getHlsPlaylist()
431 const p2pMediaLoader = {
432 playlistUrl: hlsPlaylist.playlistUrl,
433 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
434 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
435 trackerAnnounce: this.video.trackerUrls,
436 videoFiles: this.video.files
437 } as P2PMediaLoaderOptions
439 Object.assign(options, { p2pMediaLoader })
442 this.zone.runOutsideAngular(async () => {
443 this.player = await PeertubePlayerManager.initialize(mode, options)
444 this.theaterEnabled = this.player.theaterEnabled
446 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
448 this.player.on('timeupdate', () => {
449 this.currentTime = Math.floor(this.player.currentTime())
452 this.player.one('ended', () => {
454 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
458 this.player.one('stopped', () => {
460 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
464 this.player.on('theaterChange', (_: any, enabled: boolean) => {
465 this.zone.run(() => this.theaterEnabled = enabled)
469 this.setVideoDescriptionHTML()
470 this.setVideoLikesBarTooltipText()
472 this.setOpenGraphTags()
473 this.checkUserRating()
476 private setRating (nextRating: UserVideoRateType) {
478 switch (nextRating) {
480 method = this.videoService.setVideoLike
483 method = this.videoService.setVideoDislike
486 method = this.videoService.unsetVideoLike
490 method.call(this.videoService, this.video.id)
493 // Update the video like attribute
494 this.updateVideoRating(this.userRating, nextRating)
495 this.userRating = nextRating
498 (err: { message: string }) => this.notifier.error(err.message)
502 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
503 let likesToIncrement = 0
504 let dislikesToIncrement = 0
507 if (oldRating === 'like') likesToIncrement--
508 if (oldRating === 'dislike') dislikesToIncrement--
511 if (newRating === 'like') likesToIncrement++
512 if (newRating === 'dislike') dislikesToIncrement++
514 this.video.likes += likesToIncrement
515 this.video.dislikes += dislikesToIncrement
517 this.video.buildLikeAndDislikePercents()
518 this.setVideoLikesBarTooltipText()
521 private setOpenGraphTags () {
522 this.metaService.setTitle(this.video.name)
524 this.metaService.setTag('og:type', 'video')
526 this.metaService.setTag('og:title', this.video.name)
527 this.metaService.setTag('name', this.video.name)
529 this.metaService.setTag('og:description', this.video.description)
530 this.metaService.setTag('description', this.video.description)
532 this.metaService.setTag('og:image', this.video.previewPath)
534 this.metaService.setTag('og:duration', this.video.duration.toString())
536 this.metaService.setTag('og:site_name', 'PeerTube')
538 this.metaService.setTag('og:url', window.location.href)
539 this.metaService.setTag('url', window.location.href)
542 private isAutoplay () {
543 // We'll jump to the thread id, so do not play the video
544 if (this.route.snapshot.params['threadId']) return false
546 // Otherwise true by default
547 if (!this.user) return true
549 // Be sure the autoPlay is set to false
550 return this.user.autoPlayVideo !== false
553 private flushPlayer () {
554 // Remove player if it exists
556 this.player.dispose()
557 this.player = undefined