1 import { Component, ElementRef, 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 route: ActivatedRoute,
35 private videoService: VideoService,
36 private webTorrentService: WebTorrentService
42 // We are loading the video
45 console.log('Adding ' + this.video.magnetUri + '.');
47 // The callback might never return if there are network issues
48 // So we create a timer to inform the user the load is abnormally long
49 this.errorTimer = setTimeout(() => this.loadTooLong(), VideoWatchComponent.LOADTIME_TOO_LONG);
51 this.webTorrentService.add(this.video.magnetUri, (torrent) => {
52 // Clear the error timer
53 clearTimeout(this.errorTimer);
54 // Maybe the error was fired by the timer, so reset it
57 // We are not loading the video anymore
60 console.log('Added ' + this.video.magnetUri + '.');
61 torrent.files[0].appendTo(this.elementRef.nativeElement.querySelector('.embed-responsive'), (err) => {
63 alert('Cannot append the file.');
68 // Refresh each second
69 this.torrentInfosInterval = setInterval(() => {
70 this.downloadSpeed = torrent.downloadSpeed;
71 this.numPeers = torrent.numPeers;
72 this.uploadSpeed = torrent.uploadSpeed;
78 console.log('Removing video from webtorrent.');
79 clearInterval(this.torrentInfosInterval);
80 clearTimeout(this.errorTimer);
81 this.webTorrentService.remove(this.video.magnetUri);
83 this.sub.unsubscribe();
87 this.sub = this.route.params.subscribe(routeParams => {
88 let id = routeParams['id'];
89 this.videoService.getVideo(id).subscribe(
99 private loadTooLong() {
101 console.error('The video load seems to be abnormally long.');