|
| 1 | +import { createHash } from 'node:crypto'; |
| 2 | +import { readdir, readFile, writeFile } from 'node:fs/promises'; |
| 3 | +import { join } from 'node:path'; |
| 4 | +import { fileURLToPath } from 'node:url'; |
| 5 | +import { ChannelType, type Client, EmbedBuilder, type TextChannel } from 'discord.js'; |
| 6 | +import { config } from '../env.js'; |
| 7 | +import { parseMarkdown } from './markdown.js'; |
| 8 | + |
| 9 | +export type GuideInfo = { |
| 10 | + name: string; |
| 11 | + filename: string; |
| 12 | + hash: string; |
| 13 | + messageId?: string; |
| 14 | + content: string; |
| 15 | + frontmatter: Record<string, unknown>; |
| 16 | +}; |
| 17 | + |
| 18 | +const guidesColors = [0xff5733, 0x33ff57, 0x3357ff, 0xff33a8, 0xa833ff, 0x33fff5]; |
| 19 | +const getRandomColor = () => guidesColors[Math.floor(Math.random() * guidesColors.length)]; |
| 20 | +const createGuideEmbed = (guide: GuideInfo) => |
| 21 | + new EmbedBuilder() |
| 22 | + .setTitle(guide.name) |
| 23 | + .setDescription(guide.content) |
| 24 | + .setColor(getRandomColor()) |
| 25 | + .setFooter({ text: `Last updated: ${new Date().toLocaleDateString()}` }); |
| 26 | + |
| 27 | +export type GuideTracker = { |
| 28 | + [filename: string]: { |
| 29 | + hash: string; |
| 30 | + messageId?: string; |
| 31 | + }; |
| 32 | +}; |
| 33 | + |
| 34 | +const GUIDES_DIR = fileURLToPath(new URL('../commands/guides/subjects/', import.meta.url)); |
| 35 | + |
| 36 | +const TRACKER_FILE = config.guides.trackerPath ?? 'guides-tracker.json'; |
| 37 | + |
| 38 | +const calculateHash = (content: string): string => { |
| 39 | + return createHash('sha256').update(content, 'utf8').digest('hex'); |
| 40 | +}; |
| 41 | + |
| 42 | +const loadTracker = async (): Promise<GuideTracker> => { |
| 43 | + try { |
| 44 | + const content = await readFile(TRACKER_FILE, 'utf8'); |
| 45 | + return JSON.parse(content); |
| 46 | + } catch { |
| 47 | + console.log('No existing tracker file found, starting fresh'); |
| 48 | + return {}; |
| 49 | + } |
| 50 | +}; |
| 51 | + |
| 52 | +const saveTracker = async (tracker: GuideTracker): Promise<void> => { |
| 53 | + await writeFile(TRACKER_FILE, JSON.stringify(tracker, null, 2), 'utf8'); |
| 54 | +}; |
| 55 | + |
| 56 | +const scanGuideFiles = async (): Promise<GuideInfo[]> => { |
| 57 | + const files = await readdir(GUIDES_DIR); |
| 58 | + const guides: GuideInfo[] = []; |
| 59 | + |
| 60 | + for (const filename of files) { |
| 61 | + if (!filename.endsWith('.md')) { |
| 62 | + continue; |
| 63 | + } |
| 64 | + |
| 65 | + const filePath = join(GUIDES_DIR, filename); |
| 66 | + const content = await readFile(filePath, 'utf8'); |
| 67 | + const { frontmatter, content: markdownContent } = await parseMarkdown(content); |
| 68 | + |
| 69 | + const hash = calculateHash(content); |
| 70 | + const name = (frontmatter.name as string) || filename.replace('.md', ''); |
| 71 | + |
| 72 | + guides.push({ |
| 73 | + name, |
| 74 | + filename, |
| 75 | + hash, |
| 76 | + content: markdownContent, |
| 77 | + frontmatter, |
| 78 | + }); |
| 79 | + } |
| 80 | + |
| 81 | + return guides; |
| 82 | +}; |
| 83 | + |
| 84 | +const postGuideToChannel = async (channel: TextChannel, guide: GuideInfo): Promise<string> => { |
| 85 | + const message = await channel.send({ |
| 86 | + embeds: [createGuideEmbed(guide)], |
| 87 | + }); |
| 88 | + |
| 89 | + console.log(`β
Posted guide "${guide.name}" (${guide.filename})`); |
| 90 | + return message.id; |
| 91 | +}; |
| 92 | + |
| 93 | +const editGuideMessage = async ( |
| 94 | + channel: TextChannel, |
| 95 | + messageId: string, |
| 96 | + guide: GuideInfo |
| 97 | +): Promise<void> => { |
| 98 | + try { |
| 99 | + const message = await channel.messages.fetch(messageId); |
| 100 | + await message.edit({ |
| 101 | + embeds: [createGuideEmbed(guide)], |
| 102 | + }); |
| 103 | + |
| 104 | + console.log(`π Updated guide "${guide.name}" (${guide.filename})`); |
| 105 | + } catch (error) { |
| 106 | + console.error(`Failed to edit message ${messageId} for guide "${guide.name}":`, error); |
| 107 | + throw error; |
| 108 | + } |
| 109 | +}; |
| 110 | + |
| 111 | +const deleteGuideMessage = async ( |
| 112 | + channel: TextChannel, |
| 113 | + messageId: string, |
| 114 | + guideName: string |
| 115 | +): Promise<void> => { |
| 116 | + try { |
| 117 | + const message = await channel.messages.fetch(messageId); |
| 118 | + await message.delete(); |
| 119 | + |
| 120 | + console.log(`ποΈ Deleted guide "${guideName}"`); |
| 121 | + } catch (error) { |
| 122 | + console.error(`Failed to delete message ${messageId} for guide "${guideName}":`, error); |
| 123 | + } |
| 124 | +}; |
| 125 | + |
| 126 | +export const syncGuidesToChannel = async (client: Client, channelId: string): Promise<void> => { |
| 127 | + console.log('π Starting guide synchronization...'); |
| 128 | + |
| 129 | + try { |
| 130 | + const channel = await client.channels.fetch(channelId); |
| 131 | + if (!channel || !channel.isTextBased() || channel.type !== ChannelType.GuildText) { |
| 132 | + throw new Error(`Channel ${channelId} is not a valid text channel`); |
| 133 | + } |
| 134 | + // Load current state |
| 135 | + const tracker = await loadTracker(); |
| 136 | + const currentGuides = await scanGuideFiles(); |
| 137 | + |
| 138 | + // Create maps for easier lookup |
| 139 | + const currentGuideMap = new Map(currentGuides.map((guide) => [guide.filename, guide])); |
| 140 | + const trackedFiles = new Set(Object.keys(tracker)); |
| 141 | + const currentFiles = new Set(currentGuides.map((guide) => guide.filename)); |
| 142 | + |
| 143 | + // Find changes |
| 144 | + const newFiles = [...currentFiles].filter((file) => !trackedFiles.has(file)); |
| 145 | + const deletedFiles = [...trackedFiles].filter((file) => !currentFiles.has(file)); |
| 146 | + const modifiedFiles = [...currentFiles].filter((file) => { |
| 147 | + const guide = currentGuideMap.get(file); |
| 148 | + return guide && trackedFiles.has(file) && tracker[file].hash !== guide.hash; |
| 149 | + }); |
| 150 | + |
| 151 | + console.log( |
| 152 | + `π Found: ${newFiles.length} new, ${modifiedFiles.length} modified, ${deletedFiles.length} deleted` |
| 153 | + ); |
| 154 | + |
| 155 | + // Process deletions first |
| 156 | + for (const filename of deletedFiles) { |
| 157 | + const messageId = tracker[filename].messageId; |
| 158 | + if (messageId) { |
| 159 | + await deleteGuideMessage(channel, messageId, filename); |
| 160 | + } |
| 161 | + delete tracker[filename]; |
| 162 | + } |
| 163 | + |
| 164 | + // Process new guides |
| 165 | + for (const filename of newFiles) { |
| 166 | + const guide = currentGuideMap.get(filename)!; |
| 167 | + const messageId = await postGuideToChannel(channel, guide); |
| 168 | + |
| 169 | + tracker[filename] = { |
| 170 | + hash: guide.hash, |
| 171 | + messageId, |
| 172 | + }; |
| 173 | + } |
| 174 | + |
| 175 | + // Process modifications |
| 176 | + for (const filename of modifiedFiles) { |
| 177 | + const guide = currentGuideMap.get(filename)!; |
| 178 | + const messageId = tracker[filename].messageId; |
| 179 | + |
| 180 | + if (messageId) { |
| 181 | + await editGuideMessage(channel, messageId, guide); |
| 182 | + } else { |
| 183 | + // If no message ID, treat as new |
| 184 | + const newMessageId = await postGuideToChannel(channel, guide); |
| 185 | + tracker[filename].messageId = newMessageId; |
| 186 | + } |
| 187 | + |
| 188 | + tracker[filename].hash = guide.hash; |
| 189 | + } |
| 190 | + |
| 191 | + await saveTracker(tracker); |
| 192 | + |
| 193 | + const totalChanges = newFiles.length + modifiedFiles.length + deletedFiles.length; |
| 194 | + if (totalChanges === 0) { |
| 195 | + console.log('β¨ All guides are up to date!'); |
| 196 | + } else { |
| 197 | + console.log(`β
Guide synchronization complete! Made ${totalChanges} changes.`); |
| 198 | + } |
| 199 | + } catch (error) { |
| 200 | + console.error('β Guide synchronization failed:', error); |
| 201 | + throw error; |
| 202 | + } |
| 203 | +}; |
| 204 | + |
| 205 | +export const initializeGuidesChannel = async (client: Client, channelId: string): Promise<void> => { |
| 206 | + console.log('π Initializing guides channel...'); |
| 207 | + |
| 208 | + // Clear existing tracker for fresh start |
| 209 | + await saveTracker({}); |
| 210 | + |
| 211 | + await syncGuidesToChannel(client, channelId); |
| 212 | +}; |
0 commit comments