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