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