Skip to content

Commit

Permalink
Fix some runtime errors
Browse files Browse the repository at this point in the history
  • Loading branch information
mmgoodnow committed Dec 28, 2021
1 parent 0a10f76 commit 4b7996f
Show file tree
Hide file tree
Showing 11 changed files with 75 additions and 54 deletions.
23 changes: 19 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions package.json
Expand Up @@ -9,7 +9,10 @@
"prepare": "rimraf dist && npm run build && husky install"
},
"bin": {
"cross-seed": "dist/src/cmd.js"
"cross-seed": "dist/cmd.js"
},
"engines": {
"node": ">=14"
},
"files": [
"dist/"
Expand All @@ -26,7 +29,7 @@
"chalk": "^5.0.0",
"commander": "^8.3.0",
"form-data": "^4.0.0",
"lodash": "^4.17.21",
"lodash-es": "^4.17.21",
"lowdb": "^3.0.0",
"node-fetch": "^3.1.0",
"parse-torrent": "^9.1.3",
Expand Down
13 changes: 6 additions & 7 deletions src/cmd.ts
@@ -1,8 +1,7 @@
#!/usr/bin/env node
import chalk from "chalk";
import { Option, program } from "commander";
// @ts-expect-error json imports are experimental
import packageDotJson from "../package.json.js";
import { inspect } from "util";
import { generateConfig, getFileConfig } from "./configuration.js";
import { Action } from "./constants.js";
import { dropDatabase } from "./db.js";
Expand All @@ -11,15 +10,15 @@ import { initializeLogger, Label, logger } from "./logger.js";
import { main } from "./pipeline.js";
import {
initializePushNotifier,
pushNotifier,
sendTestNotification,
} from "./pushNotifier.js";
import { setRuntimeConfig } from "./runtimeConfig.js";
import { serve } from "./server.js";
import { inspect } from "util";
import "./signalHandlers";

import "./signalHandlers.js";
import { doStartupValidation } from "./startup.js";
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const packageDotJson = require("../package.json");

function fallback(...args) {
for (const arg of args) {
Expand All @@ -34,7 +33,7 @@ function processOptions(options) {
}

async function run() {
const fileConfig = getFileConfig();
const fileConfig = await getFileConfig();

function createCommandWithSharedOptions(name, description) {
return program
Expand Down
20 changes: 10 additions & 10 deletions src/configuration.ts
@@ -1,10 +1,11 @@
import chalk from "chalk";
import fs from "fs";
import { copyFileSync, existsSync, mkdirSync } from "fs";
import path from "path";
// @ts-ignore
import packageDotJson from "../package.json.js";
import configTemplate from "./config.template.js";
import { Action, CONFIG_TEMPLATE_URL } from "./constants.js";
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const packageDotJson = require("../package.json");

interface FileConfig {
action?: Action;
Expand Down Expand Up @@ -39,8 +40,8 @@ export function appDir(): string {
}

export function createAppDir(): void {
fs.mkdirSync(path.join(appDir(), "torrent_cache"), { recursive: true });
fs.mkdirSync(path.join(appDir(), "logs"), { recursive: true });
mkdirSync(path.join(appDir(), "torrent_cache"), { recursive: true });
mkdirSync(path.join(appDir(), "logs"), { recursive: true });
}

export function generateConfig({
Expand All @@ -53,11 +54,11 @@ export function generateConfig({
__dirname,
`config.template${docker ? ".docker" : ""}.js`
);
if (!force && fs.existsSync(dest)) {
if (!force && existsSync(dest)) {
console.log("Configuration file already exists.");
return;
}
fs.copyFileSync(templatePath, dest);
copyFileSync(templatePath, dest);
console.log("Configuration file created at", chalk.yellow.bold(dest));
}

Expand All @@ -72,12 +73,11 @@ function printUpdateInstructions(missingKeys) {
`);
}

export function getFileConfig(): FileConfig {
export async function getFileConfig(): Promise<FileConfig> {
const configPath = path.join(appDir(), "config.js");

try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const fileConfig = require(configPath);
const fileConfig = (await import(configPath)).default;
const { configVersion = 0 } = fileConfig;
if (configVersion < configVersion) {
const missingKeys = Object.keys(configTemplate).filter(
Expand Down
7 changes: 4 additions & 3 deletions src/db.ts
@@ -1,7 +1,7 @@
import { unlinkSync } from "fs";
import { JSONFileSync, LowSync } from "lowdb";
import path from "path";
import { sync as rimrafSync } from "rimraf";
import rimraf from "rimraf";
import { appDir, createAppDir } from "./configuration.js";
import { Decision } from "./constants.js";

Expand Down Expand Up @@ -44,20 +44,21 @@ const emptyDatabase = {
dbVersion: 3,
};

db.data ??= emptyDatabase;

const dbVersion = db.data.dbVersion;

if (!dbVersion || dbVersion < emptyDatabase.dbVersion) {
db.data = emptyDatabase;
}

db.data ??= emptyDatabase;
db.write();

export function dropDatabase(): void {
db.data = emptyDatabase;
db.write();
unlinkSync(path.join(appDir(), "cache.json"));
rimrafSync(path.join(appDir(), "torrent_cache"));
rimraf.rimrafSync(path.join(appDir(), "torrent_cache"));
}

export default db;
36 changes: 18 additions & 18 deletions src/logger.ts
@@ -1,5 +1,5 @@
import { join } from "path";
import { createLogger, format, Logger, transports } from "winston";
import winston from "winston";
import { appDir, createAppDir } from "./configuration.js";
import { getRuntimeConfig } from "./runtimeConfig.js";

Expand All @@ -14,7 +14,7 @@ export enum Label {
STARTUP = "startup",
}

export let logger: Logger;
export let logger: winston.Logger;

const redactionMsg = "[REDACTED]";

Expand Down Expand Up @@ -51,40 +51,40 @@ function redactMessage(message) {

export function initializeLogger(): void {
createAppDir();
logger = createLogger({
logger = winston.createLogger({
level: "info",
format: format.combine(
format.timestamp({
format: winston.format.combine(
winston.format.timestamp({
format: "YYYY-MM-DD HH:mm:ss",
}),
format.errors({ stack: true }),
format.splat(),
format.colorize(),
format.printf(({ level, message, label, timestamp }) => {
winston.format.errors({ stack: true }),
winston.format.splat(),
winston.format.colorize(),
winston.format.printf(({ level, message, label, timestamp }) => {
return `${timestamp} ${level}: ${
label ? `[${label}] ` : ""
}${redactMessage(message)}`;
})
),
transports: [
new transports.File({
new winston.transports.File({
filename: join(appDir(), "logs", "error.log"),
level: "error",
}),
new transports.File({
new winston.transports.File({
filename: join(appDir(), "logs", "info.log"),
}),
new transports.File({
new winston.transports.File({
filename: join(appDir(), "logs", "verbose.log"),
level: "silly",
}),
new transports.Console({
new winston.transports.Console({
level: getRuntimeConfig().verbose ? "silly" : "info",
format: format.combine(
format.errors({ stack: true }),
format.splat(),
format.colorize(),
format.printf(({ level, message, label }) => {
format: winston.format.combine(
winston.format.errors({ stack: true }),
winston.format.splat(),
winston.format.colorize(),
winston.format.printf(({ level, message, label }) => {
return `${level}: ${
label ? `[${label}] ` : ""
}${redactMessage(message)}`;
Expand Down
2 changes: 1 addition & 1 deletion src/preFilter.ts
@@ -1,4 +1,4 @@
import { uniqBy } from "lodash";
import { uniqBy } from "lodash-es";
import { Metafile } from "parse-torrent";
import path from "path";
import { EP_REGEX, EXTENSIONS } from "./constants.js";
Expand Down
2 changes: 1 addition & 1 deletion src/searchee.ts
@@ -1,4 +1,4 @@
import { sortBy } from "lodash";
import { sortBy } from "lodash-es";
import { Metafile } from "parse-torrent";
import path, { join } from "path";
import { getRuntimeConfig } from "./runtimeConfig.js";
Expand Down
2 changes: 1 addition & 1 deletion src/server.ts
@@ -1,5 +1,5 @@
import http from "http";
import { pick } from "lodash";
import { pick } from "lodash-es";
import { parse as qsParse } from "querystring";
import { inspect } from "util";
import { Label, logger } from "./logger.js";
Expand Down
15 changes: 9 additions & 6 deletions src/torrent.ts
@@ -1,7 +1,7 @@
import fs, { promises as fsPromises } from "fs";
import parseTorrent, { Metafile } from "parse-torrent";
import path from "path";
import { concat } from "simple-get";
import simpleGet from "simple-get";
import { inspect } from "util";
import db from "./db.js";
import { CrossSeedError } from "./errors.js";
Expand All @@ -26,11 +26,14 @@ export async function parseTorrentFromURL(url: string): Promise<Metafile> {
let response;
try {
response = await new Promise((resolve, reject) => {
concat({ url, followRedirects: false }, (err, res, data) => {
if (err) return reject(err);
res.data = data;
return resolve(res);
});
simpleGet.concat(
{ url, followRedirects: false },
(err, res, data) => {
if (err) return reject(err);
res.data = data;
return resolve(res);
}
);
});
} catch (e) {
logger.error(`failed to access ${url}`);
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Expand Up @@ -3,7 +3,7 @@
"outDir": "./dist",
"allowJs": true,
"target": "es2019",
"module": "node12",
"module": "nodenext",
"esModuleInterop": true,
"resolveJsonModule": true,
"sourceMap": true
Expand Down

0 comments on commit 4b7996f

Please sign in to comment.