-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.ts
139 lines (119 loc) · 3.88 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import { Context, Session, Logger, Time, Schema } from 'koishi'
import RssFeedEmitter from 'rss-feed-emitter'
declare module 'koishi' {
interface Channel {
rss: string[]
}
interface Modules {
rss: typeof import('.')
}
}
const logger = new Logger('rss')
export const name = 'RSS'
export const inject = ['database'] as const
export interface Config {
timeout?: number
refresh?: number
userAgent?: string
}
export const Config: Schema<Config> = Schema.object({
timeout: Schema.number().description('请求数据的最长时间。').default(Time.second * 10),
refresh: Schema.number().description('刷新数据的时间间隔。').default(Time.minute),
userAgent: Schema.string().description('请求时使用的 User Agent。'),
})
export function apply(ctx: Context, config: Config) {
ctx.model.extend('channel', {
rss: 'list',
})
const { timeout, refresh, userAgent } = config
const feedMap: Record<string, Set<string>> = {}
const feeder = new RssFeedEmitter({ skipFirstLoad: true, userAgent })
function subscribe(url: string, guildId: string) {
if (url in feedMap) {
feedMap[url].add(guildId)
} else {
feedMap[url] = new Set([guildId])
feeder.add({ url, refresh })
logger.debug('subscribe', url)
}
}
function unsubscribe(url: string, guildId: string) {
feedMap[url].delete(guildId)
if (!feedMap[url].size) {
delete feedMap[url]
feeder.remove(url)
logger.debug('unsubscribe', url)
}
}
ctx.on('dispose', () => {
feeder.destroy()
})
feeder.on('error', (err: Error) => {
logger.debug(err.message)
})
feeder.on('new-item', async (payload) => {
logger.debug('receive', payload.title)
const source = payload.meta.link
if (!feedMap[source]) return
const message = `${payload.meta.title} (${payload.author})\n${payload.title}`
await ctx.broadcast([...feedMap[source]], message)
})
ctx.on('ready', async () => {
const channels = await ctx.database.getAssignedChannels(['platform', 'id', 'rss'])
for (const channel of channels) {
for (const url of channel.rss) {
subscribe(url, `${channel.platform}:${channel.id}`)
}
}
})
const validators: Record<string, Promise<unknown>> = {}
async function validate(url: string, session: Session) {
if (validators[url]) {
await session.send('正在尝试连接……')
return validators[url]
}
let timer: NodeJS.Timeout
const feeder = new RssFeedEmitter({ userAgent })
return validators[url] = new Promise((resolve, reject) => {
// rss-feed-emitter's typings suck
feeder.add({ url, refresh: 1 << 30 })
feeder.on('new-item', resolve)
feeder.on('error', reject)
timer = setTimeout(() => reject(new Error('connect timeout')), timeout)
}).finally(() => {
feeder.destroy()
clearTimeout(timer)
delete validators[url]
})
}
ctx.guild()
.command('rss <url:text>', '订阅 RSS 链接')
.channelFields(['rss', 'id', 'platform'])
.option('list', '-l 查看订阅列表')
.option('remove', '-r 取消订阅')
.action(async ({ session, options }, url) => {
const { rss, id, platform } = session.channel
if (options.list) {
if (!rss.length) return '未订阅任何链接。'
return rss.join('\n')
}
const index = rss.indexOf(url)
if (options.remove) {
if (index < 0) return '未订阅此链接。'
rss.splice(index, 1)
unsubscribe(url, `${platform}:${id}`)
return '取消订阅成功!'
}
if (index >= 0) return '已订阅此链接。'
return validate(url, session).then(() => {
subscribe(url, `${platform}:${id}`)
if (!rss.includes(url)) {
rss.push(url)
return '添加订阅成功!'
}
}, (error) => {
logger.debug(error)
return '无法订阅此链接。'
})
})
}