Skip to content

Commit

Permalink
refa: implement internal protocol service
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed May 20, 2022
1 parent 1bd1425 commit 948c5e8
Show file tree
Hide file tree
Showing 7 changed files with 523 additions and 47 deletions.
4 changes: 0 additions & 4 deletions packages/core/src/internal/index.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { Awaitable, Dict, Logger, paramCase, remove, Schema } from '@koishijs/utils'
import { Dict, Logger, paramCase, remove, Schema } from '@koishijs/utils'
import { Awaitable } from 'cosmokit'
import { Context, Plugin } from 'cordis'
import { Session } from './session'
import { App } from './app'
import { Bot } from './bot'
import { Context, Plugin } from './context'

declare module 'cordis' {
interface Context {
bots: Adapter.BotList
}
}

export abstract class Adapter<S extends Bot.BaseConfig = Bot.BaseConfig, T = {}> {
public bots: Bot<S>[] = []
Expand All @@ -20,7 +26,7 @@ export abstract class Adapter<S extends Bot.BaseConfig = Bot.BaseConfig, T = {}>
disconnect(bot: Bot): Awaitable<void> {}

dispatch(session: Session) {
if (!this.ctx.app.isActive) return
if (!this.ctx.lifecycle.isActive) return
const events: string[] = [session.type]
if (session.subtype) {
events.unshift(events[0] + '/' + session.subtype)
Expand Down Expand Up @@ -137,10 +143,10 @@ export namespace Adapter {
adapters: Dict<Adapter> = {}

get caller(): Context {
return this[Context.current]
return this[Context.current] || this.ctx
}

constructor(private app: App) {
constructor(private ctx: Context) {
super()
}

Expand All @@ -154,7 +160,7 @@ export namespace Adapter {
const bot = new constructor(adapter, options)
adapter.bots.push(bot)
this.push(bot)
this.app.emit('bot-added', bot)
this.caller.emit('bot-added', bot)
this.caller.on('dispose', () => {
this.remove(bot.id)
})
Expand All @@ -166,7 +172,7 @@ export namespace Adapter {
if (index < 0) return
const [bot] = this.splice(index, 1)
const exist = remove(bot.adapter.bots, bot)
this.app.emit('bot-removed', bot)
this.caller.emit('bot-removed', bot)
return exist
}

Expand All @@ -193,3 +199,7 @@ export namespace Adapter {
}
}
}

Context.service('bots', {
constructor: Adapter.BotList,
})
36 changes: 24 additions & 12 deletions packages/core/src/bot.ts → packages/core/src/protocol/bot.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,26 @@
import { Dict, Logger, makeArray, Random, Schema, sleep } from '@koishijs/utils'
import { Awaitable } from 'cosmokit'
import { Adapter } from './adapter'
import { App } from './app'
import { Context } from 'cordis'
import { Session } from './session'

declare module 'cordis' {
interface Events {
'adapter'(name: string): void
'bot-added'(bot: Bot): void
'bot-removed'(bot: Bot): void
'bot-status-updated'(bot: Bot): void
'bot-connect'(bot: Bot): Awaitable<void>
'bot-disconnect'(bot: Bot): Awaitable<void>
}
}

const logger = new Logger('bot')

export interface Bot extends Bot.BaseConfig, Bot.Methods, Bot.UserBase {}

export abstract class Bot<T extends Bot.BaseConfig = Bot.BaseConfig> {
public app: App
public ctx: Context
public platform: string
public hidden?: boolean
public internal?: any
Expand All @@ -21,7 +33,7 @@ export abstract class Bot<T extends Bot.BaseConfig = Bot.BaseConfig> {
error?: Error

constructor(public adapter: Adapter, public config: T) {
this.app = adapter.ctx.app
this.ctx = adapter.ctx
this.platform = config.platform || adapter.platform
this.logger = new Logger(adapter.platform)
this._status = 'offline'
Expand All @@ -32,8 +44,8 @@ export abstract class Bot<T extends Bot.BaseConfig = Bot.BaseConfig> {
}

private extendModel() {
if (this.platform in this.app.model.tables.user.fields) return
this.app.model.extend('user', {
if (this.platform in this.ctx.model.tables.user.fields) return
this.ctx.model.extend('user', {
[this.platform]: { type: 'string', length: 63 },
}, {
unique: [this.platform as never],
Expand All @@ -46,8 +58,8 @@ export abstract class Bot<T extends Bot.BaseConfig = Bot.BaseConfig> {

set status(value) {
this._status = value
if (this.app.bots.includes(this)) {
this.app.emit('bot-status-updated', this)
if (this.ctx.bots.includes(this)) {
this.ctx.emit('bot-status-updated', this)
}
}

Expand All @@ -67,7 +79,7 @@ export abstract class Bot<T extends Bot.BaseConfig = Bot.BaseConfig> {
if (['connect', 'reconnect', 'online'].includes(this.status)) return
this.status = 'connect'
try {
await this.app.parallel('bot-connect', this)
await this.ctx.parallel('bot-connect', this)
await this.adapter.connect(this)
} catch (error) {
this.reject(error)
Expand All @@ -78,7 +90,7 @@ export abstract class Bot<T extends Bot.BaseConfig = Bot.BaseConfig> {
if (['disconnect', 'offline'].includes(this.status)) return
this.status = 'disconnect'
try {
await this.app.parallel('bot-disconnect', this)
await this.ctx.parallel('bot-disconnect', this)
await this.adapter.disconnect(this)
} catch (error) {
this.logger.warn(error)
Expand Down Expand Up @@ -110,7 +122,7 @@ export abstract class Bot<T extends Bot.BaseConfig = Bot.BaseConfig> {

async session(data: Partial<Session>) {
const session = this.createSession(data)
if (await this.app.serial(session, 'before-send', session)) return
if (await this.ctx.serial(session, 'before-send', session)) return
return session
}

Expand All @@ -119,15 +131,15 @@ export abstract class Bot<T extends Bot.BaseConfig = Bot.BaseConfig> {
return Object.fromEntries(list.map(info => [info.userId, info.nickname || info.username]))
}

async broadcast(channels: (string | [string, string])[], content: string, delay = this.app.options.delay.broadcast) {
async broadcast(channels: (string | [string, string])[], content: string, delay = this.ctx.app.options.delay.broadcast) {
const messageIds: string[] = []
for (let index = 0; index < channels.length; index++) {
if (index && delay) await sleep(delay)
try {
const [channelId, guildId] = makeArray(channels[index])
messageIds.push(...await this.sendMessage(channelId, content, guildId))
} catch (error) {
this.app.logger('bot').warn(error)
this.ctx.logger('bot').warn(error)
}
}
return messageIds
Expand Down
Loading

0 comments on commit 948c5e8

Please sign in to comment.