diff --git a/backup_typing_db b/backup_typing_db new file mode 100644 index 0000000..20bdbaf --- /dev/null +++ b/backup_typing_db @@ -0,0 +1,70 @@ +type Without = Pick>; +type ValueOf = T[keyof T]; +type ArrayOf = T[Exclude>]; +type SubArrayOf = ArrayOf; +type ConditionalValueOf = T[U]; + +type TypedQueryOperator = { $lt: U } | { $lte: U } | { $gt: U } | { $gte: U } | { $in: U[] }; +type TypedArrayQueryOperator = { $elemMatch: U }; +type UnknownArrayQueryOperator = { $size: number }; +type UnknownQueryOperator = { $ne: any } | { $nin: any[] } | { $exists: boolean }; +type RegexQueryOperator = { $regex: RegExp }; + +type WithID = { _id: string }; + +type QueryResult = { + [P in keyof Without]: T[P] extends TypedQueryOperator< + infer U + > + ? U + : T[P] extends UnknownQueryOperator + ? any + : T[P] extends RegexQueryOperator + ? string + : T[P] extends TypedArrayQueryOperator + ? Partial[] + : T[P] extends UnknownArrayQueryOperator + ? any[] + : T[P] extends object + ? QueryResult + : T[P]; +} & + { + [P in keyof SubArrayOf]: ValueOf>; + } & + { + [P in keyof SubArrayOf]-?: ValueOf>; + } & + { + [P in keyof ConditionalValueOf]: any; + } & + WithID & { + [key: string]: any; + }; + +type UpdateQueryDoc = {}; + +type UpdateResult = { + updated: number; + docs: (Partial> & UpdateQueryDoc)[]; +}; + +declare namespace DB { + function FindOne(refid: string, query: T): Promise>; + function FindOne(query: T): Promise>; + + function Find(refid: string, query: T): Promise>; + function Find(query: T): Promise>; + + function Insert(refid: string, doc: T): Promise; + function Insert(doc: T): Promise; + + function Remove(refid: string, query: any): Promise; + function Remove(query: any): Promise; + + function Update(refid: string, query: T, update: U): Promise>; + function Update(query: T, update: U): Promise>; + + function Upsert(refid: string, query: T, update: U): Promise>; + function Upsert(query: T, update: U): Promise>; +} diff --git a/build-env/assets/static/js/main.js b/build-env/assets/static/js/main.js index 573b6f7..f434b10 100644 --- a/build-env/assets/static/js/main.js +++ b/build-env/assets/static/js/main.js @@ -74,11 +74,13 @@ Array.from(document.getElementsByClassName('jb-notification-dismiss')).forEach(e $('[jdenticon]').each(function (i, obj) { var str = $(this).attr('jdenticon'); var size = $(this).attr('jdenticon-size'); + if (str == '') str = Math.random().toString(); $(this).html(jdenticon.toSvg(str, parseInt(size))); }); $('[geopattern]').each(function (i, obj) { var str = $(this).attr('geopattern'); + if (str == '') str = undefined; $(this).css({ background: GeoPattern.generate(str).toDataUrl() }); }); })(); diff --git a/build-env/assets/static/js/plugin_profiles.js b/build-env/assets/static/js/plugin_profiles.js new file mode 100644 index 0000000..63ddcc7 --- /dev/null +++ b/build-env/assets/static/js/plugin_profiles.js @@ -0,0 +1,23 @@ +/* Delete Button */ +(() => { + let deleting = null; + $('.profile-delete').on('click', e => { + deleting = e.currentTarget.getAttribute('deleting'); + const name = e.currentTarget.getAttribute('deleting-name'); + $('#confirm-modal-title').text(`Deleting ${name}`); + }); + + $('#confirm-delete').on('click', _ => { + if (deleting == null) { + location.reload(true); + } + axios + .delete(`/profile/${deleting}`) + .then(response => { + location.reload(true); + }) + .catch(error => { + location.reload(true); + }); + }); +})(); diff --git a/build-env/assets/views/404.pug b/build-env/assets/views/404.pug index 58c4151..5ec0ad9 100644 --- a/build-env/assets/views/404.pug +++ b/build-env/assets/views/404.pug @@ -1,13 +1,11 @@ extends _layout.pug block content - - var style = `background: ${random};` - section.hero.is-dark(style=style) + section.hero.is-dark(geopattern) .hero-body .columns .column.is-narrow - .image.is-128x128 - img(src=`data:image/svg+xml;base64,${art}` style="background-color: #ffffffaa") + .image.is-128x128(style="background-color: #ffffffaa" jdenticon jdenticon-size=128) .column h1.title Oh well. p.subtitle At least I have a random pattern for you to look at. diff --git a/build-env/assets/views/500.pug b/build-env/assets/views/500.pug index 24b5475..6491141 100644 --- a/build-env/assets/views/500.pug +++ b/build-env/assets/views/500.pug @@ -1,13 +1,11 @@ extends _layout.pug block content - - var style = `background: ${random};` - section.hero.is-dark(style=style) + section.hero.is-dark(geopattern) .hero-body .columns .column.is-narrow - .image.is-128x128 - img(src=`data:image/svg+xml;base64,${art}` style="background-color: #ffffffaa") + .image.is-128x128(style="background-color: #ffffffaa" jdenticon jdenticon-size=128) .column h1.title Something went wrong p.subtitle Let me distract you with this random pattern. diff --git a/build-env/assets/views/_layout.pug b/build-env/assets/views/_layout.pug index 53450d7..47cf9a2 100644 --- a/build-env/assets/views/_layout.pug +++ b/build-env/assets/views/_layout.pug @@ -6,7 +6,7 @@ mixin li_menu_item(icon, label, link) i.mdi(class='mdi-'+icon) span.menu-item-label #{label} -mixin li_plugin(icon, label, link) +mixin li_plugin(icon, label, link, pages) li(class=(plugin == link) ? 'is-active' : '') a.has-icon.has-dropdown-icon(class=(plugin == link) ? 'is-active' : '' href='/plugin/' + link) span.icon @@ -19,9 +19,13 @@ mixin li_plugin(icon, label, link) i.mdi.mdi-minus ul li - a(href=link class=(((title == label) && (subtitle == 'Overview')) ? 'is-active' : '')) + a(href=`/plugin/${link}` class=(((title == label) && (subtitle == 'Overview')) ? 'is-active' : '')) span Overview - + a(href=`/plugin/${link}/profiles` class=(((title == label) && (subtitle == 'Profiles')) ? 'is-active' : '')) + span Profiles + each page in pages + a(href=`/plugin/${link}/${page.link}` class=(((title == label) && (subtitle == page.name)) ? 'is-active' : '')) + span #{page.name} html.has-aside-left.has-aside-mobile-transition.has-navbar-fixed-top.has-aside-expanded head meta(charset="utf-8") @@ -98,7 +102,7 @@ html.has-aside-left.has-aside-mobile-transition.has-navbar-fixed-top.has-aside-e var isAlpha = /[a-z]/.test(char); var isNumeric = /[0-9]/.test(char); var icon = isAlpha ? `alpha-${char}-circle` : (isNumeric ? `numeric-${char}-circle` : 'record-circle'); - +li_plugin(icon, label, link) + +li_plugin(icon, label, link, plugin.pages) .content section.hero.is-hero-bar .hero-body diff --git a/build-env/assets/views/custom.pug b/build-env/assets/views/custom.pug new file mode 100644 index 0000000..3956458 --- /dev/null +++ b/build-env/assets/views/custom.pug @@ -0,0 +1,4 @@ +extends _layout.pug + +block content + | !{content} \ No newline at end of file diff --git a/build-env/assets/views/data.pug b/build-env/assets/views/data.pug index cba84e1..7d88c6b 100644 --- a/build-env/assets/views/data.pug +++ b/build-env/assets/views/data.pug @@ -1,21 +1,25 @@ extends _layout.pug block content - .notification.is-danger - h4.title - span.icon - i.mdi.mdi-alert - | Danger Zone - p Here you can erase each plugin's data. You will NOT be able to undo any action here. - p Note that plugins that you already uninstalled will still show up here, so you can clear their data if you don't want them anymore. - p PROCEED WITH CAUTION - .columns - .column - .card - header.card-header - p.card-header-title - span.icon - i.mdi.mdi-account - | Profile - .card-content - .column \ No newline at end of file + .notification.is-success + h4.title Coming Soon + p Interactive query and plugin data management will come later. + p In the mean time, you can just delete savedata.db to clear all data. + //- .notification.is-danger + //- h4.title + //- span.icon + //- i.mdi.mdi-alert + //- | Danger Zone + //- p Here you can erase each plugin's data. You will NOT be able to undo any action here. + //- p Note that plugins that you already uninstalled will still show up here, so you can clear their data if you don't want them anymore. + //- p PROCEED WITH CAUTION + //- .columns + //- .column + //- .card + //- header.card-header + //- p.card-header-title + //- span.icon + //- i.mdi.mdi-account + //- | Profile + //- .card-content + //- .column \ No newline at end of file diff --git a/build-env/assets/views/plugin_profiles.pug b/build-env/assets/views/plugin_profiles.pug new file mode 100644 index 0000000..c87cb71 --- /dev/null +++ b/build-env/assets/views/plugin_profiles.pug @@ -0,0 +1,68 @@ +extends _layout.pug + +block content + if profiles.length > 0 + .columns.is-multiline + each profile in profiles + .column.is-one-half + .card + header.card-header + p.card-header-title + span.icon + i.mdi.mdi-file + | #{profile.coreProfile.name} + .card-content + .level + .level-item.has-text-centered + .image.is-64x64(jdenticon=profile.coreProfile.name jdenticon-size=64) + .level-item.has-text-centered + div + p.heading ID + p + span.tag.is-info #{profile.refid} + .level + .level-item.has-text-centered + div + p.heading Name + p.subtitle #{profile.name} + .level-item.has-text-centered + div + p.heading Data Usage + p.subtitle #{profile.dataSize} + .buttons.is-right + a.button.is-primary(href=`/plugin/${plugin}/profile?refid=${profile.refid}`) + span.icon.is-small + i.mdi.mdi-account-edit + span Edit + button.button.is-danger.is-outlined + span.icon.is-small + i.mdi.mdi-trash-can + span Delete + + + else + section.section + .content.has-text-grey.has-text-centered + p + span.icon.is-large + i.mdi.mdi-emoticon-happy.mdi-48px + p Nothing's here yet. Let's play! + + .modal#confirm-modal + .modal-background.jb-modal-close + .modal-card + header.modal-card-head + span.icon.has-text-danger + i.mdi.mdi-alert.mdi-18px + p.modal-card-title.has-text-weight-semibold#confirm-modal-title Deleting + section.modal-card-body + p + b Are you sure? + p You will not be able to undo this action. + footer.modal-card-foot + button.button.jb-modal-close Cancel + button.button.is-danger#confirm-delete Delete + button.modal-close.is-large.jb-modal-close + +block scripts + script(type="text/javascript" src="/static/js/plugin_profiles.js") \ No newline at end of file diff --git a/build-env/assets/views/profiles.pug b/build-env/assets/views/profiles.pug index f49c025..e903963 100644 --- a/build-env/assets/views/profiles.pug +++ b/build-env/assets/views/profiles.pug @@ -8,16 +8,13 @@ block content p.card-header-title span.icon i.mdi.mdi-account-multiple - | Profiles - a(href="javascript:window.location.reload(true)" data-tooltip='Refresh') - span.icon - i.mdi.mdi-reload + | Players .card-content if profiles.length > 0 .table-container table.table.is-fullwidth.is-striped.is-hoverable thead - tr.is-size-5 + tr th th Name th.is-hidden-mobile ID @@ -25,18 +22,18 @@ block content th tbody each profile, index in profiles - tr.is-size-5 + tr td.is-image-cell .image.is-32x32(jdenticon=profile.name jdenticon-size='32') - td #{profile.name} - td.is-hidden-mobile #{profile.refid} - td #{profile.cards} - td + td.has-padding-top-7 #{profile.name} + td.is-hidden-mobile.has-padding-top-7 #{profile.__refid} + td.has-padding-top-7 #{profile.cards} + td.has-padding-right-5 .buttons.is-right.are-small - a.button.is-primary(href=`/profile/${profile.refid}`) + a.button.is-primary(href=`/profile/${profile.__refid}` data-tooltip="Edit") span.icon i.mdi.mdi-account-edit.mdi-18px - a.button.is-danger.jb-modal.profile-delete(data-target="confirm-modal" deleting=profile.refid deleting-name=profile.name) + a.button.is-danger.jb-modal.profile-delete(data-target="confirm-modal" deleting=profile.__refid deleting-name=profile.name data-tooltip="Delete") span.icon i.mdi.mdi-trash-can.mdi-18px else diff --git a/build-env/assets/views/profiles_profile.pug b/build-env/assets/views/profiles_profile.pug index 7ccb429..e0c1332 100644 --- a/build-env/assets/views/profiles_profile.pug +++ b/build-env/assets/views/profiles_profile.pug @@ -8,7 +8,7 @@ block content p.card-header-title span.icon i.mdi.mdi-account - | Profile + | Details .card-content .columns .column.is-narrow @@ -20,7 +20,7 @@ block content .field-body .field .control - span.tag.is-info#refid #{profile.refid} + span.tag.is-info#refid #{profile.__refid} form(method='post') .field.is-horizontal.is-narrow .field-label.is-normal @@ -44,7 +44,10 @@ block content else .notification.is-success.is-light #{formMessage.message} .control - button.button.is-link(type='submit') Change + button.button.is-link(type='submit') + span.icon.is-small + i.mdi.mdi-pencil + span Change .column .card header.card-header @@ -55,13 +58,15 @@ block content .card-content .field.is-horizontal.is-narrow .field-label.is-normal - label.label New Card + label.label Add .field-body .field.has-addons .control.is-expanded input.input#card-input(type='text' placeholder='Card Number' name='card') .control - button.button.is-primary#add-card Add + button.button.is-primary#add-card + span.icon.is-small + i.mdi.mdi-plus each card in profile.cards .ecard.box.is-paddingless(geopattern=card.cid) .ecard-brand ASPHYXIA diff --git a/build-env/package.json b/build-env/package.json index bd692b4..4aec7c8 100644 --- a/build-env/package.json +++ b/build-env/package.json @@ -17,7 +17,6 @@ }, "dependencies": { "pug": "^2.0.4", - "systray": "^1.0.5", "ts-node": "^8.10.1" } } diff --git a/src/AsphyxiaCore.ts b/src/AsphyxiaCore.ts index 7f4cfed..47c2c12 100644 --- a/src/AsphyxiaCore.ts +++ b/src/AsphyxiaCore.ts @@ -34,25 +34,25 @@ function Main() { Logger.info(` `); const EAMUSE = express(); - // const WEBUI = express(); EAMUSE.disable('etag'); EAMUSE.disable('x-powered-by'); if (ARGS.dev) { - Logger.info(` [Console Output Enabled]`); + Logger.info(` [Developer Mode] Console Output Enabled`); + Logger.info(``); } + + ReadConfig(); const external = LoadExternalPlugins(); + SaveConfig(); + process.title = `Asphyxia CORE ${VERSION} | Plugins: ${external.length}`; if (external.length <= 0) { Logger.warn(chalk.yellowBright('no plugins are installed.')); Logger.info(''); } - // ========== READCONFIG =========== - ReadConfig(); - SaveConfig(); - // ========== EAMUSE ============ EAMUSE.set('views', path.join(ASSETS_PATH, 'views')); EAMUSE.set('view engine', 'pug'); @@ -62,6 +62,7 @@ function Main() { // ========== LISTEN ============ const server = EAMUSE.listen(CONFIG.port, CONFIG.bind, () => { + Logger.info(``); Logger.info(` [core] Server started:`); const serverInfo = `http://${CONFIG.bind}:${CONFIG.port}`; Logger.info(` +============= Service & WebUI ============+`); diff --git a/src/eamuse/Core/CardManager.ts b/src/eamuse/Core/CardManager.ts index 59c7b1d..e405ff0 100644 --- a/src/eamuse/Core/CardManager.ts +++ b/src/eamuse/Core/CardManager.ts @@ -35,7 +35,7 @@ cardmng.add('cardmng.inquire', async (info, data, send) => { return send.status(112); } - const profile = await FindProfile(card.refid); + const profile = await FindProfile(card.__refid); if (!profile) { await DeleteCard(cid); return send.status(112); @@ -49,11 +49,11 @@ cardmng.add('cardmng.inquire', async (info, data, send) => { send.object({ '@attr': { binded: profile.models.indexOf(info.gameCode) >= 0, - dataid: card.refid, + dataid: card.__refid, ecflag: 1, expired: 0, newflag: 0, - refid: card.refid, + refid: card.__refid, }, }); @@ -67,10 +67,10 @@ cardmng.add('cardmng.getrefid', async (info, data, send) => { const card = await FindCard(cid); if (card) { // Card exists, update profile pin - const updated = await UpdateProfile(card.refid, { pin }, true); + const updated = await UpdateProfile(card.__refid, { pin }, true); if (updated) { - await BindProfile(card.refid, info.gameCode); - return send.object({ '@attr': { dataid: card.refid, refid: card.refid } }); + await BindProfile(card.__refid, info.gameCode); + return send.object({ '@attr': { dataid: card.__refid, refid: card.__refid } }); } else { return send.deny(); } @@ -82,7 +82,7 @@ cardmng.add('cardmng.getrefid', async (info, data, send) => { return send.deny(); } - const refid = newProfile.refid; + const refid = newProfile.__refid; const newCard = await CreateCard(cid, refid); if (!newCard) { diff --git a/src/eamuse/EamusePlugin.ts b/src/eamuse/EamusePlugin.ts index 48dabbb..d39a10d 100644 --- a/src/eamuse/EamusePlugin.ts +++ b/src/eamuse/EamusePlugin.ts @@ -3,6 +3,9 @@ import { EamuseInfo } from '../middlewares/EamuseMiddleware'; import { EamuseSend } from './EamuseSend'; import { isNil } from 'lodash'; import { Logger } from '../utils/Logger'; +import { PLUGIN_PATH, APIFindOne, APIFind } from '../utils/EamuseIO'; +import path from 'path'; +import { readdirSync, readFileSync } from 'fs'; import { FindCard, CreateProfile, @@ -11,6 +14,9 @@ import { GetProfileCount, } from '../utils/EamuseIO'; +import { compile } from 'pug'; +import { CONFIG } from '../utils/ArgConfig'; + async function cardToRef(gameCode: string, str: string, refMap: any): Promise { const regex = /(^|\s*)([0|E][A-F|a-f|0-9]{15})($|\s+)/g; for (const match of str.matchAll(regex)) { @@ -24,12 +30,12 @@ async function cardToRef(gameCode: string, str: string, refMap: any): Promise= 16) return null; const newProfile = await CreateProfile('unset', gameCode); if (!newProfile) return null; - const newCard = await CreateCard(cid, newProfile.refid); + const newCard = await CreateCard(cid, newProfile.__refid); if (!newCard) return null; - refMap[cid] = newCard.refid; + refMap[cid] = newCard.__refid; } else { - refMap[cid] = card.refid; - await BindProfile(card.refid, gameCode); + refMap[cid] = card.__refid; + await BindProfile(card.__refid, gameCode); } } return str.replace(regex, (_, start, card, end) => { @@ -80,13 +86,99 @@ export class EamusePlugin { link?: string; }[]; + private uiPages: string[]; + private uiProfiles: string[]; + private uiCache: { + [file: string]: { + props: { [field: string]: string }; + fn: (local: any) => string; + }; + }; + constructor(folderName: string) { - this.pluginName = folderName.split('@')[0]; + this.pluginName = folderName.split('@')[0].toUpperCase(); this.pluginIdentifier = folderName; this.gameCodes = []; this.routes = {}; this.unhandled = false; this.contributors = []; + + this.uiPages = []; + this.uiProfiles = []; + this.uiCache = {}; + const webuiPath = path.join(PLUGIN_PATH, folderName, 'webui'); + try { + const files = readdirSync(webuiPath, { encoding: 'utf8', withFileTypes: true }).filter( + file => + file.isFile() && + file.name.endsWith('.pug') && + !file.name.startsWith('_') && + file.name != 'profiles.pug' && + file.name != 'profile.pug' + ); + this.uiPages = files + .filter(f => !f.name.startsWith('profile_')) + .map(f => path.basename(f.name, '.pug')) + .sort(); + this.uiProfiles = files + .filter(f => f.name.startsWith('profile_')) + .map(f => path.basename(f.name, '.pug')) + .sort(); + this.CompilePages(); + } catch {} + } + + private ExpressionCheck(isProfile: boolean, expression: string) { + const nothingFunc = () => {}; + + const DB = { + FindOne: nothingFunc, + Find: nothingFunc, + }; + const U = { + GetConfig: nothingFunc, + }; + + if (isProfile) { + const refid: any = undefined; + eval(expression); + } else { + eval(expression); + } + } + + private CompilePages() { + for (const page of this.uiPages.concat(this.uiProfiles)) { + const filePath = path.join(PLUGIN_PATH, this.pluginIdentifier, 'webui', `${page}.pug`); + try { + const template = readFileSync(filePath, { encoding: 'utf8' }); + + const dataBlocks = template.match( + /^\/\/DATA\/\/\s*$[\n|\r|\n\r]((?:^\s+[_a-z]\w*:\s*.+$[\n|\r|\n\r]?)+)/gm + ); + + const fn = compile(template); + const props: { [field: string]: string } = {}; + + for (const block of dataBlocks) { + const lines = block.matchAll(/([_a-z]\w*):\s*(.*)/g); + for (const parts of lines) { + const field = parts[1]; + const expression = parts[2]; + + this.ExpressionCheck(page.startsWith('profile_'), expression); + props[field] = expression; + } + } + + this.uiCache[page] = { props, fn }; + } catch (err) { + Logger.error(`can not compile WebUI file "${page}.pug":`, { + plugin: this.pluginIdentifier, + }); + Logger.error(err, { plugin: this.pluginIdentifier }); + } + } } public RegisterContributor(name: string, link?: string) { @@ -109,6 +201,48 @@ export class EamusePlugin { } } + public get Pages() { + return this.uiPages; + } + + public get ProfilePages() { + return this.uiProfiles; + } + + public get FirstProfilePage() { + if (this.uiProfiles.length > 0) { + return this.uiProfiles[0]; + } + return null; + } + + public async render(page: string, refid?: string) { + const cache = this.uiCache[page]; + if (!cache) return null; + + const DB = { + FindOne: (arg1: any, arg2?: any) => { + return APIFindOne({ name: this.pluginIdentifier, core: false }, arg1, arg2); + }, + Find: (arg1: any, arg2?: any) => { + return APIFind({ name: this.pluginIdentifier, core: false }, arg1, arg2); + }, + }; + const U = { + GetConfig: (key: string) => { + if (!CONFIG[this.pluginIdentifier]) return undefined; + return CONFIG[this.pluginIdentifier][key]; + }, + }; + + const local: any = { refid }; + for (const prop in cache.props) { + local[prop] = await eval(cache.props[prop]); + } + + return cache.fn(local); + } + public async run( moduleName: string, method: string, diff --git a/src/eamuse/EamuseRootRouter.ts b/src/eamuse/EamuseRootRouter.ts index 33691af..9ff1e5b 100644 --- a/src/eamuse/EamuseRootRouter.ts +++ b/src/eamuse/EamuseRootRouter.ts @@ -1,13 +1,12 @@ import { EamuseRouteContainer, EamuseRouteHandler } from './EamuseRouteContainer'; import { EamusePlugin } from './EamusePlugin'; -import { Logger } from '../utils/Logger'; import { EamuseInfo } from '../middlewares/EamuseMiddleware'; import { EamuseSend } from './EamuseSend'; export class EamuseRootRouter { private core: EamuseRouteContainer; private pluginMap: { - [gameCode: string]: EamusePlugin; + [gameCode: string]: EamusePlugin[]; }; private pluginMapID: { [name: string]: EamusePlugin; @@ -32,12 +31,9 @@ export class EamuseRootRouter { for (const plugin of plugins) { for (const code of plugin.GameCodes) { if (this.pluginMap[code]) { - Logger.warn( - `register failed - '${code}' is already registered by ${this.pluginMap[code].Name}`, - { plugin: plugin.Identifier } - ); + this.pluginMap[code].push(plugin); } else { - this.pluginMap[code] = plugin; + this.pluginMap[code] = [plugin]; } } this.pluginMapID[plugin.Identifier] = plugin; @@ -53,11 +49,14 @@ export class EamuseRootRouter { send: EamuseSend ) { if (await this.core.run(moduleName, method, info, data, send)) return; - if ( - this.pluginMap[gameCode] && - (await this.pluginMap[gameCode].run(moduleName, method, info, data, send)) - ) - return; + if (this.pluginMap[gameCode]) { + let success = false; + for (const plugin of this.pluginMap[gameCode]) { + const res = await plugin.run(moduleName, method, info, data, send); + success = success || res; + } + if (success) return; + } await send.deny(); return; diff --git a/src/eamuse/EamuseSend.ts b/src/eamuse/EamuseSend.ts index ae0d0d8..05c4143 100644 --- a/src/eamuse/EamuseSend.ts +++ b/src/eamuse/EamuseSend.ts @@ -6,11 +6,12 @@ import LzKN from '../utils/LzKN'; import { GetCallerPlugin, PLUGIN_PATH } from '../utils/EamuseIO'; import { Logger } from '../utils/Logger'; -import { render as ejs, renderFile as ejsFile } from 'ejs'; -import { render as pug, renderFile as pugFile } from 'pug'; +import { render as ejs, compile as ejsCompile } from 'ejs'; +import { render as pug, compileFile as pugCompileFile } from 'pug'; import path from 'path'; import { EABody } from '../middlewares/EamuseMiddleware'; import chalk from 'chalk'; +import { readFileSync } from 'fs'; export interface EamuseSendOption { status?: number; @@ -31,7 +32,7 @@ export class EamuseSend { this.res = res; } - async object(content: any = {}, options: EamuseSendOption = {}) { + object(content: any = {}, options: EamuseSendOption = {}) { if (this.sent) { Logger.warn( `duplicated send operation from ${chalk.yellowBright( @@ -39,10 +40,10 @@ export class EamuseSend { )}` ); return; + } else { + this.sent = true; } - this.sent = true; - const encoding = defaultTo(options.encoding, this.body.encoding); const status = defaultTo(options.status, get(content, '@attr.status', 0)); const rootName = defaultTo(options.rootName, this.body.module); @@ -80,10 +81,15 @@ export class EamuseSend { data = key.encrypt(data); } + const plugin = GetCallerPlugin(); + if (plugin) { + this.res.setHeader('X-CORE-Plugin', plugin.identifier); + } + this.res.send(data); } - async xml(template: string, data?: any, options?: EamuseSendOption) { + xml(template: string, data?: any, options?: EamuseSendOption) { const plugin = GetCallerPlugin(); if (!plugin) { Logger.error(`unexpected error: unknown plugin`); @@ -103,7 +109,7 @@ export class EamuseSend { } } - async pug(template: string, data?: any, options?: EamuseSendOption) { + pug(template: string, data?: any, options?: EamuseSendOption) { const plugin = GetCallerPlugin(); if (!plugin) { Logger.error(`unexpected error: unknown plugin`); @@ -123,7 +129,7 @@ export class EamuseSend { } } - async xmlFile(template: string, data?: any, options?: EamuseSendOption) { + xmlFile(template: string, data?: any, options?: EamuseSendOption) { const plugin = GetCallerPlugin(); if (!plugin) { Logger.error(`unexpected error: unknown plugin`); @@ -131,8 +137,9 @@ export class EamuseSend { } try { - const xml = await ejsFile(path.join(PLUGIN_PATH, plugin.identifier, template), data, {}); - const result = xmlToData(xml); + const filePath = path.join(PLUGIN_PATH, plugin.identifier, template); + const fn = ejsCompile(readFileSync(filePath, { encoding: 'utf8' })); + const result = xmlToData(fn(data)); const keys = Object.keys(result); if (keys.length <= 0) return this.object({}, options); @@ -144,7 +151,7 @@ export class EamuseSend { } } - async pugFile(template: string, data?: any, options?: EamuseSendOption) { + pugFile(template: string, data?: any, options?: EamuseSendOption) { const plugin = GetCallerPlugin(); if (!plugin) { Logger.error(`unexpected error: unknown plugin`); @@ -152,7 +159,9 @@ export class EamuseSend { } try { - const result = xmlToData(pugFile(path.join(PLUGIN_PATH, plugin.identifier, template), data)); + const filePath = path.join(PLUGIN_PATH, plugin.identifier, template); + const fn = pugCompileFile(filePath); + const result = xmlToData(fn(data)); const keys = Object.keys(result); if (keys.length <= 0) return this.object({}, options); diff --git a/src/eamuse/ExternalPluginLoader.ts b/src/eamuse/ExternalPluginLoader.ts index da7929f..aa0140a 100644 --- a/src/eamuse/ExternalPluginLoader.ts +++ b/src/eamuse/ExternalPluginLoader.ts @@ -1,4 +1,4 @@ -import { kitem, karray, kattr, dataToXML } from '../utils/KBinJSON'; +import { kitem, karray, kattr, dataToXML, xmlToData } from '../utils/KBinJSON'; import path from 'path'; import { getAttr, @@ -15,11 +15,27 @@ import { } from '../utils/KBinJSON'; import { Logger } from '../utils/Logger'; import { KDataReader } from '../utils/KDataReader'; -import { PLUGIN_PATH, WriteFile, GetCallerPlugin } from '../utils/EamuseIO'; -import { readdirSync, existsSync, statSync } from 'fs'; -import { ARGS, PluginRegisterConfig } from '../utils/ArgConfig'; +import { + PLUGIN_PATH, + Resolve, + Exists, + WriteFile, + ReadFile, + ReadDir, + GetCallerPlugin, + APIFindOne, + APIFind, + APIInsert, + APIRemove, + APIUpdate, + APIUpsert, + APICount, +} from '../utils/EamuseIO'; +import { readdirSync, existsSync } from 'fs'; +import { ARGS, PluginRegisterConfig, CONFIG } from '../utils/ArgConfig'; import { EamusePlugin } from './EamusePlugin'; import { EamuseRouteHandler } from './EamuseRouteContainer'; +import xml2json from 'fast-xml-parser'; /* Exposing API */ const $: any = global; @@ -57,11 +73,88 @@ $.K = { ARRAY: karray, }; -$.DB = {}; +$.IO = { + Resolve, + Exists, + WriteFile, + ReadFile, + ReadDir, +}; + +$.DB = { + FindOne: async (arg1: any, arg2?: any) => { + const plugin = GetCallerPlugin(); + if (!plugin) { + Logger.error('DB unknown error'); + return null; + } + return APIFindOne({ name: plugin.identifier, core: false }, arg1, arg2); + }, + Find: async (arg1: any, arg2?: any) => { + const plugin = GetCallerPlugin(); + if (!plugin) { + Logger.error('DB unknown error'); + return []; + } + return APIFind({ name: plugin.identifier, core: false }, arg1, arg2); + }, + Insert: async (arg1: any, arg2?: any) => { + const plugin = GetCallerPlugin(); + if (!plugin) { + Logger.error('DB unknown error'); + return null; + } + return APIInsert({ name: plugin.identifier, core: false }, arg1, arg2); + }, + Remove: async (arg1: any, arg2?: any) => { + const plugin = GetCallerPlugin(); + if (!plugin) { + Logger.error('DB unknown error'); + return 0; + } + return APIRemove({ name: plugin.identifier, core: false }, arg1, arg2); + }, + Update: async (arg1: any, arg2: any, arg3?: any) => { + const plugin = GetCallerPlugin(); + if (!plugin) { + Logger.error('DB unknown error'); + return 0; + } + return APIUpdate({ name: plugin.identifier, core: false }, arg1, arg2, arg3); + }, + Upsert: async (arg1: any, arg2: any, arg3?: any) => { + const plugin = GetCallerPlugin(); + if (!plugin) { + Logger.error('DB unknown error'); + return 0; + } + return APIUpsert({ name: plugin.identifier, core: false }, arg1, arg2, arg3); + }, + Count: async (arg1: any, arg2?: any) => { + const plugin = GetCallerPlugin(); + if (!plugin) { + Logger.error('DB unknown error'); + return 0; + } + return APICount({ name: plugin.identifier, core: false }, arg1, arg2); + }, +}; $.U = { toXML: dataToXML, - WriteFile, + parseXML: (xml: string, simplify: boolean = true) => { + if (simplify) { + return xml2json.parse(xml); + } else { + return xmlToData(xml); + } + }, + GetConfig: (key: string) => { + const plugin = GetCallerPlugin(); + if (!plugin) return undefined; + if (!CONFIG[plugin.identifier]) return undefined; + return CONFIG[plugin.identifier][key]; + }, }; $.R = { @@ -135,21 +228,22 @@ export function LoadExternalPlugins() { const loaded: EamusePlugin[] = []; try { - const plugins = readdirSync(PLUGIN_PATH).filter(fileName => - statSync(path.join(PLUGIN_PATH, fileName)).isDirectory() - ); + const plugins = readdirSync(PLUGIN_PATH, { + encoding: 'utf8', + withFileTypes: true, + }).filter(fileName => fileName.isDirectory()); const instances: { instance: any; name: string }[] = []; - for (const mod of plugins) { - const name = path.basename(mod); - const pluginPath = path.resolve(PLUGIN_PATH, mod); + for (const dir of plugins) { + const name = path.basename(dir.name); + const pluginPath = path.resolve(PLUGIN_PATH, dir.name); if ( - mod.startsWith('_') || - mod.startsWith('.') || - mod.startsWith('core') || - mod == 'node_modules' + dir.name.startsWith('_') || + dir.name.startsWith('.') || + dir.name.startsWith('core') || + dir.name == 'node_modules' ) continue; diff --git a/src/utils/ArgConfig.ts b/src/utils/ArgConfig.ts index bb97c89..86a06a1 100644 --- a/src/utils/ArgConfig.ts +++ b/src/utils/ArgConfig.ts @@ -27,21 +27,6 @@ parser.addArgument(['-b', '--bind'], { 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, @@ -50,26 +35,13 @@ parser.addArgument(['-m', '--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.', +parser.addArgument(['--dev', '--console'], { + help: 'Developer mode: Enable console for plugins and data management features', 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 { @@ -172,6 +144,37 @@ export function PluginRegisterConfig(key: string, options: CONFIG_OPTIONS) { } CONFIG_MAP[plugin.identifier].set(key, options); + NormalizeConfig(plugin.identifier, key, options); +} + +export function NormalizeConfig(plugin: string, key: string, option: CONFIG_OPTIONS) { + let section = INI; + if (plugin != 'core') { + if (!INI[plugin]) { + INI[plugin] = {}; + } + section = INI[plugin]; + } + + if (section[key] == null) { + section[key] = option.default; + } else { + if (option.type == 'boolean') { + section[key] = section[key].toString() == 'true'; + } else if (option.type == 'integer') { + section[key] = parseInt(section[key]); + if (isNaN(section[key])) { + section[key] = option.default; + } + } else if (option.type == 'float') { + section[key] = parseFloat(section[key]); + if (isNaN(section[key])) { + section[key] = option.default; + } + } else { + section[key] = section[key].toString(); + } + } } export function ReadConfig() { @@ -182,36 +185,8 @@ export function ReadConfig() { INI = {}; } - for (const mod in CONFIG_MAP) { - let section = INI; - if (mod != 'core') { - if (!INI[mod]) { - INI[mod] = {}; - } - section = INI[mod]; - } - - for (const [key, option] of CONFIG_MAP[mod]) { - if (section[key] == null) { - section[key] = option.default; - } else { - if (option.type == 'boolean') { - section[key] = section[key].toString() == 'true'; - } else if (option.type == 'integer') { - section[key] = parseInt(section[key]); - if (isNaN(section[key])) { - section[key] = option.default; - } - } else if (option.type == 'float') { - section[key] = parseFloat(section[key]); - if (isNaN(section[key])) { - section[key] = option.default; - } - } else { - section[key] = section[key].toString(); - } - } - } + for (const [key, option] of CONFIG_MAP['core']) { + NormalizeConfig('core', key, option); } } diff --git a/src/utils/EamuseIO.ts b/src/utils/EamuseIO.ts index 7a4a1f3..14d7635 100644 --- a/src/utils/EamuseIO.ts +++ b/src/utils/EamuseIO.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'; +import { existsSync, mkdirSync, readFileSync, writeFile, readFile, readdir, exists } from 'fs'; import { Logger } from './Logger'; import path from 'path'; @@ -8,6 +8,7 @@ import { compress, decompress } from './SMAZ'; import hashids from 'hashids/cjs'; import { NAMES } from './Consts'; import { CONFIG } from './ArgConfig'; +import { isArray, get } from 'lodash'; const pkg: boolean = (process as any).pkg; export const EXEC_PATH = pkg ? path.dirname(process.argv0) : process.cwd(); @@ -19,8 +20,8 @@ export const CONFIG_PATH = path.join(EXEC_PATH, 'config.ini'); const DB = new nedb({ filename: SAVE_PATH, timestampData: true, - afterSerialization: compress, - beforeDeserialization: decompress, + // afterSerialization: compress, + // beforeDeserialization: decompress, }); DB.loadDatabase(err => { @@ -72,6 +73,7 @@ export function GetCallerPlugin(): { name: string; identifier: string } { let entryFile = null; for (const file of stack) { const filename: string = file.getFileName(); + if (!filename) return null; if (filename.startsWith(PLUGIN_PATH)) { entryFile = path.relative(PLUGIN_PATH, filename); inPlugin = true; @@ -100,23 +102,6 @@ export function PrepareDirectory(dir: string = ''): string { return dir; } -export function WriteFile(file: string, data: string) { - const plugin = GetCallerPlugin(); - if (!plugin) return; - - let target = file; - if (!path.isAbsolute(file)) { - target = path.resolve(PLUGIN_PATH, plugin.identifier, file); - } - - try { - PrepareDirectory(path.dirname(target)); - writeFileSync(target, data); - } catch (err) { - Logger.error(`file writing failed: ${err}`, { plugin: plugin.identifier }); - } -} - export function ReadAssets(file: string): any { let fullFile = path.join(ASSETS_PATH, `${file}`); @@ -133,6 +118,112 @@ export function ReadAssets(file: string): any { } } +// ========================================= +// Public IO +// ========================================= +export function Resolve(file: string) { + const plugin = GetCallerPlugin(); + if (!plugin) return; + + return path.resolve(PLUGIN_PATH, plugin.identifier, file); +} + +export async function Exists(file: string) { + const plugin = GetCallerPlugin(); + if (!plugin) return; + + const target = path.resolve(PLUGIN_PATH, plugin.identifier, file); + + return new Promise(resolve => { + exists(target, exists => { + resolve(exists); + }); + }); +} + +export async function ReadDir(file: string) { + const plugin = GetCallerPlugin(); + if (!plugin) return; + + const target = path.resolve(PLUGIN_PATH, plugin.identifier, file); + + return new Promise<{ name: string; type: 'file' | 'dir' | 'unsupported' }[]>(resolve => { + readdir(target, { encoding: 'utf8', withFileTypes: true }, (err, files) => { + if (err) { + Logger.error(`file writing failed: ${err}`, { plugin: plugin.identifier }); + return resolve([]); + } + resolve( + files.map(file => ({ + name: file.name, + type: file.isFile() ? 'file' : file.isDirectory() ? 'dir' : 'unsupported', + })) + ); + }); + }); +} + +export async function WriteFile( + file: string, + data: string, + options: { encoding?: string | null; mode?: number | string; flag?: string } | string | null +) { + const plugin = GetCallerPlugin(); + if (!plugin) return; + + const target = path.resolve(PLUGIN_PATH, plugin.identifier, file); + + PrepareDirectory(path.dirname(target)); + + return new Promise(resolve => { + if (options == null) { + writeFile(target, data, err => { + if (err) { + Logger.error(`file writing failed: ${err}`, { plugin: plugin.identifier }); + } + resolve(); + }); + } else { + writeFile(target, data, options, err => { + if (err) { + Logger.error(`file writing failed: ${err}`, { plugin: plugin.identifier }); + } + resolve(); + }); + } + }); +} + +export async function ReadFile( + file: string, + options: { encoding?: string | null; flag?: string } | string | undefined | null +) { + const plugin = GetCallerPlugin(); + if (!plugin) return; + + const target = path.resolve(PLUGIN_PATH, plugin.identifier, file); + + return new Promise(resolve => { + if (options == null) { + readFile(target, (err, data) => { + if (err) { + Logger.error(`file reading failed: ${err}`, { plugin: plugin.identifier }); + return resolve(null); + } + return resolve(data); + }); + } else { + readFile(target, options, (err, data) => { + if (err) { + Logger.error(`file reading failed: ${err}`, { plugin: plugin.identifier }); + return resolve(null); + } + return resolve(data); + }); + } + }); +} + // ========================================= // DB Wrapper // ========================================= @@ -353,7 +444,7 @@ export async function GetProfiles() { function CheckQuery(query: any) { for (const key in query) { if (key.startsWith('__')) { - throw new Error('query field can not starts with "__"'); + throw new Error('query or doc field can not starts with "__"'); } if (typeof query[key] == 'object') { @@ -362,29 +453,52 @@ function CheckQuery(query: any) { } } -export async function APIFindOne(plugin: string, refid: string | null, query: any) { - CheckQuery(query); - const sanitized = { ...query }; +function CleanDoc(doc: any) { + for (const prop in doc) { + if (prop.startsWith('__')) { + delete doc[prop]; + } + } + return doc; +} - if (sanitized.owner) { - sanitized.__refid = sanitized.owner; - delete sanitized.owner; +export async function APIFindOne( + plugin: { name: string; core: boolean }, + arg1: string | any, + arg2?: any +) { + let query: any = null; + + if (typeof arg1 == 'string' && typeof arg2 == 'object') { + CheckQuery(arg2); + query = { + ...arg2, + __reserved_field: 'plugins_profile', + __affiliation: plugin.name, + __refid: arg1, + }; + } else if (typeof arg1 == 'object') { + CheckQuery(arg1); + query = { + ...arg1, + __reserved_field: 'plugins', + __affiliation: plugin.name, + }; + } else { + throw new Error('invalid FindOne query'); } return new Promise((resolve, reject) => { DB.findOne( - { - ...query, - __reserved_field: 'plugins', - __affiliation: plugin, - __refid: owner, - }, - { - __reserved_field: 0, - __affiliation: 0, - __collection: 0, - __refid: 0, - }, + query, + plugin.core + ? {} + : { + __reserved_field: 0, + __affiliation: 0, + __collection: 0, + __refid: 0, + }, (err, doc) => { if (err) reject(err); else resolve(doc); @@ -394,51 +508,49 @@ export async function APIFindOne(plugin: string, refid: string | null, query: an } export async function APIFind( - plugin: string, - owner: string = 'global', - key: string = 'default', - query: any = {}, - sort: any = { createdAt: 1 } + plugin: { name: string; core: boolean }, + arg1: string | any, + arg2?: any ) { - CheckQuery(query); + let query: any = null; + if (typeof arg1 == 'string' && typeof arg2 == 'object') { + CheckQuery(arg2); + query = { + ...arg2, + __reserved_field: 'plugins_profile', + __affiliation: plugin.name, + __refid: arg1, + }; + } else if (arg1 == null && typeof arg2 == 'object') { + CheckQuery(arg2); + query = { + ...arg2, + __reserved_field: 'plugins_profile', + __affiliation: plugin.name, + }; + } else if (typeof arg1 == 'object') { + CheckQuery(arg1); + query = { + ...arg1, + __reserved_field: 'plugins', + __affiliation: plugin.name, + }; + } else { + throw new Error('invalid Find query'); + } + return new Promise((resolve, reject) => { DB.find( - { - ...query, - __reserved_field: 'plugins', - __affiliation: plugin, - __collection: key, - __refid: owner, - }, - { - __reserved_field: 0, - __affiliation: 0, - __collection: 0, - __refid: 0, - } + query, + plugin.core + ? {} + : { + __reserved_field: 0, + __affiliation: 0, + __collection: 0, + __refid: 0, + } ) - .sort(sort) - .exec((err, doc) => { - if (err) reject(err); - else resolve(doc); - }); - }); -} - -export async function APIUpdate(plugin: string, key: string, query: any) { - CheckQuery(query); - return new Promise((resolve, reject) => { - DB.find({ - ...query, - __reserved_field: 'plugins', - __affiliation: plugin, - __collection: key, - }) - .projection({ - __reserved_field: 0, - __affiliation: 0, - __collection: 0, - }) .sort({ createdAt: 1 }) .exec((err, doc) => { if (err) reject(err); @@ -446,3 +558,236 @@ export async function APIUpdate(plugin: string, key: string, query: any) { }); }); } + +export async function APIInsert( + plugin: { name: string; core: boolean }, + arg1: string | any, + arg2?: any +) { + let doc: any = null; + if (typeof arg1 == 'string' && typeof arg2 == 'object') { + CheckQuery(arg2); + doc = { + ...arg2, + __reserved_field: 'plugins_profile', + __affiliation: plugin.name, + __refid: arg1, + }; + } else if (typeof arg1 == 'object') { + CheckQuery(arg1); + doc = { + ...arg1, + __reserved_field: 'plugins', + __affiliation: plugin.name, + }; + } else { + throw new Error('invalid Insert query'); + } + + return new Promise((resolve, reject) => { + DB.insert(doc, (err, doc) => { + if (err) reject(err); + else resolve(plugin.core ? doc : CleanDoc(doc)); + }); + }); +} + +export async function APIUpdate( + plugin: { name: string; core: boolean }, + arg1: string | any, + arg2: any, + arg3?: any +) { + let query: any = null; + let update: any = null; + let signiture: any = { __affiliation: plugin.name }; + if (typeof arg1 == 'string' && typeof arg2 == 'object' && typeof arg3 == 'object') { + CheckQuery(arg2); + CheckQuery(arg3); + query = arg2; + update = arg3; + signiture.__reserved_field = 'plugins_profile'; + signiture.__refid = arg1; + } else if (arg1 == null && typeof arg2 == 'object' && typeof arg3 == 'object') { + CheckQuery(arg2); + CheckQuery(arg3); + query = arg2; + update = arg3; + signiture.__reserved_field = 'plugins_profile'; + } else if (typeof arg1 == 'object' && typeof arg2 == 'object') { + CheckQuery(arg1); + CheckQuery(arg2); + query = arg1; + update = arg2; + signiture.__reserved_field = 'plugins'; + } else { + throw new Error('invalid Update query'); + } + + query = { ...query, ...signiture }; + + if (!get(Object.keys(update), '0', '').startsWith('$')) { + update = { + ...update, + ...signiture, + }; + } + + return new Promise((resolve, reject) => { + DB.update( + query, + update, + { upsert: false, multi: true, returnUpdatedDocs: true }, + (err, num, docs: any[]) => { + if (err) reject(err); + else + resolve({ + updated: num, + docs: isArray(docs) + ? docs.map(d => (plugin.core ? d : CleanDoc(d))) + : [plugin.core ? docs : CleanDoc(docs)], + }); + } + ); + }); +} + +export async function APIUpsert( + plugin: { name: string; core: boolean }, + arg1: string | any, + arg2: any, + arg3?: any +) { + let query: any = null; + let update: any = null; + let signiture: any = { __affiliation: plugin.name }; + if (typeof arg1 == 'string' && typeof arg2 == 'object' && typeof arg3 == 'object') { + CheckQuery(arg2); + CheckQuery(arg3); + query = arg2; + update = arg3; + signiture.__reserved_field = 'plugins_profile'; + signiture.__refid = arg1; + } else if (arg1 == null && typeof arg2 == 'object' && typeof arg3 == 'object') { + CheckQuery(arg2); + CheckQuery(arg3); + query = arg2; + update = arg3; + signiture.__reserved_field = 'plugins_profile'; + } else if (typeof arg1 == 'object' && typeof arg2 == 'object') { + CheckQuery(arg1); + CheckQuery(arg2); + query = arg1; + update = arg2; + signiture.__reserved_field = 'plugins'; + } else { + throw new Error('invalid Upsert query'); + } + + query = { ...query, ...signiture }; + + if (!get(Object.keys(update), '0', '').startsWith('$')) { + update = { + ...update, + ...signiture, + }; + } + return new Promise((resolve, reject) => { + DB.update( + query, + update, + { upsert: true, multi: true, returnUpdatedDocs: true }, + (err: Error, num: number, docs: any[], upsert: boolean = false) => { + if (err) reject(err); + else + resolve({ + updated: num, + docs: isArray(docs) + ? docs.map(d => (plugin.core ? d : CleanDoc(d))) + : [plugin.core ? docs : CleanDoc(docs)], + upsert: upsert ? true : false, + }); + } + ); + }); +} + +export async function APIRemove( + plugin: { name: string; core: boolean }, + arg1: string | any, + arg2?: any +) { + let query: any = null; + if (typeof arg1 == 'string' && typeof arg2 == 'object') { + CheckQuery(arg2); + query = { + ...arg2, + __reserved_field: 'plugins_profile', + __affiliation: plugin.name, + __refid: arg1, + }; + } else if (arg1 == null && typeof arg2 == 'object') { + CheckQuery(arg2); + query = { + ...arg2, + __reserved_field: 'plugins_profile', + __affiliation: plugin.name, + }; + } else if (typeof arg1 == 'object') { + CheckQuery(arg1); + query = { + ...arg1, + __reserved_field: 'plugins', + __affiliation: plugin.name, + }; + } else { + throw new Error('invalid Remove query'); + } + + return new Promise((resolve, reject) => { + DB.remove(query, { multi: true }, (err, num) => { + if (err) reject(err); + else resolve(num); + }); + }); +} + +export async function APICount( + plugin: { name: string; core: boolean }, + arg1: string | any, + arg2?: any +) { + let query: any = null; + if (typeof arg1 == 'string' && typeof arg2 == 'object') { + CheckQuery(arg2); + query = { + ...arg2, + __reserved_field: 'plugins_profile', + __affiliation: plugin.name, + __refid: arg1, + }; + } else if (arg1 == null && typeof arg2 == 'object') { + CheckQuery(arg2); + query = { + ...arg2, + __reserved_field: 'plugins_profile', + __affiliation: plugin.name, + }; + } else if (typeof arg1 == 'object') { + CheckQuery(arg1); + query = { + ...arg1, + __reserved_field: 'plugins', + __affiliation: plugin.name, + }; + } else { + throw new Error('invalid Count query'); + } + + return new Promise((resolve, reject) => { + DB.count(query, (err, num) => { + if (err) reject(err); + else resolve(num); + }); + }); +} diff --git a/src/webui/index.ts b/src/webui/index.ts index f4f97cf..3138d8e 100644 --- a/src/webui/index.ts +++ b/src/webui/index.ts @@ -20,6 +20,7 @@ import { CreateCard, FindCard, DeleteCard, + APIFind, } from '../utils/EamuseIO'; import { urlencoded, json } from 'body-parser'; import { Logger } from '../utils/Logger'; @@ -28,6 +29,8 @@ import path from 'path'; import { ROOT_CONTAINER } from '../eamuse/index'; import { fun } from './fun'; import { card2nfc, nfc2card, cardType } from '../utils/CardCipher'; +import { groupBy } from 'lodash'; +import { sizeof } from 'sizeof'; const memorystore = createMemoryStore(session); @@ -56,7 +59,11 @@ function data(req: Request, title: string, attr?: any) { version: VERSION, formMessage, plugins: ROOT_CONTAINER.Plugins.map(p => { - return { name: p.Name, id: p.Identifier }; + return { + name: p.Name, + id: p.Identifier, + pages: p.Pages.map(f => ({ name: humanize(f), link: f })), + }; }), ...attr, }; @@ -89,7 +96,7 @@ function validate(c: CONFIG_OPTIONS, current: any) { return null; } -function configData(plugin: string) { +function ConfigData(plugin: string) { const config: CONFIG_DATA[] = []; const configMap = CONFIG_MAP[plugin]; const configData = plugin == 'core' ? CONFIG : CONFIG[plugin]; @@ -138,7 +145,7 @@ webui.get( '/', wrap(async (req, res) => { const memory = `${(process.memoryUsage().rss / 1048576).toFixed(2)}MB`; - const config = configData('core'); + const config = ConfigData('core'); const changelog = markdown.makeHtml(ReadAssets('changelog.md')); @@ -152,7 +159,7 @@ webui.get( wrap(async (req, res) => { const profiles = await GetProfiles(); for (const profile of profiles) { - profile.cards = await Count({ __reserved_field: 'card', refid: profile.refid }); + profile.cards = await Count({ __reserved_field: 'card', __refid: profile.__refid }); } res.render('profiles', data(req, 'Profiles', { profiles })); }) @@ -182,6 +189,7 @@ webui.get( } profile.cards = await FindCardsByRefid(refid); + res.render('profiles_profile', data(req, 'Profiles', { profile, subtitle: profile.name })); }) ); @@ -280,6 +288,7 @@ webui.get( }) ); +// Plugin Overview webui.get( '/plugin/:plugin', wrap(async (req, res, next) => { @@ -300,14 +309,13 @@ webui.get( readme = null; } - const config = configData(pluginName); + const config = ConfigData(pluginName); const contributors = plugin ? plugin.Contributors : []; const gameCodes = plugin ? plugin.GameCodes : []; - const name = pluginName.split('@')[0].toUpperCase(); res.render( 'plugin', - data(req, name, { + data(req, plugin.Name, { plugin: pluginName, readme, config, @@ -319,6 +327,110 @@ webui.get( }) ); +// Plugin Profiles +webui.get( + '/plugin/:plugin/profiles', + wrap(async (req, res, next) => { + const pluginName = req.params['plugin']; + const plugin = ROOT_CONTAINER.getPluginByName(pluginName); + + if (!plugin) { + return next(); + } + + const profiles = groupBy( + await APIFind({ name: plugin.Identifier, core: true }, null, {}), + '__refid' + ); + + const profileData: any[] = []; + for (const refid in profiles) { + let name = undefined; + for (const doc of profiles[refid]) { + if (typeof doc.name == 'string') { + name = doc.name; + break; + } + } + + profileData.push({ + refid, + name, + dataSize: sizeof(profiles[refid], true), + coreProfile: await FindProfile(refid), + }); + } + + res.render( + 'plugin_profiles', + data(req, plugin.Name, { plugin: pluginName, subtitle: 'Profiles', profiles: profileData }) + ); + }) +); + +// Plugin Profile Page +webui.get( + '/plugin/:plugin/profile', + wrap(async (req, res, next) => { + const pluginName = req.params['plugin']; + const plugin = ROOT_CONTAINER.getPluginByName(pluginName); + + if (!plugin) { + return next(); + } + + const refid = req.query['refid']; + + if (refid == null) { + return next(); + } + + const pageName = req.query['page']; + + let page = null; + if (pageName == null) { + page = plugin.FirstProfilePage; + } else { + page = pageName.toString(); + } + + const content = await plugin.render(page, refid.toString()); + if (content == null) { + return next(); + } + + res.render( + 'custom', + data(req, plugin.Name, { content, subtitle: 'Profiles', plugin: pluginName }) + ); + }) +); + +// Plugin Custom Pages +webui.get( + '/plugin/:plugin/:page', + wrap(async (req, res, next) => { + const pluginName = req.params['plugin']; + const plugin = ROOT_CONTAINER.getPluginByName(pluginName); + + if (!plugin) { + return next(); + } + + const pageName = req.params['page']; + + const content = await plugin.render(pageName); + if (content == null) { + return next(); + } + + res.render( + 'custom', + data(req, plugin.Name, { content, subtitle: humanize(pageName), plugin: pluginName }) + ); + }) +); + // General setting update webui.post( '*',