Skip to content

Commit

Permalink
Standardize logging and add colors
Browse files Browse the repository at this point in the history
  • Loading branch information
canibanoglu committed Nov 21, 2019
1 parent 3d62974 commit 0751987
Show file tree
Hide file tree
Showing 9 changed files with 194 additions and 112 deletions.
38 changes: 11 additions & 27 deletions bin/mkt.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/usr/bin/env node
import { checkEnvironmentVariables } from "../utils";
import { DEBUG, ERROR, INFO, checkEnvironmentVariables } from "../utils";
import { spawn } from "child_process";
import { statSync, readFileSync } from "fs";

Expand All @@ -8,7 +8,6 @@ checkEnvironmentVariables();
const path = require("path");
const createTorrent = require("can-mktorrent");
const parseTorrent = require("parse-torrent");
const fs = require("fs").promises;
const argv = require("minimist")(process.argv.slice(2));

const {
Expand All @@ -24,33 +23,18 @@ const {
} = process.env;

if (!CAN_TRACKER_ANNOUNCE_URL || !CAN_TRACKER_WEB_SEED_URL) {
console.error("Please set the require environment variables");
ERROR("Please set the require environment variables");
process.exit(1);
}

const processDir = process.cwd();

async function writeTorrentFile(fileName, torrentBuffer) {
const filePath = path.join(processDir, fileName);
const fileHandle = await fs.open(filePath, "w");
return fileHandle
.writeFile(torrentBuffer)
.catch(err => {
console.error(err);
throw err;
})
.then(() => {
console.info(`Successfully created .torrent file with name: ${fileName}`);
return filePath;
});
}

const sanitizedAnnounceUURL = CAN_TRACKER_ANNOUNCE_URL.endsWith("/")
? CAN_TRACKER_ANNOUNCE_URL.slice(0, CAN_TRACKER_ANNOUNCE_URL.length - 1)
: CAN_TRACKER_ANNOUNCE_URL;

console.info("Creating torrent...");
console.log(argv._);
INFO("Creating torrent...");
DEBUG(argv._);
const torrentFileName = `can_tracker_${path.basename(argv._[0])}.torrent`;
createTorrent({
private: true,
Expand All @@ -61,7 +45,7 @@ createTorrent({
sourcePath: argv._[0]
}).then(() => {
const filePath = path.join(process.cwd(), torrentFileName);
console.log("torrent path:", filePath);
DEBUG("torrent path:", filePath);
const parsedTorrent = parseTorrent(readFileSync(filePath));

addTorrentToDatabase(parsedTorrent).then(() => {
Expand All @@ -70,11 +54,11 @@ createTorrent({
try {
statSync(CAN_TRACKER_POST_CREATE_SCRIPT_PATH);
} catch (e) {
console.error("Post create script doesn't exist!");
ERROR("Post create script doesn't exist!");
process.exit(1);
}

console.log("Found post installation script in env");
INFO("Found post installation script in env");

let executor = null;

Expand All @@ -85,7 +69,7 @@ createTorrent({
} else if (CAN_TRACKER_POST_CREATE_SCRIPT_PATH.endsWith(".zsh")) {
executor = "zsh";
} else {
console.error("Only .js, .sh or .zsh scripts are supported.");
ERROR("Only .js, .sh or .zsh scripts are supported.");
return;
}

Expand All @@ -96,15 +80,15 @@ createTorrent({
]);

cp.stdout.on("data", data => {
console.log("post create script:", data.toString());
INFO(">\t post create script:", data.toString());
});

cp.stderr.on("data", data => {
console.error("post create script:", data.toString());
ERROR(">\t post create script:", data.toString());
});

cp.on("close", code => {
console.log("post create script exited with code:", code);
INFO(">\t post create script exited with code:", code);
});
});
});
109 changes: 59 additions & 50 deletions databaseOperations.js
Original file line number Diff line number Diff line change
@@ -1,85 +1,94 @@
const sqlite = require('sqlite3').verbose();
const path = require('path');
const sqlite = require("sqlite3").verbose();
const path = require("path");

import { checkEnvironmentVariables } from './utils';
import { checkEnvironmentVariables, DEBUG, WARN, INFO, ERROR } from "./utils";

checkEnvironmentVariables();

const {
CAN_TRACKER_PATH: DB_PATH
} = process.env;
const { CAN_TRACKER_PATH: DB_PATH } = process.env;

function getDatabase() {
return new sqlite.Database(path.join(DB_PATH, 'trackedTorrents.db'));
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) {
console.warn(`Torrent with infoHash ${infoHash} is already tracked!`);
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) {
console.error(`Couldn't add torrent with info_hash: ${infoHash} to tracking database!`);
console.error(err);
return reject(err);
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();
}
console.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) {
console.error('Something happened while running DB query!');
console.error(err);
reject(err);
return;
}

if (row === undefined) {
// We're not tracking this torrent
resolve(false);
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);
}
resolve(true);
});
})
);
});
}

