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