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