]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-watch/video-watch.component.ts
Remove video not found
[github/Chocobozzz/PeerTube.git] / client / src / app / videos / +video-watch / video-watch.component.ts
1 import { catchError } from 'rxjs/operators'
2 import { Component, ElementRef, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild, Inject } 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, loadLocale, addContextMenu } 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(
117 video => {
118 const startTime = this.route.snapshot.queryParams.start
119 this.onVideoFetched(video, startTime)
120 .catch(err => this.handleError(err))
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(this.i18n('Do you really want to blacklist this video?'), this.i18n('Blacklist'))
157 if (res === false) return
158
159 this.videoBlacklistService.blacklistVideo(this.video.id)
160 .subscribe(
161 status => {
162 this.notificationsService.success(
163 this.i18n('Success'),
164 this.i18n('Video {{videoName}} had been blacklisted.', { videoName: this.video.name })
165 )
166 this.redirectService.redirectToHomepage()
167 },
168
169 error => this.notificationsService.error(this.i18n('Error'), error.message)
170 )
171 }
172
173 showMoreDescription () {
174 if (this.completeVideoDescription === undefined) {
175 return this.loadCompleteDescription()
176 }
177
178 this.updateVideoDescription(this.completeVideoDescription)
179 this.completeDescriptionShown = true
180 }
181
182 showLessDescription () {
183 this.updateVideoDescription(this.shortVideoDescription)
184 this.completeDescriptionShown = false
185 }
186
187 loadCompleteDescription () {
188 this.descriptionLoading = true
189
190 this.videoService.loadCompleteDescription(this.video.descriptionPath)
191 .subscribe(
192 description => {
193 this.completeDescriptionShown = true
194 this.descriptionLoading = false
195
196 this.shortVideoDescription = this.video.description
197 this.completeVideoDescription = description
198
199 this.updateVideoDescription(this.completeVideoDescription)
200 },
201
202 error => {
203 this.descriptionLoading = false
204 this.notificationsService.error(this.i18n('Error'), error.message)
205 }
206 )
207 }
208
209 showReportModal (event: Event) {
210 event.preventDefault()
211 this.videoReportModal.show()
212 }
213
214 showSupportModal () {
215 this.videoSupportModal.show()
216 }
217
218 showShareModal () {
219 this.videoShareModal.show()
220 }
221
222 showDownloadModal (event: Event) {
223 event.preventDefault()
224 this.videoDownloadModal.show()
225 }
226
227 isUserLoggedIn () {
228 return this.authService.isLoggedIn()
229 }
230
231 isVideoUpdatable () {
232 return this.video.isUpdatableBy(this.authService.getUser())
233 }
234
235 isVideoBlacklistable () {
236 return this.video.isBlackistableBy(this.user)
237 }
238
239 getVideoPoster () {
240 if (!this.video) return ''
241
242 return this.video.previewUrl
243 }
244
245 getVideoTags () {
246 if (!this.video || Array.isArray(this.video.tags) === false) return []
247
248 return this.video.tags.join(', ')
249 }
250
251 isVideoRemovable () {
252 return this.video.isRemovableBy(this.authService.getUser())
253 }
254
255 async removeVideo (event: Event) {
256 event.preventDefault()
257
258 const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
259 if (res === false) return
260
261 this.videoService.removeVideo(this.video.id)
262 .subscribe(
263 status => {
264 this.notificationsService.success(
265 this.i18n('Success'),
266 this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name })
267 )
268
269 // Go back to the video-list.
270 this.redirectService.redirectToHomepage()
271 },
272
273 error => this.notificationsService.error(this.i18n('Error'), error.message)
274 )
275 }
276
277 acceptedPrivacyConcern () {
278 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
279 this.hasAlreadyAcceptedPrivacyConcern = true
280 }
281
282 private updateVideoDescription (description: string) {
283 this.video.description = description
284 this.setVideoDescriptionHTML()
285 }
286
287 private setVideoDescriptionHTML () {
288 if (!this.video.description) {
289 this.videoHTMLDescription = ''
290 return
291 }
292
293 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
294 }
295
296 private setVideoLikesBarTooltipText () {
297 this.likesBarTooltipText = this.i18n(
298 '{{likesNumber}} likes / {{dislikesNumber}} dislikes',
299 { likesNumber: this.video.likes, dislikes: this.video.dislikes }
300 )
301 }
302
303 private handleError (err: any) {
304 const errorMessage: string = typeof err === 'string' ? err : err.message
305 if (!errorMessage) return
306
307 let message = ''
308
309 if (errorMessage.indexOf('http error') !== -1) {
310 message = this.i18n('Cannot fetch video from server, maybe down.')
311 } else {
312 message = errorMessage
313 }
314
315 this.notificationsService.error(this.i18n('Error'), message)
316 }
317
318 private checkUserRating () {
319 // Unlogged users do not have ratings
320 if (this.isUserLoggedIn() === false) return
321
322 this.videoService.getUserVideoRating(this.video.id)
323 .subscribe(
324 ratingObject => {
325 if (ratingObject) {
326 this.userRating = ratingObject.rating
327 }
328 },
329
330 err => this.notificationsService.error(this.i18n('Error'), err.message)
331 )
332 }
333
334 private async onVideoFetched (video: VideoDetails, startTime = 0) {
335 this.video = video
336
337 // Re init attributes
338 this.descriptionLoading = false
339 this.completeDescriptionShown = false
340
341 this.updateOtherVideosDisplayed()
342
343 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
344 const res = await this.confirmService.confirm(
345 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
346 this.i18n('Mature or explicit content')
347 )
348 if (res === false) return this.redirectService.redirectToHomepage()
349 }
350
351 // Flush old player if needed
352 this.flushPlayer()
353
354 // Build video element, because videojs remove it on dispose
355 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
356 this.playerElement = document.createElement('video')
357 this.playerElement.className = 'video-js vjs-peertube-skin'
358 this.playerElement.setAttribute('playsinline', 'true')
359 playerElementWrapper.appendChild(this.playerElement)
360
361 const videojsOptions = getVideojsOptions({
362 autoplay: this.isAutoplay(),
363 inactivityTimeout: 2500,
364 videoFiles: this.video.files,
365 playerElement: this.playerElement,
366 videoViewUrl: this.videoService.getVideoViewUrl(this.video.uuid),
367 videoDuration: this.video.duration,
368 enableHotkeys: true,
369 peertubeLink: false,
370 poster: this.video.previewUrl,
371 startTime
372 })
373
374 if (this.videojsLocaleLoaded === false) {
375 await loadLocale(environment.apiUrl, videojs, isOnDevLocale() ? getDevLocale() : this.localeId)
376 this.videojsLocaleLoaded = true
377 }
378
379 const self = this
380 this.zone.runOutsideAngular(async () => {
381 videojs(this.playerElement, videojsOptions, function () {
382 self.player = this
383 this.on('customError', (event, data) => self.handleError(data.err))
384
385 addContextMenu(self.player, self.video.embedUrl)
386 })
387 })
388
389 this.setVideoDescriptionHTML()
390 this.setVideoLikesBarTooltipText()
391
392 this.setOpenGraphTags()
393 this.checkUserRating()
394 }
395
396 private setRating (nextRating) {
397 let method
398 switch (nextRating) {
399 case 'like':
400 method = this.videoService.setVideoLike
401 break
402 case 'dislike':
403 method = this.videoService.setVideoDislike
404 break
405 case 'none':
406 method = this.videoService.unsetVideoLike
407 break
408 }
409
410 method.call(this.videoService, this.video.id)
411 .subscribe(
412 () => {
413 // Update the video like attribute
414 this.updateVideoRating(this.userRating, nextRating)
415 this.userRating = nextRating
416 },
417 err => this.notificationsService.error(this.i18n('Error'), err.message)
418 )
419 }
420
421 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
422 let likesToIncrement = 0
423 let dislikesToIncrement = 0
424
425 if (oldRating) {
426 if (oldRating === 'like') likesToIncrement--
427 if (oldRating === 'dislike') dislikesToIncrement--
428 }
429
430 if (newRating === 'like') likesToIncrement++
431 if (newRating === 'dislike') dislikesToIncrement++
432
433 this.video.likes += likesToIncrement
434 this.video.dislikes += dislikesToIncrement
435
436 this.video.buildLikeAndDislikePercents()
437 this.setVideoLikesBarTooltipText()
438 }
439
440 private updateOtherVideosDisplayed () {
441 if (this.video && this.otherVideos && this.otherVideos.length > 0) {
442 this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
443 }
444 }
445
446 private setOpenGraphTags () {
447 this.metaService.setTitle(this.video.name)
448
449 this.metaService.setTag('og:type', 'video')
450
451 this.metaService.setTag('og:title', this.video.name)
452 this.metaService.setTag('name', this.video.name)
453
454 this.metaService.setTag('og:description', this.video.description)
455 this.metaService.setTag('description', this.video.description)
456
457 this.metaService.setTag('og:image', this.video.previewPath)
458
459 this.metaService.setTag('og:duration', this.video.duration.toString())
460
461 this.metaService.setTag('og:site_name', 'PeerTube')
462
463 this.metaService.setTag('og:url', window.location.href)
464 this.metaService.setTag('url', window.location.href)
465 }
466
467 private isAutoplay () {
468 // True by default
469 if (!this.user) return true
470
471 // Be sure the autoPlay is set to false
472 return this.user.autoPlayVideo !== false
473 }
474
475 private flushPlayer () {
476 // Remove player if it exists
477 if (this.player) {
478 this.player.dispose()
479 this.player = undefined
480 }
481 }
482 }