-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathprocess.ts
More file actions
224 lines (198 loc) · 6.17 KB
/
Copy pathprocess.ts
File metadata and controls
224 lines (198 loc) · 6.17 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
import {
COMMENT_MAX_AGE_SECONDS,
decryptAesGcm,
nowSeconds,
} from './crypto.ts';
import {
getAccount,
listActiveRules,
tryClaimComment,
updateSent,
} from './db.ts';
import { isSelfComment } from './guard.ts';
import { findMatchingRule } from './match.ts';
import { sendPrivateReply, sendPublicReply } from './meta.ts';
import type { Env } from './types.ts';
type CommentValue = {
id?: string | number;
comment_id?: string | number;
text?: string;
from?: { id?: string | number; username?: string };
media?: { id?: string | number };
media_id?: string | number;
};
type Change = { field?: string; value?: CommentValue };
type Entry = {
id?: string | number;
time?: number;
field?: string;
value?: CommentValue;
changes?: Change[];
};
type WebhookBody = {
object?: string;
entry?: Entry[];
};
function asUnixSeconds(t: number): number {
return t > 1e12 ? Math.floor(t / 1000) : t;
}
function asId(value: unknown): string | undefined {
if (value == null || value === '') return undefined;
return String(value);
}
/** Meta often sends 17-digit IDs as JSON numbers, which JS cannot represent exactly. */
export function parseWebhookPayload(raw: string): unknown {
const quoted = raw.replace(/:\s*(-?\d{15,})([,}\s])/g, ':"$1"$2');
try {
return JSON.parse(quoted);
} catch {
return JSON.parse(raw);
}
}
export function parsePublicReplyVariations(raw: string | null | undefined): string[] {
if (!raw) return [];
const trimmed = raw.trim();
if (!trimmed) return [];
if (trimmed.startsWith('[')) {
try {
const parsed = JSON.parse(trimmed);
if (Array.isArray(parsed)) {
return parsed.map((s) => String(s).trim()).filter((s) => s.length > 0);
}
} catch {
// Fall through if not valid JSON
}
}
return trimmed
.split(/\r?\n/)
.map((s) => s.trim())
.filter((s) => s.length > 0);
}
export function selectPublicReply(
raw: string | null | undefined,
randomFn: (max: number) => number = (max) => {
const arr = new Uint32Array(1);
crypto.getRandomValues(arr);
return arr[0] % max;
}
): string | null {
const variations = parsePublicReplyVariations(raw);
if (variations.length === 0) return null;
if (variations.length === 1) return variations[0];
const idx = Math.abs(randomFn(variations.length)) % variations.length;
return variations[idx];
}
function commentIdOf(value: CommentValue): string | undefined {
return asId(value.id) || asId(value.comment_id);
}
function changesOf(entry: Entry): Change[] {
if (Array.isArray(entry.changes) && entry.changes.length > 0) return entry.changes;
if (entry.field && entry.value) return [{ field: entry.field, value: entry.value }];
return [];
}
export async function processWebhook(env: Env, payload: unknown): Promise<void> {
const bodies = Array.isArray(payload) ? payload : [payload];
for (const item of bodies) {
const body = item as WebhookBody;
const entries = Array.isArray(body.entry) ? body.entry : [];
for (const entry of entries) {
for (const change of changesOf(entry)) {
if (change.field !== 'comments') continue;
const entryId = asId(entry.id);
if (!change.value || !entryId) continue;
try {
await processComment(env, entryId, entry.time, change.value);
} catch (err) {
console.error('comment processing failed', err instanceof Error ? err.message : err);
}
}
}
}
}
export async function processComment(
env: Env,
entryId: string,
entryTime: number | undefined,
value: CommentValue,
): Promise<void> {
const account = await getAccount(env.DB, entryId);
if (!account || account.active !== 1) {
console.error('no active account for webhook entry', entryId);
return;
}
const commenterId = asId(value.from?.id) ?? null;
if (isSelfComment(commenterId, account.ig_user_id)) {
console.log('ignored self-comment', commentIdOf(value));
return;
}
const commentId = commentIdOf(value);
if (!commentId) return;
const now = nowSeconds();
const text = value.text ?? '';
const mediaId = asId(value.media?.id) ?? asId(value.media_id);
if (entryTime != null) {
const ts = asUnixSeconds(entryTime);
if (now - ts > COMMENT_MAX_AGE_SECONDS) {
await tryClaimComment(env.DB, {
comment_id: commentId,
ig_user_id: account.ig_user_id,
commenter_id: commenterId,
dm_status: 'skipped',
error: 'comment older than 7 days — Instagram will not accept a private reply',
sent_at: now,
});
return;
}
}
const claimed = await tryClaimComment(env.DB, {
comment_id: commentId,
ig_user_id: account.ig_user_id,
commenter_id: commenterId,
dm_status: 'pending',
error: null,
sent_at: now,
});
if (!claimed) return;
const rules = await listActiveRules(env.DB, account.ig_user_id);
const rule = findMatchingRule(rules, text, mediaId);
if (!rule) {
await updateSent(env.DB, commentId, {
rule_id: null,
dm_status: 'skipped',
reply_status: null,
error: 'no matching rule',
sent_at: nowSeconds(),
});
return;
}
let token: string;
try {
token = await decryptAesGcm(env.TOKEN_ENCRYPTION_KEY, account.token_iv, account.access_token_enc);
} catch (err) {
await updateSent(env.DB, commentId, {
rule_id: rule.id,
dm_status: 'failed',
reply_status: null,
error: `could not decrypt access token: ${err instanceof Error ? err.message : 'unknown'}`,
sent_at: nowSeconds(),
});
return;
}
const dm = await sendPrivateReply(account.ig_user_id, token, commentId, rule.dm_text);
let replyStatus: string | null = null;
const errors: string[] = [];
if (!dm.ok) errors.push(`DM: ${dm.body}`);
const publicText = selectPublicReply(rule.public_reply_text);
if (publicText) {
const reply = await sendPublicReply(commentId, token, publicText);
replyStatus = reply.ok ? 'ok' : 'failed';
if (!reply.ok) errors.push(`public reply: ${reply.body}`);
}
await updateSent(env.DB, commentId, {
rule_id: rule.id,
dm_status: dm.ok ? 'ok' : 'failed',
reply_status: replyStatus,
error: errors.length ? errors.join('\n') : null,
sent_at: nowSeconds(),
});
}