seeding complete

This commit is contained in:
Abhishek Sinha 2018-08-14 10:01:16 +05:30
commit ccd26d19b4
14 changed files with 8571 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
node_modules/
playground/
public/js/bundle.js

0
README.md Normal file
View File

48
index.js Normal file
View File

@ -0,0 +1,48 @@
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');
//const flash = require('connect-flash');
const validator = require('express-validator');
const routes = require('./routes');
const port = process.env.PORT || 3007;
const app = express();
app.set('view engine', 'ejs');
const middleware = [
express.static(path.join(__dirname, 'public')),
bodyParser.urlencoded({extended:true}),
cookieParser(),
session({
secret: 'super-secret-key',
key: 'super-secret-cookie',
resave: false,
saveUninitialized: false,
cookie: { maxAge: 60000 }
}),
validator(),
//flash()
]
app.use(middleware);
app.use('/', routes);
app.use((req, res,next)=>{
res.status(404).send("Page Not Found");
});
app.use((err, req, res, next)=>{
console.log(err);
res.status(500).send("Page Broke!");
});
app.listen(port, ()=>{
console.log("Webtor app running on port "+port);
});

8055
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

38
package.json Normal file
View File

@ -0,0 +1,38 @@
{
"name": "webtor",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"body-parser": "^1.18.3",
"bootstrap": "^4.1.3",
"browserify": "^16.2.2",
"cookie-parser": "^1.4.3",
"drag-drop": "^4.2.0",
"ejs": "^2.6.1",
"express": "^4.16.3",
"express-session": "^1.15.6",
"express-validator": "^5.3.0",
"install": "^0.12.1",
"jquery": "^3.3.1",
"jquery-ui": "^1.12.1",
"lodash": "^4.17.10",
"npm": "^6.3.0",
"popper.js": "^1.14.4",
"watchify": "^3.11.0",
"webtorrent": "^0.102.1"
},
"devDependencies": {
"nodemon": "^1.18.3"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "browserify public/js/main.js -o public/js/bundle.js",
"watch": "watchify public/js/main.js -o public/js/bundle.js",
"prestart": "npm run build",
"start": "nodemon --ignore public/js/bundle.js index.js",
"poststart": "npm run watch"
},
"author": "",
"license": "ISC"
}

15
public/css/main.css Normal file
View File

@ -0,0 +1,15 @@
.drop-div {
border-style: dotted;
width: 1000px;
height: 500px;
}
.card {
padding: 5rem 5rem;
}
footer {
position:fixed;
bottom:0;
left:0;
}

49
public/js/main.js Normal file
View File

@ -0,0 +1,49 @@
let buffer = require('buffer')
var client = new WebTorrent()
client.on('error', function (err) {
console.error('ERROR: ' + err.message)
})
// You can pass in a DOM node or a selector string!
DragDrop('.drop-div', function (files, pos, fileList, directories) {
console.log('Here are the dropped files', files)
console.log('Dropped at coordinates', pos.x, pos.y)
console.log('Here is the raw FileList object if you need it:', fileList)
console.log('Here is the list of directories:', directories)
client.seed(files, function (torrent) {
console.log(torrent);
console.log('Client is seeding ' + torrent.magnetURI)
let t = ``;
t += `Client is seeding <strong>${torrent.magnetURI}</strong>`;
t += `<p>Name: ${torrent.name}</p>`;
t += `<p>Name: ${torrent.path}</p>`;
var hexdata = torrent.torrentFile.toString('hex');
t += `<p>Torrent: ${hexdata}</p>`;
t += `<p></p>`;
t += `<h5>Files hash</h5>`;
for (let h = 0; h < torrent._hashes.length; h++) {
const hash = torrent._hashes[h];
t += `<p>${hash}</p>`;
}
t += `<h5>Peers</h5>`;
for (let p = 0; p < torrent._peers.length; p++) {
const peer = torrent._peers[p];
t += `<p>Peer: ${peer}</p>`;
}
t += `<h5>Trackers</h5>`;
for (let r = 0; r < torrent.discovery._announce.length; r++) {
const tracker = torrent.discovery._announce[r];
t += `<p>${tracker}</p>`;
}
$("#seed-result").html(t);
})
})

