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