forked from avishkarabhishek786/webtor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes.js
323 lines (253 loc) · 8.78 KB
/
routes.js
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
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 WebtorrentHybrid = require('webtorrent-hybrid')
const client = require('./server.js');
const funcs = require('./public/js/funcs')
var path = require('path')
var fs = require('fs');
var Tracker = require('bittorrent-tracker')
var magnet = require('magnet-uri')
//const JSON = require('circular-json');
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!'
})
})
router.get('/download-magnetic-uri', (req, res)=>{
res.render('magnetic.ejs', {
data: {},
errors: {},
title: 'Download Magnetic URI!'
})
})
router.post('/download-magnetic-uri', (req, res)=>{
let params = _.pick(req.body, ['job', 'torrentId'])
if (params.job != 'download-magnetic-uri') {
return
}
var client = new WebtorrentHybrid()
client.on('error', function (err) {
console.error('ERROR: ' + err.message)
})
var torrentId = params.torrentId
if (_.trim(torrentId) == '') {
console.error("Empty torrent id");
return;
}
client.add(torrentId, function (torrent) {
//torrent.on('wire', (wire)=>{
// console.log(wire);
// console.log(wire._readableState.pipes.remoteAddress);
// console.log(wire._readableState.pipes.remoteFamily);
// console.log(wire._readableState.pipes.remotePort);
// console.log(wire._readableState.pipes.localAddress);
// console.log(wire._readableState.pipes.localPort);
//console.log(wire._readableState.pipes._pc);
// var id = wire.peerId.toString()
// var addr = wire.remoteAddress
// console.log(id);
// console.log(addr);
//})
var files = torrent.files
var length = files.length
// Stream each file to the disk
files.forEach(function (file) {
//console.log(file._torrent.path);
var source = file.createReadStream()
var destination = fs.createWriteStream(`files/${file.name}`)
let fullpath = path.resolve(`files/${file.name}`)
source.on('end', function () {
console.log('file:\t\t', file.name)
res.json({file:file.name, location:fullpath})
// close after all files are saved
if (!--length) process.exit()
}).pipe(destination)
})
})
})
router.get('/send-to-blockchain', (req, res)=>{
res.render('to_flo', {
data: {},
errors: {},
title: 'Send the torrent to flo'
})
})
router.post('/send-to-blockchain', [
check('job')
.isLength({min:1})
.withMessage('Invalid job!')
.trim(),
check('magtor')
.isLength({min:1})
.withMessage('Invalid magnetic uri!')
.trim()
],(req,res)=>{
const errors = validationResult(req)
console.log(errors.mapped());
if(!errors.isEmpty()) {
return res.render('send-to-blockchain', {
data: req.body,
errors: errors.mapped(),
title: 'Please correct your errors'
})
}
let params = _.pick(req.body, ['job', 'magtor'])
if (typeof params.job == undefined || params.job!='magtor') {
console.log("Unknown request");
return;
}
let magnetic_uri = params.magtor
if (magnetic_uri.length<1) {
res.json({error:true, "txnid":null, msg:'Magnetic uri is empty', data:null})
return
}
let toaddress = "oHyzdt8xW1A81qcZ5VcM25RbC6RVbynAg4";
let amount = 1;
try {
client.sendToAddress(toaddress, amount, "Webtor App", "Webtorrent", false, false, 1, 'UNSET', magnetic_uri)
.then((txnid) => {
console.log(txnid)
res.json({"error":false, "txnid":txnid, msg:"Transaction successfull."})
}).catch(e=> {
res.json({"error":true, "txnid":"NOTXIDKJKLGJLKSJLKGJSKJGK", msg:`${e.message}: Please start FLO wallet or FLOD daemon first.`, data:null})
});
} catch(err) {
console.log("Unable to send FLO." + err.message);
res.json({"error":true, "txnid":"NOTXIDKJKLGJLKSJLKGJSKJGK", msg:err.message, data:null})
}
return;
})
router.get('/fetch-from-blockchain', (req, res)=>{
res.render('from_flo', {
data: {},
errors: {},
title: 'Send the torrent to flo'
})
})
router.post('/fetch-from-blockchain', [
check('job')
.isLength({min:1})
.withMessage('Invalid job!')
.trim(),
check('floaddr')
.isLength({min:1})
.withMessage('Invalid FLO addrress!')
.trim()
], (req, res)=>{
const errors = validationResult(req)
console.log(errors.mapped());
if(!errors.isEmpty()) {
return res.render('fetch-from-blockchain', {
data: req.body,
errors: errors.mapped(),
title: 'Please correct your errors'
})
}
let params = _.pick(req.body, ['job', 'floaddr'])
if (typeof params.job == undefined || params.job!='flo-comment') {
console.log("Unknown request");
return;
}
let floaddr = params.floaddr
if (floaddr.length<1) {
res.json({error:true, "txnid":null, msg:'FLO address is empty', data:null})
return
}
try {
let tx_arr = []
client.listTransactions().then(lt=>{
for (let t = 0; t < lt.length; t++) {
const elem = lt[t];
if (elem.address==floaddr && elem.category=='receive') {
tx_arr.push(elem.txid)
}
}
return tx_arr;
}).then(tx_arr=>{
//console.log(tx_arr);
let tor_arr = []
for (const tx in tx_arr) {
let promise = funcs.getFloData(_.trim(tx_arr[tx]))
tor_arr.push(promise)
}
let msg_arr = []
Promise.all(tor_arr).then(msgr=>{
msgr.forEach(op=>{
msg_arr.push(op)
})
return msg_arr
}).then(flo_data=>{
//console.log(flo_data);
res.json({error:false, msg:'List of Torrent files:', data:flo_data})
})
}).catch(e=>{
console.error(e)
})
} catch (error) {
console.error(error)
}
})
router.get('/trackers-list', (req, res)=>{
res.render('trackers-list', {
data: {},
errors: {},
title: 'Trackers List'
})
})
router.post('/trackers-list', (req, res)=>{
require('events').EventEmitter.defaultMaxListeners = 100;
let params = _.pick(req.body, ['job', 'mag_url', 'pid'])
if (params.job!=="track list") {
return;
}
let magnetURI = params.mag_url
let peer_id = params.pid
var parsedTorrent = magnet(magnetURI)
var opts = {
infoHash: parsedTorrent.infoHash,
announce: parsedTorrent.announce,
peerId: new Buffer(peer_id), // hex string or Buffer
port: 6881 // torrent client port
}
var client = new Tracker(opts)
// start getting peers from the tracker
client.start()
client.on('update', function (data) {
console.log('got an announce response from tracker: ' + data.announce)
console.log('number of seeders in the swarm: ' + data.complete)
console.log('number of leechers in the swarm: ' + data.incomplete)
})
setInterval(function() {
console.log('Searching for peers...');
client.once('peer', function (addr) {
console.log(`******* Found a peer: ${addr} *******`) // 85.10.239.191:48623
})
}, 60000);
client.scrape()
client.on('scrape', function (data) {
res.write(JSON.stringify(data))
setInterval(function() {
res.end()
}, 60000)
})
})
module.exports = router