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, VideoPlaylistPrivacy, 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 { ComponentPagination } from '@app/shared/rest/component-pagination.model'
31 import { Video } from '@app/shared/video/video.model'
32 import { isWebRTCDisabled } from '../../../assets/player/utils'
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('videoShareModal') videoShareModal: VideoShareComponent
43 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
44 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
47 playerElement: HTMLVideoElement
48 theaterEnabled = false
49 userRating: UserVideoRateType = null
50 video: VideoDetails = null
51 descriptionLoading = false
53 playlist: VideoPlaylist = null
54 playlistVideos: Video[] = []
55 playlistPagination: ComponentPagination = {
60 noPlaylistVideos = false
61 currentPlaylistPosition = 1
63 completeDescriptionShown = false
64 completeVideoDescription: string
65 shortVideoDescription: string
66 videoHTMLDescription = ''
67 likesBarTooltipText = ''
68 hasAlreadyAcceptedPrivacyConcern = false
69 remoteServerDown = false
72 private currentTime: number
73 private paramsSub: Subscription
74 private queryParamsSub: Subscription
75 private configSub: Subscription
78 private elementRef: ElementRef,
79 private changeDetector: ChangeDetectorRef,
80 private route: ActivatedRoute,
81 private router: Router,
82 private videoService: VideoService,
83 private playlistService: VideoPlaylistService,
84 private videoBlacklistService: VideoBlacklistService,
85 private confirmService: ConfirmService,
86 private metaService: MetaService,
87 private authService: AuthService,
88 private serverService: ServerService,
89 private restExtractor: RestExtractor,
90 private notifier: Notifier,
91 private markdownService: MarkdownService,
93 private redirectService: RedirectService,
94 private videoCaptionService: VideoCaptionService,
96 private hotkeysService: HotkeysService,
97 @Inject(LOCALE_ID) private localeId: string
101 return this.authService.getUser()
105 this.configSub = this.serverService.configLoaded
108 isWebRTCDisabled() ||
109 this.serverService.getConfig().tracker.enabled === false ||
110 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
112 this.hasAlreadyAcceptedPrivacyConcern = true
116 this.paramsSub = this.route.params.subscribe(routeParams => {
117 const videoId = routeParams[ 'videoId' ]
118 if (videoId) this.loadVideo(videoId)
120 const playlistId = routeParams[ 'playlistId' ]
121 if (playlistId) this.loadPlaylist(playlistId)
124 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
125 const videoId = queryParams[ 'videoId' ]
126 if (videoId) this.loadVideo(videoId)
130 new Hotkey('shift+l', (event: KeyboardEvent): boolean => {
133 }, undefined, this.i18n('Like the video')),
134 new Hotkey('shift+d', (event: KeyboardEvent): boolean => {
137 }, undefined, this.i18n('Dislike the video')),
138 new Hotkey('shift+s', (event: KeyboardEvent): boolean => {
139 this.subscribeButton.subscribed ?
140 this.subscribeButton.unsubscribe() :
141 this.subscribeButton.subscribe()
143 }, undefined, this.i18n('Subscribe to the account'))
145 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
151 // Unsubscribe subscriptions
152 if (this.paramsSub) this.paramsSub.unsubscribe()
153 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
156 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
160 if (this.isUserLoggedIn() === false) return
161 if (this.userRating === 'like') {
162 // Already liked this video
163 this.setRating('none')
165 this.setRating('like')
170 if (this.isUserLoggedIn() === false) return
171 if (this.userRating === 'dislike') {
172 // Already disliked this video
173 this.setRating('none')
175 this.setRating('dislike')
179 showMoreDescription () {
180 if (this.completeVideoDescription === undefined) {
181 return this.loadCompleteDescription()
184 this.updateVideoDescription(this.completeVideoDescription)
185 this.completeDescriptionShown = true
188 showLessDescription () {
189 this.updateVideoDescription(this.shortVideoDescription)
190 this.completeDescriptionShown = false
193 loadCompleteDescription () {
194 this.descriptionLoading = true
196 this.videoService.loadCompleteDescription(this.video.descriptionPath)
199 this.completeDescriptionShown = true
200 this.descriptionLoading = false
202 this.shortVideoDescription = this.video.description
203 this.completeVideoDescription = description
205 this.updateVideoDescription(this.completeVideoDescription)
209 this.descriptionLoading = false
210 this.notifier.error(error.message)
215 showSupportModal () {
216 this.videoSupportModal.show()
220 this.videoShareModal.show(this.currentTime)
224 return this.authService.isLoggedIn()
228 if (!this.video || Array.isArray(this.video.tags) === false) return []
230 return this.video.tags
233 isVideoRemovable () {
234 return this.video.isRemovableBy(this.authService.getUser())
238 this.redirectService.redirectToHomepage()
241 acceptedPrivacyConcern () {
242 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
243 this.hasAlreadyAcceptedPrivacyConcern = true
246 isVideoToTranscode () {
247 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
250 isVideoDownloadable () {
251 return this.video && this.video.downloadEnabled
255 return this.video && this.video.state.id === VideoState.TO_IMPORT
258 hasVideoScheduledPublication () {
259 return this.video && this.video.scheduledUpdate !== undefined
262 isVideoBlur (video: Video) {
263 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
267 return this.playlist.isLocal === true && this.playlist.ownerAccount.name === this.user.username
270 isUnlistedPlaylist () {
271 return this.playlist.privacy.id === VideoPlaylistPrivacy.UNLISTED
274 isPrivatePlaylist () {
275 return this.playlist.privacy.id === VideoPlaylistPrivacy.PRIVATE
278 isPublicPlaylist () {
279 return this.playlist.privacy.id === VideoPlaylistPrivacy.PUBLIC
282 onPlaylistVideosNearOfBottom () {
284 if (this.playlistPagination.totalItems <= (this.playlistPagination.currentPage * this.playlistPagination.itemsPerPage)) return
286 this.playlistPagination.currentPage += 1
287 this.loadPlaylistElements(false)
290 onElementRemoved (video: Video) {
291 this.playlistVideos = this.playlistVideos.filter(v => v.id !== video.id)
293 this.playlistPagination.totalItems--
296 private loadVideo (videoId: string) {
297 // Video did not change
298 if (this.video && this.video.uuid === videoId) return
300 if (this.player) this.player.pause()
304 this.videoService.getVideo(videoId),
305 this.videoCaptionService.listCaptions(videoId)
308 // If 401, the video is private or blacklisted so redirect to 404
309 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
311 .subscribe(([ video, captionsResult ]) => {
312 const queryParams = this.route.snapshot.queryParams
313 const startTime = queryParams.start
314 const stopTime = queryParams.stop
315 const subtitle = queryParams.subtitle
316 const playerMode = queryParams.mode
318 this.onVideoFetched(video, captionsResult.data, { startTime, stopTime, subtitle, playerMode })
319 .catch(err => this.handleError(err))
323 private loadPlaylist (playlistId: string) {
324 // Playlist did not change
325 if (this.playlist && this.playlist.uuid === playlistId) return
327 this.playlistService.getVideoPlaylist(playlistId)
329 // If 401, the video is private or blacklisted so redirect to 404
330 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
332 .subscribe(playlist => {
333 this.playlist = playlist
335 const videoId = this.route.snapshot.queryParams['videoId']
336 this.loadPlaylistElements(!videoId)
340 private loadPlaylistElements (redirectToFirst = false) {
341 this.videoService.getPlaylistVideos(this.playlist.uuid, this.playlistPagination)
342 .subscribe(({ totalVideos, videos }) => {
343 this.playlistVideos = this.playlistVideos.concat(videos)
344 this.playlistPagination.totalItems = totalVideos
346 if (totalVideos === 0) {
347 this.noPlaylistVideos = true
351 this.updatePlaylistIndex()
353 if (redirectToFirst) {
355 queryParams: { videoId: this.playlistVideos[ 0 ].uuid },
358 this.router.navigate([], extras)
363 private updateVideoDescription (description: string) {
364 this.video.description = description
365 this.setVideoDescriptionHTML()
368 private async setVideoDescriptionHTML () {
369 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
372 private setVideoLikesBarTooltipText () {
373 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
374 likesNumber: this.video.likes,
375 dislikesNumber: this.video.dislikes
379 private handleError (err: any) {
380 const errorMessage: string = typeof err === 'string' ? err : err.message
381 if (!errorMessage) return
383 // Display a message in the video player instead of a notification
384 if (errorMessage.indexOf('from xs param') !== -1) {
386 this.remoteServerDown = true
387 this.changeDetector.detectChanges()
392 this.notifier.error(errorMessage)
395 private checkUserRating () {
396 // Unlogged users do not have ratings
397 if (this.isUserLoggedIn() === false) return
399 this.videoService.getUserVideoRating(this.video.id)
403 this.userRating = ratingObject.rating
407 err => this.notifier.error(err.message)
411 private async onVideoFetched (
413 videoCaptions: VideoCaption[],
414 urlOptions: { startTime?: number, stopTime?: number, subtitle?: string, playerMode?: string }
418 // Re init attributes
419 this.descriptionLoading = false
420 this.completeDescriptionShown = false
421 this.remoteServerDown = false
422 this.currentTime = undefined
424 this.updatePlaylistIndex()
426 let startTime = urlOptions.startTime || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
427 // If we are at the end of the video, reset the timer
428 if (this.video.duration - startTime <= 1) startTime = 0
430 if (this.isVideoBlur(this.video)) {
431 const res = await this.confirmService.confirm(
432 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
433 this.i18n('Mature or explicit content')
435 if (res === false) return this.redirectService.redirectToHomepage()
438 // Flush old player if needed
441 // Build video element, because videojs remove it on dispose
442 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
443 this.playerElement = document.createElement('video')
444 this.playerElement.className = 'video-js vjs-peertube-skin'
445 this.playerElement.setAttribute('playsinline', 'true')
446 playerElementWrapper.appendChild(this.playerElement)
448 const playerCaptions = videoCaptions.map(c => ({
449 label: c.language.label,
450 language: c.language.id,
451 src: environment.apiUrl + c.captionPath
454 const options: PeertubePlayerManagerOptions = {
456 autoplay: this.isAutoplay(),
458 playerElement: this.playerElement,
459 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
461 videoDuration: this.video.duration,
463 inactivityTimeout: 2500,
464 poster: this.video.previewUrl,
466 stopTime: urlOptions.stopTime,
469 captions: videoCaptions.length !== 0,
472 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
473 embedUrl: this.video.embedUrl,
475 language: this.localeId,
477 subtitle: urlOptions.subtitle,
479 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
480 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
481 authorizationHeader: this.authService.getRequestHeaderValue()
484 serverUrl: environment.apiUrl,
486 videoCaptions: playerCaptions
490 videoFiles: this.video.files
494 const mode: PlayerMode = urlOptions.playerMode === 'p2p-media-loader' ? 'p2p-media-loader' : 'webtorrent'
496 if (mode === 'p2p-media-loader') {
497 const hlsPlaylist = this.video.getHlsPlaylist()
499 const p2pMediaLoader = {
500 playlistUrl: hlsPlaylist.playlistUrl,
501 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
502 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
503 trackerAnnounce: this.video.trackerUrls,
504 videoFiles: this.video.files
505 } as P2PMediaLoaderOptions
507 Object.assign(options, { p2pMediaLoader })
510 this.zone.runOutsideAngular(async () => {
511 this.player = await PeertubePlayerManager.initialize(mode, options)
512 this.theaterEnabled = this.player.theaterEnabled
514 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
516 this.player.on('timeupdate', () => {
517 this.currentTime = Math.floor(this.player.currentTime())
520 this.player.one('ended', () => {
522 this.zone.run(() => this.navigateToNextPlaylistVideo())
526 this.player.one('stopped', () => {
528 this.zone.run(() => this.navigateToNextPlaylistVideo())
532 this.player.on('theaterChange', (_: any, enabled: boolean) => {
533 this.zone.run(() => this.theaterEnabled = enabled)
537 this.setVideoDescriptionHTML()
538 this.setVideoLikesBarTooltipText()
540 this.setOpenGraphTags()
541 this.checkUserRating()
544 private setRating (nextRating: UserVideoRateType) {
546 switch (nextRating) {
548 method = this.videoService.setVideoLike
551 method = this.videoService.setVideoDislike
554 method = this.videoService.unsetVideoLike
558 method.call(this.videoService, this.video.id)
561 // Update the video like attribute
562 this.updateVideoRating(this.userRating, nextRating)
563 this.userRating = nextRating
566 (err: { message: string }) => this.notifier.error(err.message)
570 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
571 let likesToIncrement = 0
572 let dislikesToIncrement = 0
575 if (oldRating === 'like') likesToIncrement--
576 if (oldRating === 'dislike') dislikesToIncrement--
579 if (newRating === 'like') likesToIncrement++
580 if (newRating === 'dislike') dislikesToIncrement++
582 this.video.likes += likesToIncrement
583 this.video.dislikes += dislikesToIncrement
585 this.video.buildLikeAndDislikePercents()
586 this.setVideoLikesBarTooltipText()
589 private updatePlaylistIndex () {
590 if (this.playlistVideos.length === 0 || !this.video) return
592 for (const video of this.playlistVideos) {
593 if (video.id === this.video.id) {
594 this.currentPlaylistPosition = video.playlistElement.position
599 // Load more videos to find our video
600 this.onPlaylistVideosNearOfBottom()
603 private setOpenGraphTags () {
604 this.metaService.setTitle(this.video.name)
606 this.metaService.setTag('og:type', 'video')
608 this.metaService.setTag('og:title', this.video.name)
609 this.metaService.setTag('name', this.video.name)
611 this.metaService.setTag('og:description', this.video.description)
612 this.metaService.setTag('description', this.video.description)
614 this.metaService.setTag('og:image', this.video.previewPath)
616 this.metaService.setTag('og:duration', this.video.duration.toString())
618 this.metaService.setTag('og:site_name', 'PeerTube')
620 this.metaService.setTag('og:url', window.location.href)
621 this.metaService.setTag('url', window.location.href)
624 private isAutoplay () {
625 // We'll jump to the thread id, so do not play the video
626 if (this.route.snapshot.params['threadId']) return false
628 // Otherwise true by default
629 if (!this.user) return true
631 // Be sure the autoPlay is set to false
632 return this.user.autoPlayVideo !== false
635 private flushPlayer () {
636 // Remove player if it exists
638 this.player.dispose()
639 this.player = undefined
643 private navigateToNextPlaylistVideo () {
644 if (this.currentPlaylistPosition < this.playlistPagination.totalItems) {
645 const next = this.playlistVideos.find(v => v.playlistElement.position === this.currentPlaylistPosition + 1)
647 const start = next.playlistElement.startTimestamp
648 const stop = next.playlistElement.stopTimestamp
649 this.router.navigate([],{ queryParams: { videoId: next.uuid, start, stop } })