]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/videos/+video-watch/video-watch.component.ts
Move video watch playlist in its own component
[github/Chocobozzz/PeerTube.git] / client / src / app / videos / +video-watch / video-watch.component.ts
CommitLineData
e972e046 1import { catchError } from 'rxjs/operators'
3b492bff 2import { ChangeDetectorRef, Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
df98563e 3import { ActivatedRoute, Router } from '@angular/router'
901637bb 4import { RedirectService } from '@app/core/routing/redirect.service'
0bd78bf3 5import { peertubeLocalStorage } from '@app/shared/misc/peertube-local-storage'
07fa4c97 6import { VideoSupportComponent } from '@app/videos/+video-watch/modal/video-support.component'
1f3e9fec 7import { MetaService } from '@ngx-meta/core'
f8b2c1b4 8import { Notifier, ServerService } from '@app/core'
16f7022b 9import { forkJoin, Subscription } from 'rxjs'
20d21199 10import { Hotkey, HotkeysService } from 'angular2-hotkeys'
72675ebe 11import { UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '../../../../../shared'
df98563e 12import { AuthService, ConfirmService } from '../../core'
a51bad1a 13import { RestExtractor, VideoBlacklistService } from '../../shared'
ff249f49 14import { VideoDetails } from '../../shared/video/video-details.model'
63c4db6d 15import { VideoService } from '../../shared/video/video.service'
4635f59d 16import { VideoShareComponent } from './modal/video-share.component'
20d21199 17import { SubscribeButtonComponent } from '@app/shared/user-subscription/subscribe-button.component'
989e526a 18import { I18n } from '@ngx-translate/i18n-polyfill'
e945b184 19import { environment } from '../../../environments/environment'
16f7022b 20import { VideoCaptionService } from '@app/shared/video-caption'
1506307f 21import { MarkdownService } from '@app/shared/renderer'
6ec0b75b
C
22import {
23 P2PMediaLoaderOptions,
24 PeertubePlayerManager,
25 PeertubePlayerManagerOptions,
597a9266 26 PlayerMode
6ec0b75b 27} from '../../../assets/player/peertube-player-manager'
e2f01c47
C
28import { VideoPlaylist } from '@app/shared/video-playlist/video-playlist.model'
29import { VideoPlaylistService } from '@app/shared/video-playlist/video-playlist.service'
e2f01c47 30import { Video } from '@app/shared/video/video.model'
31b6ddf8 31import { isWebRTCDisabled } from '../../../assets/player/utils'
72675ebe 32import { VideoWatchPlaylistComponent } from '@app/videos/+video-watch/video-watch-playlist.component'
dc8bc31b 33
dc8bc31b
C
34@Component({
35 selector: 'my-video-watch',
ec8d8440
C
36 templateUrl: './video-watch.component.html',
37 styleUrls: [ './video-watch.component.scss' ]
dc8bc31b 38})
0629423c 39export class VideoWatchComponent implements OnInit, OnDestroy {
22b59e80
C
40 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
41
72675ebe 42 @ViewChild('videoWatchPlaylist') videoWatchPlaylist: VideoWatchPlaylistComponent
df98563e 43 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
07fa4c97 44 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
20d21199 45 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
df98563e 46
2adfc7ea 47 player: any
0826c92d 48 playerElement: HTMLVideoElement
9a18a625 49 theaterEnabled = false
154898b0 50 userRating: UserVideoRateType = null
404b54e1 51 video: VideoDetails = null
80958c78 52 descriptionLoading = false
2de96f4d 53
e2f01c47 54 playlist: VideoPlaylist = null
e2f01c47 55
2de96f4d
C
56 completeDescriptionShown = false
57 completeVideoDescription: string
58 shortVideoDescription: string
9d9597df 59 videoHTMLDescription = ''
e9189001 60 likesBarTooltipText = ''
73e09f27 61 hasAlreadyAcceptedPrivacyConcern = false
6d88de72 62 remoteServerDown = false
20d21199 63 hotkeys: Hotkey[]
df98563e 64
f0a39880 65 private currentTime: number
df98563e 66 private paramsSub: Subscription
e2f01c47 67 private queryParamsSub: Subscription
31b6ddf8 68 private configSub: Subscription
df98563e
C
69
70 constructor (
4fd8aa32 71 private elementRef: ElementRef,
3b492bff 72 private changeDetector: ChangeDetectorRef,
0629423c 73 private route: ActivatedRoute,
92fb909c 74 private router: Router,
d3ef341a 75 private videoService: VideoService,
e2f01c47 76 private playlistService: VideoPlaylistService,
35bf0c83 77 private videoBlacklistService: VideoBlacklistService,
92fb909c 78 private confirmService: ConfirmService,
3ec343a4 79 private metaService: MetaService,
7ddd02c9 80 private authService: AuthService,
0883b324 81 private serverService: ServerService,
a51bad1a 82 private restExtractor: RestExtractor,
f8b2c1b4 83 private notifier: Notifier,
7ae71355 84 private markdownService: MarkdownService,
901637bb 85 private zone: NgZone,
989e526a 86 private redirectService: RedirectService,
16f7022b 87 private videoCaptionService: VideoCaptionService,
e945b184 88 private i18n: I18n,
20d21199 89 private hotkeysService: HotkeysService,
e945b184 90 @Inject(LOCALE_ID) private localeId: string
d3ef341a 91 ) {}
dc8bc31b 92
b2731bff
C
93 get user () {
94 return this.authService.getUser()
95 }
96
df98563e 97 ngOnInit () {
31b6ddf8
C
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 })
2b3b76ab 108
13fc89f4 109 this.paramsSub = this.route.params.subscribe(routeParams => {
e2f01c47
C
110 const videoId = routeParams[ 'videoId' ]
111 if (videoId) this.loadVideo(videoId)
a51bad1a 112
e2f01c47
C
113 const playlistId = routeParams[ 'playlistId' ]
114 if (playlistId) this.loadPlaylist(playlistId)
115 })
bf079b7b 116
e2f01c47
C
117 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
118 const videoId = queryParams[ 'videoId' ]
119 if (videoId) this.loadVideo(videoId)
df98563e 120 })
20d21199
RK
121
122 this.hotkeys = [
a157b3a3 123 new Hotkey('shift+l', (event: KeyboardEvent): boolean => {
20d21199
RK
124 this.setLike()
125 return false
e33f888b 126 }, undefined, this.i18n('Like the video')),
a157b3a3 127 new Hotkey('shift+d', (event: KeyboardEvent): boolean => {
20d21199
RK
128 this.setDislike()
129 return false
e33f888b 130 }, undefined, this.i18n('Dislike the video')),
a157b3a3 131 new Hotkey('shift+s', (event: KeyboardEvent): boolean => {
20d21199
RK
132 this.subscribeButton.subscribed ?
133 this.subscribeButton.unsubscribe() :
134 this.subscribeButton.subscribe()
135 return false
e33f888b 136 }, undefined, this.i18n('Subscribe to the account'))
20d21199
RK
137 ]
138 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
d1992b93
C
139 }
140
df98563e 141 ngOnDestroy () {
09edde40 142 this.flushPlayer()
067e3f84 143
13fc89f4 144 // Unsubscribe subscriptions
e2f01c47
C
145 if (this.paramsSub) this.paramsSub.unsubscribe()
146 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
20d21199
RK
147
148 // Unbind hotkeys
149 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
dc8bc31b 150 }
98b01bac 151
df98563e
C
152 setLike () {
153 if (this.isUserLoggedIn() === false) return
57a49263
BB
154 if (this.userRating === 'like') {
155 // Already liked this video
156 this.setRating('none')
157 } else {
158 this.setRating('like')
159 }
d38b8281
C
160 }
161
df98563e
C
162 setDislike () {
163 if (this.isUserLoggedIn() === false) return
57a49263
BB
164 if (this.userRating === 'dislike') {
165 // Already disliked this video
166 this.setRating('none')
167 } else {
168 this.setRating('dislike')
169 }
d38b8281
C
170 }
171
2de96f4d 172 showMoreDescription () {
2de96f4d
C
173 if (this.completeVideoDescription === undefined) {
174 return this.loadCompleteDescription()
175 }
176
177 this.updateVideoDescription(this.completeVideoDescription)
80958c78 178 this.completeDescriptionShown = true
2de96f4d
C
179 }
180
181 showLessDescription () {
2de96f4d 182 this.updateVideoDescription(this.shortVideoDescription)
80958c78 183 this.completeDescriptionShown = false
2de96f4d
C
184 }
185
186 loadCompleteDescription () {
80958c78
C
187 this.descriptionLoading = true
188
2de96f4d 189 this.videoService.loadCompleteDescription(this.video.descriptionPath)
2186386c
C
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
f8b2c1b4 203 this.notifier.error(error.message)
2186386c
C
204 }
205 )
2de96f4d
C
206 }
207
07fa4c97
C
208 showSupportModal () {
209 this.videoSupportModal.show()
210 }
211
df98563e 212 showShareModal () {
f0a39880 213 this.videoShareModal.show(this.currentTime)
99cc4f49
C
214 }
215
df98563e
C
216 isUserLoggedIn () {
217 return this.authService.isLoggedIn()
4f8c0eb0
C
218 }
219
b1fa3eba
C
220 getVideoTags () {
221 if (!this.video || Array.isArray(this.video.tags) === false) return []
222
4278710d 223 return this.video.tags
b1fa3eba
C
224 }
225
3a0fb65c
C
226 onVideoRemoved () {
227 this.redirectService.redirectToHomepage()
6725d05c
C
228 }
229
73e09f27 230 acceptedPrivacyConcern () {
0bd78bf3 231 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
73e09f27
C
232 this.hasAlreadyAcceptedPrivacyConcern = true
233 }
234
2186386c
C
235 isVideoToTranscode () {
236 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
237 }
238
516df59b
C
239 isVideoToImport () {
240 return this.video && this.video.state.id === VideoState.TO_IMPORT
241 }
242
bbe0f064
C
243 hasVideoScheduledPublication () {
244 return this.video && this.video.scheduledUpdate !== undefined
245 }
246
e2f01c47
C
247 isVideoBlur (video: Video) {
248 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
249 }
250
e2f01c47
C
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']
72675ebe 291 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
e2f01c47
C
292 })
293 }
294
2de96f4d
C
295 private updateVideoDescription (description: string) {
296 this.video.description = description
297 this.setVideoDescriptionHTML()
298 }
299
41d71344
C
300 private async setVideoDescriptionHTML () {
301 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
2de96f4d
C
302 }
303
e9189001 304 private setVideoLikesBarTooltipText () {
2186386c
C
305 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
306 likesNumber: this.video.likes,
307 dislikesNumber: this.video.dislikes
308 })
e9189001
C
309 }
310
0c31c33d
C
311 private handleError (err: any) {
312 const errorMessage: string = typeof err === 'string' ? err : err.message
bf5685f0
C
313 if (!errorMessage) return
314
6d88de72 315 // Display a message in the video player instead of a notification
0f7fedc3 316 if (errorMessage.indexOf('from xs param') !== -1) {
6d88de72
C
317 this.flushPlayer()
318 this.remoteServerDown = true
3b492bff
C
319 this.changeDetector.detectChanges()
320
6d88de72 321 return
0c31c33d
C
322 }
323
f8b2c1b4 324 this.notifier.error(errorMessage)
0c31c33d
C
325 }
326
df98563e 327 private checkUserRating () {
d38b8281 328 // Unlogged users do not have ratings
df98563e 329 if (this.isUserLoggedIn() === false) return
d38b8281
C
330
331 this.videoService.getUserVideoRating(this.video.id)
2186386c
C
332 .subscribe(
333 ratingObject => {
334 if (ratingObject) {
335 this.userRating = ratingObject.rating
336 }
337 },
338
f8b2c1b4 339 err => this.notifier.error(err.message)
2186386c 340 )
d38b8281
C
341 }
342
597a9266
C
343 private async onVideoFetched (
344 video: VideoDetails,
345 videoCaptions: VideoCaption[],
f0a39880 346 urlOptions: { startTime?: number, stopTime?: number, subtitle?: string, playerMode?: string }
597a9266 347 ) {
df98563e 348 this.video = video
92fb909c 349
c448d412
C
350 // Re init attributes
351 this.descriptionLoading = false
352 this.completeDescriptionShown = false
6d88de72 353 this.remoteServerDown = false
f0a39880 354 this.currentTime = undefined
c448d412 355
72675ebe 356 this.videoWatchPlaylist.updatePlaylistIndex(video)
e2f01c47 357
1b04f19c 358 let startTime = urlOptions.startTime || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
43483d12 359 // If we are at the end of the video, reset the timer
6e46de09
C
360 if (this.video.duration - startTime <= 1) startTime = 0
361
e2f01c47 362 if (this.isVideoBlur(this.video)) {
22b59e80 363 const res = await this.confirmService.confirm(
989e526a
C
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')
d6e32a2e 366 )
901637bb 367 if (res === false) return this.redirectService.redirectToHomepage()
92fb909c
C
368 }
369
09edde40
C
370 // Flush old player if needed
371 this.flushPlayer()
b891f9bc
C
372
373 // Build video element, because videojs remove it on dispose
e2f01c47 374 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
b891f9bc
C
375 this.playerElement = document.createElement('video')
376 this.playerElement.className = 'video-js vjs-peertube-skin'
e7eb5b39 377 this.playerElement.setAttribute('playsinline', 'true')
b891f9bc
C
378 playerElementWrapper.appendChild(this.playerElement)
379
16f7022b
C
380 const playerCaptions = videoCaptions.map(c => ({
381 label: c.language.label,
382 language: c.language.id,
383 src: environment.apiUrl + c.captionPath
384 }))
385
6ec0b75b 386 const options: PeertubePlayerManagerOptions = {
2adfc7ea
C
387 common: {
388 autoplay: this.isAutoplay(),
6ec0b75b 389
2adfc7ea 390 playerElement: this.playerElement,
6ec0b75b
C
391 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
392
2adfc7ea
C
393 videoDuration: this.video.duration,
394 enableHotkeys: true,
395 inactivityTimeout: 2500,
396 poster: this.video.previewUrl,
397 startTime,
f0a39880 398 stopTime: urlOptions.stopTime,
2adfc7ea
C
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,
aa8b6df4 410
2adfc7ea
C
411 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
412 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
413 authorizationHeader: this.authService.getRequestHeaderValue()
414 } : undefined,
aa8b6df4 415
2adfc7ea
C
416 serverUrl: environment.apiUrl,
417
418 videoCaptions: playerCaptions
6ec0b75b
C
419 },
420
421 webtorrent: {
422 videoFiles: this.video.files
09209296 423 }
e945b184
C
424 }
425
597a9266
C
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()
e945b184 430
09209296
C
431 const p2pMediaLoader = {
432 playlistUrl: hlsPlaylist.playlistUrl,
433 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
434 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
435 trackerAnnounce: this.video.trackerUrls,
2adfc7ea 436 videoFiles: this.video.files
09209296
C
437 } as P2PMediaLoaderOptions
438
439 Object.assign(options, { p2pMediaLoader })
e945b184
C
440 }
441
e945b184 442 this.zone.runOutsideAngular(async () => {
09209296 443 this.player = await PeertubePlayerManager.initialize(mode, options)
9a18a625
C
444 this.theaterEnabled = this.player.theaterEnabled
445
2adfc7ea 446 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
f0a39880
C
447
448 this.player.on('timeupdate', () => {
449 this.currentTime = Math.floor(this.player.currentTime())
450 })
e2f01c47
C
451
452 this.player.one('ended', () => {
453 if (this.playlist) {
72675ebe 454 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
e2f01c47
C
455 }
456 })
457
458 this.player.one('stopped', () => {
459 if (this.playlist) {
72675ebe 460 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
e2f01c47
C
461 }
462 })
9a18a625
C
463
464 this.player.on('theaterChange', (_: any, enabled: boolean) => {
465 this.zone.run(() => this.theaterEnabled = enabled)
466 })
b891f9bc 467 })
22b59e80
C
468
469 this.setVideoDescriptionHTML()
470 this.setVideoLikesBarTooltipText()
471
472 this.setOpenGraphTags()
473 this.checkUserRating()
92fb909c
C
474 }
475
5c6d985f 476 private setRating (nextRating: UserVideoRateType) {
57a49263
BB
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)
2186386c
C
491 .subscribe(
492 () => {
493 // Update the video like attribute
494 this.updateVideoRating(this.userRating, nextRating)
495 this.userRating = nextRating
496 },
497
f8b2c1b4 498 (err: { message: string }) => this.notifier.error(err.message)
2186386c 499 )
57a49263
BB
500 }
501
5c6d985f 502 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
df98563e
C
503 let likesToIncrement = 0
504 let dislikesToIncrement = 0
d38b8281
C
505
506 if (oldRating) {
df98563e
C
507 if (oldRating === 'like') likesToIncrement--
508 if (oldRating === 'dislike') dislikesToIncrement--
d38b8281
C
509 }
510
df98563e
C
511 if (newRating === 'like') likesToIncrement++
512 if (newRating === 'dislike') dislikesToIncrement++
d38b8281 513
df98563e
C
514 this.video.likes += likesToIncrement
515 this.video.dislikes += dislikesToIncrement
20b40b19 516
22b59e80 517 this.video.buildLikeAndDislikePercents()
20b40b19 518 this.setVideoLikesBarTooltipText()
d38b8281
C
519 }
520
df98563e
C
521 private setOpenGraphTags () {
522 this.metaService.setTitle(this.video.name)
758b996d 523
df98563e 524 this.metaService.setTag('og:type', 'video')
3ec343a4 525
df98563e
C
526 this.metaService.setTag('og:title', this.video.name)
527 this.metaService.setTag('name', this.video.name)
3ec343a4 528
df98563e
C
529 this.metaService.setTag('og:description', this.video.description)
530 this.metaService.setTag('description', this.video.description)
3ec343a4 531
d38309c3 532 this.metaService.setTag('og:image', this.video.previewPath)
3ec343a4 533
df98563e 534 this.metaService.setTag('og:duration', this.video.duration.toString())
3ec343a4 535
df98563e 536 this.metaService.setTag('og:site_name', 'PeerTube')
3ec343a4 537
df98563e
C
538 this.metaService.setTag('og:url', window.location.href)
539 this.metaService.setTag('url', window.location.href)
3ec343a4 540 }
1f3e9fec 541
d4c6a3b9 542 private isAutoplay () {
bf079b7b
C
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
d4c6a3b9
C
547 if (!this.user) return true
548
549 // Be sure the autoPlay is set to false
550 return this.user.autoPlayVideo !== false
551 }
09edde40
C
552
553 private flushPlayer () {
554 // Remove player if it exists
555 if (this.player) {
556 this.player.dispose()
557 this.player = undefined
558 }
559 }
dc8bc31b 560}