import { randomBytes } from "crypto";
|
|
import { promisify } from "util";
|
|
import DiscordBot from "./services/DiscordBot";
|
|
import Service from "./services/Service";
|
|
import TorrentClientIpc from "./services/TorrentClientIpc";
|
|
import WebServer from "./services/WebServer";
|
|
import { User, RegisterToken } from "./database/entities";
|
|
import Database from "./services/Database";
|
|
|
|
/**
|
|
* @TODO Not sure where to put this yet... here's fine for now
|
|
*/
|
|
async function createRegisterToken() {
|
|
let randomBytesPromise = promisify(randomBytes);
|
|
let token = new RegisterToken();
|
|
token.token = (await randomBytesPromise(48)).toString("hex");
|
|
await token.save();
|
|
return token;
|
|
}
|
|
|
|
/**
|
|
* The main application class
|
|
*/
|
|
export default class Application
|
|
{
|
|
/**
|
|
* All available services
|
|
*/
|
|
protected services: Service[];
|
|
|
|
/**
|
|
* The database service
|
|
*/
|
|
protected database!: Database;
|
|
|
|
/**
|
|
* The discord bot service
|
|
*/
|
|
protected discord!: DiscordBot;
|
|
|
|
/**
|
|
* The webserver service
|
|
*/
|
|
protected web!: WebServer;
|
|
|
|
/**
|
|
* The torrent client service
|
|
*/
|
|
protected torrent!: TorrentClientIpc;
|
|
|
|
/**
|
|
* Create a new application instance
|
|
*/
|
|
public constructor() {
|
|
this.services = [
|
|
this.database = new Database(this),
|
|
// this.discord = new DiscordBot(this),
|
|
this.web = new WebServer(this),
|
|
// this.torrent = new TorrentClientIpc(this)
|
|
]
|
|
|
|
// this.torrent.logging = false;
|
|
}
|
|
|
|
/**
|
|
* Boot all of the services
|
|
*/
|
|
protected async boot() {
|
|
return Promise.all(this.services.map(service => service.boot()));
|
|
}
|
|
|
|
/**
|
|
* Initialize the application if necessary
|
|
*/
|
|
protected async initialize() {
|
|
let numUsers = await User.count();
|
|
if (numUsers == 0) {
|
|
console.log("Found 0 users");
|
|
let token = await RegisterToken.findOne();
|
|
if (token === undefined) {
|
|
token = await createRegisterToken();
|
|
}
|
|
console.log("First time register with: ", token.token);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Shutdown the application
|
|
*/
|
|
protected shutdown() {
|
|
return Promise.all(this.services.map(service => service.shutdown()));
|
|
}
|
|
|
|
/**
|
|
* Start the application
|
|
*/
|
|
public async start() {
|
|
await this.boot();
|
|
await this.initialize();
|
|
this.services.forEach(service => service.start());
|
|
}
|
|
|
|
/**
|
|
* Quit the application
|
|
*/
|
|
public async quit(code: number = 0) {
|
|
await this.shutdown();
|
|
process.exit(code);
|
|
}
|
|
}
|