]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/video-watch/video-watch.component.ts
err.text -> err
[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 { Observable } from 'rxjs/Observable'
4 import { Subscription } from 'rxjs/Subscription'
5
6 import videojs from 'video.js'
7 import { MetaService } from '@ngx-meta/core'
8 import { NotificationsService } from 'angular2-notifications'
9
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'
17
18 @Component({
19 selector: 'my-video-watch',
20 templateUrl: './video-watch.component.html',
21 styleUrls: [ './video-watch.component.scss' ]
22 })
23 export class VideoWatchComponent implements OnInit, OnDestroy {
24 private static LOADTIME_TOO_LONG = 20000
25
26 @ViewChild('videoMagnetModal') videoMagnetModal: VideoMagnetComponent
27 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
28 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
29
30 downloadSpeed: number
31 error = false
32 loading = false
33 numPeers: number
34 player: videojs.Player
35 playerElement: HTMLMediaElement
36 uploadSpeed: number
37 userRating: UserVideoRateType = null
38 video: Video = null
39 videoNotFound = false
40
41 private errorTimer: number
42 private paramsSub: Subscription
43 private errorsSub: Subscription
44 private torrentInfosInterval: number
45
46 constructor (
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
57 ) {}
58
59 ngOnInit () {
60 this.paramsSub = this.route.params.subscribe(routeParams => {
61 let uuid = routeParams['uuid']
62 this.videoService.getVideo(uuid).subscribe(
63 video => this.onVideoFetched(video),
64
65 error => {
66 console.error(error)
67 this.videoNotFound = true
68 }
69 )
70 })
71
72 this.playerElement = this.elementRef.nativeElement.querySelector('#video-container')
73
74 const videojsOptions = {
75 controls: true,
76 autoplay: true
77 }
78
79 const self = this
80 videojs(this.playerElement, videojsOptions, function () {
81 self.player = this
82 })
83
84 this.errorsSub = this.webTorrentService.errors.subscribe(err => this.handleError(err))
85 }
86
87 ngOnDestroy () {
88 // Remove WebTorrent stuff
89 console.log('Removing video from webtorrent.')
90 window.clearInterval(this.torrentInfosInterval)
91 window.clearTimeout(this.errorTimer)
92
93 if (this.video !== null && this.webTorrentService.has(this.video.getDefaultMagnetUri())) {
94 this.webTorrentService.remove(this.video.getDefaultMagnetUri())
95 }
96
97 // Remove player
98 videojs(this.playerElement).dispose()
99
100 // Unsubscribe subscriptions
101 this.paramsSub.unsubscribe()
102 this.errorsSub.unsubscribe()
103 }
104
105 loadVideo () {
106 // Reset the error
107 this.error = false
108 // We are loading the video
109 this.loading = true
110
111 console.log('Adding ' + this.video.getDefaultMagnetUri() + '.')
112
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)
116
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
121 this.error = false
122
123 // We are not loading the video anymore
124 this.loading = false
125
126 console.log('Added ' + this.video.getDefaultMagnetUri() + '.')
127 torrent.files[0].renderTo(this.playerElement, (err) => {
128 if (err) {
129 this.notificationsService.error('Error', 'Cannot append the file in the video element.')
130 console.error(err)
131 }
132
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
137
138 this.player.play()
139 })
140
141 this.runInProgress(torrent)
142 })
143
144 torrent.on('error', err => this.handleError(err))
145 torrent.on('warning', err => this.handleError(err))
146 }
147
148 setLike () {
149 if (this.isUserLoggedIn() === false) return
150 // Already liked this video
151 if (this.userRating === 'like') return
152
153 this.videoService.setVideoLike(this.video.id)
154 .subscribe(
155 () => {
156 // Update the video like attribute
157 this.updateVideoRating(this.userRating, 'like')
158 this.userRating = 'like'
159 },
160
161 err => this.notificationsService.error('Error', err)
162 )
163 }
164
165 setDislike () {
166 if (this.isUserLoggedIn() === false) return
167 // Already disliked this video
168 if (this.userRating === 'dislike') return
169
170 this.videoService.setVideoDislike(this.video.id)
171 .subscribe(
172 () => {
173 // Update the video dislike attribute
174 this.updateVideoRating(this.userRating, 'dislike')
175 this.userRating = 'dislike'
176 },
177
178 err => this.notificationsService.error('Error', err)
179 )
180 }
181
182 removeVideo (event: Event) {
183 event.preventDefault()
184
185 this.confirmService.confirm('Do you really want to delete this video?', 'Delete').subscribe(
186 res => {
187 if (res === false) return
188
189 this.videoService.removeVideo(this.video.id)
190 .subscribe(
191 status => {
192 this.notificationsService.success('Success', `Video ${this.video.name} deleted.`)
193 // Go back to the video-list.
194 this.router.navigate(['/videos/list'])
195 },
196
197 error => this.notificationsService.error('Error', error.text)
198 )
199 }
200 )
201 }
202
203 blacklistVideo (event: Event) {
204 event.preventDefault()
205
206 this.confirmService.confirm('Do you really want to blacklist this video ?', 'Blacklist').subscribe(
207 res => {
208 if (res === false) return
209
210 this.videoService.blacklistVideo(this.video.id)
211 .subscribe(
212 status => {
213 this.notificationsService.success('Success', `Video ${this.video.name} had been blacklisted.`)
214 this.router.navigate(['/videos/list'])
215 },
216
217 error => this.notificationsService.error('Error', error.text)
218 )
219 }
220 )
221 }
222
223 showReportModal (event: Event) {
224 event.preventDefault()
225 this.videoReportModal.show()
226 }
227
228 showShareModal () {
229 this.videoShareModal.show()
230 }
231
232 showMagnetUriModal (event: Event) {
233 event.preventDefault()
234 this.videoMagnetModal.show()
235 }
236
237 isUserLoggedIn () {
238 return this.authService.isLoggedIn()
239 }
240
241 canUserUpdateVideo () {
242 return this.video.isUpdatableBy(this.authService.getUser())
243 }
244
245 isVideoRemovable () {
246 return this.video.isRemovableBy(this.authService.getUser())
247 }
248
249 isVideoBlacklistable () {
250 return this.video.isBlackistableBy(this.authService.getUser())
251 }
252
253 private handleError (err: any) {
254 const errorMessage: string = typeof err === 'string' ? err : err.message
255 let message = ''
256
257 if (errorMessage.indexOf('http error') !== -1) {
258 message = 'Cannot fetch video from server, maybe down.'
259 } else {
260 message = errorMessage
261 }
262
263 this.notificationsService.error('Error', message)
264 }
265
266 private checkUserRating () {
267 // Unlogged users do not have ratings
268 if (this.isUserLoggedIn() === false) return
269
270 this.videoService.getUserVideoRating(this.video.id)
271 .subscribe(
272 ratingObject => {
273 if (ratingObject) {
274 this.userRating = ratingObject.rating
275 }
276 },
277
278 err => this.notificationsService.error('Error', err)
279 )
280 }
281
282 private onVideoFetched (video: Video) {
283 this.video = video
284
285 let observable
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')
288 } else {
289 observable = Observable.of(true)
290 }
291
292 observable.subscribe(
293 res => {
294 if (res === false) {
295 return this.router.navigate([ '/videos/list' ])
296 }
297
298 this.setOpenGraphTags()
299 this.loadVideo()
300 this.checkUserRating()
301 }
302 )
303 }
304
305 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
306 let likesToIncrement = 0
307 let dislikesToIncrement = 0
308
309 if (oldRating) {
310 if (oldRating === 'like') likesToIncrement--
311 if (oldRating === 'dislike') dislikesToIncrement--
312 }
313
314 if (newRating === 'like') likesToIncrement++
315 if (newRating === 'dislike') dislikesToIncrement++
316
317 this.video.likes += likesToIncrement
318 this.video.dislikes += dislikesToIncrement
319 }
320
321 private loadTooLong () {
322 this.error = true
323 console.error('The video load seems to be abnormally long.')
324 }
325
326 private setOpenGraphTags () {
327 this.metaService.setTitle(this.video.name)
328
329 this.metaService.setTag('og:type', 'video')
330
331 this.metaService.setTag('og:title', this.video.name)
332 this.metaService.setTag('name', this.video.name)
333
334 this.metaService.setTag('og:description', this.video.description)
335 this.metaService.setTag('description', this.video.description)
336
337 this.metaService.setTag('og:image', this.video.previewPath)
338
339 this.metaService.setTag('og:duration', this.video.duration.toString())
340
341 this.metaService.setTag('og:site_name', 'PeerTube')
342
343 this.metaService.setTag('og:url', window.location.href)
344 this.metaService.setTag('url', window.location.href)
345 }
346
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
354 })
355 }, 1000)
356 }
357 }