Commit 4b4aaee8 authored by nanahira's avatar nanahira

update replacement

parent cfa0ee1b
import { Adapter, Bot, Context, Filter } from 'koishi';
import { Bot, Context, Filter, segment } from 'koishi';
import _ from 'lodash';
import { RegisterSchema, SchemaProperty } from 'schemastery-gen';
......@@ -95,6 +95,36 @@ export class SendTarget {
return ctx.intersect(this.getFilter());
}
private runForEachSegemnt(segments: segment[], action: (s: segment) => void) {
for (const s of segments) {
action(s);
if (s.children?.length) {
this.runForEachSegemnt(s.children, action);
}
}
}
replaceContent(content: string, fromKey: string, toKey: string) {
const segments = segment.parse(content);
this.runForEachSegemnt(segments, (s) => {
const { attrs } = s;
if (!attrs || s.type !== 'image') {
return;
}
if (attrs.url?.startsWith('base64')) {
const { url } = attrs;
attrs.file = url;
delete attrs.url;
}
if (attrs[fromKey]?.startsWith('http')) {
const { [fromKey]: url } = attrs;
attrs[toKey] = url;
delete attrs[fromKey];
}
});
return segments.map((s) => s.toString()).join('');
}
async send(bots: Bot[], content: string) {
const bot = this.getBot(bots);
if (!bot) {
......@@ -103,9 +133,8 @@ export class SendTarget {
let privateContent = content;
let channelContent = content;
if (this.isOneBotBot(bot)) {
content = content.replace(/,url=base64/g, ',file=base64');
privateContent = content.replace(/,url=http/g, ',file=http'); // private should be file
channelContent = content.replace(/,file=http/g, ',url=http'); // channel should be url
privateContent = this.replaceContent(content, 'url', 'file'); // private should be file
channelContent = this.replaceContent(content, 'file', 'url'); // channel should be url
}
return _.flatten(
await Promise.all([
......
import { Session } from 'koishi';
import { SendTarget } from '..';
import { segment, Session } from 'koishi';
import { SendTarget } from '../index';
describe('Target def.', () => {
const def = new SendTarget({
......@@ -81,4 +81,22 @@ describe('Target def.', () => {
} as Session),
).toBe(true);
});
it('should replace content', () => {
const target = new SendTarget({});
const imageBase64 = segment('image', { url: 'base64://foo' });
const imageBase64Replaced = segment.parse(
target.replaceContent(imageBase64.toString(), 'url', 'url'),
)[0];
const imageUrl = segment('image', {
file: 'http://example.com/1.png',
});
const imageUrlReplaced = segment.parse(
target.replaceContent(imageUrl.toString(), 'file', 'url'),
)[0];
expect(imageBase64Replaced.attrs?.url).toBeUndefined();
expect(imageBase64Replaced.attrs?.file).toBe('base64://foo');
expect(imageUrlReplaced.attrs?.url).toBe('http://example.com/1.png');
expect(imageUrlReplaced.attrs?.file).toBeUndefined();
});
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment