This repository has been archived by the owner on Sep 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 105
/
index.js
82 lines (78 loc) · 2.06 KB
/
index.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
const http = require('http')
const httpProxy = require('http-proxy')
const express = require('express')
const request = require('request')
const httpsrv = require('httpsrv')
const fs = require('fs')
const SECRET = /rpc-secret=(.*)/.exec(
fs.readFileSync('aria2c.conf', 'utf-8')
)[1]
const ENCODED_SECRET = Buffer.from(SECRET).toString('base64')
const PORT = process.env.PORT || 1234
const app = express()
const proxy = httpProxy.createProxyServer({
target: 'ws://localhost:6800',
ws: true
})
const server = http.createServer(app)
// Proxy websocket
server.on('upgrade', (req, socket, head) => {
proxy.ws(req, socket, head)
})
// Handle normal http traffic
app.use('/jsonrpc', (req, res) => {
req.pipe(request('http://localhost:6800/jsonrpc')).pipe(res)
})
app.use(
'/downloads/' + ENCODED_SECRET,
httpsrv({
basedir: __dirname + '/downloads'
})
)
app.use('/ariang', express.static(__dirname + '/ariang'))
app.use('/', express.static(__dirname + '/index'))
server.listen(PORT, () => console.log(`Listening on http://localhost:${PORT}`))
if (process.env.HEROKU_APP_NAME) {
const readNumUpload = () =>
new Promise((res, rej) =>
fs.readFile('numUpload', 'utf-8', (err, text) =>
err ? rej(err) : res(text)
)
)
const APP_URL = `https://${process.env.HEROKU_APP_NAME}.herokuapp.com`
const preventIdling = () => {
request.post(
'http://localhost:6800/jsonrpc',
{
json: {
jsonrpc: '2.0',
method: 'aria2.getGlobalStat',
id: 'preventIdling',
params: [`token:${SECRET}`]
}
},
async (err, resp, body) => {
console.log('preventIdling: getGlobalStat response', body)
const { numActive, numWaiting } = body.result
const numUpload = await readNumUpload()
console.log(
'preventIdling: numbers',
numActive,
numWaiting,
numUpload
)
if (
parseInt(numActive) +
parseInt(numWaiting) +
parseInt(numUpload) >
0
) {
console.log('preventIdling: make request to prevent idling')
request(APP_URL)
}
}
)
setTimeout(preventIdling, 5 * 60 * 1000) // 5 min
}
preventIdling()
}