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