-
Notifications
You must be signed in to change notification settings - Fork 0
/
databaseOperations.js
94 lines (81 loc) · 2.17 KB
/
databaseOperations.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
const sqlite = require("sqlite3").verbose();
const path = require("path");
import { checkEnvironmentVariables, DEBUG, WARN, INFO, ERROR } from "./utils";
checkEnvironmentVariables();
const { CAN_TRACKER_PATH: DB_PATH } = process.env;
function getDatabase() {
return new sqlite.Database(path.join(DB_PATH, "trackedTorrents.db"));
}
export async function addTorrent(parsedTorrent) {
const { infoHash } = parsedTorrent;
const isTracked = await checkTorrentIsTracked(infoHash);
if (isTracked) {
WARN(`Torrent with infoHash ${infoHash} is already tracked!`);
return Promise.resolve();
}
return new Promise(async (resolve, reject) => {
const db = getDatabase();
db.run(
"INSERT INTO tracked_torrents(info_hash) VALUES (?)",
[infoHash],
err => {
db.close();
if (err !== null) {
ERROR(
`Couldn't add torrent with info_hash: ${infoHash} to tracking database!`
);
DEBUG(err);
return reject(err);
}
INFO(`Torrent with infoHash ${infoHash} is now being tracked!`);
resolve();
}
);
});
}
export function checkTorrentIsTracked(infoHash) {
const db = getDatabase();
return new Promise((resolve, reject) => {
db.get(
`SELECT 1 FROM tracked_torrents WHERE info_hash = $infoHash`,
{
$infoHash: infoHash
},
(err, row) => {
db.close();
if (err !== null) {
ERROR("Something happened while running DB query!");
DEBUG(err);
reject(err);
return;
}
if (row === undefined) {
// We're not tracking this torrent
resolve(false);
}
resolve(true);
}
);
});
}
export function createAndInitDatabase() {
const db = getDatabase();
return new Promise((resolve, reject) => {
db.run(
`CREATE TABLE IF NOT EXISTS tracked_torrents (
info_hash TEXT PRIMARY KEY
)`,
[],
err => {
if (err !== null) {
ERROR("Something happened during DB creation!");
DEBUG(err);
reject(err);
return;
}
db.close();
resolve(1);
}
);
});
}