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'
34 selector: 'my-video-watch',
35 templateUrl: './video-watch.component.html',
36 styleUrls: [ './video-watch.component.scss' ]
38 export class VideoWatchComponent implements OnInit, OnDestroy {
39 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
41 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
42 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
43 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
46 playerElement: HTMLVideoElement
47 theaterEnabled = false
48 userRating: UserVideoRateType = null
49 video: VideoDetails = null
50 descriptionLoading = false
52 playlist: VideoPlaylist = null
53 playlistVideos: Video[] = []
54 playlistPagination: ComponentPagination = {
59 noPlaylistVideos = false
60 currentPlaylistPosition = 1
62 completeDescriptionShown = false
63 completeVideoDescription: string
64 shortVideoDescription: string
65 videoHTMLDescription = ''
66 likesBarTooltipText = ''
67 hasAlreadyAcceptedPrivacyConcern = false
68 remoteServerDown = false
71 private currentTime: number
72 private paramsSub: Subscription
73 private queryParamsSub: Subscription
76 private elementRef: ElementRef,
77 private changeDetector: ChangeDetectorRef,
78 private route: ActivatedRoute,
79 private router: Router,
80 private videoService: VideoService,
81 private playlistService: VideoPlaylistService,
82 private videoBlacklistService: VideoBlacklistService,
83 private confirmService: ConfirmService,
84 private metaService: MetaService,
85 private authService: AuthService,
86 private serverService: ServerService,
87 private restExtractor: RestExtractor,
88 private notifier: Notifier,
89 private markdownService: MarkdownService,
91 private redirectService: RedirectService,
92 private videoCaptionService: VideoCaptionService,
94 private hotkeysService: HotkeysService,
95 @Inject(LOCALE_ID) private localeId: string
99 return this.authService.getUser()
104 !!((window as any).RTCPeerConnection || (window as any).mozRTCPeerConnection || (window as any).webkitRTCPeerConnection) === false ||
105 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
107 this.hasAlreadyAcceptedPrivacyConcern = true
110 this.paramsSub = this.route.params.subscribe(routeParams => {
111 const videoId = routeParams[ 'videoId' ]
112 if (videoId) this.loadVideo(videoId)
114 const playlistId = routeParams[ 'playlistId' ]
115 if (playlistId) this.loadPlaylist(playlistId)
118 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
119 const videoId = queryParams[ 'videoId' ]
120 if (videoId) this.loadVideo(videoId)
124 new Hotkey('shift+l', (event: KeyboardEvent): boolean => {
127 }, undefined, this.i18n('Like the video')),
128 new Hotkey('shift+d', (event: KeyboardEvent): boolean => {
131 }, undefined, this.i18n('Dislike the video')),
132 new Hotkey('shift+s', (event: KeyboardEvent): boolean => {
133 this.subscribeButton.subscribed ?
134 this.subscribeButton.unsubscribe() :
135 this.subscribeButton.subscribe()
137 }, undefined, this.i18n('Subscribe to the account'))
139 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
145 // Unsubscribe subscriptions
146 if (this.paramsSub) this.paramsSub.unsubscribe()
147 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
150 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
154 if (this.isUserLoggedIn() === false) return
155 if (this.userRating === 'like') {
156 // Already liked this video
157 this.setRating('none')
159 this.setRating('like')
164 if (this.isUserLoggedIn() === false) return
165 if (this.userRating === 'dislike') {
166 // Already disliked this video
167 this.setRating('none')
169 this.setRating('dislike')
173 showMoreDescription () {
174 if (this.completeVideoDescription === undefined) {
175 return this.loadCompleteDescription()
178 this.updateVideoDescription(this.completeVideoDescription)
179 this.completeDescriptionShown = true
182 showLessDescription () {
183 this.updateVideoDescription(this.shortVideoDescription)
184 this.completeDescriptionShown = false
187 loadCompleteDescription () {
188 this.descriptionLoading = true
190 this.videoService.loadCompleteDescription(this.video.descriptionPath)
193 this.completeDescriptionShown = true
194 this.descriptionLoading = false
196 this.shortVideoDescription = this.video.description
197 this.completeVideoDescription = description
199 this.updateVideoDescription(this.completeVideoDescription)
203 this.descriptionLoading = false
204 this.notifier.error(error.message)
209 showSupportModal () {
210 this.videoSupportModal.show()
214 this.videoShareModal.show(this.currentTime)
218 return this.authService.isLoggedIn()
222 if (!this.video || Array.isArray(this.video.tags) === false) return []
224 return this.video.tags
227 isVideoRemovable () {
228 return this.video.isRemovableBy(this.authService.getUser())
232 this.redirectService.redirectToHomepage()
235 acceptedPrivacyConcern () {
236 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
237 this.hasAlreadyAcceptedPrivacyConcern = true
240 isVideoToTranscode () {
241 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
244 isVideoDownloadable () {
245 return this.video && this.video.downloadEnabled
249 return this.video && this.video.state.id === VideoState.TO_IMPORT
252 hasVideoScheduledPublication () {
253 return this.video && this.video.scheduledUpdate !== undefined
256 isVideoBlur (video: Video) {
257 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
261 return this.playlist.isLocal === true && this.playlist.ownerAccount.name === this.user.username
264 isUnlistedPlaylist () {
265 return this.playlist.privacy.id === VideoPlaylistPrivacy.UNLISTED
268 isPrivatePlaylist () {
269 return this.playlist.privacy.id === VideoPlaylistPrivacy.PRIVATE
272 isPublicPlaylist () {
273 return this.playlist.privacy.id === VideoPlaylistPrivacy.PUBLIC
276 onPlaylistVideosNearOfBottom () {
278 if (this.playlistPagination.totalItems <= (this.playlistPagination.currentPage * this.playlistPagination.itemsPerPage)) return
280 this.playlistPagination.currentPage += 1
281 this.loadPlaylistElements(false)
284 onElementRemoved (video: Video) {
285 this.playlistVideos = this.playlistVideos.filter(v => v.id !== video.id)
287 this.playlistPagination.totalItems--
290 private loadVideo (videoId: string) {
291 // Video did not change
292 if (this.video && this.video.uuid === videoId) return
294 if (this.player) this.player.pause()
298 this.videoService.getVideo(videoId),
299 this.videoCaptionService.listCaptions(videoId)
302 // If 401, the video is private or blacklisted so redirect to 404
303 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
305 .subscribe(([ video, captionsResult ]) => {
306 const queryParams = this.route.snapshot.queryParams
307 const startTime = queryParams.start
308 const stopTime = queryParams.stop
309 const subtitle = queryParams.subtitle
310 const playerMode = queryParams.mode
312 this.onVideoFetched(video, captionsResult.data, { startTime, stopTime, subtitle, playerMode })
313 .catch(err => this.handleError(err))
317 private loadPlaylist (playlistId: string) {
318 // Playlist did not change
319 if (this.playlist && this.playlist.uuid === playlistId) return
321 this.playlistService.getVideoPlaylist(playlistId)
323 // If 401, the video is private or blacklisted so redirect to 404
324 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
326 .subscribe(playlist => {
327 this.playlist = playlist
329 const videoId = this.route.snapshot.queryParams['videoId']
330 this.loadPlaylistElements(!videoId)
334 private loadPlaylistElements (redirectToFirst = false) {
335 this.videoService.getPlaylistVideos(this.playlist.uuid, this.playlistPagination)
336 .subscribe(({ totalVideos, videos }) => {
337 this.playlistVideos = this.playlistVideos.concat(videos)
338 this.playlistPagination.totalItems = totalVideos
340 if (totalVideos === 0) {
341 this.noPlaylistVideos = true
345 this.updatePlaylistIndex()
347 if (redirectToFirst) {
349 queryParams: { videoId: this.playlistVideos[ 0 ].uuid },
352 this.router.navigate([], extras)
357 private updateVideoDescription (description: string) {
358 this.video.description = description
359 this.setVideoDescriptionHTML()
362 private async setVideoDescriptionHTML () {
363 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
366 private setVideoLikesBarTooltipText () {
367 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
368 likesNumber: this.video.likes,
369 dislikesNumber: this.video.dislikes
373 private handleError (err: any) {
374 const errorMessage: string = typeof err === 'string' ? err : err.message
375 if (!errorMessage) return
377 // Display a message in the video player instead of a notification
378 if (errorMessage.indexOf('from xs param') !== -1) {
380 this.remoteServerDown = true
381 this.changeDetector.detectChanges()
386 this.notifier.error(errorMessage)
389 private checkUserRating () {
390 // Unlogged users do not have ratings
391 if (this.isUserLoggedIn() === false) return
393 this.videoService.getUserVideoRating(this.video.id)
397 this.userRating = ratingObject.rating
401 err => this.notifier.error(err.message)
405 private async onVideoFetched (
407 videoCaptions: VideoCaption[],
408 urlOptions: { startTime?: number, stopTime?: number, subtitle?: string, playerMode?: string }
412 // Re init attributes
413 this.descriptionLoading = false
414 this.completeDescriptionShown = false
415 this.remoteServerDown = false
416 this.currentTime = undefined
418 this.updatePlaylistIndex()
420 let startTime = urlOptions.startTime || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
421 // If we are at the end of the video, reset the timer
422 if (this.video.duration - startTime <= 1) startTime = 0
424 if (this.isVideoBlur(this.video)) {
425 const res = await this.confirmService.confirm(
426 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
427 this.i18n('Mature or explicit content')
429 if (res === false) return this.redirectService.redirectToHomepage()
432 // Flush old player if needed
435 // Build video element, because videojs remove it on dispose
436 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
437 this.playerElement = document.createElement('video')
438 this.playerElement.className = 'video-js vjs-peertube-skin'
439 this.playerElement.setAttribute('playsinline', 'true')
440 playerElementWrapper.appendChild(this.playerElement)
442 const playerCaptions = videoCaptions.map(c => ({
443 label: c.language.label,
444 language: c.language.id,
445 src: environment.apiUrl + c.captionPath
448 const options: PeertubePlayerManagerOptions = {
450 autoplay: this.isAutoplay(),
452 playerElement: this.playerElement,
453 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
455 videoDuration: this.video.duration,
457 inactivityTimeout: 2500,
458 poster: this.video.previewUrl,
460 stopTime: urlOptions.stopTime,
463 captions: videoCaptions.length !== 0,
466 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
467 embedUrl: this.video.embedUrl,
469 language: this.localeId,
471 subtitle: urlOptions.subtitle,
473 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
474 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
475 authorizationHeader: this.authService.getRequestHeaderValue()
478 serverUrl: environment.apiUrl,
480 videoCaptions: playerCaptions
484 videoFiles: this.video.files
488 const mode: PlayerMode = urlOptions.playerMode === 'p2p-media-loader' ? 'p2p-media-loader' : 'webtorrent'
490 if (mode === 'p2p-media-loader') {
491 const hlsPlaylist = this.video.getHlsPlaylist()
493 const p2pMediaLoader = {
494 playlistUrl: hlsPlaylist.playlistUrl,
495 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
496 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
497 trackerAnnounce: this.video.trackerUrls,
498 videoFiles: this.video.files
499 } as P2PMediaLoaderOptions
501 Object.assign(options, { p2pMediaLoader })
504 this.zone.runOutsideAngular(async () => {
505 this.player = await PeertubePlayerManager.initialize(mode, options)
506 this.theaterEnabled = this.player.theaterEnabled
508 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
510 this.player.on('timeupdate', () => {
511 this.currentTime = Math.floor(this.player.currentTime())
514 this.player.one('ended', () => {
516 this.zone.run(() => this.navigateToNextPlaylistVideo())
520 this.player.one('stopped', () => {
522 this.zone.run(() => this.navigateToNextPlaylistVideo())
526 this.player.on('theaterChange', (_: any, enabled: boolean) => {
527 this.zone.run(() => this.theaterEnabled = enabled)
531 this.setVideoDescriptionHTML()
532 this.setVideoLikesBarTooltipText()
534 this.setOpenGraphTags()
535 this.checkUserRating()
538 private setRating (nextRating: UserVideoRateType) {
540 switch (nextRating) {
542 method = this.videoService.setVideoLike
545 method = this.videoService.setVideoDislike
548 method = this.videoService.unsetVideoLike
552 method.call(this.videoService, this.video.id)
555 // Update the video like attribute
556 this.updateVideoRating(this.userRating, nextRating)
557 this.userRating = nextRating
560 (err: { message: string }) => this.notifier.error(err.message)
564 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
565 let likesToIncrement = 0
566 let dislikesToIncrement = 0
569 if (oldRating === 'like') likesToIncrement--
570 if (oldRating === 'dislike') dislikesToIncrement--
573 if (newRating === 'like') likesToIncrement++
574 if (newRating === 'dislike') dislikesToIncrement++
576 this.video.likes += likesToIncrement
577 this.video.dislikes += dislikesToIncrement
579 this.video.buildLikeAndDislikePercents()
580 this.setVideoLikesBarTooltipText()
583 private updatePlaylistIndex () {
584 if (this.playlistVideos.length === 0 || !this.video) return
586 for (const video of this.playlistVideos) {
587 if (video.id === this.video.id) {
588 this.currentPlaylistPosition = video.playlistElement.position
593 // Load more videos to find our video
594 this.onPlaylistVideosNearOfBottom()
597 private setOpenGraphTags () {
598 this.metaService.setTitle(this.video.name)
600 this.metaService.setTag('og:type', 'video')
602 this.metaService.setTag('og:title', this.video.name)
603 this.metaService.setTag('name', this.video.name)
605 this.metaService.setTag('og:description', this.video.description)
606 this.metaService.setTag('description', this.video.description)
608 this.metaService.setTag('og:image', this.video.previewPath)
610 this.metaService.setTag('og:duration', this.video.duration.toString())
612 this.metaService.setTag('og:site_name', 'PeerTube')
614 this.metaService.setTag('og:url', window.location.href)
615 this.metaService.setTag('url', window.location.href)
618 private isAutoplay () {
619 // We'll jump to the thread id, so do not play the video
620 if (this.route.snapshot.params['threadId']) return false
622 // Otherwise true by default
623 if (!this.user) return true
625 // Be sure the autoPlay is set to false
626 return this.user.autoPlayVideo !== false
629 private flushPlayer () {
630 // Remove player if it exists
632 this.player.dispose()
633 this.player = undefined
637 private navigateToNextPlaylistVideo () {
638 if (this.currentPlaylistPosition < this.playlistPagination.totalItems) {
639 const next = this.playlistVideos.find(v => v.playlistElement.position === this.currentPlaylistPosition + 1)
641 const start = next.playlistElement.startTimestamp
642 const stop = next.playlistElement.stopTimestamp
643 this.router.navigate([],{ queryParams: { videoId: next.uuid, start, stop } })