Skip to content

Commit

Permalink
fix: 修复部分已知问题 新增自定义package.json.static
Browse files Browse the repository at this point in the history
  • Loading branch information
CakmLexi committed Jul 6, 2024
1 parent dd8bc15 commit 60c6d7a
Show file tree
Hide file tree
Showing 8 changed files with 92 additions and 58 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ lerna-debug.log*
# 配置
/plugins/
/data/
/config/config
/config/
/resources

# 依赖
Expand Down
19 changes: 8 additions & 11 deletions src/adapter/input/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,11 @@ const { enable, msgToFile, token: oldToken, ip } = config.Config.AdapterInput
*/
export class AdapterInput implements KarinAdapter {
token: string
#stdin: boolean
socket!: WebSocket
account: KarinAdapter['account']
adapter: KarinAdapter['adapter']
version: KarinAdapter['version']
constructor () {
this.#stdin = false
this.token = oldToken
this.account = { uid: 'input', uin: 'input', name: 'input' }
this.adapter = { id: 'shell', name: 'input', type: 'internal', sub_type: 'internal', start_time: Date.now(), connect: '', index: 0 }
Expand All @@ -31,9 +29,6 @@ export class AdapterInput implements KarinAdapter {
}

stdin () {
if (this.#stdin) return
this.#stdin = true

if (oldToken === 'AdapterInput') {
try {
this.token = randomUUID()
Expand Down Expand Up @@ -63,9 +58,15 @@ export class AdapterInput implements KarinAdapter {
/** 注册bot */
const index = listener.addBot({ bot: this, type: this.adapter.type })
if (index) this.adapter.index = index
return this
}

init () {
process.stdin.on('data', data => this.#input(data.toString()))
process.once('stdin.close', () => process.stdin.removeAllListeners('data'))
process.once('stdin.close', () => {
process.stdin.removeAllListeners('data')
process.stdin.once('stdin.open', () => this.init())
})
}

logger (level: 'info' | 'error' | 'trace' | 'debug' | 'mark' | 'warn' | 'fatal', ...args: any[]) {
Expand Down Expand Up @@ -99,9 +100,6 @@ export class AdapterInput implements KarinAdapter {

const e = new KarinMessage(message)
e.bot = this
/**
* 快速回复 开发者不应该使用这个方法,应该使用由karin封装过后的reply方法
*/
e.replyCallback = async elements => {
this.SendMessage(e.contact, elements)
return { message_id: e.message_id }
Expand All @@ -122,7 +120,6 @@ export class AdapterInput implements KarinAdapter {
const buffer = await common.buffer(file) as Uint8Array
// 生成文件名 根据type生成不同的文件后缀
const name = `${Date.now()}.${type === 'image' ? 'jpg' : type === 'voice' ? 'mp3' : 'file'}`
// 写入文件
fs.writeFileSync(`./temp/input/${name}`, buffer)
return `[${type === 'image' ? '图片' : '语音'}: http://${ip}:${config.Server.http.port}/api/input?name=${name}&token=${this.token} ]`
}
Expand Down Expand Up @@ -204,4 +201,4 @@ export class AdapterInput implements KarinAdapter {
async GetGroupHonor (): Promise<any> { throw new Error('Method not implemented.') }
}

if (enable) new AdapterInput().stdin()
if (enable) new AdapterInput().stdin().init()
11 changes: 5 additions & 6 deletions src/core/karin.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-dupe-class-members */
import PluginApp from './plugin.app'
import { common } from 'karin/utils'
import { render } from 'karin/render'
Expand Down Expand Up @@ -60,17 +61,16 @@ export interface OptionsElement extends OptionsCommand {

export class Karin {
/**
* @param reg - 正则表达式
* @param fnc - 函数
* @param options - 选项
*/
* @param reg - 正则表达式
* @param fnc - 函数
* @param options - 选项
*/
command (reg: string | RegExp, fnc: FncFunction, options?: OptionsCommand): PluginApps
/**
* @param reg - 正则表达式
* @param element - 字符串或者KarinElement、KarinElement数组
* @param options - 选项
*/
// eslint-disable-next-line no-dupe-class-members
command (reg: string | RegExp, element: FncElement, options?: OptionsElement): PluginApps
/**
* - 快速构建命令
Expand All @@ -79,7 +79,6 @@ export class Karin {
* @param options - 选项
* @returns - 返回插件对象
*/
// eslint-disable-next-line no-dupe-class-members
command (reg: string | RegExp, second: FncFunction | FncElement, options: OptionsCommand | OptionsElement = {}): PluginApps {
reg = typeof reg === 'string' ? new RegExp(reg) : reg
const fnc = typeof second === 'function'
Expand Down
29 changes: 23 additions & 6 deletions src/core/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ export const server = new (class Server {
/**
* 构建静态资源路径
*/
staticPath () {
async staticPath () {
this.list = []
/** 读取./resources文件夹 */
const resDir = './resources'
Expand All @@ -238,17 +238,34 @@ export const server = new (class Server {
if (common.isDir(file)) this.list.push(file.replace('.', ''))
}

/** 读取./plugins/html下所有文件夹 */
const pluginsDir = './plugins'
/** 读取./plugins/xxx/resources下所有文件夹 */
const pluginsDir = './plugins' as './plugins'
const plugins = fs.readdirSync(pluginsDir)
for (const dir of plugins) {
const file = `${pluginsDir}/${dir}`
/** 忽略不是karin-plugin-开头 */
if (!dir.startsWith('karin-plugin-')) continue
const file = `${pluginsDir}/${dir}` as `./plugins/karin-plugin-${string}`
const resFile = `${file}/resources`
/** 包含resources文件夹 */
if (common.isDir(file) && common.isDir(resFile)) this.list.push(resFile.replace('.', ''))
const componentsFile = `${file}/components`
/** 包含components文件夹 兼容mys */
const componentsFile = `${file}/lib/components`
/** 包含lib/components文件夹 兼容mys */
if (common.isDir(file) && common.isDir(componentsFile)) this.list.push(componentsFile.replace('.', ''))

/** 读取package.json 查找是否存在自定义资源文件入口 */
const pkgFile = `${file}/package.json`
if (!common.exists(pkgFile)) continue

const pkg = common.readJson(pkgFile)
if (!pkg?.karin?.static || !Array.isArray(pkg.karin.static)) continue
/** 标准格式为 lib/test/xxxx */
for (let staticFile of pkg.karin.static) {
/** 不允许向上级目录 ../开头等 */
if (staticFile.startsWith('../')) continue
/** ./开头去掉./ */
if (staticFile.startsWith('./')) staticFile = staticFile.slice(2)
this.list.push(`${file}/${staticFile}`)
}
}
this.reg = new RegExp(`(${this.list.join('|')})`, 'g')
}
Expand Down
14 changes: 6 additions & 8 deletions src/event/message.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,7 @@ export class MessageHandler extends EventHandler {
for (const val of this.e.elements) {
switch (val.type) {
case 'text': {
const msg = (val.text || '')
.replace(/^\s*[#]+\s*/, '#')
.replace(/^\s*[\\*]+\s*/, '*')
.trim()
const msg = (val.text || '').replace(/^\s*[#]+\s*/, '#').replace(/^\s*[\\*]+\s*/, '*').trim()
this.e.msg += msg
/** 美观一点... */
logs.push(msg)
Expand All @@ -125,11 +122,9 @@ export class MessageHandler extends EventHandler {
break
case 'at':
/** atBot不计入e.at */
// eslint-disable-next-line eqeqeq
if (val.uid && val.uid == this.e.bot.account.uid) {
if (val.uid && val.uid === this.e.bot.account.uid) {
this.e.atBot = true
// eslint-disable-next-line eqeqeq
} else if (val.uin == this.e.bot.account.uin) {
} else if (val.uin === this.e.bot.account.uin) {
this.e.atBot = true
} else if (val.uid && val.uid === 'all') {
this.e.atAll = true
Expand Down Expand Up @@ -198,6 +193,9 @@ export class MessageHandler extends EventHandler {
case 'button':
logs.push(`[button:${JSON.stringify(val.data)}]`)
break
case 'long_msg':
logs.push(`[long_msg:${val.id}]`)
break
default:
logs.push(`[未知:${JSON.stringify(val)}]`)
}
Expand Down
4 changes: 4 additions & 0 deletions src/types/element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ export interface AtElement extends Element {
* - At的uin
*/
uin?: string
/**
* - At的名称
*/
name?: string
}

/**
Expand Down
67 changes: 42 additions & 25 deletions src/utils/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,31 @@ import { Redis, App, Config, Server, Package, GroupCfg } from 'karin/types'
* 配置文件
*/
export const config = new (class Cfg {
dir: string
_path: string
npmCfgDir: string
/**
* 根项目绝对路径
*/
projPath: string
/**
* 根项目配置文件夹路径
*/
projConfigPath: string
/**
* npm包路径
*/
pkgPath: string
/**
* karin包配置文件夹路径
*/
pkgConfigPath: string
change: Map<string, any>
watcher: Map<string, any>
review: boolean
logger!: Logger
constructor () {
this.dir = karinDir
this._path = process.cwd() + '/config'
this.npmCfgDir = this.dir + '/config/defSet'
this.projPath = process.cwd()
this.pkgPath = karinDir
this.projConfigPath = this.projPath + '/config'
this.pkgConfigPath = this.pkgPath + '/config/defSet'

/** 缓存 */
this.change = new Map()
Expand All @@ -32,35 +46,39 @@ export const config = new (class Cfg {
/** 初始化配置 */
async initCfg () {
const list = [
this._path,
this._path + '/config',
process.cwd() + '/temp/input',
'./plugins',
'./plugins/karin-plugin-example',
this.projPath + '/temp/input',
this.projPath + '/plugins/karin-plugin-example',
this.projConfigPath + '/config',
this.projConfigPath + '/plugin',

]

list.forEach(path => this.mkdir(path))
if (this.npmCfgDir !== (this._path + '/defSet').replace(/\\/g, '/')) {
const files = fs.readdirSync(this.npmCfgDir).filter(file => file.endsWith('.yaml'))
if (this.pkgConfigPath !== (this.projConfigPath + '/defSet').replace(/\\/g, '/')) {
const files = fs.readdirSync(this.pkgConfigPath).filter(file => file.endsWith('.yaml'))
files.forEach(file => {
const path = `${this._path}/config/${file}`
const pathDef = `${this.npmCfgDir}/${file}`
const path = `${this.projConfigPath}/config/${file}`
const pathDef = `${this.pkgConfigPath}/${file}`
if (!fs.existsSync(path)) fs.copyFileSync(pathDef, path)
})
}

// 创建插件文件夹文件夹
/** 为每个插件包创建统一存储的文件夹 */
const plugins = this.getPlugins()
this.dirPath('data', plugins)
this.dirPath('temp', plugins)
this.dirPath('resources', plugins)
this.dirPath('temp/html', plugins)
const DataList = [
'data',
'temp',
'resources',
'temp/html',
this.projConfigPath + '/plugin',
]
DataList.forEach(path => this.dirPath(path, plugins))
this.logger = (await import('./logger')).default
}

getPlugins () {
const files = fs.readdirSync('./plugins', { withFileTypes: true })
// 过滤掉非karin-plugin-开头或karin-adapter-开头的文件夹
// 过滤掉非karin-plugin-开头的文件夹
return files.filter(file => file.isDirectory() && (file.name.startsWith('karin-plugin-'))).map(dir => dir.name)
}

Expand All @@ -78,11 +96,10 @@ export const config = new (class Cfg {
/**
* 为每一个插件建立对应的文件夹
*/
async dirPath (name: string, plugins: string[]) {
name = `./${name}`
this.mkdir(name)
async dirPath (_path: string, plugins: string[]) {
this.mkdir(_path)
for (const plugin of plugins) {
const path = `${name}/${plugin}`
const path = `${_path}/${plugin}`
this.mkdir(path)
}
}
Expand Down
4 changes: 3 additions & 1 deletion src/utils/segment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,15 @@ export const segment = new (class Segment {
* 提供一个uid即可
* @param uid - uid
* @param uin - uin
* @param name - 名称
* @returns {AtElement} 提及元素
*/
at (uid: string, uin?: string): AtElement {
at (uid: string, uin?: string, name?: string): AtElement {
return {
type: 'at',
uid: uid + '',
uin: (uin || '') + '',
name,
}
}

Expand Down

0 comments on commit 60c6d7a

Please sign in to comment.