1 import { Component, ElementRef, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
2 import { ActivatedRoute, Router } from '@angular/router'
3 import { Observable } from 'rxjs/Observable'
4 import { Subscription } from 'rxjs/Subscription'
6 import videojs from 'video.js'
7 import { MetaService } from '@ngx-meta/core'
8 import { NotificationsService } from 'angular2-notifications'
10 import { AuthService, ConfirmService } from '../../core'
11 import { VideoMagnetComponent } from './video-magnet.component'
12 import { VideoShareComponent } from './video-share.component'
13 import { VideoReportComponent } from './video-report.component'
14 import { Video, VideoService } from '../shared'
15 import { WebTorrentService } from './webtorrent.service'
16 import { UserVideoRateType, VideoRateType, UserVideoRate } from '../../../../../shared'
19 selector: 'my-video-watch',
20 templateUrl: './video-watch.component.html',
21 styleUrls: [ './video-watch.component.scss' ]
23 export class VideoWatchComponent implements OnInit, OnDestroy {
24 private static LOADTIME_TOO_LONG = 20000
26 @ViewChild('videoMagnetModal') videoMagnetModal: VideoMagnetComponent
27 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
28 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
34 player: videojs.Player
35 playerElement: HTMLMediaElement
37 userRating: UserVideoRateType = null
41 private errorTimer: number
42 private paramsSub: Subscription
43 private errorsSub: Subscription
44 private torrentInfosInterval: number
47 private elementRef: ElementRef,
48 private ngZone: NgZone,
49 private route: ActivatedRoute,
50 private router: Router,
51 private videoService: VideoService,
52 private confirmService: ConfirmService,
53 private metaService: MetaService,
54 private webTorrentService: WebTorrentService,
55 private authService: AuthService,
56 private notificationsService: NotificationsService
60 this.paramsSub = this.route.params.subscribe(routeParams => {
61 let uuid = routeParams['uuid']
62 this.videoService.getVideo(uuid).subscribe(
63 video => this.onVideoFetched(video),
67 this.videoNotFound = true
72 this.playerElement = this.elementRef.nativeElement.querySelector('#video-container')
74 const videojsOptions = {
80 videojs(this.playerElement, videojsOptions, function () {
84 this.errorsSub = this.webTorrentService.errors.subscribe(err => this.handleError(err))
88 // Remove WebTorrent stuff
89 console.log('Removing video from webtorrent.')
90 window.clearInterval(this.torrentInfosInterval)
91 window.clearTimeout(this.errorTimer)
93 if (this.video !== null && this.webTorrentService.has(this.video.getDefaultMagnetUri())) {
94 this.webTorrentService.remove(this.video.getDefaultMagnetUri())
98 videojs(this.playerElement).dispose()
100 // Unsubscribe subscriptions
101 this.paramsSub.unsubscribe()
102 this.errorsSub.unsubscribe()
108 // We are loading the video
111 console.log('Adding ' + this.video.getDefaultMagnetUri() + '.')
113 // The callback might never return if there are network issues
114 // So we create a timer to inform the user the load is abnormally long
115 this.errorTimer = window.setTimeout(() => this.loadTooLong(), VideoWatchComponent.LOADTIME_TOO_LONG)
117 const torrent = this.webTorrentService.add(this.video.getDefaultMagnetUri(), torrent => {
118 // Clear the error timer
119 window.clearTimeout(this.errorTimer)
120 // Maybe the error was fired by the timer, so reset it
123 // We are not loading the video anymore
126 console.log('Added ' + this.video.getDefaultMagnetUri() + '.')
127 torrent.files[0].renderTo(this.playerElement, (err) => {
129 this.notificationsService.error('Error', 'Cannot append the file in the video element.')
133 // Hack to "simulate" src link in video.js >= 6
134 // If no, we can't play the video after pausing it
135 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
136 (this.player as any).src = () => true
141 this.runInProgress(torrent)
144 torrent.on('error', err => this.handleError(err))
145 torrent.on('warning', err => this.handleError(err))
149 if (this.isUserLoggedIn() === false) return
150 // Already liked this video
151 if (this.userRating === 'like') return
153 this.videoService.setVideoLike(this.video.id)
156 // Update the video like attribute
157 this.updateVideoRating(this.userRating, 'like')
158 this.userRating = 'like'
161 err => this.notificationsService.error('Error', err.message)
166 if (this.isUserLoggedIn() === false) return
167 // Already disliked this video
168 if (this.userRating === 'dislike') return
170 this.videoService.setVideoDislike(this.video.id)
173 // Update the video dislike attribute
174 this.updateVideoRating(this.userRating, 'dislike')
175 this.userRating = 'dislike'
178 err => this.notificationsService.error('Error', err.message)
182 removeVideo (event: Event) {
183 event.preventDefault()
185 this.confirmService.confirm('Do you really want to delete this video?', 'Delete').subscribe(
187 if (res === false) return
189 this.videoService.removeVideo(this.video.id)
192 this.notificationsService.success('Success', `Video ${this.video.name} deleted.`)
193 // Go back to the video-list.
194 this.router.navigate(['/videos/list'])
197 error => this.notificationsService.error('Error', error.text)
203 blacklistVideo (event: Event) {
204 event.preventDefault()
206 this.confirmService.confirm('Do you really want to blacklist this video ?', 'Blacklist').subscribe(
208 if (res === false) return
210 this.videoService.blacklistVideo(this.video.id)
213 this.notificationsService.success('Success', `Video ${this.video.name} had been blacklisted.`)
214 this.router.navigate(['/videos/list'])
217 error => this.notificationsService.error('Error', error.text)
223 showReportModal (event: Event) {
224 event.preventDefault()
225 this.videoReportModal.show()
229 this.videoShareModal.show()
232 showMagnetUriModal (event: Event) {
233 event.preventDefault()
234 this.videoMagnetModal.show()
238 return this.authService.isLoggedIn()
241 canUserUpdateVideo () {
242 return this.video.isUpdatableBy(this.authService.getUser())
245 isVideoRemovable () {
246 return this.video.isRemovableBy(this.authService.getUser())
249 isVideoBlacklistable () {
250 return this.video.isBlackistableBy(this.authService.getUser())
253 private handleError (err: any) {
254 const errorMessage: string = typeof err === 'string' ? err : err.message
257 if (errorMessage.indexOf('http error') !== -1) {
258 message = 'Cannot fetch video from server, maybe down.'
260 message = errorMessage
263 this.notificationsService.error('Error', message)
266 private checkUserRating () {
267 // Unlogged users do not have ratings
268 if (this.isUserLoggedIn() === false) return
270 this.videoService.getUserVideoRating(this.video.id)
274 this.userRating = ratingObject.rating
278 err => this.notificationsService.error('Error', err.message)
282 private onVideoFetched (video: Video) {
286 if (this.video.isVideoNSFWForUser(this.authService.getUser())) {
287 observable = this.confirmService.confirm('This video is not safe for work. Are you sure you want to watch it?', 'NSFW')
289 observable = Observable.of(true)
292 observable.subscribe(
295 return this.router.navigate([ '/videos/list' ])
298 this.setOpenGraphTags()
300 this.checkUserRating()
305 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
306 let likesToIncrement = 0
307 let dislikesToIncrement = 0
310 if (oldRating === 'like') likesToIncrement--
311 if (oldRating === 'dislike') dislikesToIncrement--
314 if (newRating === 'like') likesToIncrement++
315 if (newRating === 'dislike') dislikesToIncrement++
317 this.video.likes += likesToIncrement
318 this.video.dislikes += dislikesToIncrement
321 private loadTooLong () {
323 console.error('The video load seems to be abnormally long.')
326 private setOpenGraphTags () {
327 this.metaService.setTitle(this.video.name)
329 this.metaService.setTag('og:type', 'video')
331 this.metaService.setTag('og:title', this.video.name)
332 this.metaService.setTag('name', this.video.name)
334 this.metaService.setTag('og:description', this.video.description)
335 this.metaService.setTag('description', this.video.description)
337 this.metaService.setTag('og:image', this.video.previewPath)
339 this.metaService.setTag('og:duration', this.video.duration.toString())
341 this.metaService.setTag('og:site_name', 'PeerTube')
343 this.metaService.setTag('og:url', window.location.href)
344 this.metaService.setTag('url', window.location.href)
347 private runInProgress (torrent: any) {
348 // Refresh each second
349 this.torrentInfosInterval = window.setInterval(() => {
350 this.ngZone.run(() => {
351 this.downloadSpeed = torrent.downloadSpeed
352 this.numPeers = torrent.numPeers
353 this.uploadSpeed = torrent.uploadSpeed