summaryrefslogtreecommitdiff
path: root/index.js
blob: 737e3d9ebd0eb203dba554fa1147ec33aea7f94b (plain)
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
const http = require('http');
const https = require('https');
const fs = require('fs');
const crypto = require('crypto');
const path = require('path');
const uuid = require('uuid-v4');
const mime = require('mime-types')

global.streams = [];

function fallback(req, res) {
    res.writeHead(400);
    res.end("400 Bad Request");
}

function missing(req, res) {
    res.writeHead(400);
    res.end('400 Bad Request');
}

function forbid(req, res) {
    res.writeHead(425);
    res.end('403 Forbidden');
}

function notfound(req, res) {
    res.writeHead(404);
    res.end('404 Not Found');
}

function invalid(req, res) {
    res.writeHead(401);
    res.end('400 Bad Request');
}

function placeholder(req, res) {
    res.writeHead(302);
    res.end("302 Found");
}

const requestListener = function(req, res) {
    let uid = uuid();
    console.log(uid);
    temp[uid] = {};

    req.on('end', () => {
        process.stdout.write("-");
        delete temp[uid];
        process.stdout.write("-\n");
    })

    let userIp;
    userIp = req.socket.address().address;
    if (req.headers["x-forwarded-for"] !== undefined) {
        userIp = req.headers["x-forwarded-for"]
    }

    temp[uid].parts = req.url.split("/").filter(i => i.trim() !== "");
    console.log(temp[uid].parts, req.headers["user-agent"], req.socket.address().address);

    if (temp[uid].parts.length >= 2) {
        if (temp[uid].parts.length === 3 && temp[uid].parts[0] === "authorize") {
            let song = temp[uid].parts[1].replace(/[^0-9a-f]/gm, "");
            let quality = temp[uid].parts[2].replace(/[^a-z]/gm, "");
            let ua
            try {
                ua = temp[uid].parts[3].replace(/[^a-z]/gm, "");
            } catch (e) {
                ua = Buffer.from(req.headers["user-agent"]).toString("base64");
            }
            let ip
            try {
                ip = temp[uid].parts[4].replace(/[^a-z]/gm, "");
            } catch (e) {
                ip = Buffer.from(req.socket.address().address).toString("base64");
            }
            let id = crypto.createHash('sha512').update(crypto.randomBytes(128).toString("base64")).digest('hex');
            streams.push({
                song,
                quality: crypto.createHash('md5').update(quality).digest('hex'),
                id,
                user: Buffer.from(ua, "base64").toString(),
                ip: Buffer.from(ip, "base64").toString(),
                created: new Date()
            })
            res.write("/stream/" + song + "/" + crypto.createHash('md5').update(quality).digest('hex') + "/" + id);
            res.end();
        } else if (temp[uid].parts.length === 4 && temp[uid].parts[0] === "stream") {
            let song = temp[uid].parts[1].replace(/[^0-9a-f]/gm, "");
            let quality = temp[uid].parts[2].replace(/[^0-9a-f]/gm, "");
            let stream = temp[uid].parts[3].replace(/[^0-9a-f]/gm, "");

            if (fs.existsSync("./files/" + song)) {
                console.log(fs.readdirSync("./files/" + song).filter((i) => i.split(".")[0].split("-")[1] !== undefined).map((i) => { return [ i, i.split(".")[0].split("-")[1], crypto.createHash('md5').update(i.split(".")[0].split("-")[1]).digest('hex') ] }));
                let selected = fs.readdirSync("./files/" + song).filter((i) => i.split(".")[0].split("-")[1] !== undefined).filter((i) => crypto.createHash('md5').update(i.split(".")[0].split("-")[1]).digest('hex') === quality);

                if (selected.length > 0) {
                    if (streams.map((i) => { return i.id; }).includes(stream)) {
                        if (streams.filter(i => i.id === stream)[0].user === req.headers["user-agent"] && streams.filter(i => i.id === stream)[0].ip === req.socket.address().address && streams.filter(i => i.id === stream)[0].song === song && streams.filter(i => i.id === stream)[0].quality === quality) {
                            streams.filter(i => i.id === stream)[0].created = new Date();
                            res.writeHead(200, {
                                'Content-Type': mime.lookup(selected[0]) || 'application/octet-stream',
                                'Cache-Control': 'no-cache, must-revalidate',
                                'Content-Disposition': 'inline',
                                'Expires': '0',
                                'Content-Length': fs.statSync("./files/" + song + "/" + selected[0]).size
                            });

                            let readStream = fs.createReadStream("./files/" + song + "/" + selected[0]);
                            readStream.pipe(res);
                        } else {
                            forbid(req, res);
                        }
                    } else {
                        forbid(req, res);
                    }
                } else {
                    notfound(req, res);
                }
            } else {
                notfound(req, res);
            }
        } else {
            invalid(req, res);
        }
    } else {
        invalid(req, res);
    }
}

const server = http.createServer((req, res) => {
    global.temp = {};

    setInterval(() => {
        global.streams = streams.filter(i => new Date() - i.created < 3600000);
    }, 10000)

    try {
        requestListener(req, res);
    } catch (e) {
        console.error(e);
        res.writeHead(500);
        res.end('500 Internal Server Error');
    }
});
server.listen(8875);
console.log("Listening")