export function createAndInitDatabase() {
const db = getDatabase();

return new Promise((resolve, reject) => {
db.run(`CREATE TABLE IF NOT EXISTS tracked_torrents (
db.run(
`CREATE TABLE IF NOT EXISTS tracked_torrents (
info_hash TEXT PRIMARY KEY
)`, [], (err) => {
if (err !== null) {
console.error('Something happened during DB creation!');
console.error(err);
reject(err);
return;
)`,
[],
err => {
if (err !== null) {
ERROR("Something happened during DB creation!");
DEBUG(err);
reject(err);
return;
}
db.close();
resolve(1);
}
db.close();
resolve(1);
});
})
);
});
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"assert-env": "^0.6.0",
"bittorrent-tracker": "^9.14.4",
"can-mktorrent": "^1.0.9",
"chalk": "^3.0.0",
"esm": "^3.2.25",
"minimist": "^1.2.0",
"parse-torrent": "^7.0.1",
Expand Down
4 changes: 2 additions & 2 deletions scripts/postinstall.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env node
const { wrapBinaryCommands } = require("./wrapBinaryCommands");
const { INFO } = require("./utils");

Promise.all([wrapBinaryCommands()]).then(() => {
console.log("Done settin up");
INFO("Finished post installation!");
});

6 changes: 3 additions & 3 deletions scripts/wrapBinaryCommands.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
const packageInfo = require("../package.json");
const fs = require("fs").promises;
const path = require("path");
const { INFO } = require("utils");

const WRAPPER_CONTENT = fileName => `#!/usr/bin/env node
const path = require('path');
require = require('esm')(module);
console.log(module.path);
module.exports = require(path.join(module.path, '..', '${fileName}'));
`;

Expand All @@ -23,8 +23,8 @@ export async function wrapBinaryCommands() {
});
});

console.info("Creating wrapper bin files under ./bin/.build/");
INFO("Creating wrapper bin files under ./bin/.build/");
Promise.all(promises).then(() => {
console.info("Successfully finished wrapping binary commands");
INFO("Successfully finished wrapping binary commands");
});
}
12 changes: 11 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const mkt = require('can-mktorrent');
const mkt = require("can-mktorrent");
/*
mkt({
announceUrls: ["http://detemps.theia.feralhosting.com/cantracker/announce"],
comment: "created by can-mktorrent",
Expand All @@ -9,4 +10,13 @@ mkt({
}).then(() => {
console.log("here");
});
*/

const { DEBUG, INFO, ERROR } = require("./utils");
const util = require("util");

DEBUG("debug information");

INFO("normal information");

ERROR("error information");
46 changes: 23 additions & 23 deletions tracker.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,38 @@
import { Server } from 'bittorrent-tracker';
import { checkTorrentIsTracked} from "./databaseOperations";

const {
CAN_TRACKER_PORT: PORT
} = process.env;
import { Server } from "bittorrent-tracker";
import { checkTorrentIsTracked } from "./databaseOperations";
import { ERROR, INFO } from "./utils";

const { CAN_TRACKER_PORT: PORT } = process.env;

function filterTorrents(infoHash, params, cb) {
return checkTorrentIsTracked(infoHash).then(isTracked => {
if (isTracked) {
cb(null);
} else {
cb(new Error('Untracked torrent file'));
}
}).catch(err => {
cb(new Error(err));
});
return checkTorrentIsTracked(infoHash)
.then(isTracked => {
if (isTracked) {
cb(null);
} else {
cb(new Error("Untracked torrent file"));
}
})
.catch(err => {
DEBUG("Error responding to announce!", err);
cb(new Error("Server error"));
});
}


export function startServer() {
const server = new Server({
filter: filterTorrents,
trustProxy: false,
trustProxy: false
});

server.on('error', err => {
console.error(err);
server.on("error", err => {
ERROR(err);
});

server.on('listening', () => {
console.info('listening on http port:', server.http.address().port);
console.info('listening on udp port:', server.udp.address().port);
server.on("listening", () => {
INFO("listening on http port:", server.http.address().port);
INFO("listening on udp port:", server.udp.address().port);
});

server.listen(PORT);
};
}
Loading

0 comments on commit 0751987

Please sign in to comment.