This repository has been archived by the owner on Feb 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.ts
75 lines (61 loc) · 1.75 KB
/
index.ts
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
const express = require('express')
const app = express()
const port = process.env.PORT || 3000
import Mirror from './mirror'
import Zippy from './mirror/hosting/zippy'
let mirror, results = {}, stats = {}
app.use(express.json())
function error(status, msg) {
return new class extends Error{
status : number
constructor(status, message){
super(message)
this.status = status
}
}(status, msg)
}
app.use('/api', function(req, res, next){
var key = req.query['api-key']
if (!key) return next(error(400, 'api key required'))
if (!~apiKeys.indexOf(key)) return next(error(401, 'invalid api key'))
req.key = key
next()
})
var apiKeys = ['foo', 'bar', 'baz']
app.post('/api/torrent/start', (req, res, next) =>{
if(!req.body.uri)
next()
mirror.add(req.body.uri, new Zippy(), (result, hash) =>{
results[hash] = result
stats[hash] = {status : 'finish'}
},(stat, hash) =>{
stats[hash] = {status : 'mirror', statistic : stat}
}).then((hash)=> {
stats[hash] = {status : 'prepare'}
res.send({hash : hash})
})
})
app.get('/api/torrent/status', (req, res, next) =>{
if(!req.query.hash)
next()
let stat = stats[req.query.hash]
res.send(stat)
})
app.get('/api/torrent/result', (req, res, next) =>{
if(!req.query.hash)
next()
let result = results[req.query.hash] || []
res.send(result)
})
app.use(function(err, req, res, next){
res.status(err.status || 500)
res.send({ error: err.message })
})
app.use(function(req, res){
res.status(404)
res.send({ error: "Lame, can't find that" })
})
app.listen(port, ()=>{
mirror = new Mirror()
console.log(`listening at http://localhost:${port}`)
})