35
routes.js Normal file
View File

@ -0,0 +1,35 @@
const express = require('express');
const router = express.Router();
const { check, validationResult } = require('express-validator/check')
const { matchedData } = require('express-validator/filter')
const _ = require('lodash');
//const fetch = require('node-fetch');
var path = require('path')
var fs = require('fs');
router.get('/', (req, res)=>{
res.render('index.ejs', {
data: {},
errors: {},
title: 'Welcome!'
})
})
router.get('/seed', (req, res)=>{
res.render('seed.ejs', {
data: {},
errors: {},
title: 'Seed!'
})
})
router.get('/download', (req, res)=>{
res.render('download.ejs', {
data: {},
errors: {},
title: 'Download!'
})
})
module.exports = router

11
seed.js Normal file
View File

@ -0,0 +1,11 @@
var dragDrop = require('drag-drop')
var WebTorrent = require('webtorrent')
var client = new WebTorrent()
// When user drops files on the browser, create a new torrent and start seeding it!
dragDrop('body', function (files) {
client.seed(files, function (torrent) {
console.log('Client is seeding:', torrent.infoHash)
})
})

238
views/download.ejs Normal file
View File

@ -0,0 +1,238 @@
<!doctype html>
<html>
<body>
<h1>Download files using the WebTorrent protocol (BitTorrent over WebRTC).</h1>
<form>
<label for="torrentId">Download from a magnet link: </label>
<input name="torrentId", placeholder="magnet:" value="magnet:?xt=urn:btih:08ada5a7a6183aae1e09d831df6748d566095a10&dn=Sintel&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel.torrent">
<button type="submit">Download</button>
</form>
<h2>Log</h2>
<div class="log"></div>
<!-- Include the latest version of WebTorrent -->
<script src="https://cdn.jsdelivr.net/webtorrent/latest/webtorrent.min.js"></script>
<script>
var client = new WebTorrent()
client.on('error', function (err) {
console.error('ERROR: ' + err.message)
})
document.querySelector('form').addEventListener('submit', function (e) {
e.preventDefault() // Prevent page refresh
var torrentId = document.querySelector('form input[name=torrentId]').value
log('Adding ' + torrentId)
client.add(torrentId, onTorrent)
})
function onTorrent (torrent) {
log('Got torrent metadata!')
log(
'Torrent info hash: ' + torrent.infoHash + ' ' +
'<a href="' + torrent.magnetURI + '" target="_blank">[Magnet URI]</a> ' +
'<a href="' + torrent.torrentFileBlobURL + '" target="_blank" download="' + torrent.name + '.torrent">[Download .torrent]</a>'
)
// Print out progress every 5 seconds
var interval = setInterval(function () {
log('Progress: ' + (torrent.progress * 100).toFixed(1) + '%')
}, 5000)
torrent.on('done', function () {
log('Progress: 100%')
clearInterval(interval)
})
// Render all files into to the page
torrent.files.forEach(function (file) {
file.appendTo('.log')
log('(Blob URLs only work if the file is loaded from a server. "http//localhost" works. "file://" does not.)')
file.getBlobURL(function (err, url) {
if (err) return log(err.message)
log('File done.')
log('<a href="' + url + '">Download full file: ' + file.name + '</a>')
})
})
}
function log (str) {
var p = document.createElement('p')
p.innerHTML = str
document.querySelector('.log').appendChild(p)
}
</script>
</body>
</html>
HTML example with status showing UI
This complete HTML example mimics the UI of the webtorrent.io homepage. It downloads the sintel.torrent file, streams it in the browser and outputs some statistics to the user (peers, progress, remaining time, speed...).
You can try it right now on CodePen to see what it looks like and play around with it!
Feel free to replace torrentId with other torrent files, or magnet links, but keep in mind that the browser can only download torrents that are seeded by WebRTC peers (web peers). Use WebTorrent Desktop or Instant.io to seed torrents to the WebTorrent network.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebTorrent video player</title>
<style>
#output video {
width: 100%;
}
#progressBar {
height: 5px;
width: 0%;
background-color: #35b44f;
transition: width .4s ease-in-out;
}
body.is-seed .show-seed {
display: inline;
}
body.is-seed .show-leech {
display: none;
}
.show-seed {
display: none;
}
#status code {
font-size: 90%;
font-weight: 700;
margin-left: 3px;
margin-right: 3px;
border-bottom: 1px dashed rgba(255,255,255,0.3);
}
.is-seed #hero {
background-color: #154820;
transition: .5s .5s background-color ease-in-out;
}
#hero {
background-color: #2a3749;
}
#status {
color: #fff;
font-size: 17px;
padding: 5px;
}
a:link, a:visited {
color: #30a247;
text-decoration: none;
}
</style>
</head>
<body>
<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-leech">Downloading </span>
<span class="show-seed">Seeding </span>
<code>
<!-- Informative link to the torrent file -->
<a id="torrentLink" href="https://webtorrent.io/torrents/sintel.torrent">sintel.torrent</a>
</code>
<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>
<!-- Include the latest version of WebTorrent -->
<script src="https://cdn.jsdelivr.net/webtorrent/latest/webtorrent.min.js"></script>
<!-- Moment is used to show a human-readable remaining time -->
<script src="http://momentjs.com/downloads/moment.min.js"></script>
<script>
var torrentId = 'https://webtorrent.io/torrents/sintel.torrent'
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')
// 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) {
return file.name.endsWith('.mp4')
})
// Stream the file in the browser
file.appendTo('#output')
// 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>
</body>
</html>

