Repository navigation
Expand file tree
/
Copy pathattachments.js
More file actions
310 lines (282 loc) · 10.8 KB
/
Copy pathattachments.js
File metadata and controls
310 lines (282 loc) · 10.8 KB
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
const MAX_FILES = 2;
const MAX_BYTES = 40 * 1024;
const TIMEOUT_MS = 8_000;
const ALLOWED_EXT = /\.(log|txt|json)$/i;
function attachmentsList(attachments) {
if (!attachments) return [];
if (typeof attachments.values === 'function') return [...attachments.values()];
if (Array.isArray(attachments)) return attachments;
return Object.values(attachments);
}
function isAllowedTextAttachment(att) {
if (!att) return false;
const name = String(att.name || att.filename || '');
const type = String(att.contentType || att.content_type || '').toLowerCase();
if (type.startsWith('image/') || type.startsWith('video/') || type.startsWith('audio/')) return false;
if (ALLOWED_EXT.test(name)) return true;
if (type === 'text/plain' || type === 'application/json') return true;
return false;
}
function hasUsableAttachment(message) {
return attachmentsList(message?.attachments).some(isAllowedTextAttachment);
}
function clipAttachmentText(text, max = MAX_BYTES) {
const s = String(text || '');
if (Buffer.byteLength(s, 'utf8') <= max) return s;
let out = s;
while (out.length && Buffer.byteLength(out, 'utf8') > max) {
out = out.slice(0, Math.max(0, out.length - 256));
}
return `${out}\n…`;
}
function isSpoilerImageName(name) {
if (!String(name).startsWith('SPOILER_')) return false;
return !/\.(mp4|mov|webm|mp3|m4a|wav|ogg|log|txt|json)$/i.test(name);
}
function isWatchableAttachment(att) {
if (!att) return false;
const type = String(att.contentType || att.content_type || '').toLowerCase();
const name = String(att.name || att.filename || '');
if (type.startsWith('image/') || type.startsWith('video/') || type.startsWith('audio/')) return true;
if (/\.(png|jpe?g|gif|webp|mp4|mov|webm|mp3|m4a|wav|ogg)$/i.test(name)) return true;
return isSpoilerImageName(name);
}
function shouldMentionUnreadMedia(attachments, textFiles, read = {}) {
const logRead = (textFiles || []).some((file) => file && String(file.text || '').trim());
return attachmentsList(attachments).some((att) => {
if (!isWatchableAttachment(att)) return false;
if ((logRead || read.image) && isImageAttachment(att)) return false;
if (read.video && isVideoAttachment(att)) return false;
return true;
});
}
function looksLikeDevicePhoto(question) {
const q = String(question || '');
if (/\b(error|screenshot|screen|crash|exception|log)\b/i.test(q)) return false;
return /\b(charg(?:e|er|ing)|cable|pendant)\b/i.test(q);
}
function unreadMediaSentence(question) {
if (looksLikeDevicePhoto(question)) {
return 'I did not use the photo to guess a hardware fault. A still picture cannot show whether the contact, the cable, or the device is the problem.';
}
return 'I did not watch or listen to the file. Type the error line shown on the screen.';
}
function isErrorLine(line) {
return /transcription unavailable/i.test(line)
|| /websocket/i.test(line)
|| /\b1011\b/.test(line)
|| /server_error/i.test(line)
|| /\berror\b/i.test(line)
|| /\bexception\b/i.test(line)
|| /\bfailed\b/i.test(line)
|| /\bdisconnected\b/i.test(line)
|| /\bcode\s*[:#-]?\s*\d+/i.test(line)
|| /\btimed out\b/i.test(line)
|| /\bnot capturing\b/i.test(line);
}
function isOtherChatLine(line) {
if (isErrorLine(line)) return false;
if (/\bconversations\b/i.test(line)) return true;
if (/waiting for transcript/i.test(line)) return true;
if (looksLikeDate(line)) return true;
if (looksLikeShortName(line)) return true;
return !isErrorLine(line);
}
function looksLikeDate(line) {
if (/^(today|yesterday|tomorrow)$/i.test(line)) return true;
if (/^\d{1,2}[\/.-]\d{1,2}([\/.-]\d{2,4})?$/.test(line)) return true;
if (/^(jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\.?\s+\d{1,2}(,\s*\d{4})?$/i.test(line)) return true;
if (/^\d{1,2}\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\.?(,\s*\d{4})?$/i.test(line)) return true;
return false;
}
function looksLikeShortName(line) {
const cleaned = line.replace(/[,|·•]/g, ' ').replace(/\s+/g, ' ').trim();
if (!cleaned || cleaned.length > 40) return false;
const words = cleaned.split(' ');
if (words.length > 4) return false;
return words.every((word) => /^[A-Z][a-zA-Z'-]{0,20}$/.test(word) || /^[A-Z]{2,6}$/.test(word));
}
function errorLinesFromImageText(text) {
const kept = [];
for (const raw of String(text ?? '').split(/\r?\n/)) {
const line = raw.trim();
if (!line || isOtherChatLine(line)) continue;
kept.push(line);
}
return kept.join('\n');
}
function screenshotErrorLines(text) {
return errorLinesFromImageText(text);
}
async function defaultRecognize(buf) {
const { createWorker } = require('tesseract.js');
const worker = await createWorker('eng');
try {
const result = await worker.recognize(buf);
return result?.data?.text || '';
} finally {
await worker.terminate();
}
}
async function imageErrorLines(attachments, { fetchImpl, recognize } = {}) {
const fetchFn = fetchImpl || fetch;
const read = recognize || (process.env.VECTOR_OCR === '1' ? defaultRecognize : null);
if (typeof read !== 'function') return '';
const images = attachmentsList(attachments).filter(isImageAttachment).slice(0, 1);
const kept = [];
for (const att of images) {
const url = att.url || att.proxyURL || att.proxy_url;
if (!url) continue;
try {
const res = await fetchFn(url);
if (!res.ok) continue;
const len = Number(res.headers?.get?.('content-length') || 0);
if (len > 4 * 1024 * 1024) continue;
const buf = Buffer.from(await res.arrayBuffer());
if (buf.length > 4 * 1024 * 1024) continue;
const text = await read(buf);
const lines = errorLinesFromImageText(text);
if (lines) kept.push(lines);
} catch (err) {
console.error('[Attach] image read failed:', err.message);
}
}
return kept.join('\n');
}
function isVideoAttachment(att) {
if (!att) return false;
const type = String(att.contentType || att.content_type || '').toLowerCase();
const name = String(att.name || att.filename || '');
if (type.startsWith('video/')) return true;
return /\.(mp4|mov|webm)$/i.test(name);
}
const VIDEO_CAP = 8 * 1024 * 1024;
function extractVideoFrame(buf) {
const ffmpeg = require('ffmpeg-static');
const { spawnSync } = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'vec-'));
try {
const input = path.join(dir, 'clip.bin');
const output = path.join(dir, 'frame.png');
fs.writeFileSync(input, buf);
const result = spawnSync(ffmpeg, ['-y', '-ss', '1', '-i', input, '-frames:v', '1', output], { timeout: 8000 });
if (result.status !== 0 || !fs.existsSync(output)) return null;
return fs.readFileSync(output);
} finally {
// The clip and its frame are a customer's attachment. They do not stay on disk.
fs.rmSync(dir, { recursive: true, force: true });
}
}
async function videoErrorLines(attachments, { fetchImpl, extractFrame, recognize } = {}) {
const fetchFn = fetchImpl || fetch;
const frameOf = extractFrame || extractVideoFrame;
const read = recognize || (process.env.VECTOR_OCR === '1' ? defaultRecognize : null);
if (typeof read !== 'function') return '';
const clips = attachmentsList(attachments).filter(isVideoAttachment).slice(0, 1);
const kept = [];
for (const att of clips) {
const url = att.url || att.proxyURL || att.proxy_url;
if (!url) continue;
try {
const res = await fetchFn(url);
if (!res.ok) continue;
const len = Number(res.headers?.get?.('content-length') || 0);
if (len > VIDEO_CAP) continue;
const buf = Buffer.from(await res.arrayBuffer());
if (buf.length > VIDEO_CAP) continue;
const frame = await frameOf(buf);
if (!frame) continue;
const lines = errorLinesFromImageText(await read(frame));
if (lines) kept.push(lines);
} catch (err) {
console.error('[Attach] video read failed:', err.message);
}
}
return kept.join('\n');
}
function isImageAttachment(att) {
if (!att) return false;
const type = String(att.contentType || att.content_type || '').toLowerCase();
const name = String(att.name || att.filename || '');
if (type.startsWith('image/')) return true;
if (type.startsWith('video/') || type.startsWith('audio/')) return false;
if (/\.(mp4|mov|webm|mp3|m4a|wav|ogg)$/i.test(name)) return false;
if (/\.(png|jpe?g|gif|webp)$/i.test(name)) return true;
return isSpoilerImageName(name);
}
function shouldMentionUnreadImage(attachments, textFiles) {
const hasImage = attachmentsList(attachments).some(isImageAttachment);
if (!hasImage) return false;
if ((textFiles || []).some((file) => file && String(file.text || '').trim())) return false;
if (attachmentsList(attachments).some(isAllowedTextAttachment)) return false;
return true;
}
function unreadImageSentence() {
return 'I did not read the picture. Type the error line shown on the screen.';
}
function chatFiles(attachments) {
return attachmentsList(attachments)
.map((att) => ({
name: String(att?.name || att?.filename || 'file'),
url: String(att?.url || att?.proxyURL || att?.proxy_url || ''),
type: String(att?.contentType || att?.content_type || ''),
}))
.filter((file) => file.url)
.slice(0, 4);
}
function formatQuestion(userText, files) {
const caption = String(userText || '').trim();
const blocks = (files || [])
.filter((f) => f && f.text)
.map((f) => `Attachment ${f.name || 'file'}:\n${f.text}`)
.join('\n\n');
if (caption && blocks) return `${caption}\n\n${blocks}`;
return caption || blocks || '';
}
async function fetchTextAttachments(discordAttachments, fetchImpl = globalThis.fetch) {
const picked = attachmentsList(discordAttachments)
.filter((att) => isAllowedTextAttachment(att) && !isWatchableAttachment(att))
.slice(0, MAX_FILES);
const out = [];
for (const att of picked) {
if (!att.url) continue;
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), TIMEOUT_MS);
try {
const res = await fetchImpl(att.url, { signal: ctrl.signal });
if (!res.ok) continue;
const buf = Buffer.from(await res.arrayBuffer());
const text = clipAttachmentText(buf.subarray(0, MAX_BYTES + 1).toString('utf8'));
if (text.trim()) out.push({ name: att.name || 'file', text });
} catch (err) {
console.error('[Attach] fetch failed:', err.message);
} finally {
clearTimeout(timer);
}
}
return out;
}
module.exports = {
MAX_FILES,
MAX_BYTES,
isAllowedTextAttachment,
hasUsableAttachment,
clipAttachmentText,
formatQuestion,
fetchTextAttachments,
isImageAttachment,
shouldMentionUnreadImage,
unreadImageSentence,
isWatchableAttachment,
shouldMentionUnreadMedia,
unreadMediaSentence,
chatFiles,
errorLinesFromImageText,
screenshotErrorLines,
imageErrorLines,
isVideoAttachment,
videoErrorLines,
};