mirror of
https://gitcode.com/gh_mirrors/hy/Hydro.git
synced 2026-10-19 17:38:19 +08:00
core: add provideModule and injectUI API
This commit is contained in:
1 parent
672c553f4c
commit
28f03dbcbd
18 files changed
+211
-97
No files matched your search
@@ -5,7 +5,7 @@ import AdmZip from 'adm-zip';
|
||||
import fs from 'fs-extra';
|
||||
import yaml from 'js-yaml';
|
||||
import { ValidationError } from '../error';
|
||||
import { ProblemAdd } from '../lib/ui';
|
||||
import { PluginContext } from '../loader';
|
||||
import { PERM, PRIV } from '../model/builtin';
|
||||
import problem, { ProblemDoc } from '../model/problem';
|
||||
import { Handler } from '../service/server';
|
||||
@@ -93,7 +93,7 @@ class ProblemImportHydroHandler extends Handler {
|
||||
}
|
||||
}
|
||||
|
||||
export async function apply(ctx) {
|
||||
ProblemAdd('problem_import_hydro', {}, 'copy', 'Import From Hydro');
|
||||
export async function apply(ctx: PluginContext) {
|
||||
ctx.Route('problem_import_hydro', '/problem/import/hydro', ProblemImportHydroHandler, PERM.PERM_CREATE_PROBLEM);
|
||||
ctx.inject('ProblemAdd', 'problem_import_hydro', { icon: 'copy', text: 'Import From Hydro' });
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
SystemError, UserAlreadyExistError, UserFacingError,
|
||||
UserNotFoundError, ValidationError, VerifyPasswordError,
|
||||
} from '../error';
|
||||
import { OAuthUserResponse, Udoc, User } from '../interface';
|
||||
import { Udoc, User } from '../interface';
|
||||
import avatar from '../lib/avatar';
|
||||
import { sendMail } from '../lib/mail';
|
||||
import { isEmail, isPassword } from '../lib/validator';
|
||||
@@ -359,7 +359,7 @@ class OauthHandler extends Handler {
|
||||
|
||||
@param('type', Types.String)
|
||||
async get(domainId: string, type: string) {
|
||||
await global.Hydro.lib[`oauth_${type}`]?.get?.call(this);
|
||||
await global.Hydro.module.oauth[type]?.get.call(this);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,8 +367,8 @@ class OauthCallbackHandler extends Handler {
|
||||
noCheckPermView = true;
|
||||
|
||||
async get(args: any) {
|
||||
if (!global.Hydro.lib[`oauth_${args.type}`]) throw new UserFacingError('Oauth type');
|
||||
const r = await global.Hydro.lib[`oauth_${args.type}`].callback.call(this, args) as OAuthUserResponse;
|
||||
if (!global.Hydro.module.oauth[args.type]) throw new UserFacingError('Oauth type');
|
||||
const r = await global.Hydro.module.oauth[args.type].callback.call(this, args);
|
||||
const uid = await oauth.get(r._id);
|
||||
if (uid) {
|
||||
await user.setById(uid, { loginat: new Date(), loginip: this.request.ip });
|
||||
|
||||
@@ -19,6 +19,12 @@ if (!global.Hydro) {
|
||||
script: {},
|
||||
// @ts-ignore
|
||||
lib: {},
|
||||
module: new Proxy({} as any, {
|
||||
get(self, key) {
|
||||
if (!self[key]) self[key] = {};
|
||||
return self[key];
|
||||
},
|
||||
}),
|
||||
// @ts-ignore
|
||||
ui: {
|
||||
template: {},
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Dictionary, NumericDictionary } from 'lodash';
|
||||
import type { ItemBucketMetadata } from 'minio';
|
||||
import type { Cursor, ObjectID } from 'mongodb';
|
||||
import type { ProblemDoc } from './model/problem';
|
||||
import type { Handler } from './service/server';
|
||||
|
||||
type document = typeof import('./model/document');
|
||||
|
||||
@@ -686,10 +687,11 @@ export interface ProblemSearchOptions {
|
||||
|
||||
export type ProblemSearch = (domainId: string, q: string, options?: ProblemSearchOptions) => Promise<ProblemSearchResponse>;
|
||||
|
||||
export { Context as PluginContext } from './service/module';
|
||||
|
||||
export interface Lib extends Record<string, any> {
|
||||
difficulty: typeof import('./lib/difficulty'),
|
||||
buildContent: typeof import('./lib/content').buildContent,
|
||||
'hash.hydro': typeof import('./lib/hash.hydro'),
|
||||
i18n: typeof import('./lib/i18n'),
|
||||
mail: typeof import('./lib/mail'),
|
||||
paginate: typeof import('./lib/paginate'),
|
||||
@@ -705,27 +707,36 @@ export interface Lib extends Record<string, any> {
|
||||
|
||||
export type UIInjectableFields = 'ProblemAdd' | 'Nav' | 'UserDropdown';
|
||||
export interface UI {
|
||||
template: Dictionary<string>,
|
||||
template: Record<string, string>,
|
||||
nodes: Record<UIInjectableFields, any[]>,
|
||||
getNodes: typeof import('./lib/ui').getNodes,
|
||||
Nav: typeof import('./lib/ui').Nav,
|
||||
ProblemAdd: typeof import('./lib/ui').ProblemAdd,
|
||||
inject: typeof import('./lib/ui').inject,
|
||||
}
|
||||
|
||||
export interface ModuleInterfaces {
|
||||
oauth: {
|
||||
text: string;
|
||||
icon?: string;
|
||||
get: (this: Handler) => Promise<void>;
|
||||
callback: (this: Handler, args: Record<string, any>) => Promise<OAuthUserResponse>;
|
||||
};
|
||||
hash: (password: string, salt: string, user: User) => boolean | string;
|
||||
}
|
||||
|
||||
export interface HydroGlobal {
|
||||
version: Record<string, string>,
|
||||
model: Model,
|
||||
version: Record<string, string>;
|
||||
model: Model;
|
||||
/** @deprecated */
|
||||
handler: Record<string, Function>,
|
||||
script: Record<string, Script>,
|
||||
service: Service,
|
||||
lib: Lib,
|
||||
ui: UI,
|
||||
error: typeof import('./error'),
|
||||
Logger: typeof import('./logger').Logger,
|
||||
logger: typeof import('./logger').logger,
|
||||
locales: Record<string, Record<string, string>>,
|
||||
handler: Record<string, Function>;
|
||||
script: Record<string, Script>;
|
||||
service: Service;
|
||||
lib: Lib;
|
||||
module: { [K in keyof ModuleInterfaces]: Record<string, ModuleInterfaces[K]> };
|
||||
ui: UI;
|
||||
error: typeof import('./error');
|
||||
Logger: typeof import('./logger').Logger;
|
||||
logger: typeof import('./logger').logger;
|
||||
locales: Record<string, Record<string, string>>;
|
||||
}
|
||||
|
||||
declare global {
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import crypto from 'crypto';
|
||||
|
||||
function hash(password: string, salt: string) {
|
||||
return crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha256').toString('hex').substr(0, 64);
|
||||
return crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha256').toString('hex').substring(0, 64);
|
||||
}
|
||||
|
||||
export = hash;
|
||||
|
||||
global.Hydro.lib['hash.hydro'] = hash;
|
||||
global.Hydro.module.hash.hydro = hash;
|
||||
@@ -31,7 +31,9 @@ export const nodes = new Proxy({}, {
|
||||
},
|
||||
});
|
||||
export function inject(node: UIInjectableFields, name: string, args: Record<string, any> = {}, ...permPrivChecker: PermPrivChecker) {
|
||||
nodes[node].push({ name, args: args || {}, checker: buildChecker(...permPrivChecker) });
|
||||
const obj = { name, args: args || {}, checker: buildChecker(...permPrivChecker) };
|
||||
nodes[node].push(obj);
|
||||
return () => { nodes[node] = nodes[node].filter((i) => i !== obj); };
|
||||
}
|
||||
export function getNodes(name: UIInjectableFields) {
|
||||
return nodes[name];
|
||||
@@ -65,5 +67,4 @@ inject('ProblemAdd', 'problem_create', { icon: 'add', text: 'Create Problem' });
|
||||
global.Hydro.ui.inject = inject;
|
||||
global.Hydro.ui.nodes = nodes as any;
|
||||
global.Hydro.ui.getNodes = getNodes;
|
||||
global.Hydro.ui.Nav = Nav;
|
||||
global.Hydro.ui.ProblemAdd = ProblemAdd;
|
||||
Object.assign(global.Hydro.ui, { ProblemAdd, Nav });
|
||||
@@ -132,7 +132,7 @@ export class User {
|
||||
}
|
||||
|
||||
checkPassword(password: string) {
|
||||
const h = global.Hydro.lib[`hash.${this.hashType}`];
|
||||
const h = global.Hydro.module.hash[this.hashType];
|
||||
if (!h) throw new Error('Unknown hash method');
|
||||
const result = h(password, this._salt, this);
|
||||
if (result !== true && result !== this._hash) {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import Schema from 'schemastery';
|
||||
import { inject } from '../lib/ui';
|
||||
import { ModuleInterfaces } from '../loader';
|
||||
import * as bus from './bus';
|
||||
|
||||
export const runtimes: Record<string, Runtime> = Object.create(null);
|
||||
@@ -9,6 +11,12 @@ function addScript<K>(name: string, description: string, validate: Schema<K>, ru
|
||||
return () => delete global.Hydro.script[name];
|
||||
}
|
||||
|
||||
function provideModule<T extends keyof ModuleInterfaces>(type: T, id: string, module: ModuleInterfaces[T]) {
|
||||
if (global.Hydro.module[type][id]) throw new Error(`duplicate script ${type}/${id} registered.`);
|
||||
global.Hydro.module[type as any][id] = module;
|
||||
return () => delete global.Hydro.module[type][id];
|
||||
}
|
||||
|
||||
export interface Context {
|
||||
Route: typeof import('./server').Route;
|
||||
Connection: typeof import('./server').Connection;
|
||||
@@ -16,6 +24,8 @@ export interface Context {
|
||||
once: typeof bus['once'];
|
||||
off: typeof bus['off'];
|
||||
addScript: typeof addScript;
|
||||
provideModule: typeof provideModule;
|
||||
inject: typeof inject;
|
||||
}
|
||||
|
||||
export class Runtime {
|
||||
@@ -46,6 +56,8 @@ export class Runtime {
|
||||
setInterval: T(setInterval, clearInterval),
|
||||
setTimeout: T(setTimeout, clearTimeout),
|
||||
setImmediate: T(setImmediate, clearImmediate),
|
||||
provideModule: T(provideModule),
|
||||
inject: T(inject),
|
||||
} as Context);
|
||||
if (module.sideEffect) this.sideEffect = true;
|
||||
this.loaded = true;
|
||||
|
||||
@@ -7,7 +7,6 @@ import Body from 'koa-body';
|
||||
import Compress from 'koa-compress';
|
||||
import proxy from 'koa-proxies';
|
||||
import cache from 'koa-static-cache';
|
||||
import { filter } from 'lodash';
|
||||
import WebSocket from 'ws';
|
||||
import { parseMemoryMB } from '@hydrooj/utils/lib/utils';
|
||||
import {
|
||||
@@ -176,11 +175,11 @@ export class Handler extends HandlerCommon {
|
||||
async init() {
|
||||
if (!argv.options.benchmark) await this.limitRate('global', 5, 88);
|
||||
if (!this.noCheckPermView && !this.user.hasPriv(PRIV.PRIV_VIEW_ALL_DOMAIN)) this.checkPerm(PERM.PERM_VIEW);
|
||||
this.loginMethods = filter(Object.keys(global.Hydro.lib), (str) => str.startsWith('oauth_'))
|
||||
this.loginMethods = Object.keys(global.Hydro.module.oauth)
|
||||
.map((key) => ({
|
||||
id: key.split('_')[1],
|
||||
icon: global.Hydro.lib[key].icon,
|
||||
text: global.Hydro.lib[key].text,
|
||||
id: key,
|
||||
icon: global.Hydro.module.oauth[key].icon,
|
||||
text: global.Hydro.module.oauth[key].text,
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -52,7 +52,8 @@ class Watcher {
|
||||
if (process.env.WATCH_ROOT) roots.push(process.env.WATCH_ROOT);
|
||||
this.watcher = watch(roots, {
|
||||
...this.config,
|
||||
ignored: ['**/node_modules/**', '**/.git/**', '**/logs/**', '**/.cache/**'],
|
||||
ignored: ['node_modules', '.git', 'logs', '.cache']
|
||||
.map((i) => `**/${i}/**`).concat('**/tsconfig.tsbuildinfo'),
|
||||
});
|
||||
logger.info(`Start watching changes in ${this.root}`);
|
||||
|
||||
|
||||
Reference in new issue
Block a user