1 import { Component, ElementRef, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core';
2 import { ActivatedRoute } from '@angular/router';
4 import { ModalDirective } from 'ng2-bootstrap/components/modal';
6 import { Video, VideoService } from '../shared';
7 import { WebTorrentService } from './webtorrent.service';
10 selector: 'my-video-watch',
11 templateUrl: './video-watch.component.html',
12 styleUrls: [ './video-watch.component.scss' ]
15 export class VideoWatchComponent implements OnInit, OnDestroy {
16 private static LOADTIME_TOO_LONG: number = 30000;
18 @ViewChild('magnetUriModal') magnetUriModal: ModalDirective;
20 downloadSpeed: number;
21 error: boolean = false;
22 loading: boolean = false;
27 private errorTimer: NodeJS.Timer;
29 private torrentInfosInterval: NodeJS.Timer;
32 private elementRef: ElementRef,
33 private ngZone: NgZone,
34 private route: ActivatedRoute,
35 private videoService: VideoService,
36 private webTorrentService: WebTorrentService
40 this.sub = this.route.params.subscribe(routeParams => {
41 let id = routeParams['id'];
42 this.videoService.getVideo(id).subscribe(
47 error => alert(error.text)
53 console.log('Removing video from webtorrent.');
54 clearInterval(this.torrentInfosInterval);
55 clearTimeout(this.errorTimer);
56 this.webTorrentService.remove(this.video.magnetUri);
58 this.sub.unsubscribe();
64 // We are loading the video
67 console.log('Adding ' + this.video.magnetUri + '.');
69 // The callback might never return if there are network issues
70 // So we create a timer to inform the user the load is abnormally long
71 this.errorTimer = setTimeout(() => this.loadTooLong(), VideoWatchComponent.LOADTIME_TOO_LONG);
73 this.webTorrentService.add(this.video.magnetUri, (torrent) => {
74 // Clear the error timer
75 clearTimeout(this.errorTimer);
76 // Maybe the error was fired by the timer, so reset it
79 // We are not loading the video anymore
82 console.log('Added ' + this.video.magnetUri + '.');
83 torrent.files[0].appendTo(this.elementRef.nativeElement.querySelector('.embed-responsive'), (err) => {
85 alert('Cannot append the file.');
90 this.runInProgress(torrent);
94 showMagnetUriModal() {
95 this.magnetUriModal.show();
98 hideMagnetUriModal() {
99 this.magnetUriModal.hide();
102 private loadTooLong() {
104 console.error('The video load seems to be abnormally long.');
107 private runInProgress(torrent: any) {
108 // Refresh each second
109 this.torrentInfosInterval = setInterval(() => {
110 this.ngZone.run(() => {
111 this.downloadSpeed = torrent.downloadSpeed;
112 this.numPeers = torrent.numPeers;
113 this.uploadSpeed = torrent.uploadSpeed;