aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/app/videos/video-watch/video-watch.component.ts
blob: 71fb4f6342867156bf36c0c0192a16d9de91cd84 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { Component, ElementRef, OnInit } from '@angular/core';
import { CanDeactivate, ComponentInstruction, RouteParams } from '@angular/router-deprecated';

import { BytesPipe } from 'angular-pipes/src/math/bytes.pipe';

import { LoaderComponent, Video, VideoService } from '../shared/index';
import { WebTorrentService } from './webtorrent.service';

@Component({
  selector: 'my-video-watch',
  templateUrl: 'client/app/videos/video-watch/video-watch.component.html',
  styleUrls: [ 'client/app/videos/video-watch/video-watch.component.css' ],
  providers: [ WebTorrentService ],
  directives: [ LoaderComponent ],
  pipes: [ BytesPipe ]
})

export class VideoWatchComponent implements OnInit, CanDeactivate {
  downloadSpeed: number;
  loading: boolean = false;
  numPeers: number;
  uploadSpeed: number;
  video: Video;

  private interval: NodeJS.Timer;

  constructor(
    private elementRef: ElementRef,
    private routeParams: RouteParams,
    private videoService: VideoService,
    private webTorrentService: WebTorrentService
  ) {}

  loadVideo(video: Video) {
    this.loading = true;
    this.video = video;
    console.log('Adding ' + this.video.magnetUri + '.');

    this.webTorrentService.add(this.video.magnetUri, (torrent) => {
      this.loading = false;
      console.log('Added ' + this.video.magnetUri + '.');
      torrent.files[0].appendTo(this.elementRef.nativeElement.querySelector('.embed-responsive'), (err) => {
        if (err) {
          alert('Cannot append the file.');
          console.error(err);
        }
      });

      // Refresh each second
      this.interval = setInterval(() => {
        this.downloadSpeed = torrent.downloadSpeed;
        this.numPeers = torrent.numPeers;
        this.uploadSpeed = torrent.uploadSpeed;
      }, 1000);
    });
  }

  ngOnInit() {
    let id = this.routeParams.get('id');
    this.videoService.getVideo(id).subscribe(
      video => this.loadVideo(video),
      error => alert(error)
    );
  }

  routerCanDeactivate(next: ComponentInstruction, prev: ComponentInstruction) {
    console.log('Removing video from webtorrent.');
    clearInterval(this.interval);
    this.webTorrentService.remove(this.video.magnetUri);
    return true;
  }
}