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