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 { VideoDownloadComponent } from './modal/video-download.component'
17 import { VideoReportComponent } from './modal/video-report.component'
18 import { VideoShareComponent } from './modal/video-share.component'
19 import { VideoBlacklistComponent } from './modal/video-blacklist.component'
20 import { SubscribeButtonComponent } from '@app/shared/user-subscription/subscribe-button.component'
21 import { I18n } from '@ngx-translate/i18n-polyfill'
22 import { environment } from '../../../environments/environment'
23 import { VideoCaptionService } from '@app/shared/video-caption'
24 import { MarkdownService } from '@app/shared/renderer'
26 P2PMediaLoaderOptions,
27 PeertubePlayerManager,
28 PeertubePlayerManagerOptions,
30 } from '../../../assets/player/peertube-player-manager'
33 selector: 'my-video-watch',
34 templateUrl: './video-watch.component.html',
35 styleUrls: [ './video-watch.component.scss' ]
37 export class VideoWatchComponent implements OnInit, OnDestroy {
38 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
40 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
41 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
42 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
43 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
44 @ViewChild('videoBlacklistModal') videoBlacklistModal: VideoBlacklistComponent
45 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
48 playerElement: HTMLVideoElement
49 userRating: UserVideoRateType = null
50 video: VideoDetails = null
51 descriptionLoading = false
53 completeDescriptionShown = false
54 completeVideoDescription: string
55 shortVideoDescription: string
56 videoHTMLDescription = ''
57 likesBarTooltipText = ''
58 hasAlreadyAcceptedPrivacyConcern = false
59 remoteServerDown = false
62 private paramsSub: Subscription
65 private elementRef: ElementRef,
66 private changeDetector: ChangeDetectorRef,
67 private route: ActivatedRoute,
68 private router: Router,
69 private videoService: VideoService,
70 private videoBlacklistService: VideoBlacklistService,
71 private confirmService: ConfirmService,
72 private metaService: MetaService,
73 private authService: AuthService,
74 private serverService: ServerService,
75 private restExtractor: RestExtractor,
76 private notifier: Notifier,
77 private markdownService: MarkdownService,
79 private redirectService: RedirectService,
80 private videoCaptionService: VideoCaptionService,
82 private hotkeysService: HotkeysService,
83 @Inject(LOCALE_ID) private localeId: string
87 return this.authService.getUser()
92 !!((window as any).RTCPeerConnection || (window as any).mozRTCPeerConnection || (window as any).webkitRTCPeerConnection) === false ||
93 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
95 this.hasAlreadyAcceptedPrivacyConcern = true
98 this.paramsSub = this.route.params.subscribe(routeParams => {
99 const uuid = routeParams[ 'uuid' ]
101 // Video did not change
102 if (this.video && this.video.uuid === uuid) return
104 if (this.player) this.player.pause()
108 this.videoService.getVideo(uuid),
109 this.videoCaptionService.listCaptions(uuid)
112 // If 401, the video is private or blacklisted so redirect to 404
113 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
115 .subscribe(([ video, captionsResult ]) => {
116 const startTime = this.route.snapshot.queryParams.start
117 const subtitle = this.route.snapshot.queryParams.subtitle
118 const playerMode = this.route.snapshot.queryParams.mode
120 this.onVideoFetched(video, captionsResult.data, { startTime, subtitle, playerMode })
121 .catch(err => this.handleError(err))
126 new Hotkey('shift+l', (event: KeyboardEvent): boolean => {
129 }, undefined, this.i18n('Like the video')),
130 new Hotkey('shift+d', (event: KeyboardEvent): boolean => {
133 }, undefined, this.i18n('Dislike the video')),
134 new Hotkey('shift+s', (event: KeyboardEvent): boolean => {
135 this.subscribeButton.subscribed ?
136 this.subscribeButton.unsubscribe() :
137 this.subscribeButton.subscribe()
139 }, undefined, this.i18n('Subscribe to the account'))
141 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
147 // Unsubscribe subscriptions
148 this.paramsSub.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 showReportModal (event: Event) {
211 event.preventDefault()
212 this.videoReportModal.show()
215 showSupportModal () {
216 this.videoSupportModal.show()
220 const currentTime = this.player ? this.player.currentTime() : undefined
222 this.videoShareModal.show(currentTime)
225 showDownloadModal (event: Event) {
226 event.preventDefault()
227 this.videoDownloadModal.show()
230 showBlacklistModal (event: Event) {
231 event.preventDefault()
232 this.videoBlacklistModal.show()
235 async unblacklistVideo (event: Event) {
236 event.preventDefault()
238 const confirmMessage = this.i18n(
239 'Do you really want to remove this video from the blacklist? It will be available again in the videos list.'
242 const res = await this.confirmService.confirm(confirmMessage, this.i18n('Unblacklist'))
243 if (res === false) return
245 this.videoBlacklistService.removeVideoFromBlacklist(this.video.id).subscribe(
247 this.notifier.success(this.i18n('Video {{name}} removed from the blacklist.', { name: this.video.name }))
249 this.video.blacklisted = false
250 this.video.blacklistedReason = null
253 err => this.notifier.error(err.message)
258 return this.authService.isLoggedIn()
261 isVideoUpdatable () {
262 return this.video.isUpdatableBy(this.authService.getUser())
265 isVideoBlacklistable () {
266 return this.video.isBlackistableBy(this.user)
269 isVideoUnblacklistable () {
270 return this.video.isUnblacklistableBy(this.user)
274 if (!this.video || Array.isArray(this.video.tags) === false) return []
276 return this.video.tags
279 isVideoRemovable () {
280 return this.video.isRemovableBy(this.authService.getUser())
283 async removeVideo (event: Event) {
284 event.preventDefault()
286 const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
287 if (res === false) return
289 this.videoService.removeVideo(this.video.id)
292 this.notifier.success(this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name }))
294 // Go back to the video-list.
295 this.redirectService.redirectToHomepage()
298 error => this.notifier.error(error.message)
302 acceptedPrivacyConcern () {
303 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
304 this.hasAlreadyAcceptedPrivacyConcern = true
307 isVideoToTranscode () {
308 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
312 return this.video && this.video.state.id === VideoState.TO_IMPORT
315 hasVideoScheduledPublication () {
316 return this.video && this.video.scheduledUpdate !== undefined
319 private updateVideoDescription (description: string) {
320 this.video.description = description
321 this.setVideoDescriptionHTML()
324 private setVideoDescriptionHTML () {
325 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
328 private setVideoLikesBarTooltipText () {
329 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
330 likesNumber: this.video.likes,
331 dislikesNumber: this.video.dislikes
335 private handleError (err: any) {
336 const errorMessage: string = typeof err === 'string' ? err : err.message
337 if (!errorMessage) return
339 // Display a message in the video player instead of a notification
340 if (errorMessage.indexOf('from xs param') !== -1) {
342 this.remoteServerDown = true
343 this.changeDetector.detectChanges()
348 this.notifier.error(errorMessage)
351 private checkUserRating () {
352 // Unlogged users do not have ratings
353 if (this.isUserLoggedIn() === false) return
355 this.videoService.getUserVideoRating(this.video.id)
359 this.userRating = ratingObject.rating
363 err => this.notifier.error(err.message)
367 private async onVideoFetched (
369 videoCaptions: VideoCaption[],
370 urlOptions: { startTime?: number, subtitle?: string, playerMode?: string }
374 // Re init attributes
375 this.descriptionLoading = false
376 this.completeDescriptionShown = false
377 this.remoteServerDown = false
379 let startTime = urlOptions.startTime || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
380 // If we are at the end of the video, reset the timer
381 if (this.video.duration - startTime <= 1) startTime = 0
383 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
384 const res = await this.confirmService.confirm(
385 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
386 this.i18n('Mature or explicit content')
388 if (res === false) return this.redirectService.redirectToHomepage()
391 // Flush old player if needed
394 // Build video element, because videojs remove it on dispose
395 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
396 this.playerElement = document.createElement('video')
397 this.playerElement.className = 'video-js vjs-peertube-skin'
398 this.playerElement.setAttribute('playsinline', 'true')
399 playerElementWrapper.appendChild(this.playerElement)
401 const playerCaptions = videoCaptions.map(c => ({
402 label: c.language.label,
403 language: c.language.id,
404 src: environment.apiUrl + c.captionPath
407 const options: PeertubePlayerManagerOptions = {
409 autoplay: this.isAutoplay(),
411 playerElement: this.playerElement,
412 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
414 videoDuration: this.video.duration,
416 inactivityTimeout: 2500,
417 poster: this.video.previewUrl,
421 captions: videoCaptions.length !== 0,
424 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
425 embedUrl: this.video.embedUrl,
427 language: this.localeId,
429 subtitle: urlOptions.subtitle,
431 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
432 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
433 authorizationHeader: this.authService.getRequestHeaderValue()
436 serverUrl: environment.apiUrl,
438 videoCaptions: playerCaptions
442 videoFiles: this.video.files
446 const mode: PlayerMode = urlOptions.playerMode === 'p2p-media-loader' ? 'p2p-media-loader' : 'webtorrent'
448 if (mode === 'p2p-media-loader') {
449 const hlsPlaylist = this.video.getHlsPlaylist()
451 const p2pMediaLoader = {
452 playlistUrl: hlsPlaylist.playlistUrl,
453 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
454 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
455 trackerAnnounce: this.video.trackerUrls,
456 videoFiles: this.video.files
457 } as P2PMediaLoaderOptions
459 Object.assign(options, { p2pMediaLoader })
462 this.zone.runOutsideAngular(async () => {
463 this.player = await PeertubePlayerManager.initialize(mode, options)
464 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
467 this.setVideoDescriptionHTML()
468 this.setVideoLikesBarTooltipText()
470 this.setOpenGraphTags()
471 this.checkUserRating()
474 private setRating (nextRating: UserVideoRateType) {
476 switch (nextRating) {
478 method = this.videoService.setVideoLike
481 method = this.videoService.setVideoDislike
484 method = this.videoService.unsetVideoLike
488 method.call(this.videoService, this.video.id)
491 // Update the video like attribute
492 this.updateVideoRating(this.userRating, nextRating)
493 this.userRating = nextRating
496 (err: { message: string }) => this.notifier.error(err.message)
500 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
501 let likesToIncrement = 0
502 let dislikesToIncrement = 0
505 if (oldRating === 'like') likesToIncrement--
506 if (oldRating === 'dislike') dislikesToIncrement--
509 if (newRating === 'like') likesToIncrement++
510 if (newRating === 'dislike') dislikesToIncrement++
512 this.video.likes += likesToIncrement
513 this.video.dislikes += dislikesToIncrement
515 this.video.buildLikeAndDislikePercents()
516 this.setVideoLikesBarTooltipText()
519 private setOpenGraphTags () {
520 this.metaService.setTitle(this.video.name)
522 this.metaService.setTag('og:type', 'video')
524 this.metaService.setTag('og:title', this.video.name)
525 this.metaService.setTag('name', this.video.name)
527 this.metaService.setTag('og:description', this.video.description)
528 this.metaService.setTag('description', this.video.description)
530 this.metaService.setTag('og:image', this.video.previewPath)
532 this.metaService.setTag('og:duration', this.video.duration.toString())
534 this.metaService.setTag('og:site_name', 'PeerTube')
536 this.metaService.setTag('og:url', window.location.href)
537 this.metaService.setTag('url', window.location.href)
540 private isAutoplay () {
541 // We'll jump to the thread id, so do not play the video
542 if (this.route.snapshot.params['threadId']) return false
544 // Otherwise true by default
545 if (!this.user) return true
547 // Be sure the autoPlay is set to false
548 return this.user.autoPlayVideo !== false
551 private flushPlayer () {
552 // Remove player if it exists
554 this.player.dispose()
555 this.player = undefined