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