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 { VideoActionsDisplayType } from '@app/shared/video/video-actions-dropdown.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('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
77 private elementRef: ElementRef,
78 private changeDetector: ChangeDetectorRef,
79 private route: ActivatedRoute,
80 private router: Router,
81 private videoService: VideoService,
82 private playlistService: VideoPlaylistService,
83 private videoBlacklistService: VideoBlacklistService,
84 private confirmService: ConfirmService,
85 private metaService: MetaService,
86 private authService: AuthService,
87 private serverService: ServerService,
88 private restExtractor: RestExtractor,
89 private notifier: Notifier,
90 private markdownService: MarkdownService,
92 private redirectService: RedirectService,
93 private videoCaptionService: VideoCaptionService,
95 private hotkeysService: HotkeysService,
96 @Inject(LOCALE_ID) private localeId: string
100 return this.authService.getUser()
105 !!((window as any).RTCPeerConnection || (window as any).mozRTCPeerConnection || (window as any).webkitRTCPeerConnection) === false ||
106 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
108 this.hasAlreadyAcceptedPrivacyConcern = true
111 this.paramsSub = this.route.params.subscribe(routeParams => {
112 const videoId = routeParams[ 'videoId' ]
113 if (videoId) this.loadVideo(videoId)
115 const playlistId = routeParams[ 'playlistId' ]
116 if (playlistId) this.loadPlaylist(playlistId)
119 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
120 const videoId = queryParams[ 'videoId' ]
121 if (videoId) this.loadVideo(videoId)
125 new Hotkey('shift+l', (event: KeyboardEvent): boolean => {
128 }, undefined, this.i18n('Like the video')),
129 new Hotkey('shift+d', (event: KeyboardEvent): boolean => {
132 }, undefined, this.i18n('Dislike the video')),
133 new Hotkey('shift+s', (event: KeyboardEvent): boolean => {
134 this.subscribeButton.subscribed ?
135 this.subscribeButton.unsubscribe() :
136 this.subscribeButton.subscribe()
138 }, undefined, this.i18n('Subscribe to the account'))
140 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
146 // Unsubscribe subscriptions
147 if (this.paramsSub) this.paramsSub.unsubscribe()
148 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
151 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
155 if (this.isUserLoggedIn() === false) return
156 if (this.userRating === 'like') {
157 // Already liked this video
158 this.setRating('none')
160 this.setRating('like')
165 if (this.isUserLoggedIn() === false) return
166 if (this.userRating === 'dislike') {
167 // Already disliked this video
168 this.setRating('none')
170 this.setRating('dislike')
174 showMoreDescription () {
175 if (this.completeVideoDescription === undefined) {
176 return this.loadCompleteDescription()
179 this.updateVideoDescription(this.completeVideoDescription)
180 this.completeDescriptionShown = true
183 showLessDescription () {
184 this.updateVideoDescription(this.shortVideoDescription)
185 this.completeDescriptionShown = false
188 loadCompleteDescription () {
189 this.descriptionLoading = true
191 this.videoService.loadCompleteDescription(this.video.descriptionPath)
194 this.completeDescriptionShown = true
195 this.descriptionLoading = false
197 this.shortVideoDescription = this.video.description
198 this.completeVideoDescription = description
200 this.updateVideoDescription(this.completeVideoDescription)
204 this.descriptionLoading = false
205 this.notifier.error(error.message)
210 showSupportModal () {
211 this.videoSupportModal.show()
215 this.videoShareModal.show(this.currentTime)
219 return this.authService.isLoggedIn()
223 if (!this.video || Array.isArray(this.video.tags) === false) return []
225 return this.video.tags
228 isVideoRemovable () {
229 return this.video.isRemovableBy(this.authService.getUser())
233 this.redirectService.redirectToHomepage()
236 acceptedPrivacyConcern () {
237 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
238 this.hasAlreadyAcceptedPrivacyConcern = true
241 isVideoToTranscode () {
242 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
245 isVideoDownloadable () {
246 return this.video && this.video.downloadEnabled
250 return this.video && this.video.state.id === VideoState.TO_IMPORT
253 hasVideoScheduledPublication () {
254 return this.video && this.video.scheduledUpdate !== undefined
257 isVideoBlur (video: Video) {
258 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
262 return this.playlist.isLocal === true && this.playlist.ownerAccount.name === this.user.username
265 isUnlistedPlaylist () {
266 return this.playlist.privacy.id === VideoPlaylistPrivacy.UNLISTED
269 isPrivatePlaylist () {
270 return this.playlist.privacy.id === VideoPlaylistPrivacy.PRIVATE
273 isPublicPlaylist () {
274 return this.playlist.privacy.id === VideoPlaylistPrivacy.PUBLIC
277 onPlaylistVideosNearOfBottom () {
279 if (this.playlistPagination.totalItems <= (this.playlistPagination.currentPage * this.playlistPagination.itemsPerPage)) return
281 this.playlistPagination.currentPage += 1
282 this.loadPlaylistElements(false)
285 onElementRemoved (video: Video) {
286 this.playlistVideos = this.playlistVideos.filter(v => v.id !== video.id)
288 this.playlistPagination.totalItems--
291 private loadVideo (videoId: string) {
292 // Video did not change
293 if (this.video && this.video.uuid === videoId) return
295 if (this.player) this.player.pause()
299 this.videoService.getVideo(videoId),
300 this.videoCaptionService.listCaptions(videoId)
303 // If 401, the video is private or blacklisted so redirect to 404
304 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
306 .subscribe(([ video, captionsResult ]) => {
307 const queryParams = this.route.snapshot.queryParams
308 const startTime = queryParams.start
309 const stopTime = queryParams.stop
310 const subtitle = queryParams.subtitle
311 const playerMode = queryParams.mode
313 this.onVideoFetched(video, captionsResult.data, { startTime, stopTime, subtitle, playerMode })
314 .catch(err => this.handleError(err))
318 private loadPlaylist (playlistId: string) {
319 // Playlist did not change
320 if (this.playlist && this.playlist.uuid === playlistId) return
322 this.playlistService.getVideoPlaylist(playlistId)
324 // If 401, the video is private or blacklisted so redirect to 404
325 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
327 .subscribe(playlist => {
328 this.playlist = playlist
330 const videoId = this.route.snapshot.queryParams['videoId']
331 this.loadPlaylistElements(!videoId)
335 private loadPlaylistElements (redirectToFirst = false) {
336 this.videoService.getPlaylistVideos(this.playlist.uuid, this.playlistPagination)
337 .subscribe(({ totalVideos, videos }) => {
338 this.playlistVideos = this.playlistVideos.concat(videos)
339 this.playlistPagination.totalItems = totalVideos
341 if (totalVideos === 0) {
342 this.noPlaylistVideos = true
346 this.updatePlaylistIndex()
348 if (redirectToFirst) {
350 queryParams: { videoId: this.playlistVideos[ 0 ].uuid },
353 this.router.navigate([], extras)
358 private updateVideoDescription (description: string) {
359 this.video.description = description
360 this.setVideoDescriptionHTML()
363 private async setVideoDescriptionHTML () {
364 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
367 private setVideoLikesBarTooltipText () {
368 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
369 likesNumber: this.video.likes,
370 dislikesNumber: this.video.dislikes
374 private handleError (err: any) {
375 const errorMessage: string = typeof err === 'string' ? err : err.message
376 if (!errorMessage) return
378 // Display a message in the video player instead of a notification
379 if (errorMessage.indexOf('from xs param') !== -1) {
381 this.remoteServerDown = true
382 this.changeDetector.detectChanges()
387 this.notifier.error(errorMessage)
390 private checkUserRating () {
391 // Unlogged users do not have ratings
392 if (this.isUserLoggedIn() === false) return
394 this.videoService.getUserVideoRating(this.video.id)
398 this.userRating = ratingObject.rating
402 err => this.notifier.error(err.message)
406 private async onVideoFetched (
408 videoCaptions: VideoCaption[],
409 urlOptions: { startTime?: number, stopTime?: number, subtitle?: string, playerMode?: string }
413 // Re init attributes
414 this.descriptionLoading = false
415 this.completeDescriptionShown = false
416 this.remoteServerDown = false
417 this.currentTime = undefined
419 this.updatePlaylistIndex()
421 let startTime = urlOptions.startTime || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
422 // If we are at the end of the video, reset the timer
423 if (this.video.duration - startTime <= 1) startTime = 0
425 if (this.isVideoBlur(this.video)) {
426 const res = await this.confirmService.confirm(
427 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
428 this.i18n('Mature or explicit content')
430 if (res === false) return this.redirectService.redirectToHomepage()
433 // Flush old player if needed
436 // Build video element, because videojs remove it on dispose
437 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
438 this.playerElement = document.createElement('video')
439 this.playerElement.className = 'video-js vjs-peertube-skin'
440 this.playerElement.setAttribute('playsinline', 'true')
441 playerElementWrapper.appendChild(this.playerElement)
443 const playerCaptions = videoCaptions.map(c => ({
444 label: c.language.label,
445 language: c.language.id,
446 src: environment.apiUrl + c.captionPath
449 const options: PeertubePlayerManagerOptions = {
451 autoplay: this.isAutoplay(),
453 playerElement: this.playerElement,
454 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
456 videoDuration: this.video.duration,
458 inactivityTimeout: 2500,
459 poster: this.video.previewUrl,
461 stopTime: urlOptions.stopTime,
464 captions: videoCaptions.length !== 0,
467 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
468 embedUrl: this.video.embedUrl,
470 language: this.localeId,
472 subtitle: urlOptions.subtitle,
474 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
475 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
476 authorizationHeader: this.authService.getRequestHeaderValue()
479 serverUrl: environment.apiUrl,
481 videoCaptions: playerCaptions
485 videoFiles: this.video.files
489 const mode: PlayerMode = urlOptions.playerMode === 'p2p-media-loader' ? 'p2p-media-loader' : 'webtorrent'
491 if (mode === 'p2p-media-loader') {
492 const hlsPlaylist = this.video.getHlsPlaylist()
494 const p2pMediaLoader = {
495 playlistUrl: hlsPlaylist.playlistUrl,
496 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
497 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
498 trackerAnnounce: this.video.trackerUrls,
499 videoFiles: this.video.files
500 } as P2PMediaLoaderOptions
502 Object.assign(options, { p2pMediaLoader })
505 this.zone.runOutsideAngular(async () => {
506 this.player = await PeertubePlayerManager.initialize(mode, options)
507 this.theaterEnabled = this.player.theaterEnabled
509 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
511 this.player.on('timeupdate', () => {
512 this.currentTime = Math.floor(this.player.currentTime())
515 this.player.one('ended', () => {
517 this.zone.run(() => this.navigateToNextPlaylistVideo())
521 this.player.one('stopped', () => {
523 this.zone.run(() => this.navigateToNextPlaylistVideo())
527 this.player.on('theaterChange', (_: any, enabled: boolean) => {
528 this.zone.run(() => this.theaterEnabled = enabled)
532 this.setVideoDescriptionHTML()
533 this.setVideoLikesBarTooltipText()
535 this.setOpenGraphTags()
536 this.checkUserRating()
539 private setRating (nextRating: UserVideoRateType) {
541 switch (nextRating) {
543 method = this.videoService.setVideoLike
546 method = this.videoService.setVideoDislike
549 method = this.videoService.unsetVideoLike
553 method.call(this.videoService, this.video.id)
556 // Update the video like attribute
557 this.updateVideoRating(this.userRating, nextRating)
558 this.userRating = nextRating
561 (err: { message: string }) => this.notifier.error(err.message)
565 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
566 let likesToIncrement = 0
567 let dislikesToIncrement = 0
570 if (oldRating === 'like') likesToIncrement--
571 if (oldRating === 'dislike') dislikesToIncrement--
574 if (newRating === 'like') likesToIncrement++
575 if (newRating === 'dislike') dislikesToIncrement++
577 this.video.likes += likesToIncrement
578 this.video.dislikes += dislikesToIncrement
580 this.video.buildLikeAndDislikePercents()
581 this.setVideoLikesBarTooltipText()
584 private updatePlaylistIndex () {
585 if (this.playlistVideos.length === 0 || !this.video) return
587 for (const video of this.playlistVideos) {
588 if (video.id === this.video.id) {
589 this.currentPlaylistPosition = video.playlistElement.position
594 // Load more videos to find our video
595 this.onPlaylistVideosNearOfBottom()
598 private setOpenGraphTags () {
599 this.metaService.setTitle(this.video.name)
601 this.metaService.setTag('og:type', 'video')
603 this.metaService.setTag('og:title', this.video.name)
604 this.metaService.setTag('name', this.video.name)
606 this.metaService.setTag('og:description', this.video.description)
607 this.metaService.setTag('description', this.video.description)
609 this.metaService.setTag('og:image', this.video.previewPath)
611 this.metaService.setTag('og:duration', this.video.duration.toString())
613 this.metaService.setTag('og:site_name', 'PeerTube')
615 this.metaService.setTag('og:url', window.location.href)
616 this.metaService.setTag('url', window.location.href)
619 private isAutoplay () {
620 // We'll jump to the thread id, so do not play the video
621 if (this.route.snapshot.params['threadId']) return false
623 // Otherwise true by default
624 if (!this.user) return true
626 // Be sure the autoPlay is set to false
627 return this.user.autoPlayVideo !== false
630 private flushPlayer () {
631 // Remove player if it exists
633 this.player.dispose()
634 this.player = undefined
638 private navigateToNextPlaylistVideo () {
639 if (this.currentPlaylistPosition < this.playlistPagination.totalItems) {
640 const next = this.playlistVideos.find(v => v.playlistElement.position === this.currentPlaylistPosition + 1)
642 const start = next.playlistElement.startTimestamp
643 const stop = next.playlistElement.stopTimestamp
644 this.router.navigate([],{ queryParams: { videoId: next.uuid, start, stop } })