Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update code #133

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 53 additions & 99 deletions server/index.js
Original file line number Diff line number Diff line change
@@ -1,108 +1,62 @@
import { toConsole } from "../src/utils/log.js";

toConsole("setup", "Setting up server...");

// Support require
import { createRequire } from "module";
const require = createRequire(import.meta.url);

// Attempt to read .env file
// If it doesn't exist, create an .env file with example.env information
toConsole("setup", "Looking for .env file...");
const fs = require("fs");
var firstRun = true;
function readEnvironmentFile(firstRun) {
let environmentFile = "";
try {
environmentFile = fs.readFileSync("config/.env", { encoding: "utf8", flag: "r" });
if (environmentFile == "") throw new Error(".env file empty!");
if (firstRun) toConsole("info", ".env file found! Attempting to read...");
} catch {
if (firstRun) toConsole("info", ".env file not found! Creating a new one...");
environmentFile = fs.readFileSync("config/example.env", { encoding: "utf8", flag: "r" });
fs.writeFileSync("config/.env", environmentFile);
}
return environmentFile;
}
readEnvironmentFile(firstRun);
firstRun = false;

// Import stuff
toConsole("setup", "Importing important stuff...");
const { parse, stringify } = require("envfile");
var open = require("open");
var express = require("express");
var path = require("path");
var cors = require("cors");
var app = express();
import { readFileSync, writeFileSync } from "fs";
import express from "express";
import { parse, stringify } from "envfile";
import { resolve } from "path";
import open from "open";

// Setup express with CORS on port 3250
toConsole("setup", "Starting server...");
app.use(cors());
app.options("*", cors());
app.listen(3250, "0.0.0.0", listening);

function listening() {
toConsole("setup", "Server started!");
const require = createRequire(import.meta.url);
const app = express();
const port = 3250;
const envFile = "config/.env";
const exampleEnvFile = "config/example.env";
const configFile = "config/config.json";

// Attempt to read .env file, if it doesn't exist, create an .env file with example.env information
let environmentFile = "";
try {
environmentFile = readFileSync(envFile, { encoding: "utf8", flag: "r" });
if (environmentFile === "") throw new Error(".env file empty!");
toConsole("info", ".env file found! Attempting to read...");
} catch {
toConsole("info", ".env file not found! Creating a new one...");
environmentFile = readFileSync(exampleEnvFile, { encoding: "utf8", flag: "r" });
writeFileSync(envFile, environmentFile);
}

app.use(express.static("public"));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

/*
Setup routes
*/
toConsole("setup", "Setting up routes...");

// index.html: https://localhost:3250/
app.get("/", getPage);
function getPage(request, response) {
response.sendFile(path.join(path.resolve() + "/server/index.html"));
}

// GET .env: https://localhost:3250/env
app.get("/env", getEnvironment);
function getEnvironment(request, response) {
let environmentFile = readEnvironmentFile(firstRun);
response.send(parse(environmentFile));
}

// POST .env: https://localhost:3250/env
app.post("/env", postEnvironment);
function postEnvironment(request, response) {
toConsole("info", "Settings received! Saving to .env...");
let environmentSettings = stringify(request.body);

fs.writeFile("config/.env", environmentSettings, "utf8", function (error) {
if (error) {
response.status(400).send({ error: "Error writing .env" });
} else {
response.send({ message: "Successfully saved .env" });
}
});
}

// GET config.json: https://localhost:3250/config
app.get("/config", getSettings);
function getSettings(request, response) {
response.sendFile(path.join(path.resolve() + "/config/config.json"));
}

// POST config.json: https://localhost:3250/config
app.post("/config", postSettings);
function postSettings(request, response) {
toConsole("info", "Settings received! Saving to config.json...");
let settings = JSON.stringify(request.body, undefined, 4);

fs.writeFile("config/config.json", settings, "utf8", function (error) {
if (error) {
response.status(400).send({ error: "Error writing config.json" });
} else {
response.send({ message: "Successfully saved config.json" });
}
});
}

toConsole("info", "Opening settings page on http://localhost:3250/...");
open("http://localhost:3250/");
// Setup routes
app.get("/", (req, res) => {
res.sendFile(resolve() + "/server/index.html");
});

app.get("/env", (req, res) => {
res.send(parse(environmentFile));
});

app.post("/env", (req, res) => {
const environmentSettings = stringify(req.body);
writeFileSync(envFile, environmentSettings, "utf8");
res.send({ message: "Successfully saved .env" });
});

app.get("/config", (req, res) => {
res.sendFile(resolve() + "/config/config.json");
});

app.post("/config", (req, res) => {
const settings = JSON.stringify(req.body, undefined, 4);
writeFileSync(configFile, settings, "utf8");
res.send({ message: "Successfully saved config.json" });
});

// Start server
app.listen(port, "0.0.0.0", () => {
toConsole("setup", `Server started on port ${port}`);
toConsole("info", `Opening settings page on http://localhost:${port}/...`);
open(`http://localhost:${port}/`);
});
85 changes: 42 additions & 43 deletions src/item.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,62 +6,61 @@ export default class Item {
this.url = url;
this.notificationSent = false;
this.shouldSendNotification = true;
this.html = undefined;
this.html = null;
this.info = {
title: undefined,
inventory: undefined,
image: undefined,
title: null,
inventory: null,
image: null,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please tell me whether this makes any difference or the reason this was changed.

};
}

/*
Fetches the item page and assigns the html to this.html
Returns a promise of true if successful, false otherwise
*/
async getPage(store, use_proxies, badProxies) {
const response = await fetchPage(this.url, store, use_proxies, badProxies);
switch (response.status) {
case "ok":
this.html = response.html;
return {
status: "ok",
};
/**
* Fetches the item page and assigns the html to this.html
* Returns a promise of an object with status and badProxies keys
*/
async getPage(store, useProxies, badProxies) {
const { status, html, error, badProxies: responseBadProxies } = await fetchPage(
this.url,
store,
useProxies,
badProxies
);

case "retry":
this.html = response.html;
return {
status: "retry",
bad_proxies: response.badProxies,
};

case "error":
this.html = response.html;
toFile(store, response.error, this);
return {
status: "error",
};
this.html = html;
if (status === "error") {
toFile(store, error, this);
}

return { status, badProxies: responseBadProxies };
}

/*
Extract item information based on the passed callback function and assigns it to this.info
Returns true if successful, false otherwise
*/
/**
* Extract item information based on the passed callback function and assigns it to this.info
* Returns a boolean indicating success or failure
*/
async extractInformation(store, storeFunction) {
const info = await storeFunction(this.html);
if (info.title && info.image && typeof info.inventory == "boolean") {
// Change notification status to false once item goes out of stock
if (this.notificationSent && !info.inventory) this.notificationSent = false;

this.shouldSendNotification = !this.info.inventory && info.inventory; // Check change in item stock
this.info = info;
return true;
} else if (info.error) {
toFile(store, info.error, this);
return false;
} else {
if (!info.title || !info.image || typeof info.inventory !== "boolean") {
toFile(store, "Unable to get information", Object.assign(this, info));
return false;
}

const { title, image, inventory } = info;
const { inventory: currentInventory } = this.info;

if (this.notificationSent && !inventory) {
this.notificationSent = false;
}

this.shouldSendNotification = !currentInventory && inventory;
this.info = { title, image, inventory };

if (info.error) {
toFile(store, info.error, this);
return false;
}

return true;
}
}