]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/videos/+video-watch/video-watch.component.ts
Reset playlist add component when video changes
[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 121
1c8ddbfa 122 this.initHotkeys()
d1992b93
C
123 }
124
df98563e 125 ngOnDestroy () {
09edde40 126 this.flushPlayer()
067e3f84 127
13fc89f4 128 // Unsubscribe subscriptions
e2f01c47
C
129 if (this.paramsSub) this.paramsSub.unsubscribe()
130 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
20d21199
RK
131
132 // Unbind hotkeys
133 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
dc8bc31b 134 }
98b01bac 135
df98563e
C
136 setLike () {
137 if (this.isUserLoggedIn() === false) return
57a49263
BB
138 if (this.userRating === 'like') {
139 // Already liked this video
140 this.setRating('none')
141 } else {
142 this.setRating('like')
143 }
d38b8281
C
144 }
145
df98563e
C
146 setDislike () {
147 if (this.isUserLoggedIn() === false) return
57a49263
BB
148 if (this.userRating === 'dislike') {
149 // Already disliked this video
150 this.setRating('none')
151 } else {
152 this.setRating('dislike')
153 }
d38b8281
C
154 }
155
2de96f4d 156 showMoreDescription () {
2de96f4d
C
157 if (this.completeVideoDescription === undefined) {
158 return this.loadCompleteDescription()
159 }
160
161 this.updateVideoDescription(this.completeVideoDescription)
80958c78 162 this.completeDescriptionShown = true
2de96f4d
C
163 }
164
165 showLessDescription () {
2de96f4d 166 this.updateVideoDescription(this.shortVideoDescription)
80958c78 167 this.completeDescriptionShown = false
2de96f4d
C
168 }
169
170 loadCompleteDescription () {
80958c78
C
171 this.descriptionLoading = true
172
2de96f4d 173 this.videoService.loadCompleteDescription(this.video.descriptionPath)
2186386c
C
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
f8b2c1b4 187 this.notifier.error(error.message)
2186386c
C
188 }
189 )
2de96f4d
C
190 }
191
07fa4c97
C
192 showSupportModal () {
193 this.videoSupportModal.show()
194 }
195
df98563e 196 showShareModal () {
f0a39880 197 this.videoShareModal.show(this.currentTime)
99cc4f49
C
198 }
199
df98563e
C
200 isUserLoggedIn () {
201 return this.authService.isLoggedIn()
4f8c0eb0
C
202 }
203
b1fa3eba
C
204 getVideoTags () {
205 if (!this.video || Array.isArray(this.video.tags) === false) return []
206
4278710d 207 return this.video.tags
b1fa3eba
C
208 }
209
3a0fb65c
C
210 onVideoRemoved () {
211 this.redirectService.redirectToHomepage()
6725d05c
C
212 }
213
73e09f27 214 acceptedPrivacyConcern () {
0bd78bf3 215 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
73e09f27
C
216 this.hasAlreadyAcceptedPrivacyConcern = true
217 }
218
2186386c
C
219 isVideoToTranscode () {
220 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
221 }
222
516df59b
C
223 isVideoToImport () {
224 return this.video && this.video.state.id === VideoState.TO_IMPORT
225 }
226
bbe0f064
C
227 hasVideoScheduledPublication () {
228 return this.video && this.video.scheduledUpdate !== undefined
229 }
230
e2f01c47
C
231 isVideoBlur (video: Video) {
232 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
233 }
234
e2f01c47
C
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']
72675ebe 275 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
e2f01c47
C
276 })
277 }
278
2de96f4d
C
279 private updateVideoDescription (description: string) {
280 this.video.description = description
281 this.setVideoDescriptionHTML()
282 }
283
41d71344
C
284 private async setVideoDescriptionHTML () {
285 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
2de96f4d
C
286 }
287
e9189001 288 private setVideoLikesBarTooltipText () {
2186386c
C
289 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
290 likesNumber: this.video.likes,
291 dislikesNumber: this.video.dislikes
292 })
e9189001
C
293 }
294
0c31c33d
C
295 private handleError (err: any) {
296 const errorMessage: string = typeof err === 'string' ? err : err.message
bf5685f0
C
297 if (!errorMessage) return
298
6d88de72 299 // Display a message in the video player instead of a notification
0f7fedc3 300 if (errorMessage.indexOf('from xs param') !== -1) {
6d88de72
C
301 this.flushPlayer()
302 this.remoteServerDown = true
3b492bff
C
303 this.changeDetector.detectChanges()
304
6d88de72 305 return
0c31c33d
C
306 }
307
f8b2c1b4 308 this.notifier.error(errorMessage)
0c31c33d
C
309 }
310
df98563e 311 private checkUserRating () {
d38b8281 312 // Unlogged users do not have ratings
df98563e 313 if (this.isUserLoggedIn() === false) return
d38b8281
C
314
315 this.videoService.getUserVideoRating(this.video.id)
2186386c
C
316 .subscribe(
317 ratingObject => {
318 if (ratingObject) {
319 this.userRating = ratingObject.rating
320 }
321 },
322
f8b2c1b4 323 err => this.notifier.error(err.message)
2186386c 324 )
d38b8281
C
325 }
326
597a9266
C
327 private async onVideoFetched (
328 video: VideoDetails,
329 videoCaptions: VideoCaption[],
f0a39880 330 urlOptions: { startTime?: number, stopTime?: number, subtitle?: string, playerMode?: string }
597a9266 331 ) {
df98563e 332 this.video = video
92fb909c 333
c448d412
C
334 // Re init attributes
335 this.descriptionLoading = false
336 this.completeDescriptionShown = false
6d88de72 337 this.remoteServerDown = false
f0a39880 338 this.currentTime = undefined
c448d412 339
72675ebe 340 this.videoWatchPlaylist.updatePlaylistIndex(video)
e2f01c47 341
1b04f19c 342 let startTime = urlOptions.startTime || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
43483d12 343 // If we are at the end of the video, reset the timer
6e46de09
C
344 if (this.video.duration - startTime <= 1) startTime = 0
345
e2f01c47 346 if (this.isVideoBlur(this.video)) {
22b59e80 347 const res = await this.confirmService.confirm(
989e526a
C
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')
d6e32a2e 350 )
901637bb 351 if (res === false) return this.redirectService.redirectToHomepage()
92fb909c
C
352 }
353
09edde40
C
354 // Flush old player if needed
355 this.flushPlayer()
b891f9bc
C
356
357 // Build video element, because videojs remove it on dispose
e2f01c47 358 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
b891f9bc
C
359 this.playerElement = document.createElement('video')
360 this.playerElement.className = 'video-js vjs-peertube-skin'
e7eb5b39 361 this.playerElement.setAttribute('playsinline', 'true')
b891f9bc
C
362 playerElementWrapper.appendChild(this.playerElement)
363
16f7022b
C
364 const playerCaptions = videoCaptions.map(c => ({
365 label: c.language.label,
366 language: c.language.id,
367 src: environment.apiUrl + c.captionPath
368 }))
369
6ec0b75b 370 const options: PeertubePlayerManagerOptions = {
2adfc7ea
C
371 common: {
372 autoplay: this.isAutoplay(),
6ec0b75b 373
2adfc7ea 374 playerElement: this.playerElement,
6ec0b75b
C
375 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
376
2adfc7ea
C
377 videoDuration: this.video.duration,
378 enableHotkeys: true,
379 inactivityTimeout: 2500,
380 poster: this.video.previewUrl,
381 startTime,
f0a39880 382 stopTime: urlOptions.stopTime,
2adfc7ea
C
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,
aa8b6df4 394
2adfc7ea
C
395 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
396 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
397 authorizationHeader: this.authService.getRequestHeaderValue()
398 } : undefined,
aa8b6df4 399
2adfc7ea
C
400 serverUrl: environment.apiUrl,
401
402 videoCaptions: playerCaptions
6ec0b75b
C
403 },
404
405 webtorrent: {
406 videoFiles: this.video.files
09209296 407 }
e945b184
C
408 }
409
65659166
C
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 }
597a9266
C
419
420 if (mode === 'p2p-media-loader') {
421 const hlsPlaylist = this.video.getHlsPlaylist()
e945b184 422
09209296
C
423 const p2pMediaLoader = {
424 playlistUrl: hlsPlaylist.playlistUrl,
425 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
426 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
427 trackerAnnounce: this.video.trackerUrls,
2adfc7ea 428 videoFiles: this.video.files
09209296
C
429 } as P2PMediaLoaderOptions
430
431 Object.assign(options, { p2pMediaLoader })
e945b184
C
432 }
433
e945b184 434 this.zone.runOutsideAngular(async () => {
09209296 435 this.player = await PeertubePlayerManager.initialize(mode, options)
9a18a625
C
436 this.theaterEnabled = this.player.theaterEnabled
437
2adfc7ea 438 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
f0a39880
C
439
440 this.player.on('timeupdate', () => {
441 this.currentTime = Math.floor(this.player.currentTime())
442 })
e2f01c47
C
443
444 this.player.one('ended', () => {
445 if (this.playlist) {
72675ebe 446 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
e2f01c47
C
447 }
448 })
449
450 this.player.one('stopped', () => {
451 if (this.playlist) {
72675ebe 452 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
e2f01c47
C
453 }
454 })
9a18a625
C
455
456 this.player.on('theaterChange', (_: any, enabled: boolean) => {
457 this.zone.run(() => this.theaterEnabled = enabled)
458 })
b891f9bc 459 })
22b59e80
C
460
461 this.setVideoDescriptionHTML()
462 this.setVideoLikesBarTooltipText()
463
464 this.setOpenGraphTags()
465 this.checkUserRating()
92fb909c
C
466 }
467
5c6d985f 468 private setRating (nextRating: UserVideoRateType) {
57a49263
BB
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)
2186386c
C
483 .subscribe(
484 () => {
485 // Update the video like attribute
486 this.updateVideoRating(this.userRating, nextRating)
487 this.userRating = nextRating
488 },
489
f8b2c1b4 490 (err: { message: string }) => this.notifier.error(err.message)
2186386c 491 )
57a49263
BB
492 }
493
5c6d985f 494 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
df98563e
C
495 let likesToIncrement = 0
496 let dislikesToIncrement = 0
d38b8281
C
497
498 if (oldRating) {
df98563e
C
499 if (oldRating === 'like') likesToIncrement--
500 if (oldRating === 'dislike') dislikesToIncrement--
d38b8281
C
501 }
502
df98563e
C
503 if (newRating === 'like') likesToIncrement++
504 if (newRating === 'dislike') dislikesToIncrement++
d38b8281 505
df98563e
C
506 this.video.likes += likesToIncrement
507 this.video.dislikes += dislikesToIncrement
20b40b19 508
22b59e80 509 this.video.buildLikeAndDislikePercents()
20b40b19 510 this.setVideoLikesBarTooltipText()
d38b8281
C
511 }
512
df98563e
C
513 private setOpenGraphTags () {
514 this.metaService.setTitle(this.video.name)
758b996d 515
df98563e 516 this.metaService.setTag('og:type', 'video')
3ec343a4 517
df98563e
C
518 this.metaService.setTag('og:title', this.video.name)
519 this.metaService.setTag('name', this.video.name)
3ec343a4 520
df98563e
C
521 this.metaService.setTag('og:description', this.video.description)
522 this.metaService.setTag('description', this.video.description)
3ec343a4 523
d38309c3 524 this.metaService.setTag('og:image', this.video.previewPath)
3ec343a4 525
df98563e 526 this.metaService.setTag('og:duration', this.video.duration.toString())
3ec343a4 527
df98563e 528 this.metaService.setTag('og:site_name', 'PeerTube')
3ec343a4 529
df98563e
C
530 this.metaService.setTag('og:url', window.location.href)
531 this.metaService.setTag('url', window.location.href)
3ec343a4 532 }
1f3e9fec 533
d4c6a3b9 534 private isAutoplay () {
bf079b7b
C
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
d4c6a3b9
C
539 if (!this.user) return true
540
541 // Be sure the autoPlay is set to false
542 return this.user.autoPlayVideo !== false
543 }
09edde40
C
544
545 private flushPlayer () {
546 // Remove player if it exists
547 if (this.player) {
548 this.player.dispose()
549 this.player = undefined
550 }
551 }
1c8ddbfa
C
552
553 private initHotkeys () {
554 this.hotkeys = [
555 new Hotkey('shift+l', (event: KeyboardEvent): boolean => {
556 this.setLike()
557 return false
558 }, undefined, this.i18n('Like the video')),
559 new Hotkey('shift+d', (event: KeyboardEvent): boolean => {
560 this.setDislike()
561 return false
562 }, undefined, this.i18n('Dislike the video')),
563 new Hotkey('shift+s', (event: KeyboardEvent): boolean => {
564 this.subscribeButton.subscribed ?
565 this.subscribeButton.unsubscribe() :
566 this.subscribeButton.subscribe()
567 return false
568 }, undefined, this.i18n('Subscribe to the account'))
569 ]
570 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
571 }
dc8bc31b 572}