Skip to content

Commit

Permalink
feat(satori): upgrade http api
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Feb 15, 2024
1 parent cf899ea commit 5841dbd
Show file tree
Hide file tree
Showing 22 changed files with 35 additions and 39 deletions.
2 changes: 1 addition & 1 deletion adapters/dingtalk/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export class Internal {
if (!args.length) throw new Error(`too few arguments for ${path}, received ${raw}`)
return args.shift()
})
const config: Quester.AxiosRequestConfig = {}
const config: Quester.RequestConfig = {}
if (args.length === 1) {
if (method === 'GET' || method === 'DELETE') {
config.params = args[0]
Expand Down
2 changes: 1 addition & 1 deletion adapters/dingtalk/src/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export class DingtalkMessageEncoder<C extends Context = Context> extends Message
// await this.sendMessage('sampleImageMsg', {
// photoURL: src,
// })
if (await this.bot.http.isPrivate(src)) {
if (await this.bot.http.isLocal(src)) {
const temp = this.bot.ctx.get('server.temp')
if (!temp) {
return this.bot.logger.warn('missing temporary file service, cannot send assets with private url')
Expand Down
2 changes: 1 addition & 1 deletion adapters/discord/src/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export class DiscordMessageEncoder<C extends Context = Context> extends MessageE
return this.post({ ...addition, content: attrs.src || attrs.url })
}

if (await this.bot.http.isPrivate(attrs.src || attrs.url)) {
if (await this.bot.http.isLocal(attrs.src || attrs.url)) {
return await this.sendEmbed(attrs, addition)
}

Expand Down
2 changes: 1 addition & 1 deletion adapters/discord/src/types/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export class Internal {
if (!args.length) throw new Error(`too few arguments for ${path}, received ${raw}`)
return args.shift()
})
const config: Quester.AxiosRequestConfig = {}
const config: Quester.RequestConfig = {}
if (args.length === 1) {
if (method === 'GET' || method === 'DELETE') {
config.params = args[0]
Expand Down
2 changes: 1 addition & 1 deletion adapters/kook/src/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export class KookMessageEncoder<C extends Context = Context> extends MessageEnco

private async transformUrl({ type, attrs }: h) {
const src = attrs.src || attrs.url
if (await this.bot.http.isPrivate(src)) {
if (await this.bot.http.isLocal(src)) {
const payload = new FormData()
const result = await this.bot.ctx.http.file(src, attrs)
payload.append('file', Buffer.from(result.data), {
Expand Down
8 changes: 4 additions & 4 deletions adapters/kook/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -665,15 +665,15 @@ export class Internal {

static define(name: string, method: Quester.Method, path: string) {
Internal.prototype[name] = async function (this: Internal, ...args: any[]) {
const config: Quester.AxiosRequestConfig = {}
const config: Quester.RequestConfig = {}
if (method === 'GET' || method === 'DELETE') {
config.params = args[0]
} else {
config.data = args[0]
}
const req = await this.http(method, path, config)
if (req?.code !== 0) throw new Error(req?.message || 'Unexpected Error')
return req?.data
const { data } = await this.http(method, path, config)
if (data?.code !== 0) throw new Error(data?.message || 'Unexpected Error')
return data?.data
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion adapters/lark/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export class HttpServer<C extends Context = Context> extends Adapter<C, FeishuBo
const bot = this.bots.find((bot) => bot.selfId === selfId)
if (!bot) return ctx.status = 404

const resp = await bot.http.axios<internal.Readable>(`/im/v1/messages/${messageId}/resources/${key}`, {
const resp = await bot.http<internal.Readable>(`/im/v1/messages/${messageId}/resources/${key}`, {
method: 'GET',
params: { type },
responseType: 'stream',
Expand Down
2 changes: 1 addition & 1 deletion adapters/lark/src/types/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export class Internal {
if (!args.length) throw new Error(`too few arguments for ${path}, received ${raw}`)
return args.shift()
})
const config: Quester.AxiosRequestConfig = {}
const config: Quester.RequestConfig = {}
if (args.length === 1) {
if (method === 'GET' || method === 'DELETE') {
config.params = args[0]
Expand Down
13 changes: 6 additions & 7 deletions adapters/lark/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import crypto from 'crypto'
import { Channel, Guild, Message, User } from '@satorijs/protocol'
import { Context, h, Session, trimSlash } from '@satorijs/satori'
import { Context, h, Session, trimSlash, Universal } from '@satorijs/satori'
import { FeishuBot, LarkBot } from './bot'
import { AllEvents, Events, Lark, Message as LarkMessage, MessageContentType, MessageType } from './types'

Expand Down Expand Up @@ -86,7 +85,7 @@ export function adaptSession<C extends Context>(bot: FeishuBot<C>, body: AllEven
}

// TODO: This function has many duplicated code with `adaptMessage`, should refactor them
export async function decodeMessage(bot: LarkBot, body: LarkMessage): Promise<Message> {
export async function decodeMessage(bot: LarkBot, body: LarkMessage): Promise<Universal.Message> {
const json = JSON.parse(body.body.content) as MessageContentType<MessageType>
const assetEndpoint = trimSlash(bot.config.selfUrl ?? bot.ctx.server.config.selfUrl) + bot.config.path + '/assets'
const content: h[] = []
Expand Down Expand Up @@ -146,24 +145,24 @@ export function extractIdType(id: string): Lark.ReceiveIdType {
return 'user_id'
}

export function decodeChannel(guild: Lark.Guild): Channel {
export function decodeChannel(guild: Lark.Guild): Universal.Channel {
return {
id: guild.chat_id,
type: Channel.Type.TEXT,
type: Universal.Channel.Type.TEXT,
name: guild.name,
parentId: guild.chat_id,
}
}

export function decodeGuild(guild: Lark.Guild): Guild {
export function decodeGuild(guild: Lark.Guild): Universal.Guild {
return {
id: guild.chat_id,
name: guild.name,
avatar: guild.avatar,
}
}

export function decodeUser(user: Lark.User): User {
export function decodeUser(user: Lark.User): Universal.User {
return {
id: user.open_id,
avatar: user.avatar?.avatar_origin,
Expand Down
2 changes: 1 addition & 1 deletion adapters/line/src/types/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class Internal {
if (!args.length) throw new Error(`too few arguments for ${path}, received ${raw}`)
return args.shift()
})
const config: Quester.AxiosRequestConfig = {}
const config: Quester.RequestConfig = {}
if (args.length === 1) {
if (method === 'GET' || method === 'DELETE') {
config.params = args[0]
Expand Down
5 changes: 2 additions & 3 deletions adapters/qq/src/bot/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,8 @@ export class QQBot<C extends Context = Context> extends Bot<C, QQBot.Config> {

async _ensureAccessToken() {
try {
const result = await this.ctx.http.axios<GetAppAccessTokenResult>({
url: 'https://bots.qq.com/app/getAppAccessToken',
method: 'post',
const result = await this.ctx.http<GetAppAccessTokenResult>('https://bots.qq.com/app/getAppAccessToken', {
method: 'POST',
data: {
appId: this.config.id,
clientSecret: this.config.secret,
Expand Down
2 changes: 1 addition & 1 deletion adapters/qq/src/internal/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class Internal {
if (!args.length) throw new Error(`too few arguments for ${path}, received ${raw}`)
return args.shift()
})
const config: Quester.AxiosRequestConfig = {}
const config: Quester.RequestConfig = {}
if (args.length === 1) {
if (method === 'GET' || method === 'DELETE') {
config.params = args[0]
Expand Down
4 changes: 2 additions & 2 deletions adapters/qq/src/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export class QQGuildMessageEncoder<C extends Context = Context> extends MessageE
}

async resolveFile(attrs: Dict, download = false) {
if (!download && !await this.bot.ctx.http.isPrivate(attrs.src || attrs.url)) {
if (!download && !await this.bot.ctx.http.isLocal(attrs.src || attrs.url)) {
return this.fileUrl = attrs.src || attrs.url
}
const { data, filename } = await this.bot.ctx.http.file(this.fileUrl || attrs.src || attrs.url, attrs)
Expand Down Expand Up @@ -305,7 +305,7 @@ export class QQMessageEncoder<C extends Context = Context> extends MessageEncode

async sendFile(type: string, attrs: Dict) {
let url = attrs.src || attrs.url, entry: Entry | undefined
if (await this.bot.ctx.http.isPrivate(url)) {
if (await this.bot.ctx.http.isLocal(url)) {
const temp = this.bot.ctx.get('server.temp')
if (!temp) {
return this.bot.logger.warn('missing temporary file service, cannot send assets with private url')
Expand Down
3 changes: 1 addition & 2 deletions adapters/qq/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Bot, Context, h, Session, Universal } from '@satorijs/satori'
import * as QQ from './types'
import { QQBot } from './bot'
import { unescape } from '@satorijs/element'

export const decodeGuild = (guild: QQ.Guild): Universal.Guild => ({
id: guild.id,
Expand Down Expand Up @@ -75,7 +74,7 @@ export async function decodeMessage(
.reduce((content, attachment) => content + h.image('https://' + attachment.url), message.content)
message.elements = h.parse(message.content)
message.elements = h.transform(message.elements, {
text: (attrs) => unescape(attrs.content),
text: (attrs) => h.unescape(attrs.content),
})

if (data.message_reference) {
Expand Down
4 changes: 2 additions & 2 deletions adapters/slack/src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ export class SlackBot<C extends Context = Context, T extends SlackBot.Config = S
async request<T = any>(method: Quester.Method, path: string, data = {}, headers: any = {}, zap: boolean = false): Promise<T> {
headers['Authorization'] = `Bearer ${zap ? this.config.token : this.config.botToken}`
if (method === 'GET') {
return (await this.http.get(path, { params: data, headers })).data
return await this.http.get(path, { params: data, headers })
} else {
if (!headers['content-type']) {
data = data instanceof FormData ? data : JSON.stringify(data)
const type = data instanceof FormData ? 'multipart/form-data' : 'application/json; charset=utf-8'
headers['content-type'] = type
}
return (await this.http(method, path, { data, headers }))
return (await this.http(method, path, { data, headers })).data
}
}

Expand Down
2 changes: 1 addition & 1 deletion adapters/slack/src/types/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export class Internal {
const method = key as Quester.Method
for (const name of Object.keys(routes[path][method])) {
Internal.prototype[name] = async function (this: Internal, ...args: any[]) {
const config: Quester.AxiosRequestConfig = {
const config: Quester.RequestConfig = {
headers: {},
}
let token = ''
Expand Down
2 changes: 1 addition & 1 deletion adapters/wechat-official/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ export class HttpServer<C extends Context = Context> extends Adapter<C, WechatOf
const selfId = ctx.params.self_id
const localBot = this.bots.find((bot) => bot.selfId === selfId)
if (!localBot) return ctx.status = 404
const resp = await localBot.http.axios<ReadableStream>(`/cgi-bin/media/get`, {
const resp = await localBot.http<ReadableStream>(`/cgi-bin/media/get`, {
method: 'GET',
responseType: 'stream',
params: {
Expand Down
2 changes: 1 addition & 1 deletion adapters/wecom/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export class HttpServer<C extends Context = Context> extends Adapter<C, WecomBot
const selfId = ctx.params.self_id
const localBot = this.bots.find((bot) => bot.selfId === selfId)
if (!localBot) return ctx.status = 404
const resp = await localBot.http.axios<ReadableStream>(`/cgi-bin/media/get`, {
const resp = await localBot.http<ReadableStream>(`/cgi-bin/media/get`, {
method: 'GET',
responseType: 'stream',
params: {
Expand Down
3 changes: 1 addition & 2 deletions adapters/whatsapp/src/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@ class HttpServer {

const fetched = await bot.internal.getMedia(mediaId)
this.logger.debug(fetched.url)
const resp = await bot.ctx.http.axios<internal.Readable>({
url: fetched.url,
const resp = await bot.ctx.http<internal.Readable>(fetched.url, {
method: 'GET',
responseType: 'stream',
})
Expand Down
4 changes: 2 additions & 2 deletions adapters/zulip/src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export class ZulipBot<C extends Context = Context> extends Bot<C, ZulipBot.Confi
}

export namespace ZulipBot {
export interface Config extends Quester.Config, HttpPolling.Config {
export interface Config extends Quester.Config, HttpPolling.Options {
email: string
key: string
}
Expand All @@ -114,7 +114,7 @@ export namespace ZulipBot {
key: Schema.string().required().role('secret').description('API Key'),
}),
Schema.union([
HttpPolling.Config,
HttpPolling.Options,
]).description('推送设置'),
Quester.createConfig(),
])
Expand Down
4 changes: 2 additions & 2 deletions adapters/zulip/src/polling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,14 @@ export class HttpPolling<C extends Context = Context> extends Adapter<C, ZulipBo
}

export namespace HttpPolling {
export interface Config {
export interface Options {
protocol: 'polling'
// pollingTimeout?: number
retryTimes?: number
retryInterval?: number
}

export const Config: Schema<Config> = Schema.object({
export const Options: Schema<Options> = Schema.object({
protocol: Schema.const('polling').required(process.env.KOISHI_ENV !== 'browser'),
// pollingTimeout: Schema.natural().role('ms').default(Time.second * 25).description('通过长轮询获取更新时请求的超时 (单位为毫秒)。'),
retryTimes: Schema.natural().description('连接时的最大重试次数。').default(6),
Expand Down
2 changes: 1 addition & 1 deletion adapters/zulip/src/types/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class Internal {
if (!args.length) throw new Error(`too few arguments for ${path}, received ${raw}`)
return args.shift()
})
const config: Quester.AxiosRequestConfig = {}
const config: Quester.RequestConfig = {}
if (args.length === 1) {
if (method === 'GET' || method === 'DELETE') {
config.params = args[0]
Expand Down

0 comments on commit 5841dbd

Please sign in to comment.