Skip to content

Commit

Permalink
chore: move all currency data ops to backend
Browse files Browse the repository at this point in the history
  • Loading branch information
zunderscore committed Dec 30, 2024
1 parent 6086469 commit 63c4a16
Show file tree
Hide file tree
Showing 11 changed files with 183 additions and 174 deletions.
2 changes: 1 addition & 1 deletion src/backend/app-management/electron/events/when-ready.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ exports.whenReady = async () => {

windowManagement.updateSplashScreenStatus("Loading currencies...");
const currencyAccess = require("../../../currency/currency-access").default;
currencyAccess.refreshCurrencyCache();
currencyAccess.loadCurrencies();

windowManagement.updateSplashScreenStatus("Loading ranks...");
const viewerRanksManager = require("../../../ranks/rank-manager");
Expand Down
133 changes: 119 additions & 14 deletions src/backend/currency/currency-access.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { FirebotViewer } from "../../types/viewers";
import EventEmitter from "events";
import { JsonDB } from "node-json-db";

import { FirebotViewer } from "../../types/viewers";
import logger from "../logwrapper";
import frontendCommunicator from "../common/frontend-communicator";
import { SettingsManager } from "../common/settings-manager";
Expand All @@ -15,7 +17,7 @@ export type Currency = {
payout: number;

/** Offline payout */
offline: number;
offline?: number | string;

/** Maps user role IDs to the amount of bonus payout they receive. */
bonus: Record<string, number>;
Expand All @@ -25,42 +27,69 @@ type CurrencyCache = {
[currencyName: string]: Currency
};

class CurrencyAccess {
class CurrencyAccess extends EventEmitter {
private _currencyCache: CurrencyCache = {};

constructor() {
// Refresh Currency Cache
// This gets a message from front end when a currency needs to be created.
// This is also triggered in the currencyManager.
frontendCommunicator.on("refresh-currency-cache", () => {
this.refreshCurrencyCache();
super();

frontendCommunicator.on("currencies:get-currencies", () => {
return this.getCurrencies();
});

frontendCommunicator.on("currencies:get-currency-by-id", (currencyId: string) => {
return this.getCurrencyById(currencyId);
});

frontendCommunicator.on("currencies:get-currency-by-name", (currencyName: string) => {
return this.getCurrencyByName(currencyName);
});

frontendCommunicator.on("currencies:create-currency", (currency: Currency) => {
this.createCurrency(currency);
});

frontendCommunicator.on("currencies:update-currency", (currency: Currency) => {
this.updateCurrency(currency);
});

frontendCommunicator.on("currencies:delete-currency", (currency: Currency) => {
this.deleteCurrency(currency);
});
}

isViewerDBOn(): boolean {
return SettingsManager.getSetting("ViewerDB");
}

refreshCurrencyCache(): void {
getCurrencyDb(): JsonDB {
return profileManager.getJsonDbInProfile("/currency/currency");
}

loadCurrencies(): void {
if (this.isViewerDBOn() !== true) {
return;
}

logger.debug("Refreshing currency cache");
const db = profileManager.getJsonDbInProfile("/currency/currency");
const db = this.getCurrencyDb();

let resaveCurrencies = false;
const cache: CurrencyCache = db.getData("/");

let issue2801 = false;
const cache = db.getData("/");
Object.keys(cache).forEach((currencyId) => {
if (cache[currencyId].offline === null || cache[currencyId].offline === "") {
issue2801 = true;
resaveCurrencies = true;
cache[currencyId].offline = undefined;
}
});
if (issue2801) {

if (resaveCurrencies) {
db.push("/", cache);
}

this._currencyCache = cache;
frontendCommunicator.send("currencies:currencies-updated", this.getCurrencies());
}

getCurrencies(): CurrencyCache {
Expand Down Expand Up @@ -94,6 +123,82 @@ class CurrencyAccess {

return viewer;
}

importCurrency(currency: Currency) {
if (this.isViewerDBOn() !== true) {
return;
}

if (currency == null || currency.id == null) {
return;
}

if (!currency.offline) {
currency.offline = undefined;
}

if (this.getCurrencyById(currency.id)) {
this.updateCurrency(currency);
} else {
let hasDuplicate = false;
let counter = 1;
let name = currency.name;
do {
hasDuplicate = Object.values(this.getCurrencies())
.some(c => c.name === name);
if (hasDuplicate) {
name = currency.name + counter;
counter++;
}
} while (hasDuplicate);
currency.name = name;

this.createCurrency(currency);
}
}

createCurrency(currency: Currency) {
if (this.isViewerDBOn() !== true) {
return false;
}

if (Object.values(this._currencyCache).some(c => c.name === currency.name)) {
logger.error(`User tried to create currency with the same name as another currency: ${currency.name}.`);
return false;
}

this._currencyCache[currency.id] = currency;
this.saveAllCurrencies();
this.emit("currencies:currency-created", currency);

logger.debug(`Currency created with name: ${currency.name}`);
return true;
}

updateCurrency(currency: Currency) {
if (this.isViewerDBOn() !== true) {
return;
}

this._currencyCache[currency.id] = currency;
this.saveAllCurrencies();
this.emit("currencies:currency-updated", currency);
}

deleteCurrency(currency: Currency) {
if (this.isViewerDBOn() !== true) {
return;
}

delete this._currencyCache[currency.id];
this.saveAllCurrencies();
this.emit("currencies:currency-deleted", currency);
}

private saveAllCurrencies() {
this.getCurrencyDb().push("/", this._currencyCache);
frontendCommunicator.send("currencies:currencies-updated", this.getCurrencies());
}
}

const currencyAccess = new CurrencyAccess();
Expand Down
31 changes: 13 additions & 18 deletions src/backend/currency/currency-command-manager.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,31 @@
import { SystemCommand } from "../../types/commands";

import currencyAccess from "./currency-access";
import currencyAccess, { Currency } from "./currency-access";
import currencyManager from "./currency-manager";
import commandManager from "../chat/commands/command-manager";
import logger from "../logwrapper";
import frontendCommunicator from "../common/frontend-communicator";
import util from "../utility";

interface BasicCurrency {
id: string;
name: string;
}

type CurrencyCommandRefreshRequestAction = "create" | "update" | "delete";

interface CurrencyCommandRefreshRequest {
action: CurrencyCommandRefreshRequestAction;
currency: BasicCurrency;
}

class CurrencyCommandManager {
constructor() {
// Refresh our currency commands.
frontendCommunicator.on("refreshCurrencyCommands", (request: CurrencyCommandRefreshRequest) => {
this.refreshCurrencyCommands(request.action, request.currency);
currencyAccess.on("currencies:currency-created", (currency: Currency) => {
this.refreshCurrencyCommands("create", currency);
});

currencyAccess.on("currencies:currency-updated", (currency: Currency) => {
this.refreshCurrencyCommands("update", currency);
});

currencyAccess.on("currencies:currency-deleted", (currency: Currency) => {
this.refreshCurrencyCommands("delete", currency);
});
}

/**
* Creates a command definition when given a currency name.
*/
createCurrencyCommandDefinition(currency: BasicCurrency): SystemCommand<{
createCurrencyCommandDefinition(currency: Partial<Currency>): SystemCommand<{
currencyBalanceMessageTemplate: string;
whisperCurrencyBalanceMessage: boolean;
addMessageTemplate: string;
Expand Down Expand Up @@ -438,7 +433,7 @@ class CurrencyCommandManager {
*/
refreshCurrencyCommands(
action: CurrencyCommandRefreshRequestAction = null,
currency: BasicCurrency = null
currency: Partial<Currency> = null
): void {
// If we don't get currency stop here.
if (currency == null) {
Expand Down
37 changes: 13 additions & 24 deletions src/backend/currency/currency-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,20 @@ class CurrencyManager {
private _currencyInterval: NodeJS.Timeout;

constructor() {
// Create Currency Event
// This gets a message from front end when a currency needs to be created.
frontendCommunicator.onAsync("create-currency", async (currencyId: string) => {
currencyAccess.on("currencies:currency-created", async (currency: Currency) => {
if (currencyAccess.isViewerDBOn() !== true) {
return;
}
logger.info(`Creating a new currency with id ${currencyId}`);
await this.addCurrencyToAllViewers(currencyId, 0);
logger.info(`Creating a new currency with id ${currency.id}`);
await this.addCurrencyToAllViewers(currency.id, 0);
});

currencyAccess.on("currencies:currency-deleted", async (currency: Currency) => {
if (currencyAccess.isViewerDBOn() !== true) {
return;
}
logger.info(`Deleting currency with id ${currency.id}`);
await this.deleteCurrencyById(currency.id);
});

frontendCommunicator.onAsync("give-currency", async ({
Expand Down Expand Up @@ -81,30 +87,13 @@ class CurrencyManager {

// Purge Currency Event
// This gets a message from front end when a currency needs to be purged.
frontendCommunicator.onAsync("purge-currency", async (currencyId: string) => {
frontendCommunicator.onAsync("currencies:purge-currency", async (currencyId: string) => {
if (currencyAccess.isViewerDBOn() !== true) {
return;
}
logger.info(`Purging currency with id ${currencyId}`);
await this.purgeCurrencyById(currencyId);
});

// Delete Currency Event
// This gets a message from front end when a currency needs to be deleted
frontendCommunicator.onAsync("delete-currency", async (currencyId: string) => {
if (currencyAccess.isViewerDBOn() !== true) {
return;
}
logger.info(`Deleting currency with id ${currencyId}`);
await this.deleteCurrencyById(currencyId);
});


// Start up our currency timers.
// Also fired in currency-access.
frontendCommunicator.on("refresh-currency-cache", () => {
this.startTimer();
});
}

/**
Expand Down Expand Up @@ -267,7 +256,7 @@ class CurrencyManager {
continue;
}

basePayout = currency.offline;
basePayout = currency.offline as number;
}

const currentMinutes = DateTime.utc().minute;
Expand Down
2 changes: 1 addition & 1 deletion src/backend/database/currencyDatabase.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const currencyAccess = require("../currency/currency-access").default;
const currencyManager = require("../currency/currency-manager");

exports.isViewerDBOn = () => currencyAccess.isViewerDBOn();
exports.refreshCurrencyCache = () => currencyAccess.refreshCurrencyCache();
exports.refreshCurrencyCache = () => currencyAccess.loadCurrencies();
exports.addCurrencyToNewUser = viewer => currencyAccess.addCurrencyToNewViewer(viewer);
exports.getCurrencies = () => currencyAccess.getCurrencies();
exports.getCurrencyById = id => currencyAccess.getCurrencyById(id);
Expand Down
2 changes: 1 addition & 1 deletion src/backend/effects/builtin/currency.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ const currency = {
$scope.currencies = currencyService.getCurrencies();

$scope.getCurrencyName = function(currencyId) {
const currency = currencyService.getCurrencies(currencyId);
const currency = currencyService.getCurrency(currencyId);
return currency.name;
};

Expand Down
7 changes: 4 additions & 3 deletions src/backend/import/setups/setup-importer.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const quickActionManager = require("../../quick-actions/quick-action-manager");
const variableMacroManager = require("../../variables/macro-manager");
const rankManager = require("../../ranks/rank-manager");
const { escapeRegExp } = require("../../utility");
const currencyAccess = require("../../currency/currency-access").default;

function findAndReplaceCurrency(data, currency) {
const entries = Object.entries(data);
Expand Down Expand Up @@ -105,7 +106,7 @@ async function importSetup(setup, selectedCurrency) {
// currencies
const currencies = setup.components.currencies || [];
for (const currency of currencies) {
frontendCommunicator.send("import-currency", currency);
currencyAccess.importCurrency(currency);
}

// effect queues
Expand Down Expand Up @@ -209,7 +210,7 @@ async function importSetup(setup, selectedCurrency) {
function removeSetupComponents(components) {
Object.entries(components)
.forEach(([componentType, componentList]) => {
componentList.forEach(({id, name}) => {
componentList.forEach((id) => {
switch (componentType) {
case "commands":
commandManager.deleteCustomCommand(id);
Expand All @@ -218,7 +219,7 @@ function removeSetupComponents(components) {
countersManager.deleteItem(id);
break;
case "currencies":
frontendCommunicator.send("remove-currency", { id, name });
currencyAccess.deleteCurrency(id);
break;
case "effectQueues":
effectQueueManager.deleteItem(id);
Expand Down
Loading

0 comments on commit 63c4a16

Please sign in to comment.