]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-watch/video-watch.component.ts
Add concept of video state, and add ability to wait transcoding before
[github/Chocobozzz/PeerTube.git] / client / src / app / videos / +video-watch / video-watch.component.ts
1 import { catchError } from 'rxjs/operators'
2 import { 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 { NotificationsService } from 'angular2-notifications'
9 import { Subscription } from 'rxjs'
10 import * as videojs from 'video.js'
11 import 'videojs-hotkeys'
12 import * as WebTorrent from 'webtorrent'
13 import { UserVideoRateType, VideoRateType, VideoState } from '../../../../../shared'
14 import '../../../assets/player/peertube-videojs-plugin'
15 import { AuthService, ConfirmService } from '../../core'
16 import { RestExtractor, VideoBlacklistService } from '../../shared'
17 import { VideoDetails } from '../../shared/video/video-details.model'
18 import { Video } from '../../shared/video/video.model'
19 import { VideoService } from '../../shared/video/video.service'
20 import { MarkdownService } from '../shared'
21 import { VideoDownloadComponent } from './modal/video-download.component'
22 import { VideoReportComponent } from './modal/video-report.component'
23 import { VideoShareComponent } from './modal/video-share.component'
24 import { addContextMenu, getVideojsOptions, loadLocale } from '../../../assets/player/peertube-player'
25 import { ServerService } from '@app/core'
26 import { I18n } from '@ngx-translate/i18n-polyfill'
27 import { environment } from '../../../environments/environment'
28 import { getDevLocale, isOnDevLocale } from '@app/shared/i18n/i18n-utils'
29
30 @Component({
31 selector: 'my-video-watch',
32 templateUrl: './video-watch.component.html',
33 styleUrls: [ './video-watch.component.scss' ]
34 })
35 export class VideoWatchComponent implements OnInit, OnDestroy {
36 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
37
38 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
39 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
40 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
41 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
42
43 otherVideosDisplayed: Video[] = []
44
45 player: videojs.Player
46 playerElement: HTMLVideoElement
47 userRating: UserVideoRateType = null
48 video: VideoDetails = null
49 descriptionLoading = false
50
51 completeDescriptionShown = false
52 completeVideoDescription: string
53 shortVideoDescription: string
54 videoHTMLDescription = ''
55 likesBarTooltipText = ''
56 hasAlreadyAcceptedPrivacyConcern = false
57
58 private videojsLocaleLoaded = false
59 private otherVideos: Video[] = []
60 private paramsSub: Subscription
61
62 constructor (
63 private elementRef: ElementRef,
64 private route: ActivatedRoute,
65 private router: Router,
66 private videoService: VideoService,
67 private videoBlacklistService: VideoBlacklistService,
68 private confirmService: ConfirmService,
69 private metaService: MetaService,
70 private authService: AuthService,
71 private serverService: ServerService,
72 private restExtractor: RestExtractor,
73 private notificationsService: NotificationsService,
74 private markdownService: MarkdownService,
75 private zone: NgZone,
76 private redirectService: RedirectService,
77 private i18n: I18n,
78 @Inject(LOCALE_ID) private localeId: string
79 ) {}
80
81 get user () {
82 return this.authService.getUser()
83 }
84
85 ngOnInit () {
86 if (
87 WebTorrent.WEBRTC_SUPPORT === false ||
88 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
89 ) {
90 this.hasAlreadyAcceptedPrivacyConcern = true
91 }
92
93 this.videoService.getVideos({ currentPage: 1, itemsPerPage: 5 }, '-createdAt')
94 .subscribe(
95 data => {
96 this.otherVideos = data.videos
97 this.updateOtherVideosDisplayed()
98 },
99
100 err => console.error(err)
101 )
102
103 this.paramsSub = this.route.params.subscribe(routeParams => {
104 if (this.player) {
105 this.player.pause()
106 }
107
108 const uuid = routeParams[ 'uuid' ]
109
110 // Video did not change
111 if (this.video && this.video.uuid === uuid) return
112 // Video did change
113 this.videoService
114 .getVideo(uuid)
115 .pipe(catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 404 ])))
116 .subscribe(video => {
117 const startTime = this.route.snapshot.queryParams.start
118 this.onVideoFetched(video, startTime)
119 .catch(err => this.handleError(err))
120 })
121 })
122 }
123
124 ngOnDestroy () {
125 this.flushPlayer()
126
127 // Unsubscribe subscriptions
128 this.paramsSub.unsubscribe()
129 }
130
131 setLike () {
132 if (this.isUserLoggedIn() === false) return
133 if (this.userRating === 'like') {
134 // Already liked this video
135 this.setRating('none')
136 } else {
137 this.setRating('like')
138 }
139 }
140
141 setDislike () {
142 if (this.isUserLoggedIn() === false) return
143 if (this.userRating === 'dislike') {
144 // Already disliked this video
145 this.setRating('none')
146 } else {
147 this.setRating('dislike')
148 }
149 }
150
151 async blacklistVideo (event: Event) {
152 event.preventDefault()
153
154 const res = await this.confirmService.confirm(this.i18n('Do you really want to blacklist this video?'), this.i18n('Blacklist'))
155 if (res === false) return
156
157 this.videoBlacklistService.blacklistVideo(this.video.id)
158 .subscribe(
159 () => {
160 this.notificationsService.success(
161 this.i18n('Success'),
162 this.i18n('Video {{videoName}} had been blacklisted.', { videoName: this.video.name })
163 )
164 this.redirectService.redirectToHomepage()
165 },
166
167 error => this.notificationsService.error(this.i18n('Error'), error.message)
168 )
169 }
170
171 showMoreDescription () {
172 if (this.completeVideoDescription === undefined) {
173 return this.loadCompleteDescription()
174 }
175
176 this.updateVideoDescription(this.completeVideoDescription)
177 this.completeDescriptionShown = true
178 }
179
180 showLessDescription () {
181 this.updateVideoDescription(this.shortVideoDescription)
182 this.completeDescriptionShown = false
183 }
184
185 loadCompleteDescription () {
186 this.descriptionLoading = true
187
188 this.videoService.loadCompleteDescription(this.video.descriptionPath)
189 .subscribe(
190 description => {
191 this.completeDescriptionShown = true
192 this.descriptionLoading = false
193
194 this.shortVideoDescription = this.video.description
195 this.completeVideoDescription = description
196
197 this.updateVideoDescription(this.completeVideoDescription)
198 },
199
200 error => {
201 this.descriptionLoading = false
202 this.notificationsService.error(this.i18n('Error'), error.message)
203 }
204 )
205 }
206
207 showReportModal (event: Event) {
208 event.preventDefault()
209 this.videoReportModal.show()
210 }
211
212 showSupportModal () {
213 this.videoSupportModal.show()
214 }
215
216 showShareModal () {
217 this.videoShareModal.show()
218 }
219
220 showDownloadModal (event: Event) {
221 event.preventDefault()
222 this.videoDownloadModal.show()
223 }
224
225 isUserLoggedIn () {
226 return this.authService.isLoggedIn()
227 }
228
229 isVideoUpdatable () {
230 return this.video.isUpdatableBy(this.authService.getUser())
231 }
232
233 isVideoBlacklistable () {
234 return this.video.isBlackistableBy(this.user)
235 }
236
237 getVideoPoster () {
238 if (!this.video) return ''
239
240 return this.video.previewUrl
241 }
242
243 getVideoTags () {
244 if (!this.video || Array.isArray(this.video.tags) === false) return []
245
246 return this.video.tags.join(', ')
247 }
248
249 isVideoRemovable () {
250 return this.video.isRemovableBy(this.authService.getUser())
251 }
252
253 async removeVideo (event: Event) {
254 event.preventDefault()
255
256 const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
257 if (res === false) return
258
259 this.videoService.removeVideo(this.video.id)
260 .subscribe(
261 status => {
262 this.notificationsService.success(
263 this.i18n('Success'),
264 this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name })
265 )
266
267 // Go back to the video-list.
268 this.redirectService.redirectToHomepage()
269 },
270
271 error => this.notificationsService.error(this.i18n('Error'), error.message)
272 )
273 }
274
275 acceptedPrivacyConcern () {
276 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
277 this.hasAlreadyAcceptedPrivacyConcern = true
278 }
279
280 isVideoToTranscode () {
281 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
282 }
283
284 private updateVideoDescription (description: string) {
285 this.video.description = description
286 this.setVideoDescriptionHTML()
287 }
288
289 private setVideoDescriptionHTML () {
290 if (!this.video.description) {
291 this.videoHTMLDescription = ''
292 return
293 }
294
295 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
296 }
297
298 private setVideoLikesBarTooltipText () {
299 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
300 likesNumber: this.video.likes,
301 dislikesNumber: this.video.dislikes
302 })
303 }
304
305 private handleError (err: any) {
306 const errorMessage: string = typeof err === 'string' ? err : err.message
307 if (!errorMessage) return
308
309 let message = ''
310
311 if (errorMessage.indexOf('http error') !== -1) {
312 message = this.i18n('Cannot fetch video from server, maybe down.')
313 } else {
314 message = errorMessage
315 }
316
317 this.notificationsService.error(this.i18n('Error'), message)
318 }
319
320 private checkUserRating () {
321 // Unlogged users do not have ratings
322 if (this.isUserLoggedIn() === false) return
323
324 this.videoService.getUserVideoRating(this.video.id)
325 .subscribe(
326 ratingObject => {
327 if (ratingObject) {
328 this.userRating = ratingObject.rating
329 }
330 },
331
332 err => this.notificationsService.error(this.i18n('Error'), err.message)
333 )
334 }
335
336 private async onVideoFetched (video: VideoDetails, startTime = 0) {
337 this.video = video
338
339 // Re init attributes
340 this.descriptionLoading = false
341 this.completeDescriptionShown = false
342
343 this.updateOtherVideosDisplayed()
344
345 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
346 const res = await this.confirmService.confirm(
347 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
348 this.i18n('Mature or explicit content')
349 )
350 if (res === false) return this.redirectService.redirectToHomepage()
351 }
352
353 // Flush old player if needed
354 this.flushPlayer()
355
356 // Build video element, because videojs remove it on dispose
357 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
358 this.playerElement = document.createElement('video')
359 this.playerElement.className = 'video-js vjs-peertube-skin'
360 this.playerElement.setAttribute('playsinline', 'true')
361 playerElementWrapper.appendChild(this.playerElement)
362
363 const videojsOptions = getVideojsOptions({
364 autoplay: this.isAutoplay(),
365 inactivityTimeout: 2500,
366 videoFiles: this.video.files,
367 playerElement: this.playerElement,
368 videoViewUrl: this.videoService.getVideoViewUrl(this.video.uuid),
369 videoDuration: this.video.duration,
370 enableHotkeys: true,
371 peertubeLink: false,
372 poster: this.video.previewUrl,
373 startTime,
374 theaterMode: true
375 })
376
377 if (this.videojsLocaleLoaded === false) {
378 await loadLocale(environment.apiUrl, videojs, isOnDevLocale() ? getDevLocale() : this.localeId)
379 this.videojsLocaleLoaded = true
380 }
381
382 const self = this
383 this.zone.runOutsideAngular(async () => {
384 videojs(this.playerElement, videojsOptions, function () {
385 self.player = this
386 this.on('customError', (event, data) => self.handleError(data.err))
387
388 addContextMenu(self.player, self.video.embedUrl)
389 })
390 })
391
392 this.setVideoDescriptionHTML()
393 this.setVideoLikesBarTooltipText()
394
395 this.setOpenGraphTags()
396 this.checkUserRating()
397 }
398
399 private setRating (nextRating) {
400 let method
401 switch (nextRating) {
402 case 'like':
403 method = this.videoService.setVideoLike
404 break
405 case 'dislike':
406 method = this.videoService.setVideoDislike
407 break
408 case 'none':
409 method = this.videoService.unsetVideoLike
410 break
411 }
412
413 method.call(this.videoService, this.video.id)
414 .subscribe(
415 () => {
416 // Update the video like attribute
417 this.updateVideoRating(this.userRating, nextRating)
418 this.userRating = nextRating
419 },
420
421 err => this.notificationsService.error(this.i18n('Error'), err.message)
422 )
423 }
424
425 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
426 let likesToIncrement = 0
427 let dislikesToIncrement = 0
428
429 if (oldRating) {
430 if (oldRating === 'like') likesToIncrement--
431 if (oldRating === 'dislike') dislikesToIncrement--
432 }
433
434 if (newRating === 'like') likesToIncrement++
435 if (newRating === 'dislike') dislikesToIncrement++
436
437 this.video.likes += likesToIncrement
438 this.video.dislikes += dislikesToIncrement
439
440 this.video.buildLikeAndDislikePercents()
441 this.setVideoLikesBarTooltipText()
442 }
443
444 private updateOtherVideosDisplayed () {
445 if (this.video && this.otherVideos && this.otherVideos.length > 0) {
446 this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
447 }
448 }
449
450 private setOpenGraphTags () {
451 this.metaService.setTitle(this.video.name)
452
453 this.metaService.setTag('og:type', 'video')
454
455 this.metaService.setTag('og:title', this.video.name)
456 this.metaService.setTag('name', this.video.name)
457
458 this.metaService.setTag('og:description', this.video.description)
459 this.metaService.setTag('description', this.video.description)
460
461 this.metaService.setTag('og:image', this.video.previewPath)
462
463 this.metaService.setTag('og:duration', this.video.duration.toString())
464
465 this.metaService.setTag('og:site_name', 'PeerTube')
466
467 this.metaService.setTag('og:url', window.location.href)
468 this.metaService.setTag('url', window.location.href)
469 }
470
471 private isAutoplay () {
472 // True by default
473 if (!this.user) return true
474
475 // Be sure the autoPlay is set to false
476 return this.user.autoPlayVideo !== false
477 }
478
479 private flushPlayer () {
480 // Remove player if it exists
481 if (this.player) {
482 this.player.dispose()
483 this.player = undefined
484 }
485 }
486 }