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