forked from paator/AY-Machine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
376 lines (343 loc) · 9.17 KB
/
index.js
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
import { AttachmentBuilder, Client } from "discord.js";
import "dotenv/config";
import { execSync } from "child_process";
import { existsSync, writeFileSync, rmSync, readFileSync } from "fs";
import fetch from "node-fetch";
import { parseBuffer } from "music-metadata";
import fs from "fs/promises";
import path from "path";
try {
const supportedZXTuneFormats = new Set([
"ASC",
"FTC",
"GTR",
"PSC",
"PSG",
"PSM",
"PT1",
"PT2",
"PT3",
"SQT",
"STC",
"ST1",
"ST3",
"STP",
"VTX",
"YM",
"CHI",
"DMM",
"DST",
"ET1",
"PDT",
"SQD",
"STR",
"TFC",
"TFD",
"TFE",
"669",
"AMF",
"DMF",
"FAR",
"FNK",
"GDM",
"IMF",
"IT",
"LIQ",
"MDL",
"MTM",
"PTM",
"RTM",
"S3M",
"STIM",
"STM",
"STX",
"ULT",
"XM",
"DBM",
"EMOD",
"MOD",
"MTN",
"IMS",
"MED",
"OKT",
"PT36",
"SFX",
"AHX",
"DTM",
"GTK",
"TCB",
"SAP",
"DTT",
"COP",
"SID",
"AYC",
"SPC",
"MTC",
"VGM",
"GYM",
"NSF",
"NSFe",
"GBS",
"GSF",
"HES",
"KSS",
]);
const supportedFurnaceFormats = new Set(["FUR"]);
const supportedChipnsfxFormats = new Set(["CHP"]);
const supportedPSGplayFormats = new Set(["SNDH", "SND"]);
const supportedArkosFormats = new Set(["AKS", "128", "SKS", "WYZ"]);
const commonAYMChipFrequencies = [
["zx", "1773400"],
["pentagon", "1750000"],
["bk", "1710000"],
["vectrex", "1500000"],
["cpc", "1000000"],
["oric", "1000000"],
["st", "2000000"],
["taganrog", "3000000"],
];
const commonAYMLayouts = ["abc", "acb", "bac", "bca", "cba", "cab", "mono"];
const client = new Client({
intents: ["Guilds", "GuildMessages", "MessageContent"],
failIfNotExists: false,
});
const toolsDir = "./tools/";
const checkDependencies = () => {
const dependencies = [
"zxtune123",
"furnace",
"ffmpeg",
"chipnsfx",
"SongToWav",
"psgplay",
];
for (const dep of dependencies) {
if (!existsSync(toolsDir + dep)) {
console.log(`${dep} not found, quitting`);
process.exit(1);
}
}
};
const parseUserFlags = (messageContent) => {
try {
const def_aymClockRate = 1750000;
const def_aymLayout = 0;
const def_aymType = 0;
let aymClockRate = def_aymClockRate;
let aymLayout = def_aymLayout;
let aymType = def_aymType;
if (messageContent) {
const userFlags = messageContent.replaceAll(" ", "").split(",");
for (const flag of userFlags) {
const [key, value] = flag.split("=").map((s) => s.toLowerCase());
if (key === "clock") {
const match = commonAYMChipFrequencies.find(([name]) =>
value.includes(name)
);
if (match) aymClockRate = match[1];
}
if (key === "layout") {
const layoutIndex = commonAYMLayouts.indexOf(value);
if (layoutIndex !== -1) aymLayout = layoutIndex;
}
if (key === "type" && value === "ym") {
aymType = 1;
}
}
}
catch (e) {
await message.reply(
"fuckup at user flag parse",
{ failIfNotExists: false }
);
}
}
return { aymClockRate, aymLayout, aymType };
};
const downloadAttachment = async (url, path) => {
const response = await fetch(url);
const buffer = Buffer.from(await response.arrayBuffer());
writeFileSync(path, buffer);
return buffer;
};
const convertToMp3 = (outputWavPath, outputMp3Path) => {
execSync(
`${toolsDir}ffmpeg -i "${outputWavPath}" -ab 320k "${outputMp3Path}" -hide_banner -loglevel error`
);
};
const convertWithZXTune = (
inputPath,
outputPath,
{ aymClockRate, aymLayout, aymType }
) => {
execSync(
`${toolsDir}zxtune123 --core-options aym.clockrate="${aymClockRate}",aym.layout="${aymLayout}",aym.type="${aymType}" --mp3 filename="${outputPath}",bitrate=320 "${inputPath}"`
);
};
const convertWithFurnace = (inputPath, outputWavPath, outputMp3Path) => {
execSync(
`${toolsDir}furnace -console "${process.cwd()}/${inputPath}" -output "${process.cwd()}/${outputWavPath}"`
);
convertToMp3(outputWavPath, outputMp3Path);
};
const convertWithChipnsfx = (inputPath, outputWavPath, outputMp3Path) => {
execSync(`${toolsDir}chipnsfx -w "${inputPath}" "${outputWavPath}"`);
convertToMp3(outputWavPath, outputMp3Path);
};
const convertWithPSGplay = (inputPath, outputWavPath, outputMp3Path) => {
execSync(
`${toolsDir}psgplay --stop=auto --length=3:25 "${inputPath}" -o "${outputWavPath}"`
);
convertToMp3(outputWavPath, outputMp3Path);
};
const convertWithArkos = (inputPath, outputWavPath, outputMp3Path) => {
execSync(`${toolsDir}SongToWav "${inputPath}" "${outputWavPath}"`);
convertToMp3(outputWavPath, outputMp3Path);
};
const handleConversion = async (message, extension, buffer, attachment) => {
try {
const inputPath = attachment.name;
const mp3Path = `${inputPath}.mp3`;
const reply = await message.reply(
"🤖 Initiating file conversion to format audible by humans. Please standby...",
{ failIfNotExists: false }
);
writeFileSync(inputPath, buffer);
const userFlags = parseUserFlags(message.content);
try {
if (supportedZXTuneFormats.has(extension)) {
// ZXTune
convertWithZXTune(inputPath, mp3Path, userFlags);
} else if (supportedFurnaceFormats.has(extension)) {
// Furnace
const wavPath = `${inputPath}.wav`;
convertWithFurnace(inputPath, wavPath, mp3Path);
rmSync(wavPath);
} else if (supportedChipnsfxFormats.has(extension)) {
// chipnsfx
const wavPath = `${inputPath}.wav`;
convertWithChipnsfx(inputPath, wavPath, mp3Path);
rmSync(wavPath);
} else if (supportedPSGplayFormats.has(extension)) {
// psgplay
const wavPath = `${inputPath}.wav`;
convertWithPSGplay(inputPath, wavPath, mp3Path);
rmSync(wavPath);
} else if (supportedArkosFormats.has(extension)) {
// Arkos Tracker 2
const wavPath = `${inputPath}.wav`;
convertWithArkos(inputPath, wavPath, mp3Path);
rmSync(wavPath);
}
const mp3Buffer = readFileSync(mp3Path);
const metadata = await parseBuffer(mp3Buffer, {
mimeType: "audio/mpeg",
size: mp3Buffer.length,
});
const artist = metadata.common.artist;
const title = metadata.common.title;
let messageContent;
if (artist && title) {
messageContent = `🎶 Your track "${title}" by ${artist} is ready for listening! 🎧🔥`;
} else if (artist) {
messageContent = `🎶 Your track by ${artist} is ready for listening! 🎧🔥`;
} else if (title) {
messageContent = `🎶 Your track "${title}" is ready for listening! 🎧🔥`;
} else {
messageContent = `🎶 Your track is ready for listening! 🎧🔥`;
}
await reply.edit({
content: messageContent,
files: [
new AttachmentBuilder()
.setName(`${attachment.name}.mp3`)
.setFile(mp3Buffer),
],
});
} catch (error) {
console.error("Error during conversion:", error);
await reply.edit(
`🤖 An error occurred during the conversion process. Please try again. ${error}`
);
} finally {
rmSync(inputPath);
rmSync(mp3Path);
}
}
catch (e) {
await message.reply(
"fuckup at conversion",
{ failIfNotExists: false }
);
}
};
const logUsage = async (user, guild, channel, attachmentName) => {
const logFile = "usage_log.json";
let logData = [];
try {
if (existsSync(logFile)) {
const fileContent = await fs.readFile(logFile, "utf-8");
logData = JSON.parse(fileContent);
}
logData.push({
timestamp: new Date().toISOString(),
user: {
id: user.id,
username: user.username,
discriminator: user.discriminator,
},
guild: guild
? {
id: guild.id,
name: guild.name,
}
: null,
channel: {
id: channel.id,
name: channel.name,
},
attachment: attachmentName,
});
await fs.writeFile(logFile, JSON.stringify(logData, null, 2));
} catch (error) {
console.error("Error logging usage:", error);
}
};
client.on("ready", () => {
console.log("Bot operational and ready to process commands.");
});
client.on("messageCreate", async (message) => {
if (
!message.author.bot &&
message.attachments.size > 0 &&
!message.content.toLowerCase().includes("$aymignorefile")
) {
const attachment = message.attachments.first();
const extension = attachment.name.split(".").pop().toUpperCase();
if (
supportedZXTuneFormats.has(extension) ||
supportedFurnaceFormats.has(extension) ||
supportedChipnsfxFormats.has(extension) ||
supportedPSGplayFormats.has(extension) ||
supportedArkosFormats.has(extension)
) {
await logUsage(
message.author,
message.guild,
message.channel,
attachment.name
);
const buffer = await downloadAttachment(attachment.url, attachment.name);
await handleConversion(message, extension, buffer, attachment);
}
}
});
checkDependencies();
client.login(process.env.BOT_TOKEN);
}
catch (e) {
await message.reply(
"okay what the FUCK",
{ failIfNotExists: false }
);
}