-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathmanCommand.ts
202 lines (166 loc) · 6.74 KB
/
manCommand.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
/*
* Copyright (c) 2021, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
import {
ActionRowBuilder,
ButtonBuilder,
ButtonInteraction,
ButtonStyle,
ChatInputCommandInteraction,
Embed,
EmbedBuilder,
Interaction,
SlashCommandBuilder,
} from "discord.js";
import githubAPI from "../apis/githubAPI";
import { getMaximize, getMinimize, getSadCaret } from "../util/emoji";
import Command from "./command";
interface Paragraph {
title?: string;
content: string;
truncateFollowingLines?: boolean;
}
export class ManCommand extends Command {
override data() {
return [
new SlashCommandBuilder()
.setName("man")
.setDescription("Show a particular program's man page")
.addIntegerOption(section =>
section
.setName("section")
.setDescription("The section in which the page to display is")
.setRequired(true)
)
.addStringOption(page =>
page
.setName("page")
.setDescription("The name of the page to display")
.setRequired(true)
)
.toJSON(),
];
}
override buttonData(): Array<string> {
return ["/man:maximize", "/man:minimize"];
}
override async handleCommand(interaction: ChatInputCommandInteraction): Promise<void> {
const section = interaction.options.getInteger("section", true).toString();
const page = interaction.options.getString("page", true);
const result = await githubAPI.fetchSerenityManpage(section, page).catch(() => null);
if (result) {
const { markdown, url: githubUrl } = result;
await interaction.reply({
fetchReply: true,
embeds: [ManCommand.embedForMan(markdown, githubUrl, section, page, true)],
components: [await ManCommand.buttons(interaction)],
});
return;
}
const sadcaret = await getSadCaret(interaction);
await interaction.reply({
ephemeral: true,
content: `No matching man page found for ${page}(${section}) ${sadcaret ?? ":^("}`,
});
}
override async handleButton(interaction: ButtonInteraction): Promise<void> {
if (!interaction.channel) return;
const message = await interaction.channel.messages.fetch(interaction.message.id);
if (interaction.user.id !== message.interaction?.user.id) {
interaction.reply({
ephemeral: true,
content: `Only ${message.interaction?.user.tag} can update this embed`,
});
return;
}
const collapsed: boolean = interaction.customId === "/man:minimize";
if (message.embeds.length === 1) {
const embed: Embed = message.embeds[0];
if (!embed.description) return;
const result = await githubAPI.fetchSerenityManpageByUrl(
embed.description?.match(/\(([^)]+)\)/)![1]
);
if (result == null) return;
const { markdown, url: githubUrl, page, section } = result;
interaction.update({
embeds: [ManCommand.embedForMan(markdown, githubUrl, section, page, collapsed)],
});
}
}
static async buttons(interaction: Interaction) {
const maximizeButton = new ButtonBuilder()
.setCustomId("/man:maximize")
.setLabel("Maximize")
.setStyle(ButtonStyle.Primary);
const minimizeButton = new ButtonBuilder()
.setCustomId("/man:minimize")
.setLabel("Minimize")
.setStyle(ButtonStyle.Primary);
const maximizeEmote = await getMaximize(interaction);
const minimizeEmote = await getMinimize(interaction);
if (maximizeEmote) maximizeButton.setEmoji(maximizeEmote.identifier);
if (minimizeEmote) minimizeButton.setEmoji(minimizeEmote.identifier);
return new ActionRowBuilder<ButtonBuilder>().addComponents(maximizeButton, minimizeButton);
}
static embedForMan(
markdown: string,
githubUrl: string,
section: string,
page: string,
collapsed: boolean
): EmbedBuilder {
const paragraphs: Array<Paragraph> = new Array<Paragraph>();
let currentParagraph: Paragraph = { content: "" };
let truncated = false;
let name: string | undefined;
for (let line of markdown.split("\n")) {
if (line.startsWith("## ")) {
if (currentParagraph.content !== "") {
if (currentParagraph.title === "Name") {
name = currentParagraph.content.replace(/[\r\n]/g, "");
} else {
paragraphs.push(currentParagraph);
}
}
currentParagraph = { content: "" };
currentParagraph.title = line.substring(3).trim();
} else if (!currentParagraph.truncateFollowingLines) {
if (currentParagraph.content.length + line.length + 4 > (collapsed ? 512 : 1024)) {
currentParagraph.content += "\n...";
currentParagraph.truncateFollowingLines = true;
truncated = true;
} else {
if (line.startsWith("```")) line = line.replace(/\*/g, "");
currentParagraph.content += line + "\n";
}
}
}
const url = `https://man.serenityos.org/man${section}/${page}.html`;
const embed = new EmbedBuilder()
.setTitle(`${page}(${section})`)
.setDescription(
`${
name ?? "Name not found"
}\n\n[View on GitHub](${githubUrl}) - [View on man.serenityos.org](${url})`
)
.setURL(url)
.setTimestamp();
for (const paragraph of paragraphs)
if ((!collapsed || paragraph.title === "Description") && paragraph.title)
embed.addFields({
name: paragraph.title,
value: paragraph.content,
});
if (truncated && !collapsed)
embed.setFooter({
text: `The following paragraphs have been truncated: ${paragraphs
.filter(paragraph => paragraph.title && paragraph.truncateFollowingLines)
.map(paragraph => paragraph.title)
.join(", ")}`,
});
if (collapsed) embed.setFooter({ text: "React with maximize to expand sections" });
return embed;
}
}