-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathsearchUtils.ts
424 lines (360 loc) · 11.3 KB
/
searchUtils.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
import { extname } from 'node:path'
import type { Post } from 'booru'
import {
type AnyThreadChannel,
type AutocompleteInteraction,
ChannelType,
type ColorResolvable,
type CommandInteraction,
EmbedBuilder,
type ForumChannel,
type MediaChannel,
type NewsChannel,
type TextBasedChannel,
type TextChannel,
type ThreadOnlyChannel,
escapeMarkdown,
} from 'discord.js'
/**
* Get the channel that a slash command was called in, for threads, this is the parent channel
* @param interaction The interaction to fetch the channel for
* @returns The channel the interaction was called in
*/
export async function getInteractionChannel(
interaction: CommandInteraction | AutocompleteInteraction,
): Promise<TextBasedChannel | ThreadOnlyChannel> {
const channel =
interaction.channel ??
(await interaction.client.channels.fetch(interaction.channelId))
if (channel) {
if (channel.isThread()) {
const parent = await getParentChannel(channel)
if (parent.isTextBased() || parent.isThreadOnly()) {
return parent
}
} else if (channel.isTextBased()) {
return channel
}
}
throw new Error(
`Could not find channel ${interaction.channelId} for interaction ${interaction.id}`,
)
}
/**
* Get the parent channel of a thread, since this is somehow actually complicated to handle
* @param thread The thread to get the parent channel for
* @returns The parent channel of the thread
*/
export async function getParentChannel(
thread: AnyThreadChannel,
): Promise<NewsChannel | TextChannel | ForumChannel | MediaChannel> {
if (thread.parent) {
return thread.parent
}
let { parentId } = thread // Starting a thread without a message returns null parent ID (???? ????)
if (parentId == null) {
const threadChannel = await thread.guild.channels.fetch(thread.id)
if (threadChannel === null || threadChannel.parentId === null) {
throw new Error(
`Thread ${thread.id} has no parent ID even after fetching the thread, give up`,
)
}
parentId = threadChannel.parentId
}
const parent = await thread.guild.channels.fetch(parentId)
if (!parent) {
throw new Error(`Thread ${thread.id} has no parent channel?`)
}
if (
parent.type === ChannelType.GuildNews ||
parent.type === ChannelType.GuildText
) {
return parent
}
throw new Error(
`Thread ${thread.id} has an unexpected parent channel type ${parent.type}`,
)
}
export async function nsfwAllowedInChannel(
channel: TextBasedChannel | ThreadOnlyChannel,
allowNSFW: boolean,
): Promise<boolean> {
// There are 3 cases:
// - We're in a DM, which can't be age-restricted
// - In this case, we'll fall back to a `allowNSFW` config option
// - We're in a thread, where the *parent* channel can be age-restricted or not
// - Check if allowNSFW, then check parent channel
// - We're in a text guild channel (regular, news, voice) which can be age-restricted or not
// - Check if allowNSFW, then check channel
// false = disable *everywhere*
if (!allowNSFW) {
return false
}
// true = enable in DMs or age-restricted channels
if (channel.isDMBased()) {
return allowNSFW
}
if (channel.isThread()) {
// Already checked allowNSFW, check parent channel
return await getParentChannel(channel).then((parent) => parent.nsfw)
}
// Already checked allowNSFW, check channel
return channel.nsfw
}
/**
* Settings that apply for this specific invocation
*/
interface ContextSettings {
minScore: number | null
allowNSFW: boolean
blacklistedTags: string[]
}
interface FilteredPost {
post: Post
reason: string
}
interface FilterResults {
posts: Post[]
filtered: FilteredPost[]
}
export function filterPosts(
posts: Post[],
{ minScore, allowNSFW, blacklistedTags }: ContextSettings,
): FilterResults {
const passing: Post[] = []
const filtered: FilteredPost[] = []
for (const post of posts) {
if (!post.fileUrl) {
filtered.push({ post, reason: 'No file URL' })
} else if (!post.available) {
filtered.push({ post, reason: 'Unavailable' })
} else if (minScore !== null && post.score < minScore) {
filtered.push({ post, reason: `Score below ${minScore}` })
} else if (!allowNSFW && isNSFWPost(post)) {
filtered.push({ post, reason: 'NSFW' })
} else if (postMatchesBlacklist(post, blacklistedTags)) {
filtered.push({ post, reason: 'Blacklisted tags' })
} else {
passing.push(post)
}
}
return { posts: passing, filtered }
}
export function formatFilteredPosts(filteredPosts: FilteredPost[]): string {
return Array.from(
filteredPosts
.reduce(
(acc, { reason }) => acc.set(reason, (acc.get(reason) ?? 0) + 1),
new Map<string, number>(),
)
.entries(),
)
.map(([reason, count]) => `${count}: ${reason}`)
.join(', ')
}
/**
* Check if a post is considered NSFW by checking the rating
* @param post The post to check
* @returns Is the post considered NSFW?
*/
function isNSFWPost(post: Post): boolean {
return !['s', 'g'].includes(post.rating)
}
const EXPANDED_RATINGS = {
s: 'safe',
q: 'questionable',
e: 'explicit',
u: 'unrated',
} as const
type RatingLetter = keyof typeof EXPANDED_RATINGS
export const NSFW_RATINGS = ['q', 'e', 'u'].flatMap((r) => [
`rating:${r}`,
`rating:${EXPANDED_RATINGS[r as RatingLetter]}`,
])
export function postMatchesBlacklist(post: Post, blacklist: string[]): boolean {
// Check rating
const ratings = [
`rating:${post.rating}`,
`rating:${EXPANDED_RATINGS[post.rating as RatingLetter]}`,
]
// Check filetype
const filetype = `type:${extname(post.fileUrl ?? '').slice(1)}`
// Check tags
const finalTags = [...ratings, filetype, ...post.tags]
return finalTags.some((tag) => compareTagAgainstBlacklist(tag, blacklist))
}
/**
* List all tags that match a given blacklist
* @param tags Tags to compare against the blacklist
* @param blacklist The blacklist to compare against
* @returns All tags that matched the blacklist
*/
export function getTagsMatchingBlacklist(
tags: string[],
blacklist: string[],
): string[] {
// Get all matches
return tags.filter((tag) => compareTagAgainstBlacklist(tag, blacklist))
}
/**
* Compares a tag against a blacklist, returning if it matched
* @param tag The tag to compare against the blacklist
* @param blacklist The blacklist to compare against
* @returns If the tag matched the blacklist
*/
function compareTagAgainstBlacklist(tag: string, blacklist: string[]): boolean {
const lowerTag = tag.toLowerCase()
return blacklist.includes(lowerTag)
}
/**
* Check if an extension is embeddable inside of an embed (`.setImage`)
* @param ext The extension to check for.
* @returns If the extension is embeddable in an embed
*/
function isEmbeddableFileType(ext: string): boolean {
return ['.jpg', '.jpeg', '.png', '.gif'].includes(ext)
}
function notEmpty(str: string): boolean {
return str.trim() !== ''
}
/** This regex will match up to 75 characters, then cleanly end the match at the next `,`, up to a max of 100 characters total */
const regexCutTags = /[\S\s]{1,75}[^,]{0,25}/
export function formatTags(tags: string[]): string {
const tagString = tags.join(', ')
if (tagString.length < 100) {
return tagString
}
const tagCutMatch = tagString.match(regexCutTags) ?? []
return `${escapeMarkdown(tagCutMatch[0] ?? '')}...`
}
function formatTime(time: bigint): string {
return `${(Number(time) / 1e6).toFixed(2)}ms`
}
interface PostFormatOptions {
post: Post
color?: ColorResolvable | null
timeTaken?: bigint
postNumber?: number
postCount?: number
filteredPosts?: FilteredPost[]
appendContent?: string
tags?: string[]
defaultTags?: string[]
}
interface FormattedPost {
content: string | null
embeds: EmbedBuilder[]
}
const ratingEmojis: Record<string, string | undefined> = {
s: '<:rating_safe:1194080016779202610>',
g: '<:rating_general:1194080014413615216>',
q: '<:rating_questionable:1194080015353127023>',
e: '<:rating_explicit:1194080012769431645>',
u: '<:rating_unknown:1194080018536603669>',
}
function formatRating(rating: string): string {
return ratingEmojis[rating] ?? rating.toUpperCase()
}
function formatScore(score: number): string {
if (score > 0) {
return `<:green_arrow_up:1194080011330801744> ${score}`
}
if (score < 0) {
return `<:red_arrow_down:1194080019719401603> ${score}`
}
return `<:yellow_tilde:1194080020956729364> ${score}`
}
export function formatPostToEmbed({
post,
color = '#34363C',
timeTaken,
postNumber,
postCount,
filteredPosts = [],
appendContent = '',
tags = [],
defaultTags = [],
}: PostFormatOptions): FormattedPost {
const ext = extname(
// biome-ignore lint/complexity/useLiteralKeys: Typescript doesn't like us access data like this
(post['data'] as Record<string, string | undefined>).file_name ??
post.fileUrl ??
'',
).toLowerCase()
const leadingDescription = [
`**Score:** ${formatScore(post.score)}`,
`**Rating:** ${formatRating(post.rating)}`,
`[File URL](${post.fileUrl})`,
`\`${ext}\``,
].join(' | ')
const description = [leadingDescription, `**Tags:** ${formatTags(post.tags)}`]
.filter(notEmpty)
.join('\n')
const footerText = [
post.booru.domain,
postNumber ? `${postNumber}/${postCount ?? postNumber}` : '',
timeTaken ? formatTime(timeTaken) : '',
]
.filter(notEmpty)
.join(' · ')
const tagLine = [
tags.length > 0 ? `**Tags:** ${formatTags(tags)}` : '',
defaultTags.length > 0
? `**Default Tags:** ${formatTags(defaultTags)}`
: '',
]
.filter(notEmpty)
.join(' + ')
const filterCount = filteredPosts.length
const reasonCount = formatFilteredPosts(filteredPosts)
const hiddenCount =
filterCount > 0
? `${filterCount} hidden ${pluralize(
'post',
filterCount,
)} (${reasonCount})`
: ''
const contentLines = [tagLine, hiddenCount]
const embeds: EmbedBuilder[] = []
// If the file is embeddable, use an embed (it looks prettier!)
// Otherwise, we need to fallback to no embed and let Discord handle creating the embed from the file URL
// If you have an embed in your message, Discord won't automatically embed the file URL, and embeds sent by bots can't add videos
// yay :/
if (isEmbeddableFileType(ext)) {
const embed = new EmbedBuilder()
.setColor(color)
.setTitle(`Post #${post.id}`)
.setURL(post.postView)
.setDescription(description)
.setImage(post.fileUrl)
.setFooter({
text: footerText,
iconURL: `https://${post.booru.domain}/favicon.ico`,
})
embeds.push(embed)
} else {
contentLines.unshift(
`>>> **[Post #${post.id}](<${post.postView}>)**`,
description,
footerText,
)
}
const content = contentLines.filter(notEmpty).join('\n')
return {
content: `${content}${appendContent}`.trim(),
embeds,
}
}
const ORDER_TAGS = ['order:', 'sort:'] as const
export function hasOrderTag(tags: string[]): boolean {
return ORDER_TAGS.some((ot) => tags.some((tag) => tag.startsWith(ot)))
}
function pluralize(str: string, count: number, plural?: string): string {
return count === 1 ? str : (plural ?? `${str}s`)
}
export function getErrorMessage(e: unknown): string {
if (e instanceof Error) {
return e.message
}
return String(e)
}