rename modules as plugins

This commit is contained in:
Freddie
2020-05-16 09:25:19 +01:00
parent 0db481305b
commit 83839fd24e
35 changed files with 734 additions and 614 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,8 @@
.logo {
margin-right: 0.3em;
}
aside {
overflow-y: auto;
overflow-x: hidden;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,67 @@
/* Aside: submenus toggle */
Array.from(document.getElementsByClassName('menu is-menu-main')).forEach(el => {
Array.from(el.getElementsByClassName('has-dropdown-icon')).forEach(elA => {
elA.addEventListener('click', e => {
const dropdownIcon = e.currentTarget
.getElementsByClassName('dropdown-icon')[0]
.getElementsByClassName('mdi')[0];
e.currentTarget.parentNode.classList.toggle('is-active');
dropdownIcon.classList.toggle('mdi-plus');
dropdownIcon.classList.toggle('mdi-minus');
});
});
});
/* Aside Mobile toggle */
Array.from(document.getElementsByClassName('jb-aside-mobile-toggle')).forEach(el => {
el.addEventListener('click', e => {
const dropdownIcon = e.currentTarget
.getElementsByClassName('icon')[0]
.getElementsByClassName('mdi')[0];
document.documentElement.classList.toggle('has-aside-mobile-expanded');
dropdownIcon.classList.toggle('mdi-forwardburger');
dropdownIcon.classList.toggle('mdi-backburger');
});
});
/* NavBar menu mobile toggle */
Array.from(document.getElementsByClassName('jb-navbar-menu-toggle')).forEach(el => {
el.addEventListener('click', e => {
const dropdownIcon = e.currentTarget
.getElementsByClassName('icon')[0]
.getElementsByClassName('mdi')[0];
document
.getElementById(e.currentTarget.getAttribute('data-target'))
.classList.toggle('is-active');
dropdownIcon.classList.toggle('mdi-dots-vertical');
dropdownIcon.classList.toggle('mdi-close');
});
});
/* Modal: open */
Array.from(document.getElementsByClassName('jb-modal')).forEach(el => {
el.addEventListener('click', e => {
const modalTarget = e.currentTarget.getAttribute('data-target');
document.getElementById(modalTarget).classList.add('is-active');
document.documentElement.classList.add('is-clipped');
});
});
/* Modal: close */
Array.from(document.getElementsByClassName('jb-modal-close')).forEach(el => {
el.addEventListener('click', e => {
e.currentTarget.closest('.modal').classList.remove('is-active');
document.documentElement.classList.remove('is-clipped');
});
});
/* Notification dismiss */
Array.from(document.getElementsByClassName('jb-notification-dismiss')).forEach(el => {
el.addEventListener('click', e => {
e.currentTarget.closest('.notification').classList.add('is-hidden');
});
});

View File

@@ -0,0 +1,65 @@
doctype html
html.has-aside-left.has-aside-mobile-transition.has-navbar-fixed-top.has-aside-expanded
head
meta(charset="utf-8")
meta(http-equiv="X-UA-Compatible", content="ie=edge")
meta(name="viewport", content="width=device-width, initial-scale=1.0")
title Asphyxia CORE - #{title}
link(rel="stylesheet", href="static/css/bulma.min.css")
link(rel="stylesheet", href="static/css/materialdesignicons.min.css")
link(rel="stylesheet", href="static/css/style.css")
body
#app
nav.navbar.is-fixed-top#navbar-main
.navbar-brand
a.navbar-item.is-hidden-desktop.jb-aside-mobile-toggle
span.icon
i.mdi.mdi-forwardburger.mdi-24px
.navbar-item
img.logo(src="static/img/logo.png")
span Asphyxia CORE
.navbar-brand.is-right
a.navbar-item.is-hidden-desktop.jb-navbar-menu-toggle(data-target="navbar-menu")
span.icon
i.mdi.mdi-dots-vertical
.navbar-menu#navbar-menu
.navbar-end
.navbar-item.has-dropdown.has-dropdown-with-icons.has-divider.is-hoverable
a.navbar-link.is-arrowless
span.icon
i.mdi.mdi-menu
span Menu
span.icon
i.mdi.mdi-chevron-down
.navbar-dropdown
a.navbar-item
span.icon
i.mdi.mdi-account
span Subitem
aside.aside.is-placed-left.is-expanded
.aside-tools
.aside-tools-label
span #{version}
.menu.is-menu-main
p.menu-label Core
ul.menu-list
li
a.is-active.router-link-active.has-icon
span.icon
i.mdi.mdi-desktop-mac
span.menu-item-label Dashboard
li
a.router-link-active.has-icon
span.icon
i.mdi.mdi-account
span.menu-item-label Profiles
li
a.router-link-active.has-icon
span.icon
i.mdi.mdi-cog
span.menu-item-label Settings
p.menu-label Module
script(type="text/javascript" src="static/js/main.js")

View File

@@ -0,0 +1 @@
extends _layout.pug

107
package-lock.json generated
View File

@@ -117,6 +117,12 @@
"integrity": "sha512-LKjVkuAyxzYAz2Ek0AX8cm9Kyjw+5eHVqUZwQiquWYwnDDdQcCabqkxPvlIf7/sEbY6jPuKgsmKPDGLV4owkPg==",
"dev": true
},
"@types/ini": {
"version": "1.3.30",
"resolved": "https://registry.npmjs.org/@types/ini/-/ini-1.3.30.tgz",
"integrity": "sha512-2+iF8zPSbpU83UKE+PNd4r/MhwNAdyGpk3H+VMgEH3EhjFZq1kouLgRoZrmIcmoGX97xFvqdS44DkICR5Nz3tQ==",
"dev": true
},
"@types/lodash": {
"version": "4.14.150",
"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.150.tgz",
@@ -129,6 +135,15 @@
"integrity": "sha512-FwI9gX75FgVBJ7ywgnq/P7tw+/o1GUbtP0KzbtusLigAOgIgNISRK0ZPl4qertvXSIE8YbsVJueQ90cDt9YYyw==",
"dev": true
},
"@types/nedb": {
"version": "1.8.9",
"resolved": "https://registry.npmjs.org/@types/nedb/-/nedb-1.8.9.tgz",
"integrity": "sha512-w9Tl3DQCkdT0Ghes+PKhe+3/pZppBXuFFpSCjPJbb2KE3DjYmUpEyCYzjrAYlT9Y1TndnbbnChzkax2h/JorVQ==",
"dev": true,
"requires": {
"@types/node": "*"
}
},
"@types/node": {
"version": "13.13.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-13.13.4.tgz",
@@ -336,6 +351,14 @@
"tweetnacl": "^0.14.3"
}
},
"binary-search-tree": {
"version": "0.2.5",
"resolved": "https://registry.npmjs.org/binary-search-tree/-/binary-search-tree-0.2.5.tgz",
"integrity": "sha1-fbs7IQ/coIJFDa0jNMMErzm9x4Q=",
"requires": {
"underscore": "~1.4.4"
}
},
"body-parser": {
"version": "1.19.0",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz",
@@ -1093,6 +1116,11 @@
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.4.tgz",
"integrity": "sha512-MzbUSahkTW1u7JpKKjY7LCARd1fU5W2rLdxlM4kdkayuCwZImjkpluF9CM1aLewYJguPDqewLam18Y6AU69A8A=="
},
"immediate": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",
"integrity": "sha1-nbHb0Pr43m++D13V5Wu2BigN5ps="
},
"inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
@@ -1108,6 +1136,11 @@
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz",
"integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4="
},
"ini": {
"version": "1.3.5",
"resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz",
"integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw=="
},
"interpret": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/interpret/-/interpret-1.2.0.tgz",
@@ -1363,6 +1396,22 @@
"type-check": "~0.3.2"
}
},
"lie": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/lie/-/lie-3.1.1.tgz",
"integrity": "sha1-mkNrLMd0bKWd56QfpGmz77dr2H4=",
"requires": {
"immediate": "~3.0.5"
}
},
"localforage": {
"version": "1.7.3",
"resolved": "https://registry.npmjs.org/localforage/-/localforage-1.7.3.tgz",
"integrity": "sha512-1TulyYfc4udS7ECSBT2vwJksWbkwwTX8BzeUIiq8Y07Riy7bDAAnxDaPU/tWyOVmQAcWJIEIFP9lPfBGqVoPgQ==",
"requires": {
"lie": "3.1.1"
}
},
"lodash": {
"version": "4.17.15",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz",
@@ -1515,6 +1564,25 @@
}
}
},
"nedb": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/nedb/-/nedb-1.8.0.tgz",
"integrity": "sha1-DjUCzYLABNU1WkPJ5VV3vXvZHYg=",
"requires": {
"async": "0.2.10",
"binary-search-tree": "0.2.5",
"localforage": "^1.3.0",
"mkdirp": "~0.5.1",
"underscore": "~1.4.4"
},
"dependencies": {
"async": {
"version": "0.2.10",
"resolved": "https://registry.npmjs.org/async/-/async-0.2.10.tgz",
"integrity": "sha1-trvgsGdLnXGXCMo43owjfLUmw9E="
}
}
},
"negotiator": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz",
@@ -2158,40 +2226,6 @@
"has-flag": "^4.0.0"
}
},
"systray": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/systray/-/systray-1.0.5.tgz",
"integrity": "sha512-qLsl5lk8lUuqCTaREJ0nR6NgF2y2Ni01vBjUs0cVWf54ZeV4pr3TFLMcUT+od1Twb1qQMq/SKyj+BKd2vg6+Fg==",
"requires": {
"debug": "^3.0.1",
"fs-extra": "^4.0.2"
},
"dependencies": {
"debug": {
"version": "3.2.6",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz",
"integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==",
"requires": {
"ms": "^2.1.1"
}
},
"fs-extra": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-4.0.3.tgz",
"integrity": "sha512-q6rbdDd1o2mAnQreO7YADIxf/Whx4AHBiRf6d+/cVT8h44ss+lHgxf1FemcqDnQt9X3ct4McHr+JMGlYSsK7Cg==",
"requires": {
"graceful-fs": "^4.1.2",
"jsonfile": "^4.0.0",
"universalify": "^0.1.0"
}
},
"ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
}
}
},
"text-hex": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz",
@@ -2342,6 +2376,11 @@
"resolved": "https://registry.npmjs.org/uid2/-/uid2-0.0.3.tgz",
"integrity": "sha1-SDEm4Rd03y9xuLY53NeZw3YWK4I="
},
"underscore": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/underscore/-/underscore-1.4.4.tgz",
"integrity": "sha1-YaajIBBiKvoHljvzJSA88SI51gQ="
},
"unique-temp-dir": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unique-temp-dir/-/unique-temp-dir-1.0.0.tgz",

