]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-watch/video-watch.component.ts
Fix video watch page responsive
[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 error = false
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 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 changed
103 if (this.video && this.video.uuid === uuid) return
104
105 this.videoService.getVideo(uuid).subscribe(
106 video => this.onVideoFetched(video),
107
108 error => {
109 this.videoNotFound = true
110 console.error(error)
111 }
112 )
113 })
114 }
115
116 ngOnDestroy () {
117 this.flushPlayer()
118
119 // Unsubscribe subscriptions
120 this.paramsSub.unsubscribe()
121 }
122
123 setLike () {
124 if (this.isUserLoggedIn() === false) return
125 if (this.userRating === 'like') {
126 // Already liked this video
127 this.setRating('none')
128 } else {
129 this.setRating('like')
130 }
131 }
132
133 setDislike () {
134 if (this.isUserLoggedIn() === false) return
135 if (this.userRating === 'dislike') {
136 // Already disliked this video
137 this.setRating('none')
138 } else {
139 this.setRating('dislike')
140 }
141 }
142
143 async blacklistVideo (event: Event) {
144 event.preventDefault()
145
146 const res = await this.confirmService.confirm('Do you really want to blacklist this video?', 'Blacklist')
147 if (res === false) return
148
149 this.videoBlacklistService.blacklistVideo(this.video.id)
150 .subscribe(
151 status => {
152 this.notificationsService.success('Success', `Video ${this.video.name} had been blacklisted.`)
153 this.redirectService.redirectToHomepage()
154 },
155
156 error => this.notificationsService.error('Error', error.message)
157 )
158 }
159
160 showMoreDescription () {
161 if (this.completeVideoDescription === undefined) {
162 return this.loadCompleteDescription()
163 }
164
165 this.updateVideoDescription(this.completeVideoDescription)
166 this.completeDescriptionShown = true
167 }
168
169 showLessDescription () {
170 this.updateVideoDescription(this.shortVideoDescription)
171 this.completeDescriptionShown = false
172 }
173
174 loadCompleteDescription () {
175 this.descriptionLoading = true
176
177 this.videoService.loadCompleteDescription(this.video.descriptionPath)
178 .subscribe(
179 description => {
180 this.completeDescriptionShown = true
181 this.descriptionLoading = false
182
183 this.shortVideoDescription = this.video.description
184 this.completeVideoDescription = description
185
186 this.updateVideoDescription(this.completeVideoDescription)
187 },
188
189 error => {
190 this.descriptionLoading = false
191 this.notificationsService.error('Error', error.message)
192 }
193 )
194 }
195
196 showReportModal (event: Event) {
197 event.preventDefault()
198 this.videoReportModal.show()
199 }
200
201 showSupportModal () {
202 this.videoSupportModal.show()
203 }
204
205 showShareModal () {
206 this.videoShareModal.show()
207 }
208
209 showDownloadModal (event: Event) {
210 event.preventDefault()
211 this.videoDownloadModal.show()
212 }
213
214 isUserLoggedIn () {
215 return this.authService.isLoggedIn()
216 }
217
218 isVideoUpdatable () {
219 return this.video.isUpdatableBy(this.authService.getUser())
220 }
221
222 isVideoBlacklistable () {
223 return this.video.isBlackistableBy(this.user)
224 }
225
226 getAvatarPath () {
227 return Account.GET_ACCOUNT_AVATAR_URL(this.video.account)
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) {
320 this.video = video
321
322 this.updateOtherVideosDisplayed()
323
324 if (this.video.isVideoNSFWForUser(this.user)) {
325 const res = await this.confirmService.confirm(
326 'This video contains mature or explicit content. Are you sure you want to watch it?',
327 'Mature or explicit content'
328 )
329 if (res === false) return this.redirectService.redirectToHomepage()
330 }
331
332 // Flush old player if needed
333 this.flushPlayer()
334
335 // Build video element, because videojs remove it on dispose
336 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
337 this.playerElement = document.createElement('video')
338 this.playerElement.className = 'video-js vjs-peertube-skin'
339 playerElementWrapper.appendChild(this.playerElement)
340
341 const videojsOptions = getVideojsOptions({
342 autoplay: this.isAutoplay(),
343 inactivityTimeout: 2500,
344 videoFiles: this.video.files,
345 playerElement: this.playerElement,
346 videoViewUrl: this.videoService.getVideoViewUrl(this.video.uuid),
347 videoDuration: this.video.duration,
348 enableHotkeys: true,
349 peertubeLink: false,
350 poster: this.video.previewUrl
351 })
352
353 const self = this
354 this.zone.runOutsideAngular(() => {
355 videojs(this.playerElement, videojsOptions, function () {
356 self.player = this
357 this.on('customError', (event, data) => self.handleError(data.err))
358 })
359 })
360
361 this.setVideoDescriptionHTML()
362 this.setVideoLikesBarTooltipText()
363
364 this.setOpenGraphTags()
365 this.checkUserRating()
366 }
367
368 private setRating (nextRating) {
369 let method
370 switch (nextRating) {
371 case 'like':
372 method = this.videoService.setVideoLike
373 break
374 case 'dislike':
375 method = this.videoService.setVideoDislike
376 break
377 case 'none':
378 method = this.videoService.unsetVideoLike
379 break
380 }
381
382 method.call(this.videoService, this.video.id)
383 .subscribe(
384 () => {
385 // Update the video like attribute
386 this.updateVideoRating(this.userRating, nextRating)
387 this.userRating = nextRating
388 },
389 err => this.notificationsService.error('Error', err.message)
390 )
391 }
392
393 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
394 let likesToIncrement = 0
395 let dislikesToIncrement = 0
396
397 if (oldRating) {
398 if (oldRating === 'like') likesToIncrement--
399 if (oldRating === 'dislike') dislikesToIncrement--
400 }
401
402 if (newRating === 'like') likesToIncrement++
403 if (newRating === 'dislike') dislikesToIncrement++
404
405 this.video.likes += likesToIncrement
406 this.video.dislikes += dislikesToIncrement
407
408 this.video.buildLikeAndDislikePercents()
409 this.setVideoLikesBarTooltipText()
410 }
411
412 private updateOtherVideosDisplayed () {
413 if (this.video && this.otherVideos && this.otherVideos.length > 0) {
414 this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
415 }
416 }
417
418 private setOpenGraphTags () {
419 this.metaService.setTitle(this.video.name)
420
421 this.metaService.setTag('og:type', 'video')
422
423 this.metaService.setTag('og:title', this.video.name)
424 this.metaService.setTag('name', this.video.name)
425
426 this.metaService.setTag('og:description', this.video.description)
427 this.metaService.setTag('description', this.video.description)
428
429 this.metaService.setTag('og:image', this.video.previewPath)
430
431 this.metaService.setTag('og:duration', this.video.duration.toString())
432
433 this.metaService.setTag('og:site_name', 'PeerTube')
434
435 this.metaService.setTag('og:url', window.location.href)
436 this.metaService.setTag('url', window.location.href)
437 }
438
439 private isAutoplay () {
440 // True by default
441 if (!this.user) return true
442
443 // Be sure the autoPlay is set to false
444 return this.user.autoPlayVideo !== false
445 }
446
447 private flushPlayer () {
448 // Remove player if it exists
449 if (this.player) {
450 this.player.dispose()
451 this.player = undefined
452 }
453 }
454 }