]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-watch/video-watch.component.ts
Merge remote-tracking branch 'origin/pr/1785' 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.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 let mode: PlayerMode
427
428 if (urlOptions.playerMode) {
429 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
430 else mode = 'webtorrent'
431 } else {
432 if (this.video.hasHlsPlaylist()) mode = 'p2p-media-loader'
433 else mode = 'webtorrent'
434 }
435
436 if (mode === 'p2p-media-loader') {
437 const hlsPlaylist = this.video.getHlsPlaylist()
438
439 const p2pMediaLoader = {
440 playlistUrl: hlsPlaylist.playlistUrl,
441 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
442 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
443 trackerAnnounce: this.video.trackerUrls,
444 videoFiles: this.video.files
445 } as P2PMediaLoaderOptions
446
447 Object.assign(options, { p2pMediaLoader })
448 }
449
450 this.zone.runOutsideAngular(async () => {
451 this.player = await PeertubePlayerManager.initialize(mode, options)
452 this.theaterEnabled = this.player.theaterEnabled
453
454 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
455
456 this.player.on('timeupdate', () => {
457 this.currentTime = Math.floor(this.player.currentTime())
458 })
459
460 this.player.one('ended', () => {
461 if (this.playlist) {
462 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
463 }
464 })
465
466 this.player.one('stopped', () => {
467 if (this.playlist) {
468 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
469 }
470 })
471
472 this.player.on('theaterChange', (_: any, enabled: boolean) => {
473 this.zone.run(() => this.theaterEnabled = enabled)
474 })
475 })
476
477 this.setVideoDescriptionHTML()
478 this.setVideoLikesBarTooltipText()
479
480 this.setOpenGraphTags()
481 this.checkUserRating()
482 }
483
484 private setRating (nextRating: UserVideoRateType) {
485 let method
486 switch (nextRating) {
487 case 'like':
488 method = this.videoService.setVideoLike
489 break
490 case 'dislike':
491 method = this.videoService.setVideoDislike
492 break
493 case 'none':
494 method = this.videoService.unsetVideoLike
495 break
496 }
497
498 method.call(this.videoService, this.video.id)
499 .subscribe(
500 () => {
501 // Update the video like attribute
502 this.updateVideoRating(this.userRating, nextRating)
503 this.userRating = nextRating
504 },
505
506 (err: { message: string }) => this.notifier.error(err.message)
507 )
508 }
509
510 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
511 let likesToIncrement = 0
512 let dislikesToIncrement = 0
513
514 if (oldRating) {
515 if (oldRating === 'like') likesToIncrement--
516 if (oldRating === 'dislike') dislikesToIncrement--
517 }
518
519 if (newRating === 'like') likesToIncrement++
520 if (newRating === 'dislike') dislikesToIncrement++
521
522 this.video.likes += likesToIncrement
523 this.video.dislikes += dislikesToIncrement
524
525 this.video.buildLikeAndDislikePercents()
526 this.setVideoLikesBarTooltipText()
527 }
528
529 private setOpenGraphTags () {
530 this.metaService.setTitle(this.video.name)
531
532 this.metaService.setTag('og:type', 'video')
533
534 this.metaService.setTag('og:title', this.video.name)
535 this.metaService.setTag('name', this.video.name)
536
537 this.metaService.setTag('og:description', this.video.description)
538 this.metaService.setTag('description', this.video.description)
539
540 this.metaService.setTag('og:image', this.video.previewPath)
541
542 this.metaService.setTag('og:duration', this.video.duration.toString())
543
544 this.metaService.setTag('og:site_name', 'PeerTube')
545
546 this.metaService.setTag('og:url', window.location.href)
547 this.metaService.setTag('url', window.location.href)
548 }
549
550 private isAutoplay () {
551 // We'll jump to the thread id, so do not play the video
552 if (this.route.snapshot.params['threadId']) return false
553
554 // Otherwise true by default
555 if (!this.user) return true
556
557 // Be sure the autoPlay is set to false
558 return this.user.autoPlayVideo !== false
559 }
560
561 private flushPlayer () {
562 // Remove player if it exists
563 if (this.player) {
564 this.player.dispose()
565 this.player = undefined
566 }
567 }
568 }