]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-watch/video-watch.component.ts
Add ability to set a public to private in client
[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 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
139 // Already liked this video
140 if (this.userRating === 'like') this.setRating('none')
141 else this.setRating('like')
142 }
143
144 setDislike () {
145 if (this.isUserLoggedIn() === false) return
146
147 // Already disliked this video
148 if (this.userRating === 'dislike') this.setRating('none')
149 else this.setRating('dislike')
150 }
151
152 showMoreDescription () {
153 if (this.completeVideoDescription === undefined) {
154 return this.loadCompleteDescription()
155 }
156
157 this.updateVideoDescription(this.completeVideoDescription)
158 this.completeDescriptionShown = true
159 }
160
161 showLessDescription () {
162 this.updateVideoDescription(this.shortVideoDescription)
163 this.completeDescriptionShown = false
164 }
165
166 loadCompleteDescription () {
167 this.descriptionLoading = true
168
169 this.videoService.loadCompleteDescription(this.video.descriptionPath)
170 .subscribe(
171 description => {
172 this.completeDescriptionShown = true
173 this.descriptionLoading = false
174
175 this.shortVideoDescription = this.video.description
176 this.completeVideoDescription = description
177
178 this.updateVideoDescription(this.completeVideoDescription)
179 },
180
181 error => {
182 this.descriptionLoading = false
183 this.notifier.error(error.message)
184 }
185 )
186 }
187
188 showSupportModal () {
189 this.videoSupportModal.show()
190 }
191
192 showShareModal () {
193 this.videoShareModal.show(this.currentTime)
194 }
195
196 isUserLoggedIn () {
197 return this.authService.isLoggedIn()
198 }
199
200 getVideoTags () {
201 if (!this.video || Array.isArray(this.video.tags) === false) return []
202
203 return this.video.tags
204 }
205
206 onVideoRemoved () {
207 this.redirectService.redirectToHomepage()
208 }
209
210 acceptedPrivacyConcern () {
211 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
212 this.hasAlreadyAcceptedPrivacyConcern = true
213 }
214
215 isVideoToTranscode () {
216 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
217 }
218
219 isVideoToImport () {
220 return this.video && this.video.state.id === VideoState.TO_IMPORT
221 }
222
223 hasVideoScheduledPublication () {
224 return this.video && this.video.scheduledUpdate !== undefined
225 }
226
227 isVideoBlur (video: Video) {
228 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
229 }
230
231 private loadVideo (videoId: string) {
232 // Video did not change
233 if (this.video && this.video.uuid === videoId) return
234
235 if (this.player) this.player.pause()
236
237 // Video did change
238 forkJoin(
239 this.videoService.getVideo(videoId),
240 this.videoCaptionService.listCaptions(videoId)
241 )
242 .pipe(
243 // If 401, the video is private or blacklisted so redirect to 404
244 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
245 )
246 .subscribe(([ video, captionsResult ]) => {
247 const queryParams = this.route.snapshot.queryParams
248
249 const urlOptions = {
250 startTime: queryParams.start,
251 stopTime: queryParams.stop,
252 subtitle: queryParams.subtitle,
253 playerMode: queryParams.mode
254 }
255
256 this.onVideoFetched(video, captionsResult.data, urlOptions)
257 .catch(err => this.handleError(err))
258 })
259 }
260
261 private loadPlaylist (playlistId: string) {
262 // Playlist did not change
263 if (this.playlist && this.playlist.uuid === playlistId) return
264
265 this.playlistService.getVideoPlaylist(playlistId)
266 .pipe(
267 // If 401, the video is private or blacklisted so redirect to 404
268 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
269 )
270 .subscribe(playlist => {
271 this.playlist = playlist
272
273 const videoId = this.route.snapshot.queryParams['videoId']
274 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
275 })
276 }
277
278 private updateVideoDescription (description: string) {
279 this.video.description = description
280 this.setVideoDescriptionHTML()
281 .catch(err => console.error(err))
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
389 ? this.videoService.getVideoViewUrl(this.video.uuid)
390 : null,
391 embedUrl: this.video.embedUrl,
392
393 language: this.localeId,
394
395 subtitle: urlOptions.subtitle,
396
397 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
398 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
399 authorizationHeader: this.authService.getRequestHeaderValue()
400 } : undefined,
401
402 serverUrl: environment.apiUrl,
403
404 videoCaptions: playerCaptions
405 },
406
407 webtorrent: {
408 videoFiles: this.video.files
409 }
410 }
411
412 let mode: PlayerMode
413
414 if (urlOptions.playerMode) {
415 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
416 else mode = 'webtorrent'
417 } else {
418 if (this.video.hasHlsPlaylist()) mode = 'p2p-media-loader'
419 else mode = 'webtorrent'
420 }
421
422 if (mode === 'p2p-media-loader') {
423 const hlsPlaylist = this.video.getHlsPlaylist()
424
425 const p2pMediaLoader = {
426 playlistUrl: hlsPlaylist.playlistUrl,
427 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
428 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
429 trackerAnnounce: this.video.trackerUrls,
430 videoFiles: this.video.files
431 } as P2PMediaLoaderOptions
432
433 Object.assign(options, { p2pMediaLoader })
434 }
435
436 this.zone.runOutsideAngular(async () => {
437 this.player = await PeertubePlayerManager.initialize(mode, options)
438 this.theaterEnabled = this.player.theaterEnabled
439
440 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
441
442 this.player.on('timeupdate', () => {
443 this.currentTime = Math.floor(this.player.currentTime())
444 })
445
446 this.player.one('ended', () => {
447 if (this.playlist) {
448 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
449 }
450 })
451
452 this.player.one('stopped', () => {
453 if (this.playlist) {
454 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
455 }
456 })
457
458 this.player.on('theaterChange', (_: any, enabled: boolean) => {
459 this.zone.run(() => this.theaterEnabled = enabled)
460 })
461 })
462
463 this.setVideoDescriptionHTML()
464 this.setVideoLikesBarTooltipText()
465
466 this.setOpenGraphTags()
467 this.checkUserRating()
468 }
469
470 private setRating (nextRating: UserVideoRateType) {
471 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
472 like: this.videoService.setVideoLike,
473 dislike: this.videoService.setVideoDislike,
474 none: this.videoService.unsetVideoLike
475 }
476
477 ratingMethods[nextRating].call(this.videoService, this.video.id)
478 .subscribe(
479 () => {
480 // Update the video like attribute
481 this.updateVideoRating(this.userRating, nextRating)
482 this.userRating = nextRating
483 },
484
485 (err: { message: string }) => this.notifier.error(err.message)
486 )
487 }
488
489 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
490 let likesToIncrement = 0
491 let dislikesToIncrement = 0
492
493 if (oldRating) {
494 if (oldRating === 'like') likesToIncrement--
495 if (oldRating === 'dislike') dislikesToIncrement--
496 }
497
498 if (newRating === 'like') likesToIncrement++
499 if (newRating === 'dislike') dislikesToIncrement++
500
501 this.video.likes += likesToIncrement
502 this.video.dislikes += dislikesToIncrement
503
504 this.video.buildLikeAndDislikePercents()
505 this.setVideoLikesBarTooltipText()
506 }
507
508 private setOpenGraphTags () {
509 this.metaService.setTitle(this.video.name)
510
511 this.metaService.setTag('og:type', 'video')
512
513 this.metaService.setTag('og:title', this.video.name)
514 this.metaService.setTag('name', this.video.name)
515
516 this.metaService.setTag('og:description', this.video.description)
517 this.metaService.setTag('description', this.video.description)
518
519 this.metaService.setTag('og:image', this.video.previewPath)
520
521 this.metaService.setTag('og:duration', this.video.duration.toString())
522
523 this.metaService.setTag('og:site_name', 'PeerTube')
524
525 this.metaService.setTag('og:url', window.location.href)
526 this.metaService.setTag('url', window.location.href)
527 }
528
529 private isAutoplay () {
530 // We'll jump to the thread id, so do not play the video
531 if (this.route.snapshot.params['threadId']) return false
532
533 // Otherwise true by default
534 if (!this.user) return true
535
536 // Be sure the autoPlay is set to false
537 return this.user.autoPlayVideo !== false
538 }
539
540 private flushPlayer () {
541 // Remove player if it exists
542 if (this.player) {
543 try {
544 this.player.dispose()
545 this.player = undefined
546 } catch (err) {
547 console.error('Cannot dispose player.', err)
548 }
549 }
550 }
551
552 private initHotkeys () {
553 this.hotkeys = [
554 new Hotkey('shift+l', () => {
555 this.setLike()
556 return false
557 }, undefined, this.i18n('Like the video')),
558
559 new Hotkey('shift+d', () => {
560 this.setDislike()
561 return false
562 }, undefined, this.i18n('Dislike the video')),
563
564 new Hotkey('shift+s', () => {
565 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
566 return false
567 }, undefined, this.i18n('Subscribe to the account'))
568 ]
569 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
570 }
571 }