View File

@@ -8,7 +8,9 @@
"@types/ejs": "^3.0.3",
"@types/express": "^4.17.6",
"@types/get-caller-file": "^1.0.0",
"@types/ini": "^1.3.30",
"@types/lodash": "^4.14.150",
"@types/nedb": "^1.8.9",
"@types/node": "^13.13.4",
"@types/pug": "^2.0.4",
"prettier": "^2.0.5",
@@ -24,11 +26,12 @@
"fast-xml-parser": "^3.16.0",
"get-caller-file": "^2.0.5",
"iconv-lite": "^0.5.1",
"ini": "^1.3.5",
"lodash": "^4.17.15",
"nedb": "^1.8.0",
"open": "^7.0.3",
"pkg": "^4.4.8",
"pug": "^2.0.4",
"systray": "^1.0.5",
"ts-node": "^8.10.1",
"winston": "^3.2.1"
}

View File

@@ -1,15 +1,18 @@
if ((process as any).pkg) process.env.NODE_ENV = 'production';
import { Logger } from './utils/Logger';
import { ARGS } from './utils/ArgParser';
import { services } from './eamuse/Services';
import { ARGS, CONFIG, ReadConfig, SaveConfig } from './utils/ArgConfig';
import { services } from './eamuse';
import { VERSION } from './utils/Consts';
import { pad } from 'lodash';
import express from 'express';
import chalk from 'chalk';
import { LoadExternalModules } from './eamuse/ExternalModuleLoader';
// import { CreateTray } from './utils/Systray';
import { LoadExternalPlugins } from './eamuse/ExternalPluginLoader';
import { webui } from './webui/index';
import path from 'path';
import { ASSETS_PATH } from './utils/EamuseIO';
process.title = `Asphyxia CORE ${VERSION}`;
// CreateTray();
Logger.info(' _ _ ');
Logger.info(' /\\ | | (_) ');
@@ -37,15 +40,23 @@ EAMUSE.disable('x-powered-by');
if (ARGS.dev) {
Logger.info(` [Console Output Enabled]`);
}
const external = LoadExternalModules();
process.title = `Asphyxia CORE ${VERSION} | Modules: ${external.modules.length}`;
if (external.modules.length <= 0) {
Logger.warn(chalk.yellowBright('no modules are installed.'));
const external = LoadExternalPlugins();
process.title = `Asphyxia CORE ${VERSION} | Plugins: ${external.plugins.length}`;
if (external.plugins.length <= 0) {
Logger.warn(chalk.yellowBright('no plugins are installed.'));
Logger.info('');
}
// ========== READCONFIG ===========
ReadConfig();
SaveConfig();
// ========== EAMUSE ============
EAMUSE.use('*', services(`http://${ARGS.bind}:${ARGS.port}`, external.router));
EAMUSE.set('views', path.join(ASSETS_PATH, 'views'));
EAMUSE.set('view engine', 'pug');
EAMUSE.use('*', services(`http://${CONFIG.bind}:${CONFIG.port}`, external.router));
EAMUSE.use('/static', express.static(path.join(ASSETS_PATH, 'static')));
EAMUSE.use(webui);
// // ========== WEB_UI ============
// WEBUI.get('/', async (req, res) => {
@@ -53,9 +64,9 @@ EAMUSE.use('*', services(`http://${ARGS.bind}:${ARGS.port}`, external.router));
// });
// ========== LISTEN ============
const server = EAMUSE.listen(ARGS.port, ARGS.bind, () => {
const server = EAMUSE.listen(CONFIG.port, CONFIG.bind, () => {
Logger.info(` [core] Server started:`);
const serverInfo = `http://${ARGS.bind}:${ARGS.port}`;
const serverInfo = `http://${CONFIG.bind}:${CONFIG.port}`;
Logger.info(` +==================== EA ==================+`);
Logger.info(` |${pad(serverInfo, 42)}|`);
Logger.info(` +==========================================+`);

View File

@@ -1,16 +1,38 @@
import { xmlToData, dataToXML, kencode, kitem, kdecode } from './utils/KBinJSON';
import { xmlToData, dataToXML, kencode, kitem, kdecode, kattr, karray } from './utils/KBinJSON';
import { KonmaiEncrypt } from './utils/KonmaiEncrypt';
import iconv from 'iconv-lite';
import { writeFileSync, readFileSync, write } from 'fs';
import { ReadConfig, SaveConfig } from './utils/ArgConfig';
// const data = readFileSync('response.bin');
// const decode = kdecode(data);
// console.log(dataToXML(decode));
const request = iconv.encode(
'<call model="GLD:J:A:A:2007072301" srcid="01201000000E7AC029BE">\n<services method="get"/>\n</call>',
'utf8'
);
// const request = iconv.encode(
// '<call model="GLD:J:A:A:2007072301" srcid="01201000000E7AC029BE">\n<services method="get"/>\n</call>',
// 'utf8'
// );
const key = new KonmaiEncrypt('1-5ebc47ba-9868');
writeFileSync(`${key.getPublicKey()}.bin`, key.encrypt(request));
// const key = new KonmaiEncrypt('1-5ebc47ba-9868');
// writeFileSync(`${key.getPublicKey()}.bin`, key.encrypt(request));
// const data = kattr(
// {
// test: '"',
// test2: '&',
// },
// {
// child: kitem('s32', 5),
// child2: kitem('ip4', '192.168.1.1'),
// group: [kitem('s64', BigInt(1000)), kitem('bin', Buffer.from('HAHA'))],
// group2: [karray('s64', [BigInt(1000), BigInt(1000)]), kitem('2s32', [32, 32])],
// test: kitem('str', 'This is a string'),
// }
// );
// const data2 = dataToXML({ data });
// console.log(data2);
// console.log(JSON.stringify(xmlToData(data2), null, 2));
ReadConfig();
SaveConfig();

View File

@@ -1,9 +1,9 @@
import { EamuseModuleContainer } from '../EamuseModuleContainer';
import { EamusePluginContainer } from '../EamusePluginContainer';
import { padStart, get, toSafeInteger, toString } from 'lodash';
import { Logger } from '../../utils/Logger';
import { SAFEHEX } from '../../utils/Consts';
export const cardmng = new EamuseModuleContainer();
export const cardmng = new EamusePluginContainer();
const ProfileCheck: {
[key: string]: () => boolean;

View File

@@ -1,9 +1,9 @@
import { set } from 'lodash';
import { kitem } from '../../utils/KBinJSON';
import { EamuseModuleContainer } from '../EamuseModuleContainer';
import { EamusePluginContainer } from '../EamusePluginContainer';
export const eacoin = new EamuseModuleContainer();
export const eacoin = new EamusePluginContainer();
eacoin.add('*', 'eacoin.checkout', async (info, data, send) => {
await send.success();

View File

@@ -1,12 +1,12 @@
import { ip2int, kitem } from '../../utils/KBinJSON';
import { VERSION } from '../../utils/Consts';
import { ARGS } from '../../utils/ArgParser';
import { EamuseModuleContainer } from '../EamuseModuleContainer';
import { EamusePluginContainer } from '../EamusePluginContainer';
import { CONFIG } from '../../utils/ArgConfig';
export const facility = new EamuseModuleContainer();
export const facility = new EamusePluginContainer();
facility.add('*', 'facility.get', async (info, data, send) => {
const port = ARGS.mport;
const port = CONFIG.matching_port;
const result = {
location: {

View File

@@ -1,6 +1,6 @@
import { EamuseModuleContainer } from '../EamuseModuleContainer';
import { EamusePluginContainer } from '../EamusePluginContainer';
export const pcbtracker = new EamuseModuleContainer();
export const pcbtracker = new EamusePluginContainer();
pcbtracker.add('*', 'pcbtracker.alive', async (info, data, send) => {
const result = {

View File

@@ -3,10 +3,10 @@ import { eacoin } from './EamuseCoin';
import { facility } from './Facility';
import { pcbtracker } from './PCBTracker';
import { kitem } from '../../utils/KBinJSON';
import { EamuseModuleContainer } from '../EamuseModuleContainer';
import { EamusePluginContainer } from '../EamusePluginContainer';
import { Logger } from '../../utils/Logger';
export const core = new EamuseModuleContainer();
export const core = new EamusePluginContainer();
core.add('*', 'message.get', async (info, data, send) => {
await send.object({

View File

@@ -1,39 +0,0 @@
import { Logger } from '../utils/Logger';
import path from 'path';
export class EamuseModule {
private instance: any;
private dir: string;
constructor(moduleDir: string) {
var localPath = process.cwd();
if ((process as any).pkg) {
localPath = path.dirname(process.argv0);
}
this.dir = moduleDir;
try {
const modulePath = path.join(localPath, 'modules', moduleDir);
this.instance = require(modulePath);
if (this.instance && this.instance.default != null) {
this.instance = this.instance.default;
}
} catch (err) {
Logger.error(`Failed to load module "${this.dir}"`);
Logger.error(err);
}
}
moduleDirname() {
return this.dir;
}
register() {
if (this.instance && typeof this.instance.register === 'function') {
this.instance.register();
} else {
Logger.warning(`register() in module "${this.dir}" is not implemented`);
}
}
}

View File

@@ -1,36 +1,36 @@
import { isNil } from 'lodash';
import { EamuseInfo } from '../middlewares/EamuseMiddleware';
import { GetCallerModule } from '../utils/EamuseIO';
import { GetCallerPlugin } from '../utils/EamuseIO';
import { Logger } from '../utils/Logger';
import { EamuseSend } from './EamuseSend';
export type EamuseModuleRoute = (info: EamuseInfo, data: any, send: EamuseSend) => Promise<any>;
export type EamusePluginRoute = (info: EamuseInfo, data: any, send: EamuseSend) => Promise<any>;
export class EamuseModuleContainer {
private modules: {
[key: string]: boolean | EamuseModuleRoute;
export class EamusePluginContainer {
private plugins: {
[key: string]: boolean | EamusePluginRoute;
};
private fallback: {
[key: string]: EamuseModuleRoute;
[key: string]: EamusePluginRoute;
};
private children: EamuseModuleContainer[];
private children: EamusePluginContainer[];
constructor() {
this.modules = {};
this.plugins = {};
this.fallback = {};
this.children = [];
}
public add(gameCode: string, method: string): void;
public add(gameCode: string, method: string, handler: EamuseModuleRoute | boolean): void;
public add(gameCode: EamuseModuleContainer): void;
public add(gameCode: string, method: string, handler: EamusePluginRoute | boolean): void;
public add(gameCode: EamusePluginContainer): void;
public add(
gameCode: string | EamuseModuleContainer,
gameCode: string | EamusePluginContainer,
method?: string,
handler?: EamuseModuleRoute | boolean
handler?: EamusePluginRoute | boolean
): void {
if (typeof gameCode === 'string' && method !== null && typeof method === 'string') {
let key = `${gameCode}:${method}`;
@@ -38,31 +38,31 @@ export class EamuseModuleContainer {
key = `${method}`;
}
if (handler) {
this.modules[key] = handler;
this.plugins[key] = handler;
} else {
this.modules[key] = false;
this.plugins[key] = false;
}
}
if (gameCode instanceof EamuseModuleContainer) {
if (gameCode instanceof EamusePluginContainer) {
this.children.push(gameCode);
}
}
public unhandled(gameCode: string, handler?: EamuseModuleRoute) {
const mod = GetCallerModule();
public unhandled(gameCode: string, handler?: EamusePluginRoute) {
const plugin = GetCallerPlugin();
if (typeof handler === 'function') {
this.fallback[gameCode] = handler;
} else {
this.fallback[gameCode] = async (info, data, send) => {
Logger.warn(`unhandled method ${info.module}.${info.method}`, { module: mod.name });
Logger.warn(`unhandled method ${info.module}.${info.method}`, { plugin: plugin.name });
send.deny();
};
}
}
public removeHandler(gameCode: string, method: string) {
delete this.modules[`${gameCode}:${method}`];
delete this.plugins[`${gameCode}:${method}`];
}
public removeUnhandled(gameCode: string) {
@@ -70,10 +70,10 @@ export class EamuseModuleContainer {
}
public clear() {
delete this.modules;
delete this.plugins;
delete this.fallback;
delete this.children;
this.modules = {};
this.plugins = {};
this.fallback = {};
this.children = [];
}
@@ -87,8 +87,8 @@ export class EamuseModuleContainer {
send: EamuseSend,
root: boolean = true
): boolean {
let handler = this.modules[`${moduleName}.${method}`];
if (isNil(handler)) handler = this.modules[`${gameCode}:${moduleName}.${method}`];
let handler = this.plugins[`${moduleName}.${method}`];
if (isNil(handler)) handler = this.plugins[`${gameCode}:${moduleName}.${method}`];
if (isNil(handler)) {
if (this.fallback[gameCode]) {

View File

@@ -3,7 +3,7 @@ import { defaultTo, set, get } from 'lodash';
import { kencode, xmlToData, KBinEncoding, dataToXMLBuffer } from '../utils/KBinJSON';
import { KonmaiEncrypt } from '../utils/KonmaiEncrypt';
import LzKN from '../utils/LzKN';
import { GetCallerModule, MODULE_PATH } from '../utils/EamuseIO';
import { GetCallerPlugin, PLUGIN_PATH } from '../utils/EamuseIO';
import { Logger } from '../utils/Logger';
import { render as ejs, renderFile as ejsFile } from 'ejs';
@@ -84,9 +84,9 @@ export class EamuseSend {
}
async xml(template: string, data?: any, options?: EamuseSendOption) {
const mod = GetCallerModule();
if (!mod) {
Logger.error(`unexpected error: unknown module`);
const plugin = GetCallerPlugin();
if (!plugin) {
Logger.error(`unexpected error: unknown plugin`);
return this.object({}, { status: 1 });
}
@@ -98,15 +98,15 @@ export class EamuseSend {
const rootName = keys[0];
return this.object(result[rootName], { rootName, ...options });
} catch (err) {
Logger.error(err, { module: mod.name });
Logger.error(err, { plugin: plugin.name });
return this.object({}, { status: 1 });
}
}
async pug(template: string, data?: any, options?: EamuseSendOption) {
const mod = GetCallerModule();
if (!mod) {
Logger.error(`unexpected error: unknown module`);
const plugin = GetCallerPlugin();
if (!plugin) {
Logger.error(`unexpected error: unknown plugin`);
return this.object({}, { status: 1 });
}
@@ -118,25 +118,27 @@ export class EamuseSend {
const rootName = keys[0];
return this.object(result[rootName], { rootName, ...options });
} catch (err) {
Logger.error(err, { module: mod.name });
Logger.error(err, { plugin: plugin.name });
return this.object({}, { status: 1 });
}
}
async xmlFile(template: string, data?: any, options?: EamuseSendOption) {
const mod = GetCallerModule();
if (!mod) {
Logger.error(`unexpected error: unknown module`);
const plugin = GetCallerPlugin();
if (!plugin) {
Logger.error(`unexpected error: unknown plugin`);
return this.object({}, { status: 1 });
}
if (mod.single) {
Logger.error(`cannot render file templates from single-file modules`, { module: mod.name });
if (plugin.single) {
Logger.error(`cannot render file templates from single-file plugins`, {
plugin: plugin.name,
});
return this.object({}, { status: 1 });
}
try {
const xml = await ejsFile(path.join(MODULE_PATH, mod.name, template), data, {});
const xml = await ejsFile(path.join(PLUGIN_PATH, plugin.name, template), data, {});
const result = xmlToData(xml);
const keys = Object.keys(result);
@@ -144,32 +146,34 @@ export class EamuseSend {
const rootName = keys[0];
return this.object(result[rootName], { rootName, ...options });
} catch (err) {
Logger.error(err, { module: mod.name });
Logger.error(err, { plugin: plugin.name });
return this.object({}, { status: 1 });
}
}
async pugFile(template: string, data?: any, options?: EamuseSendOption) {
const mod = GetCallerModule();
if (!mod) {
Logger.error(`unexpected error: unknown module`);
const plugin = GetCallerPlugin();
if (!plugin) {
Logger.error(`unexpected error: unknown plugin`);
return this.object({}, { status: 1 });
}
if (mod.single) {
Logger.error(`cannot render file templates from single-file modules`, { module: mod.name });
if (plugin.single) {
Logger.error(`cannot render file templates from single-file plugins`, {
plugin: plugin.name,
});
return this.object({}, { status: 1 });
}
try {
const result = xmlToData(pugFile(path.join(MODULE_PATH, mod.name, template), data));
const result = xmlToData(pugFile(path.join(PLUGIN_PATH, plugin.name, template), data));
const keys = Object.keys(result);
if (keys.length <= 0) return this.object({}, options);
const rootName = keys[0];
return this.object(result[rootName], { rootName, ...options });
} catch (err) {
Logger.error(err, { module: mod.name });
Logger.error(err, { plugin: plugin.name });
return this.object({}, { status: 1 });
}
}

View File

@@ -1,4 +1,4 @@
import { EamuseModuleContainer, EamuseModuleRoute } from './EamuseModuleContainer';
import { EamusePluginContainer, EamusePluginRoute } from './EamusePluginContainer';
import { kitem, karray, kattr, dataToXML } from '../utils/KBinJSON';
import path from 'path';
import {
@@ -15,25 +15,17 @@ import {
getStr,
} from '../utils/KBinJSON';
import { Logger } from '../utils/Logger';
import { ARGS } from '../utils/ArgParser';
import { KDataReader } from '../utils/KDataReader';
import {
ReadSave,
MODULE_PATH,
WriteSave,
WriteFile,
GetCallerModule,
ReadPlayerSave,
WritePlayerSave,
} from '../utils/EamuseIO';
import { PLUGIN_PATH, WriteFile, GetCallerPlugin } from '../utils/EamuseIO';
import { readdirSync, existsSync } from 'fs';
import { AddProfileCheck } from './Core/CardManager';
import { ARGS } from '../utils/ArgConfig';
/* Exposing API */
const $: any = global;
const MODULE_ROUTER = new EamuseModuleContainer();
const PLUGIN_ROUTER = new EamusePluginContainer();
const tsconfig = path.join(MODULE_PATH, 'tsconfig.json');
const tsconfig = path.join(PLUGIN_PATH, 'tsconfig.json');
/* ncc/pkg hack */
// require('typescript');
const ts_node = require('ts-node');
@@ -45,13 +37,13 @@ if (existsSync(tsconfig)) {
}
$.R = {
Route: (gameCode: string, method: string, handler: EamuseModuleRoute | boolean) => {
Route: (gameCode: string, method: string, handler: EamusePluginRoute | boolean) => {
if (gameCode === '*') return;
MODULE_ROUTER.add(gameCode, method, handler);
PLUGIN_ROUTER.add(gameCode, method, handler);
},
Unhandled: (gameCode: string, handler?: EamuseModuleRoute) => {
Unhandled: (gameCode: string, handler?: EamusePluginRoute) => {
if (gameCode === '*') return;
MODULE_ROUTER.unhandled(gameCode, handler);
PLUGIN_ROUTER.unhandled(gameCode, handler);
},
ProfileCheck: (gameCode: string, handler: () => boolean) => {
if (gameCode === '*') return;
@@ -72,7 +64,6 @@ $.$.ELEMENTS = getElements;
$.$.NUMBER = getNumber;
$.$.NUMBERS = getNumbers;
$.$.STR = getStr;
$.$.toXML = dataToXML;
$.K = {
ATTR: kattr,
@@ -80,12 +71,11 @@ $.K = {
ARRAY: karray,
};
$.IO = {
ReadSave,
WriteSave,
$.DB = {};
$.U = {
toXML: dataToXML,
WriteFile,
ReadPlayerSave,
WritePlayerSave,
};
if (!ARGS.dev) {
@@ -96,9 +86,9 @@ if (!ARGS.dev) {
$.console.info = () => {};
} else {
$.console.log = (...msgs: any[]) => {
const mod = GetCallerModule();
if (mod) {
Logger.info(msgs.join(' '), { module: mod.name });
const plugin = GetCallerPlugin();
if (plugin) {
Logger.info(msgs.join(' '), { plugin: plugin.name });
} else {
Logger.info(msgs.join(' '));
}
@@ -106,64 +96,64 @@ if (!ARGS.dev) {
$.console.debug = $.console.log;
$.console.info = $.console.log;
$.console.warn = (...msgs: any[]) => {
const mod = GetCallerModule();
if (mod) {
Logger.warn(msgs.join(' '), { module: mod.name });
const plugin = GetCallerPlugin();
if (plugin) {
Logger.warn(msgs.join(' '), { plugin: plugin.name });
} else {
Logger.warn(msgs.join(' '));
}
};
$.console.error = (...msgs: any[]) => {
const mod = GetCallerModule();
if (mod) {
Logger.error(msgs.join(' '), { module: mod.name });
const plugin = GetCallerPlugin();
if (plugin) {
Logger.error(msgs.join(' '), { plugin: plugin.name });
} else {
Logger.error(msgs.join(' '));
}
};
}
export function LoadExternalModules() {
const loadedModules = [];
export function LoadExternalPlugins() {
const loadedPlugins = [];
try {
const modules = readdirSync(MODULE_PATH);
for (const mod of modules) {
const plugins = readdirSync(PLUGIN_PATH);
for (const mod of plugins) {
const name = path.basename(mod);
const modulePath = path.resolve(MODULE_PATH, mod);
const moduleExt = path.extname(modulePath);
const pluginPath = path.resolve(PLUGIN_PATH, mod);
const pluginExt = path.extname(pluginPath);
if (
modulePath.endsWith('.d.ts') ||
pluginPath.endsWith('.d.ts') ||
mod.startsWith('_') ||
mod.startsWith('core') ||
mod == 'node_modules' ||
(moduleExt !== '' && moduleExt !== '.ts' && moduleExt !== '.js')
(pluginExt !== '' && pluginExt !== '.ts' && pluginExt !== '.js')
)
continue;
try {
let instance = require(modulePath);
let instance = require(pluginPath);
if (instance && instance.default != null) {
instance = instance.default;
}
loadedModules.push({ name, instance });
loadedPlugins.push({ name, instance });
} catch (err) {
Logger.error(`failed to load`, { module: name });
Logger.error(`failed to load`, { plugin: name });
Logger.error(err);
}
}
for (const loaded of loadedModules) {
for (const loaded of loadedPlugins) {
try {
loaded.instance.register();
} catch (err) {
Logger.error(`${err}`, { module: loaded.name });
Logger.error(`${err}`, { plugin: loaded.name });
}
}
} catch (err) {
Logger.warn(`can not find "modules" directory.`);
Logger.warn(`make sure your modules are installed under: ${MODULE_PATH}`);
Logger.warn(`can not find "plugins" directory.`);
Logger.warn(`make sure your plugins are installed under: ${PLUGIN_PATH}`);
}
/* Disable route registering after external module has been loaded */
@@ -172,7 +162,7 @@ export function LoadExternalModules() {
}
return {
modules: loadedModules,
router: MODULE_ROUTER,
plugins: loadedPlugins,
router: PLUGIN_ROUTER,
};
}

View File

@@ -2,12 +2,11 @@ import { Router } from 'express';
import { EamuseMiddleware, EamuseRoute } from '../middlewares/EamuseMiddleware';
import { core } from './Core';
import { EamuseModuleContainer } from './EamuseModuleContainer';
import { dataToXML } from '../utils/KBinJSON';
import { EamusePluginContainer } from './EamusePluginContainer';
export const services = (url: string, modules: EamuseModuleContainer) => {
export const services = (url: string, plugins: EamusePluginContainer) => {
const routeEamuse = Router();
const rootEA = new EamuseModuleContainer();
const rootEA = new EamusePluginContainer();
const coreModules = [
'cardmng',
@@ -63,34 +62,13 @@ export const services = (url: string, modules: EamuseModuleContainer) => {
services.item.push({ '@attr': { name: moduleName, url } });
}
// <response>
// <services>
// <item name="pcbtracker" url="http://192.168.1.57:60079/+" />
// <item name="posevent" url="http://192.168.1.57:60079/+" />
// <item name="pcbevent" url="http://192.168.1.57:60079/+" />
// <item name="message" url="http://192.168.1.57:60079/+" />
// <item name="facility" url="http://192.168.1.57:60079/+" />
// <item name="userdata" url="http://192.168.1.57:60079/+" />
// <item name="userid" url="http://192.168.1.57:60079/+" />
// <item name="cardmng" url="http://192.168.1.57:60079/+" />
// <item name="sidmgr" url="http://192.168.1.57:60079/+" />
// <item name="local" url="http://192.168.1.57:60079/+" />
// <item name="ntp" url="http://192.168.1.57:60079/+" />
// <item name="globby" url="http://192.168.1.57:5730/+" />
// <item
// name="keepalive"
// url="http://192.168.1.57:60079/+&amp;ga=192.168.1.57:60079&amp;ma=192.168.1.57:60079&amp;pa=192.168.1.57:60079&amp;ia=192.168.1.57:60079&amp;t1=1&amp;t2=5"
// />
// </services>
// </response>;
await send.object(services);
return;
});
/* Core */
rootEA.add(core);
rootEA.add(modules);
rootEA.add(plugins);
return routeEamuse;
};

View File

@@ -12,7 +12,7 @@ import {
import { KonmaiEncrypt } from '../utils/KonmaiEncrypt';
import LzKN from '../utils/LzKN';
import { Logger } from '../utils/Logger';
import { EamuseModuleContainer } from '../eamuse/EamuseModuleContainer';
import { EamusePluginContainer } from '../eamuse/EamusePluginContainer';
import { EamuseSend } from '../eamuse/EamuseSend';
import { dataToXML } from '../utils/KBinJSON';
@@ -39,12 +39,11 @@ export interface EamuseInfo {
export const EamuseMiddleware: RequestHandler = async (req, res, next) => {
res.set('X-Powered-By', 'Asphyxia');
const agent = req.headers['user-agent'];
const agent = req.headers['user-agent'] || '';
if (agent.indexOf('Mozilla') >= 0) {
// Skip browser
// res.redirect(`http://${ARGS.ui_bind}:${ARGS.ui_port}`);
return res.sendStatus(404);
(req as any).skip = true;
return next();
}
// if (ACCEPT_AGENTS.indexOf(agent) < 0) {
@@ -155,20 +154,56 @@ export const EamuseMiddleware: RequestHandler = async (req, res, next) => {
});
};
export const EamuseRoute = (container: EamuseModuleContainer): RequestHandler => {
const route: RequestHandler = async (req, res) => {
function uncarded(str: string): string {
return str.replace(/(^|\s*)[0|E][A-F|a-f|0-9]{15}($|\s+)/g, '$1DEADC0DEFEEDBEEF$2');
}
function removeCardID(data: any): any {
if (typeof data !== 'object') return undefined;
if (Array.isArray(data)) {
for (const element of data) {
removeCardID(element);
}
} else {
for (const prop in data) {
if (prop == '@attr') {
for (const attr in data[prop]) {
data['@attr'][attr] = uncarded(data[prop][attr]);
}
} else if (prop == '@content') {
const content = data['@content'];
if (typeof content == 'string') {
data['@content'] = uncarded(content);
}
} else {
removeCardID(data[prop]);
}
}
}
return data;
}
export const EamuseRoute = (container: EamusePluginContainer): RequestHandler => {
const route: RequestHandler = async (req, res, next) => {
if ((req as any).skip) {
next();
return;
}
const body = req.body as EABody;
const gameCode = body.model.split(':')[0];
const send = new EamuseSend(body, res);
const data = removeCardID(get(body.data, `call.${body.module}`));
try {
container.run(
gameCode,
body.module,
body.method,
{ module: body.module, method: body.method, model: body.model },
get(body.data, `call.${body.module}`),
data,
send
);
} catch (err) {

195
src/utils/ArgConfig.ts Normal file
View File

@@ -0,0 +1,195 @@
import { ArgumentParser } from 'argparse';
import { VERSION } from './Consts';
import { GetCallerPlugin, CONFIG_PATH } from './EamuseIO';
import { Logger } from './Logger';
import { readFileSync, writeFileSync } from 'fs';
import { parse, stringify } from 'ini';
const parser = new ArgumentParser({
version: VERSION,
addHelp: true,
description: 'AsphyxiaCore: A Rhythm Game Helper',
prog: 'asphyxia_core',
});
parser.addArgument(['-p', '--port'], {
help: 'Set listening port. (default: 8083)',
defaultValue: 8083,
type: 'int',
metavar: 'PORT',
dest: 'port',
});
parser.addArgument(['-b', '--bind'], {
help: 'Hostname binding. In case you need to access it through LAN. (default: "localhost")',
defaultValue: 'localhost',
metavar: 'HOST',
dest: 'bind',
});
// parser.addArgument(['-uip', '--webui-port'], {
// help: 'Set WebUI port. (default: 8084)',
// defaultValue: 8084,
// type: 'int',
// metavar: 'PORT',
// dest: 'ui_port',
// });
// parser.addArgument(['-uib', '--webui-bind'], {
// help: 'WebUI Hostname binding. (default: "localhost")',
// defaultValue: 'localhost',
// metavar: 'HOST',
// dest: 'ui_bind',
// });
parser.addArgument(['-m', '--matching-port'], {
help: 'Set matching port. (default: 5700)',
defaultValue: 5700,
type: 'int',
dest: 'matching_port',
metavar: 'PORT',
});
// parser.addArgument(['-s', '--save-path'], {
// help: 'Set custom savedata directory',
// dest: 'save_path',
// metavar: 'PATH',
// });
parser.addArgument(['--console'], {
help: 'Enable console for plugins.',
defaultValue: false,
dest: 'dev',
action: 'storeTrue',
});
parser.addArgument(['--no-tray'], {
help: 'Disable system tray icon',
defaultValue: false,
dest: 'no-tray',
action: 'storeTrue',
});
export const ARGS = parser.parseArgs();
export interface CONFIG_OPTIONS {
name?: string;
desc?: string;
type: 'string' | 'integer' | 'float' | 'boolean';
range?: [number, number];
validator?: (data: string) => boolean;
onchange?: (key: string, value: string) => void;
slider?: boolean;
options?: string[];
default: any;
}
let INI: any = null;
const CONFIG_MAP: {
[key: string]: {
[key: string]: CONFIG_OPTIONS;
};
} = {
core: {
port: { type: 'integer', range: [0, 65535], default: 8083 },
bind: { type: 'string', default: 'localhost' },
matching_port: { type: 'integer', range: [0, 65535], default: 5700 },
systray: { type: 'boolean', default: false },
webui_enabled: { name: 'Enable WebUI', type: 'boolean', default: true },
},
};
export function PluginRegisterConfig(key: string, options: CONFIG_OPTIONS) {
const plugin = GetCallerPlugin();
if (!plugin) {
Logger.error('failed to register config entry: unknown plugin');
return;
}
if (!options) {
Logger.error(`failed to register config entry ${key}: config options not specified`, {
plugin: plugin.name,
});
}
if (!options.default) {
Logger.error(`failed to register config entry ${key}: default value not specified`, {
plugin: plugin.name,
});
}
if (!options.type) {
Logger.error(`failed to register config entry ${key}: value type not specified`, {
plugin: plugin.name,
});
}
if (!CONFIG_MAP[plugin.name]) {
CONFIG_MAP[plugin.name] = {};
}
CONFIG_MAP[plugin.name][key] = options;
}
export function ReadConfig() {
try {
const file = readFileSync(CONFIG_PATH, { encoding: 'utf-8' });
INI = parse(file);
} catch (err) {
INI = {};
}
for (const mod in CONFIG_MAP) {
let section = INI;
if (mod != 'core') {
if (!INI[mod]) {
INI[mod] = {};
}
section = INI[mod];
}
for (const op in CONFIG_MAP[mod]) {
const option = CONFIG_MAP[mod][op];
if (!section[op]) {
section[op] = option.default;
} else {
if (option.type == 'boolean') {
section[op] = section[op].toString() == 'true';
} else if (option.type == 'integer') {
section[op] = parseInt(section[op]);
if (isNaN(section[op])) {
section[op] = option.default;
}
} else if (option.type == 'float') {
section[op] = parseFloat(section[op]);
if (isNaN(section[op])) {
section[op] = option.default;
}
} else {
section[op] = section[op].toString();
}
}
}
}
}
export function SaveConfig() {
try {
writeFileSync(CONFIG_PATH, stringify(INI));
} catch (err) {
Logger.error(`failed to write config: ${err}`);
}
}
export const CONFIG: any = new Proxy(
{},
{
get: (_, prop) => {
return ARGS.prop || INI[prop];
},
set: () => {
return true;
},
}
);

View File

@@ -1,62 +0,0 @@
import { ArgumentParser } from 'argparse';
import { VERSION } from './Consts';
const parser = new ArgumentParser({
version: VERSION,
addHelp: true,
description: 'AsphyxiaCore: A Rhythm Game Helper',
prog: 'asphyxia_core',
});
parser.addArgument(['-p', '--port'], {
help: 'Set listening port. (default: 8083)',
defaultValue: 8083,
type: 'int',
metavar: 'PORT',
dest: 'port',
});
parser.addArgument(['-b', '--bind'], {
help: 'Hostname binding. In case you need to access it through LAN. (default: "localhost")',
defaultValue: 'localhost',
metavar: 'HOST',
dest: 'bind',
});
// parser.addArgument(['-uip', '--webui-port'], {
// help: 'Set WebUI port. (default: 8084)',
// defaultValue: 8084,
// type: 'int',
// metavar: 'PORT',
// dest: 'ui_port',
// });
// parser.addArgument(['-uib', '--webui-bind'], {
// help: 'WebUI Hostname binding. (default: "localhost")',
// defaultValue: 'localhost',
// metavar: 'HOST',
// dest: 'ui_bind',
// });
parser.addArgument(['-m', '--matching-port'], {
help: 'Set matching port. (default: 5700)',
defaultValue: 5700,
type: 'int',
dest: 'mport',
metavar: 'PORT',
});
parser.addArgument(['-s', '--save-path'], {
help: 'Set custom savedata directory',
dest: 'save_path',
metavar: 'PATH',
});
parser.addArgument(['--console'], {
help: 'Enable console for modules.',
defaultValue: false,
dest: 'dev',
action: 'storeTrue',
});
export const ARGS = parser.parseArgs();

View File

@@ -1,2 +1,2 @@
export const VERSION = 'v1.04 beta';
export const VERSION = 'v1.10 beta';
export const SAFEHEX = 'ADEBEEFA';

View File

@@ -2,39 +2,43 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
import { Logger } from './Logger';
import path from 'path';
import { ARGS } from './ArgParser';
import { getProfileFromRef } from '../eamuse/Core/CardManager';
import nedb from 'nedb';
export const EXEC_PATH = (process as any).pkg ? path.dirname(process.argv0) : process.cwd();
export const MODULE_PATH = path.join(EXEC_PATH, 'modules');
export const SAVE_PATH = ARGS.save_path || path.join(EXEC_PATH, 'savedata');
const pkg: boolean = (process as any).pkg;
export const EXEC_PATH = pkg ? path.dirname(process.argv0) : process.cwd();
export const PLUGIN_PATH = path.join(EXEC_PATH, 'plugins');
export const SAVE_PATH = path.join(EXEC_PATH, 'savedata');
export const ASSETS_PATH = path.join(pkg ? __dirname : `../../build-env`, 'assets');
export const CONFIG_PATH = path.join(EXEC_PATH, 'config.ini');
export function GetCallerModule(): { name: string; single: boolean } {
export const DB = new nedb({ filename: path.join(SAVE_PATH, 'core.db'), autoload: true });
export function GetCallerPlugin(): { name: string; single: boolean } {
const oldPrepareStackTrace = Error.prepareStackTrace;
Error.prepareStackTrace = (_, stack) => stack;
const stack = new Error().stack as any;
Error.prepareStackTrace = oldPrepareStackTrace;
if (stack !== null && typeof stack === 'object') {
let inModule = false;
let inPlugin = false;
let entryFile = null;
for (const file of stack) {
const filename: string = file.getFileName();
if (filename.startsWith(MODULE_PATH)) {
entryFile = path.relative(MODULE_PATH, filename);
inModule = true;
if (filename.startsWith(PLUGIN_PATH)) {
entryFile = path.relative(PLUGIN_PATH, filename);
inPlugin = true;
} else {
if (inModule) {
if (inPlugin) {
break;
}
}
}
if (entryFile !== null) {
const mod = entryFile.split(path.sep)[0];
if (mod.endsWith('.js') || mod.endsWith('.ts')) {
return { name: mod.substr(0, mod.length - 3), single: true };
const plugin = entryFile.split(path.sep)[0];
if (plugin.endsWith('.js') || plugin.endsWith('.ts')) {
return { name: plugin.substr(0, plugin.length - 3), single: true };
} else {
return { name: mod, single: false };
return { name: plugin, single: false };
}
} else {
return null;
@@ -43,17 +47,7 @@ export function GetCallerModule(): { name: string; single: boolean } {
return null;
}
// export function ExistsFile(file: string, ref?: string): boolean {
// try {
// return existsSync(`${file}.json`);
// } catch (err) {
// return false;
// }
// }
export function PrepareSaveDirectory(mod: string, profileDir: string = ''): string {
const dir = path.join(SAVE_PATH, mod, profileDir);
export function PrepareDirectory(dir: string = ''): string {
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
@@ -61,177 +55,32 @@ export function PrepareSaveDirectory(mod: string, profileDir: string = ''): stri
return dir;
}
export function ReadPlayerSave(refid: string, file: string): any {
const mod = GetCallerModule();
if (!mod) {
Logger.error(`unknown module:`);
Logger.error(new Error().stack);
}
const profile = getProfileFromRef(refid);
if (!profile) {
Logger.warn(`invalid refid. aborted reading`, { module: mod.name });
return null;
}
const dir = PrepareSaveDirectory(mod.name, profile);
const fullFile = path.join(dir, `${file}.json`);
try {
if (!existsSync(fullFile)) {
return null;
}
const data = JSON.parse(
readFileSync(fullFile, {
encoding: 'UTF-8',
})
);
return data;
} catch (err) {
Logger.error(err);
return null;
}
}
export function ReadSave(file: string): any {
const mod = GetCallerModule();
if (!mod) {
Logger.error(`unknown module:`);
Logger.error(new Error().stack);
}
const dir = PrepareSaveDirectory(mod.name);
const fullFile = path.join(dir, `${file}.json`);
try {
if (!existsSync(fullFile)) {
return null;
}
const data = JSON.parse(
readFileSync(fullFile, {
encoding: 'UTF-8',
})
);
return data;
} catch (err) {
Logger.error(err);
return null;
}
}
export function WriteSave(file: string, data: any, formated = false) {
const mod = GetCallerModule();
if (!mod) {
Logger.error(`unknown module:`);
Logger.error(new Error().stack);
}
const dir = PrepareSaveDirectory(mod.name);
const fullFile = path.join(dir, `${file}.json`);
try {
if (formated) {
writeFileSync(fullFile, JSON.stringify(data, null, 4));
} else {
writeFileSync(fullFile, JSON.stringify(data));
}
Logger.info(`${file}.json saved`, { module: mod.name });
} catch (err) {
Logger.error(`file writing failed: ${err}`, { module: mod.name });
}
}
export function WritePlayerSave(refid: string, file: string, data: any, formated = false) {
const mod = GetCallerModule();
if (!mod) {
Logger.error(`unknown module:`);
Logger.error(new Error().stack);
}
const profile = getProfileFromRef(refid);
if (!profile) {
Logger.warn(`invalid refid. aborted saving`, { module: mod.name });
return;
}
const dir = PrepareSaveDirectory(mod.name, profile);
const fullFile = path.join(dir, `${file}.json`);
try {
if (formated) {
writeFileSync(fullFile, JSON.stringify(data, null, 4));
} else {
writeFileSync(fullFile, JSON.stringify(data));
}
Logger.info(`${profile}/${file}.json saved`, { module: mod.name });
} catch (err) {
Logger.error(`file writing failed: ${err}`, { module: mod.name });
}
}
// export function WriteDebugFile(file: string, data: any) {
// if (process.env.ASPHYXIA_PRINT_LOG !== 'print') return;
// try {
// let output = JSON.stringify(data, null, 2);
// const kitemReplace = /\{\s*\n\s*['"]@attr['"]: \{\s*\n\s*['"]?__type['"]?: ['"](.*)['"],?\s*\n\s*\},\s*\n\s*['"]@content['"]: \[\s*\n*\s*(.*)\s*\n*\s*\],?\s*\n\s*\}/g;
// const strReplace = /\{\s*\n\s*['"]@attr['"]: \{\s*\n\s*['"]?__type['"]?: ['"](str)['"],?\s*\n\s*\},\s*\n\s*['"]@content['"]: (['"].*['"]),?\s*\n\s*\}/g;
// const karrayReplace = /\{\s*\n\s*['"]@attr['"]: \{\s*\n\s*['"]?__type['"]?: ['"](.*)['"],\s*\n\s*['"]?__count['"]?: .*\s*\n\s*\},?\s*\n\s*['"]@content['"]: (\[(?:[^\]]|\n)*\]),?\s*\n\s*\}/g;
// output = output.replace(kitemReplace, "kitem('$1', $2)");
// output = output.replace(strReplace, "kitem('$1', $2)");
// output = output.replace(karrayReplace, "karray('$1', $2)");
// writeFileSync(`${file}.js`, `const debug = ${output};`);
// Logger.debug(`Debug File ${file}.js Saved`);
// } catch (err) {
// Logger.debug(`Debug File ${file}.js Saving Failed`);
// }
// }
// export function ReadXML(file: string): any {
// try {
// if (!existsSync(`${file}.xml`)) {
// return null;
// }
// const data = xmlToData(readFileSync(`${file}.xml`));
// return data;
// } catch (err) {
// Logger.error(err);
// return false;
// }
// }
export function WriteFile(file: string, data: string) {
const mod = GetCallerModule();
if (!mod) return;
const plugin = GetCallerPlugin();
if (!plugin) return;
let target = file;
if (!path.isAbsolute(file)) {
target = path.resolve(MODULE_PATH, mod.name, file);
target = path.resolve(PLUGIN_PATH, plugin.name, file);
}
try {
PrepareDirectory(path.dirname(target));
writeFileSync(target, data);
} catch (err) {
Logger.error(`file writing failed: ${err}`, { module: mod });
Logger.error(`file writing failed: ${err}`, { plugin: plugin.name });
}
}
// export function PrintXML(data: any) {
// try {
// Logger.info(dataToXML(data));
// } catch (err) {
// Logger.error(err);
// }
// }
export function ReadAssets(file: string): any {
let fullFile = path.join(__dirname, 'assets', `${file}`);
if (!(process as any).pkg) {
fullFile = path.join('../../build-env/assets', `${file}`);
}
let fullFile = path.join(ASSETS_PATH, `${file}`);
try {
if (!existsSync(fullFile)) {
return null;
}
const data = readFileSync(fullFile, {
encoding: 'UTF-8',
encoding: 'utf-8',
});
return data;
} catch (err) {

View File

@@ -436,18 +436,7 @@ function bufferToString(data: Buffer, encoding: KBinEncoding): string {
}
const str = iconv.decode(data, encoding);
const result = str.substr(0, str.length - 1);
// if (result.startsWith(SAFEHEX)) return result;
// if (result.length == 16) {
// const hex_checker = /^[0-9a-fA-F]+$/;
// if (hex_checker.test(result)) {
// return 'DEADC0DEFEEDBEEF';
// }
// }
return result;
// replace(/(^|\s*)[0|E][A-F|a-f|0-9]{15}($|\s+)/g, '$1DEADC0DEFEEDBEEF$2');
}
function nodeToBinary(
@@ -787,82 +776,84 @@ function unescape(data: string | number): string {
.replace(/&gt;/g, '>');
}
function transformJObj(obj: any, toStr = true): void {
if (obj !== null && obj !== undefined) {
const data = obj['@content'];
function stringed(data: any): any {
if (typeof data !== 'object') return undefined;
if (obj['@attr']) {
for (const attr in obj['@attr']) {
if (toStr) {
obj['@attr'][attr] = escape(obj['@attr'][attr]);
} else {
obj['@attr'][attr] = unescape(obj['@attr'][attr]);
}
}
let result: any = {};
if (Array.isArray(data)) {
result = [];
for (const element of data) {
result.push(stringed(element));
}
if (data !== undefined) {
let vType = 'void';
if (obj['@attr'] && obj['@attr'].__type) {
vType = obj['@attr'].__type;
}
if (obj['@attr'] && obj['@attr'].__count) {
obj['@attr'].__count = toSafeInteger(obj['@attr'].__count);
}
if (toStr) {
if (typeof data == 'string') {
obj['@content'] = escape(data);
} else if (typeof data !== 'object') {
obj['@content'] = data.toString();
} else {
if (Buffer.isBuffer(data)) {
obj['@content'] = data.toString('hex');
} else if (Array.isArray(data)) {
if (vType === 'ip4') {
obj['@content'] = data.map(v => int2ip(v)).join(' ');
} else {
obj['@content'] = data.join(' ');
}
} else {
for (const prop in data) {
if (prop == '@attr') {
result['@attr'] = {};
for (const attr in data[prop]) {
result['@attr'][attr] = escape(data[prop][attr]);
}
} else if (prop == '@content') {
const content = data['@content'];
let type = get(data, '@attr.__type', 'str');
if (typeof content == 'string') {
result['@content'] = escape(content);
} else if (Buffer.isBuffer(content)) {
result['@content'] = content.toString('hex');
} else if (Array.isArray(content)) {
if (type == 'ip4') {
result['@content'] = content.map(v => int2ip(v)).join(' ');
} else {
result['@content'] = content.join(' ');
}
}
} else {
if (typeof data === 'string') {
if (vType === 'bin') {
obj['@content'] = Buffer.from(data, 'hex');
} else if (vType === 'ip4') {
const parts = data.split(' ');
obj['@content'] = parts.map(ip2int);
} else if (vType !== 'str' && vType !== 'void') {
const parts = data.split(' ');
if (vType.endsWith('64')) {
obj['@content'] = parts.map(v => BigInt(v));
} else {
obj['@content'] = parts.map(v => parseFloat(v));
}
} else {
obj['@content'] = unescape(data);
}
}
}
} else {
for (const child in obj) {
if (typeof obj[child] == 'string' && !toStr) {
if (obj[child] === '') {
obj[child] = {};
} else {
obj[child] = {
'@attr': {
__type: 'str',
},
'@content': obj[child],
};
}
} else if (child !== '@attr') {
transformJObj(obj[child], toStr);
}
result[prop] = stringed(data[prop]);
}
}
}
return result;
}
function unstringed(data: any): any {
if (typeof data !== 'object') return undefined;
let result: any = {};
if (Array.isArray(data)) {
result = [];
for (const element of data) {
result.push(unstringed(element));
}
} else {
for (const prop in data) {
if (prop == '@attr') {
result['@attr'] = {};
for (const attr in data[prop]) {
result['@attr'][attr] = unescape(data[prop][attr]);
}
} else if (prop == '@content') {
const content = data['@content'];
let type = get(data, '@attr.__type', 'str');
if (typeof type != 'string' || typeof content != 'string') {
return undefined;
}
if (type == 'str') {
result['@content'] = unescape(content);
} else if (type == 'bin') {
result['@content'] = Buffer.from(content, 'hex');
} else if (type == 'ip4') {
result['@content'] = content.split(' ').map(v => ip2int(v));
} else if (type.endsWith('64')) {
result['@content'] = content.split(' ').map(v => BigInt(v));
} else {
result['@content'] = content.split(' ').map(v => parseFloat(v));
}
} else {
result[prop] = unstringed(data[prop]);
}
}
}
return result;
}
export function dataToXML(data: any, header: boolean = true): string {
@@ -879,12 +870,8 @@ export function dataToXML(data: any, header: boolean = true): string {
supressEmptyNode: true,
};
transformJObj(data);
const parser = new json2xml(options);
const xml = parser.parse(data);
transformJObj(data, false);
const xml = parser.parse(stringed(data));
if (header) return "<?xml version='1.0' encoding='UTF-8'?>\n" + xml;
else return xml;
@@ -904,12 +891,9 @@ export function dataToXMLBuffer(data: any, encoding: KBinEncoding): Buffer {
supressEmptyNode: true,
};
transformJObj(data);
const parser = new json2xml(options);
const xml = parser.parse(data);
const xml = parser.parse(stringed(data));
transformJObj(data, false);
return iconv.encode(`<?xml version='1.0' encoding='${ICONV2XML[encoding]}'?>\n${xml}`, encoding);
}
@@ -947,8 +931,7 @@ export function xmlToData(xml: string | Buffer, encoding?: KBinEncoding): any {
trimValues: true,
};
const data = xml2json.parse(xmlStr, options);
transformJObj(data, false);
const data = unstringed(xml2json.parse(xmlStr, options));
return data;
}

View File

@@ -2,24 +2,25 @@ import winston from 'winston';
import chalk from 'chalk';
const isDebug = (process as any).pkg == null;
export const Logger = winston.createLogger({
level: isDebug ? 'debug' : 'info',
format: winston.format.combine(
winston.format.colorize(),
winston.format.printf(info => {
const module =
info.module == 'core' ? chalk.cyanBright('core') : chalk.yellowBright(info.module);
const plugin =
info.plugin == 'core' ? chalk.cyanBright('core') : chalk.yellowBright(info.plugin);
if (info.level.indexOf('info') < 0) {
return ` [${module}] ${info.level}: ${info.message}`;
return ` [${plugin}] ${info.level}: ${info.message}`;
} else {
if (info.module == 'core') {
if (info.plugin == 'core') {
return `${info.message}`;
}
return ` [${module}] ${info.message}`;
return ` [${plugin}] ${info.message}`;
}
})
),
defaultMeta: { module: 'core' },
defaultMeta: { plugin: 'core' },
transports: [
new winston.transports.Console({
stderrLevels: ['error'],

View File

@@ -1,42 +0,0 @@
import SysTray from 'systray';
import { ReadAssets } from './EamuseIO';
import opn from 'open';
import { VERSION } from './Consts';
export function CreateTray() {
if (process.platform === 'win32') {
const systray = new SysTray({
menu: {
// you should using .png icon in macOS/Linux, but .ico format in windows
icon: ReadAssets('icon.b64'),
title: 'Asphyxia CORE',
tooltip: `Asphyxia CORE ${VERSION}`,
items: [
{
title: 'Config',
tooltip: 'Open WebUI',
checked: false,
enabled: true,
},
{
title: 'Exit',
tooltip: 'Exit CORE',
checked: false,
enabled: true,
},
],
},
debug: false,
copyDir: true,
});
systray.onClick(action => {
if (action.seq_id === 0) {
opn('http://localhost:8083');
} else if (action.seq_id === 1) {
systray.kill();
systray.writeLine;
}
});
}
}

7
src/webui/index.ts Normal file
View File

@@ -0,0 +1,7 @@
import { Router } from 'express';
import { ASSETS_PATH } from '../utils/EamuseIO';
export const webui = Router();
webui.get('/', async (req, res) => {
res.render('index');
});