1 import { Component, ElementRef, NgZone, OnDestroy, OnInit } from '@angular/core';
2 import { ActivatedRoute } from '@angular/router';
4 import { BytesPipe } from 'angular-pipes/src/math/bytes.pipe';
6 import { LoaderComponent, Video, VideoService } from '../shared';
7 import { WebTorrentService } from './webtorrent.service';
10 selector: 'my-video-watch',
11 template: require('./video-watch.component.html'),
12 styles: [ require('./video-watch.component.scss') ],
13 providers: [ WebTorrentService ],
14 directives: [ LoaderComponent ],
18 export class VideoWatchComponent implements OnInit, OnDestroy {
19 private static LOADTIME_TOO_LONG: number = 30000;
21 downloadSpeed: number;
22 error: boolean = false;
23 loading: boolean = false;
28 private errorTimer: NodeJS.Timer;
30 private torrentInfosInterval: NodeJS.Timer;
33 private elementRef: ElementRef,
34 private ngZone: NgZone,
35 private route: ActivatedRoute,
36 private videoService: VideoService,
37 private webTorrentService: WebTorrentService
43 // We are loading the video
46 console.log('Adding ' + this.video.magnetUri + '.');
48 // The callback might never return if there are network issues
49 // So we create a timer to inform the user the load is abnormally long
50 this.errorTimer = setTimeout(() => this.loadTooLong(), VideoWatchComponent.LOADTIME_TOO_LONG);
52 this.webTorrentService.add(this.video.magnetUri, (torrent) => {
53 // Clear the error timer
54 clearTimeout(this.errorTimer);
55 // Maybe the error was fired by the timer, so reset it
58 // We are not loading the video anymore
61 console.log('Added ' + this.video.magnetUri + '.');
62 torrent.files[0].appendTo(this.elementRef.nativeElement.querySelector('.embed-responsive'), (err) => {
64 alert('Cannot append the file.');
69 this.runInProgress(torrent);
74 console.log('Removing video from webtorrent.');
75 clearInterval(this.torrentInfosInterval);
76 this.webTorrentService.remove(this.video.magnetUri);
78 this.sub.unsubscribe();
82 this.sub = this.route.params.subscribe(routeParams => {
83 let id = routeParams['id'];
84 this.videoService.getVideo(id).subscribe(
89 error => alert(error.text)
94 private loadTooLong() {
96 console.error('The video load seems to be abnormally long.');
99 private runInProgress(torrent: any) {
100 // Refresh each second
101 this.torrentInfosInterval = setInterval(() => {
102 this.ngZone.run(() => {
103 this.downloadSpeed = torrent.downloadSpeed;
104 this.numPeers = torrent.numPeers;
105 this.uploadSpeed = torrent.uploadSpeed;