]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-watch/video-watch.component.ts
Add params to share modal
[github/Chocobozzz/PeerTube.git] / client / src / app / videos / +video-watch / video-watch.component.ts
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, Observable, 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'
22 import {
23 CustomizationOptions,
24 P2PMediaLoaderOptions,
25 PeertubePlayerManager,
26 PeertubePlayerManagerOptions,
27 PlayerMode
28 } from '../../../assets/player/peertube-player-manager'
29 import { VideoPlaylist } from '@app/shared/video-playlist/video-playlist.model'
30 import { VideoPlaylistService } from '@app/shared/video-playlist/video-playlist.service'
31 import { Video } from '@app/shared/video/video.model'
32 import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils'
33 import { VideoWatchPlaylistComponent } from '@app/videos/+video-watch/video-watch-playlist.component'
34 import { getStoredTheater } from '../../../assets/player/peertube-player-local-storage'
35
36 @Component({
37 selector: 'my-video-watch',
38 templateUrl: './video-watch.component.html',
39 styleUrls: [ './video-watch.component.scss' ]
40 })
41 export class VideoWatchComponent implements OnInit, OnDestroy {
42 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
43
44 @ViewChild('videoWatchPlaylist') videoWatchPlaylist: VideoWatchPlaylistComponent
45 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
46 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
47 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
48
49 player: any
50 playerElement: HTMLVideoElement
51 theaterEnabled = false
52 userRating: UserVideoRateType = null
53 descriptionLoading = false
54
55 video: VideoDetails = null
56 videoCaptions: VideoCaption[] = []
57
58 playlist: VideoPlaylist = null
59
60 completeDescriptionShown = false
61 completeVideoDescription: string
62 shortVideoDescription: string
63 videoHTMLDescription = ''
64 likesBarTooltipText = ''
65 hasAlreadyAcceptedPrivacyConcern = false
66 remoteServerDown = false
67 hotkeys: Hotkey[]
68
69 private currentTime: number
70 private paramsSub: Subscription
71 private queryParamsSub: Subscription
72 private configSub: Subscription
73
74 constructor (
75 private elementRef: ElementRef,
76 private changeDetector: ChangeDetectorRef,
77 private route: ActivatedRoute,
78 private router: Router,
79 private videoService: VideoService,
80 private playlistService: VideoPlaylistService,
81 private videoBlacklistService: VideoBlacklistService,
82 private confirmService: ConfirmService,
83 private metaService: MetaService,
84 private authService: AuthService,
85 private serverService: ServerService,
86 private restExtractor: RestExtractor,
87 private notifier: Notifier,
88 private markdownService: MarkdownService,
89 private zone: NgZone,
90 private redirectService: RedirectService,
91 private videoCaptionService: VideoCaptionService,
92 private i18n: I18n,
93 private hotkeysService: HotkeysService,
94 @Inject(LOCALE_ID) private localeId: string
95 ) {}
96
97 get user () {
98 return this.authService.getUser()
99 }
100
101 ngOnInit () {
102 this.configSub = this.serverService.configLoaded
103 .subscribe(() => {
104 if (
105 isWebRTCDisabled() ||
106 this.serverService.getConfig().tracker.enabled === false ||
107 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
108 ) {
109 this.hasAlreadyAcceptedPrivacyConcern = true
110 }
111 })
112
113 this.paramsSub = this.route.params.subscribe(routeParams => {
114 const videoId = routeParams[ 'videoId' ]
115 if (videoId) this.loadVideo(videoId)
116
117 const playlistId = routeParams[ 'playlistId' ]
118 if (playlistId) this.loadPlaylist(playlistId)
119 })
120
121 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
122 const videoId = queryParams[ 'videoId' ]
123 if (videoId) this.loadVideo(videoId)
124 })
125
126 this.initHotkeys()
127
128 this.theaterEnabled = getStoredTheater()
129 }
130
131 ngOnDestroy () {
132 this.flushPlayer()
133
134 // Unsubscribe subscriptions
135 if (this.paramsSub) this.paramsSub.unsubscribe()
136 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
137
138 // Unbind hotkeys
139 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
140 }
141
142 setLike () {
143 if (this.isUserLoggedIn() === false) return
144
145 // Already liked this video
146 if (this.userRating === 'like') this.setRating('none')
147 else this.setRating('like')
148 }
149
150 setDislike () {
151 if (this.isUserLoggedIn() === false) return
152
153 // Already disliked this video
154 if (this.userRating === 'dislike') this.setRating('none')
155 else this.setRating('dislike')
156 }
157
158 showMoreDescription () {
159 if (this.completeVideoDescription === undefined) {
160 return this.loadCompleteDescription()
161 }
162
163 this.updateVideoDescription(this.completeVideoDescription)
164 this.completeDescriptionShown = true
165 }
166
167 showLessDescription () {
168 this.updateVideoDescription(this.shortVideoDescription)
169 this.completeDescriptionShown = false
170 }
171
172 loadCompleteDescription () {
173 this.descriptionLoading = true
174
175 this.videoService.loadCompleteDescription(this.video.descriptionPath)
176 .subscribe(
177 description => {
178 this.completeDescriptionShown = true
179 this.descriptionLoading = false
180
181 this.shortVideoDescription = this.video.description
182 this.completeVideoDescription = description
183
184 this.updateVideoDescription(this.completeVideoDescription)
185 },
186
187 error => {
188 this.descriptionLoading = false
189 this.notifier.error(error.message)
190 }
191 )
192 }
193
194 showSupportModal () {
195 this.videoSupportModal.show()
196 }
197
198 showShareModal () {
199 this.videoShareModal.show(this.currentTime)
200 }
201
202 isUserLoggedIn () {
203 return this.authService.isLoggedIn()
204 }
205
206 getVideoTags () {
207 if (!this.video || Array.isArray(this.video.tags) === false) return []
208
209 return this.video.tags
210 }
211
212 onVideoRemoved () {
213 this.redirectService.redirectToHomepage()
214 }
215
216 acceptedPrivacyConcern () {
217 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
218 this.hasAlreadyAcceptedPrivacyConcern = true
219 }
220
221 isVideoToTranscode () {
222 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
223 }
224
225 isVideoToImport () {
226 return this.video && this.video.state.id === VideoState.TO_IMPORT
227 }
228
229 hasVideoScheduledPublication () {
230 return this.video && this.video.scheduledUpdate !== undefined
231 }
232
233 isVideoBlur (video: Video) {
234 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
235 }
236
237 private loadVideo (videoId: string) {
238 // Video did not change
239 if (this.video && this.video.uuid === videoId) return
240
241 if (this.player) this.player.pause()
242
243 // Video did change
244 forkJoin(
245 this.videoService.getVideo(videoId),
246 this.videoCaptionService.listCaptions(videoId)
247 )
248 .pipe(
249 // If 401, the video is private or blacklisted so redirect to 404
250 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
251 )
252 .subscribe(([ video, captionsResult ]) => {
253 const queryParams = this.route.snapshot.queryParams
254
255 const urlOptions = {
256 startTime: queryParams.start,
257 stopTime: queryParams.stop,
258
259 muted: queryParams.muted,
260 loop: queryParams.loop,
261 subtitle: queryParams.subtitle,
262
263 playerMode: queryParams.mode,
264 peertubeLink: false
265 }
266
267 this.onVideoFetched(video, captionsResult.data, urlOptions)
268 .catch(err => this.handleError(err))
269 })
270 }
271
272 private loadPlaylist (playlistId: string) {
273 // Playlist did not change
274 if (this.playlist && this.playlist.uuid === playlistId) return
275
276 this.playlistService.getVideoPlaylist(playlistId)
277 .pipe(
278 // If 401, the video is private or blacklisted so redirect to 404
279 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
280 )
281 .subscribe(playlist => {
282 this.playlist = playlist
283
284 const videoId = this.route.snapshot.queryParams['videoId']
285 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
286 })
287 }
288
289 private updateVideoDescription (description: string) {
290 this.video.description = description
291 this.setVideoDescriptionHTML()
292 .catch(err => console.error(err))
293 }
294
295 private async setVideoDescriptionHTML () {
296 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
297 }
298
299 private setVideoLikesBarTooltipText () {
300 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
301 likesNumber: this.video.likes,
302 dislikesNumber: this.video.dislikes
303 })
304 }
305
306 private handleError (err: any) {
307 const errorMessage: string = typeof err === 'string' ? err : err.message
308 if (!errorMessage) return
309
310 // Display a message in the video player instead of a notification
311 if (errorMessage.indexOf('from xs param') !== -1) {
312 this.flushPlayer()
313 this.remoteServerDown = true
314 this.changeDetector.detectChanges()
315
316 return
317 }
318
319 this.notifier.error(errorMessage)
320 }
321
322 private checkUserRating () {
323 // Unlogged users do not have ratings
324 if (this.isUserLoggedIn() === false) return
325
326 this.videoService.getUserVideoRating(this.video.id)
327 .subscribe(
328 ratingObject => {
329 if (ratingObject) {
330 this.userRating = ratingObject.rating
331 }
332 },
333
334 err => this.notifier.error(err.message)
335 )
336 }
337
338 private async onVideoFetched (
339 video: VideoDetails,
340 videoCaptions: VideoCaption[],
341 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
342 ) {
343 this.video = video
344 this.videoCaptions = videoCaptions
345
346 // Re init attributes
347 this.descriptionLoading = false
348 this.completeDescriptionShown = false
349 this.remoteServerDown = false
350 this.currentTime = undefined
351
352 this.videoWatchPlaylist.updatePlaylistIndex(video)
353
354 let startTime = timeToInt(urlOptions.startTime) || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
355 // If we are at the end of the video, reset the timer
356 if (this.video.duration - startTime <= 1) startTime = 0
357
358 if (this.isVideoBlur(this.video)) {
359 const res = await this.confirmService.confirm(
360 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
361 this.i18n('Mature or explicit content')
362 )
363 if (res === false) return this.redirectService.redirectToHomepage()
364 }
365
366 // Flush old player if needed
367 this.flushPlayer()
368
369 // Build video element, because videojs remove it on dispose
370 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
371 this.playerElement = document.createElement('video')
372 this.playerElement.className = 'video-js vjs-peertube-skin'
373 this.playerElement.setAttribute('playsinline', 'true')
374 playerElementWrapper.appendChild(this.playerElement)
375
376 const playerCaptions = videoCaptions.map(c => ({
377 label: c.language.label,
378 language: c.language.id,
379 src: environment.apiUrl + c.captionPath
380 }))
381
382 const options: PeertubePlayerManagerOptions = {
383 common: {
384 autoplay: this.isAutoplay(),
385
386 playerElement: this.playerElement,
387 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
388
389 videoDuration: this.video.duration,
390 enableHotkeys: true,
391 inactivityTimeout: 2500,
392 poster: this.video.previewUrl,
393
394 startTime,
395 stopTime: urlOptions.stopTime,
396 controls: urlOptions.controls,
397 muted: urlOptions.muted,
398 loop: urlOptions.loop,
399 subtitle: urlOptions.subtitle,
400
401 peertubeLink: urlOptions.peertubeLink,
402
403 theaterMode: true,
404 captions: videoCaptions.length !== 0,
405
406 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE
407 ? this.videoService.getVideoViewUrl(this.video.uuid)
408 : null,
409 embedUrl: this.video.embedUrl,
410
411 language: this.localeId,
412
413 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
414 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
415 authorizationHeader: this.authService.getRequestHeaderValue()
416 } : undefined,
417
418 serverUrl: environment.apiUrl,
419
420 videoCaptions: playerCaptions
421 },
422
423 webtorrent: {
424 videoFiles: this.video.files
425 }
426 }
427
428 let mode: PlayerMode
429
430 if (urlOptions.playerMode) {
431 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
432 else mode = 'webtorrent'
433 } else {
434 if (this.video.hasHlsPlaylist()) mode = 'p2p-media-loader'
435 else mode = 'webtorrent'
436 }
437
438 if (mode === 'p2p-media-loader') {
439 const hlsPlaylist = this.video.getHlsPlaylist()
440
441 const p2pMediaLoader = {
442 playlistUrl: hlsPlaylist.playlistUrl,
443 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
444 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
445 trackerAnnounce: this.video.trackerUrls,
446 videoFiles: this.video.files
447 } as P2PMediaLoaderOptions
448
449 Object.assign(options, { p2pMediaLoader })
450 }
451
452 this.zone.runOutsideAngular(async () => {
453 this.player = await PeertubePlayerManager.initialize(mode, options)
454
455 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
456
457 this.player.on('timeupdate', () => {
458 this.currentTime = Math.floor(this.player.currentTime())
459 })
460
461 this.player.one('ended', () => {
462 if (this.playlist) {
463 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
464 }
465 })
466
467 this.player.one('stopped', () => {
468 if (this.playlist) {
469 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
470 }
471 })
472
473 this.player.on('theaterChange', (_: any, enabled: boolean) => {
474 this.zone.run(() => this.theaterEnabled = enabled)
475 })
476 })
477
478 this.setVideoDescriptionHTML()
479 this.setVideoLikesBarTooltipText()
480
481 this.setOpenGraphTags()
482 this.checkUserRating()
483 }
484
485 private setRating (nextRating: UserVideoRateType) {
486 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
487 like: this.videoService.setVideoLike,
488 dislike: this.videoService.setVideoDislike,
489 none: this.videoService.unsetVideoLike
490 }
491
492 ratingMethods[nextRating].call(this.videoService, this.video.id)
493 .subscribe(
494 () => {
495 // Update the video like attribute
496 this.updateVideoRating(this.userRating, nextRating)
497 this.userRating = nextRating
498 },
499
500 (err: { message: string }) => this.notifier.error(err.message)
501 )
502 }
503
504 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
505 let likesToIncrement = 0
506 let dislikesToIncrement = 0
507
508 if (oldRating) {
509 if (oldRating === 'like') likesToIncrement--
510 if (oldRating === 'dislike') dislikesToIncrement--
511 }
512
513 if (newRating === 'like') likesToIncrement++
514 if (newRating === 'dislike') dislikesToIncrement++
515
516 this.video.likes += likesToIncrement
517 this.video.dislikes += dislikesToIncrement
518
519 this.video.buildLikeAndDislikePercents()
520 this.setVideoLikesBarTooltipText()
521 }
522
523 private setOpenGraphTags () {
524 this.metaService.setTitle(this.video.name)
525
526 this.metaService.setTag('og:type', 'video')
527
528 this.metaService.setTag('og:title', this.video.name)
529 this.metaService.setTag('name', this.video.name)
530
531 this.metaService.setTag('og:description', this.video.description)
532 this.metaService.setTag('description', this.video.description)
533
534 this.metaService.setTag('og:image', this.video.previewPath)
535
536 this.metaService.setTag('og:duration', this.video.duration.toString())
537
538 this.metaService.setTag('og:site_name', 'PeerTube')
539
540 this.metaService.setTag('og:url', window.location.href)
541 this.metaService.setTag('url', window.location.href)
542 }
543
544 private isAutoplay () {
545 // We'll jump to the thread id, so do not play the video
546 if (this.route.snapshot.params['threadId']) return false
547
548 // Otherwise true by default
549 if (!this.user) return true
550
551 // Be sure the autoPlay is set to false
552 return this.user.autoPlayVideo !== false
553 }
554
555 private flushPlayer () {
556 // Remove player if it exists
557 if (this.player) {
558 try {
559 this.player.dispose()
560 this.player = undefined
561 } catch (err) {
562 console.error('Cannot dispose player.', err)
563 }
564 }
565 }
566
567 private initHotkeys () {
568 this.hotkeys = [
569 new Hotkey('shift+l', () => {
570 this.setLike()
571 return false
572 }, undefined, this.i18n('Like the video')),
573
574 new Hotkey('shift+d', () => {
575 this.setDislike()
576 return false
577 }, undefined, this.i18n('Dislike the video')),
578
579 new Hotkey('shift+s', () => {
580 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
581 return false
582 }, undefined, this.i18n('Subscribe to the account'))
583 ]
584 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
585 }
586 }