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