10
views/index.ejs Normal file
View File

@ -0,0 +1,10 @@
<%include partials/header.ejs %>
<div class="container">
<ul>
<li><a href="/seed">Seed Torrent</a></li>
<li><a href="/download">Download Torrent</a></li>
</ul>
</div>
<%include partials/footer.ejs %>

15
views/partials/footer.ejs Normal file
View File

@ -0,0 +1,15 @@
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.jsdelivr.net/npm/webtorrent@latest/webtorrent.min.js"></script>
<script src="https://rawgit.com/feross/drag-drop/master/dragdrop.min.js"></script>
<script src="/js/bundle.js"></script>
<!-- FOOTER -->
<footer class="container">
<p class="float-right"><a href="#">Back to top</a></p>
<p>&copy; <a href="https://ranchimall.net" target="_blank">Ranchi Mall</a> 2018-2019 Company, Inc. &middot; <a href="https://ranchimall.net/privacypolicy.htm" target="_blank">Privacy</a> &middot; <a href="#">Terms</a></p>
</footer>
</main>
</body>
</html>

37
views/partials/header.ejs Normal file
View File

@ -0,0 +1,37 @@
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="/css/main.css" rel="stylesheet">
<!--<link href="https://fonts.googleapis.com/css?family=Amatic+SC|Arapey:400,400i|Caveat|Dancing+Script|Great+Vibes|Lobster|Ranga" rel="stylesheet"> -->
<title><%=title%></title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Ranchi Mall WebTorrent</a>
<div class="collapse navbar-collapse" id="navbarTogglerDemo03">
<ul class="navbar-nav mr-auto mt-2 mt-lg-0">
<li class="nav-item active">
<a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/seed">Seed</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/download">Download</a>
</li>
</ul>
</div>
</nav>

17
views/seed.ejs Normal file
View File

@ -0,0 +1,17 @@
<%include partials/header.ejs %>
<div class="container">
<p id='#drag'>hello</p>
<div class="card drop-div" id="_drop"></div>
<div class="card">
<div id="seed-result"></div>
</div>
</div>
<%include partials/footer.ejs %>
<script>
//const funcs = require('./public/js/main')
funcs.seedTorrent()
</script>