-
Notifications
You must be signed in to change notification settings - Fork 67
/
server.ts
90 lines (82 loc) · 2.03 KB
/
server.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import fs from "fs";
import http from "http";
import qs from "querystring";
import { validateJackettApi } from "./jackett";
import { Label, logger } from "./logger";
import {
searchForSingleTorrentByName,
searchForSingleTorrentByHash,
} from "./pipeline";
import { getRuntimeConfig } from "./runtimeConfig";
function getData(req) {
return new Promise((resolve) => {
const chunks = [];
req.on("data", (chunk) => {
chunks.push(chunk.toString());
});
req.on("end", async () => {
resolve(chunks.join(""));
});
});
}
function parseData(data) {
try {
return JSON.parse(data);
} catch (_) {
const parsed = qs.parse(data);
if ("name" in parsed || "hash" in parsed) return parsed;
throw new Error(`Unable to parse request body: "${data}"`);
}
}
async function handleRequest(req, res) {
if (req.method !== "POST") {
res.writeHead(405);
res.end();
return;
}
if (req.url !== "/api/webhook") {
res.writeHead(404);
res.end();
return;
}
const dataStr = await getData(req);
const { name, hash } = parseData(dataStr);
const criteria = name ? name : hash;
const message = `Received ${name ? "name" : "hash"} ${criteria}`;
res.writeHead(204);
res.end();
logger.info({ label: Label.SERVER, message });
try {
let numFound = null;
if (name) {
numFound = await searchForSingleTorrentByName(name);
}
// Just in case both name and hash are passed.
if (hash && !numFound) {
numFound = await searchForSingleTorrentByHash(hash);
}
if (numFound === null) {
logger.info({
label: Label.SERVER,
message: `Did not search for ${criteria}`,
});
} else {
logger.info({
label: Label.SERVER,
message: `Found ${numFound} torrents for ${criteria}`,
});
}
} catch (e) {
logger.error(e);
}
}
export async function serve(): Promise<void> {
const { outputDir } = getRuntimeConfig();
fs.mkdirSync(outputDir, { recursive: true });
const server = http.createServer(handleRequest);
server.listen(2468);
logger.info({
label: Label.SERVER,
message: "Server is running on port 2468, ^C to stop.",
});
}