Skip to content

Commit

Permalink
feat: Better reverse proxy strategy for images. (#84)
Browse files Browse the repository at this point in the history
* feat: use assets to save images

* feat: use base64 to sent images

* fix: re-add Logger

* fix: add Result field "buffer"

* feat: add error handler of base64

* refactor: Convert images to base64 in method

* chore: change unique file type specifiers

* refactor: use axios and return a valid mime tag

* docs: add a link about assets service

* chore: change return null and timestamp

* chore: remove field

* chore: declare using @koishijs/assets

* chore: declare option service

* fix: Handling exceptions when dumping images

* fix: add type annotation and format error message.

* fix: remove redundant protocol headers.

* Update packages/core/src/index.ts

---------

Co-authored-by: Maiko Sinkyaet Tan <maiko.tan.coding@gmail.com>
  • Loading branch information
SaarChaffee and MaikoTan authored Jul 4, 2023
1 parent 59d186b commit a18b8f7
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
4 changes: 4 additions & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,17 @@
"service": {
"implements": [
"booru"
],
"optional": [
"assets"
]
}
},
"peerDependencies": {
"koishi": "^4.10.0"
},
"devDependencies": {
"@koishijs/assets": "^1.0.2",
"koishi": "^4.12.4"
},
"dependencies": {
Expand Down
40 changes: 40 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Context, Dict, Element, Logger, Quester, Schema, Service, Session } from 'koishi'
import LanguageDetect from 'languagedetect'
import { ImageSource } from './source'
import { } from '@koishijs/assets'

export * from './source'

Expand Down Expand Up @@ -74,6 +75,26 @@ class ImageService extends Service {

return undefined
}

async imgUrlToAssetUrl(image: ImageSource.Result): Promise<string> {
return await this.ctx.assets.upload(image.url, Date.now().toString()).catch(() => {
logger.warn('Request failed when trying to store image with assets service.')
return null
})
}

async imgUrlToBase64(image: ImageSource.Result): Promise<string> {
return this.ctx.http.axios(image.url, { method: 'GET', responseType: 'arraybuffer' }).then(resp => {
return `data:${resp.headers['content-type']};base64,${Buffer.from(resp.data, 'binary').toString('base64')}`
}).catch(err => {
if (Quester.isAxiosError(err)) {
logger.warn(`Request images failed with HTTP status ${err.status}: ${JSON.stringify(err.response?.data)}.`)
} else {
logger.error(`Request images failed with unknown error: ${err.message}.`)
}
return null
})
}
}

namespace ImageService {
Expand All @@ -97,6 +118,8 @@ export interface Config {
maxCount: number
output: OutputType
nsfw: boolean
asset: boolean
base64: boolean
}

interface ImageArray extends Array<ImageSource.Result> {
Expand Down Expand Up @@ -126,6 +149,8 @@ export const Config = Schema.intersect([
Schema.const(2).description('发送图片、相关信息和链接'),
Schema.const(3).description('发送全部信息'),
]).description('输出方式。').default(1),
asset: Schema.boolean().default(false).description('优先使用 [assets服务](https://assets.koishi.chat/) 转存图片。'),
base64: Schema.boolean().default(false).description('使用 base64 发送图片。')
}).description('输出设置'),
])

Expand Down Expand Up @@ -164,7 +189,22 @@ export function apply(ctx: Context, config: Config) {
if (!filtered?.length) return session?.text('.no-result')

const output: (string | Element)[] = []

for (const image of filtered) {
if (config.asset && ctx.assets) {
image.url = await ctx.booru.imgUrlToAssetUrl(image)
if (!image.url) {
output.unshift(session.text('.no-image'))
continue
}
}
if (config.base64) {
image.url = await ctx.booru.imgUrlToBase64(image)
if (!image.url) {
output.unshift(session.text('.no-image'))
continue
}
}
switch (config.output) {
case OutputType.All:
if (image.tags)
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/locales/zh-CN.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ commands:
messages:
no-source: 当前未找到可用图源。请从插件市场添加 booru 系图源插件并启用 (插件名通常以 booru- 开头)。
no-result: 没有找到符合条件的图片
no-image: 获取图片失败
output:
image: <message><image url={url}></image></message>
info: |
Expand Down

0 comments on commit a18b8f7

Please sign in to comment.