<%include partials/header.ejs %>

<div class="container">
  <h1>Download files using the WebTorrent protocol (BitTorrent over WebRTC).</h1>
  <small><a target="_blank" href="https://github.com/webtorrent/webtorrent/blob/master/docs/free-torrents.md">Sample torrents</a></small>

  <div id="hero">
    <div id="output">
      <div id="progressBar"></div>
      <!-- The video player will be added here -->
    </div>
    <!-- Statistics -->
    <div id="status">
      <div>
        <span class="show-seed">Seeding </span>
        <label for="torrent_url">Enter a .torrent file url: (Torrent file must contain .mp4, .webm, .avi, .pdf or .mp3 file only)</label>
        <input type="text" name="torrent_url" id="torrent_url" class="form-control">
        <button id="btn-download" class="btn btn-primary">Start Download</button>
        <span class="show-leech">Downloading torent file</span>
        <span class="show-leech"> from </span>
        <span class="show-seed"> to </span>
        <code id="numPeers">0 peers</code>.
      </div>
      <div>
        <code id="downloaded"></code>
        of <code id="total"></code>
        — <span id="remaining"></span><br/>
        &#x2198;<code id="downloadSpeed">0 b/s</code>
        / &#x2197;<code id="uploadSpeed">0 b/s</code>
      </div>
    </div>
  </div>

</div>

<%include partials/footer.ejs %>

<script>

//http://www.ytsyify.org/[EZTV]/(eztvtorrent.net)%20The%20Originals%20(S05E04)%20(480p).torrent
    $(document).on('click', '#btn-download', function() {
        var torrentId = $('#torrent_url').val();

        var client = new WebTorrent()

        // HTML elements
        var $body = document.body
        var $progressBar = document.querySelector('#progressBar')
        var $numPeers = document.querySelector('#numPeers')
        var $downloaded = document.querySelector('#downloaded')
        var $total = document.querySelector('#total')
        var $remaining = document.querySelector('#remaining')
        var $uploadSpeed = document.querySelector('#uploadSpeed')
        var $downloadSpeed = document.querySelector('#downloadSpeed')

        if ($.trim(torrentId).length<1) {
            alert("Please specify a valid .torrent file.");
            return;
        }

        // Download the torrent
        client.add(torrentId, function (torrent) {
            
            // Torrents can contain many files. Let's use the .mp4 file
            var file = torrent.files.find(function (file) {
                if (file.name.endsWith('.mp4')) {
                    return file.name.endsWith('.mp4')    
                } else if (file.name.endsWith('.webm')) {
                    return file.name.endsWith('.webm')    
                } else if (file.name.endsWith('.avi')) {
                    return file.name.endsWith('.avi')    
                } else if (file.name.endsWith('.pdf')) {
                    return file.name.endsWith('.pdf')    
                } else if (file.name.endsWith('.mp3')) {
                    return file.name.endsWith('.mp3')    
                } else if (file.name.endsWith('.jpg')) {
                    return file.name.endsWith('.jpg')    
                } else if (file.name.endsWith('.png')) {
                    return file.name.endsWith('.png')    
                } else if (file.name.endsWith('.gif')) {
                    return file.name.endsWith('.gif')    
                }       
            })

        if (typeof file==undefined) {
            alert("Unsupported files: Torrent file must contain .mp4, .webm, .avi, .pdf, .jpg, .png, .gif or .mp3 file only.");
            return false;
        }

        // Stream the file in the browser
        file.appendTo('#output')

        torrent.on('done', function (file) {
            // Seed file
            client.seed(file, function (tor) {
                console.log(tor);
                console.log('Client is seeding ' + tor.magnetURI)
            })
        })

        // Trigger statistics refresh
        torrent.on('done', onDone)
        setInterval(onProgress, 500)
        onProgress()

    // Statistics
    function onProgress () {
        // Peers
        $numPeers.innerHTML = torrent.numPeers + (torrent.numPeers === 1 ? ' peer' : ' peers')

        // Progress
        var percent = Math.round(torrent.progress * 100 * 100) / 100
        $progressBar.style.width = percent + '%'
        $downloaded.innerHTML = prettyBytes(torrent.downloaded)
        $total.innerHTML = prettyBytes(torrent.length)

        // Remaining time
        var remaining
        if (torrent.done) {
            remaining = 'Done.'
        } else {
            remaining = moment.duration(torrent.timeRemaining / 1000, 'seconds').humanize()
            remaining = remaining[0].toUpperCase() + remaining.substring(1) + ' remaining.'
        }
        $remaining.innerHTML = remaining

        // Speed rates
        $downloadSpeed.innerHTML = prettyBytes(torrent.downloadSpeed) + '/s'
        $uploadSpeed.innerHTML = prettyBytes(torrent.uploadSpeed) + '/s'
    }
    function onDone () {
        $body.className += ' is-seed'
        onProgress()
        }
    })

    // Human readable bytes util
    function prettyBytes(num) {
        var exponent, unit, neg = num < 0, units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
        if (neg) num = -num
        if (num < 1) return (neg ? '-' : '') + num + ' B'
        exponent = Math.min(Math.floor(Math.log(num) / Math.log(1000)), units.length - 1)
        num = Number((num / Math.pow(1000, exponent)).toFixed(2))
        unit = units[exponent]
        return (neg ? '-' : '') + num + ' ' + unit
    }
});
        
</script>