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