birdclaw 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -1
- package/README.md +108 -7
- package/package.json +24 -23
- package/playwright.config.ts +1 -0
- package/public/favicon.ico +0 -0
- package/public/logo192.png +0 -0
- package/public/logo512.png +0 -0
- package/public/manifest.json +2 -2
- package/src/cli.ts +563 -18
- package/src/components/AppNav.tsx +66 -29
- package/src/components/AvatarChip.tsx +10 -5
- package/src/components/ConversationThread.tsx +125 -0
- package/src/components/DmWorkspace.tsx +96 -98
- package/src/components/EmbeddedTweetCard.tsx +20 -14
- package/src/components/InboxCard.tsx +92 -90
- package/src/components/LinkPreviewCard.tsx +270 -0
- package/src/components/ProfilePreview.tsx +8 -3
- package/src/components/SavedTimelineView.tsx +48 -38
- package/src/components/TimelineCard.tsx +228 -84
- package/src/components/TweetRichText.tsx +6 -2
- package/src/lib/archive-import.ts +1567 -65
- package/src/lib/authored-live.ts +1074 -0
- package/src/lib/backup.ts +318 -14
- package/src/lib/bird-actions.ts +1 -10
- package/src/lib/bird-command.ts +57 -0
- package/src/lib/bird.ts +89 -5
- package/src/lib/config.ts +1 -1
- package/src/lib/db.ts +282 -4
- package/src/lib/follow-graph.ts +1053 -0
- package/src/lib/link-index.ts +629 -0
- package/src/lib/link-insights.ts +834 -0
- package/src/lib/link-preview-metadata.ts +334 -0
- package/src/lib/media-fetch.ts +787 -0
- package/src/lib/media-includes.ts +165 -0
- package/src/lib/mention-threads-live.ts +535 -43
- package/src/lib/mentions-live.ts +623 -19
- package/src/lib/moderation-target.ts +6 -0
- package/src/lib/profile-hydration.ts +1 -1
- package/src/lib/profile-resolver.ts +115 -1
- package/src/lib/queries.ts +233 -7
- package/src/lib/seed.ts +127 -8
- package/src/lib/timeline-collections-live.ts +145 -22
- package/src/lib/timeline-live.ts +10 -15
- package/src/lib/tweet-account-edges.ts +9 -2
- package/src/lib/tweet-render.ts +97 -0
- package/src/lib/types.ts +219 -2
- package/src/lib/ui.ts +375 -147
- package/src/lib/url-expansion-store.ts +110 -0
- package/src/lib/url-expansion.ts +33 -8
- package/src/lib/x-profile.ts +7 -2
- package/src/lib/xurl.ts +296 -12
- package/src/routeTree.gen.ts +105 -0
- package/src/routes/__root.tsx +7 -3
- package/src/routes/api/conversation.tsx +34 -0
- package/src/routes/api/link-insights.tsx +79 -0
- package/src/routes/api/link-preview.tsx +43 -0
- package/src/routes/api/profile-hydrate.tsx +51 -0
- package/src/routes/blocks.tsx +111 -86
- package/src/routes/dms.tsx +90 -78
- package/src/routes/inbox.tsx +98 -86
- package/src/routes/index.tsx +63 -50
- package/src/routes/links.tsx +883 -0
- package/src/routes/mentions.tsx +63 -50
- package/src/styles.css +106 -43
|
@@ -0,0 +1,787 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Respectful media caching for tweet records already present in birdclaw.
|
|
3
|
+
*
|
|
4
|
+
* This is not a scraper: it never crawls, enumerates, or derives Twitter/X CDN
|
|
5
|
+
* URLs. It only downloads media URLs already stored in `tweets.media_json`,
|
|
6
|
+
* skips files present on disk, paces requests, and backs off on 429.
|
|
7
|
+
*/
|
|
8
|
+
import {
|
|
9
|
+
existsSync,
|
|
10
|
+
mkdirSync,
|
|
11
|
+
readFileSync,
|
|
12
|
+
readdirSync,
|
|
13
|
+
statSync,
|
|
14
|
+
} from "node:fs";
|
|
15
|
+
import { appendFile, copyFile, rename, rm, writeFile } from "node:fs/promises";
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import { getBirdclawPaths } from "./config";
|
|
18
|
+
import { getNativeDb } from "./db";
|
|
19
|
+
|
|
20
|
+
type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
21
|
+
type Row = { id: string; media_json: string };
|
|
22
|
+
type MediaKind = "image" | "video" | "gif";
|
|
23
|
+
type Candidate = {
|
|
24
|
+
kind: MediaKind;
|
|
25
|
+
mediaKey: string;
|
|
26
|
+
tweetId: string;
|
|
27
|
+
url: string;
|
|
28
|
+
path: string;
|
|
29
|
+
tmpPath: string;
|
|
30
|
+
archivePath?: string;
|
|
31
|
+
};
|
|
32
|
+
type FetchOneResult = {
|
|
33
|
+
fetched: number;
|
|
34
|
+
bytes: number;
|
|
35
|
+
rateLimited: boolean;
|
|
36
|
+
kind?: MediaKind;
|
|
37
|
+
reusedFromArchive?: boolean;
|
|
38
|
+
failure?: MediaFetchResult["failures"][number];
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export type MediaFetchResult = {
|
|
42
|
+
ok: true;
|
|
43
|
+
fetched: number;
|
|
44
|
+
images_fetched: number;
|
|
45
|
+
videos_fetched: number;
|
|
46
|
+
gifs_fetched: number;
|
|
47
|
+
reused_from_archive: number;
|
|
48
|
+
skipped_cached: number;
|
|
49
|
+
failed: number;
|
|
50
|
+
rate_limited: number;
|
|
51
|
+
bytes: number;
|
|
52
|
+
image_bytes: number;
|
|
53
|
+
video_bytes: number;
|
|
54
|
+
gif_bytes: number;
|
|
55
|
+
duration_ms: number;
|
|
56
|
+
failures: Array<{ media_key: string; url: string; reason: string }>;
|
|
57
|
+
dry_run?: true;
|
|
58
|
+
would_fetch?: Array<{
|
|
59
|
+
media_key: string;
|
|
60
|
+
tweet_id: string;
|
|
61
|
+
kind: MediaKind;
|
|
62
|
+
url: string;
|
|
63
|
+
path: string;
|
|
64
|
+
}>;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
export type MediaFetchOptions = {
|
|
68
|
+
account?: string;
|
|
69
|
+
limit?: number;
|
|
70
|
+
kind?: string;
|
|
71
|
+
since?: string;
|
|
72
|
+
parallel?: number;
|
|
73
|
+
pacingMs?: number;
|
|
74
|
+
videoPacingMs?: number;
|
|
75
|
+
retryMax?: number;
|
|
76
|
+
dryRun?: boolean;
|
|
77
|
+
includeVideo?: boolean;
|
|
78
|
+
maxBytes?: number;
|
|
79
|
+
fetchImpl?: FetchLike;
|
|
80
|
+
sleep?: (ms: number) => Promise<void>;
|
|
81
|
+
now?: () => number;
|
|
82
|
+
userAgent?: string;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const DEFAULT_MAX_BYTES = 100 * 1024 * 1024;
|
|
86
|
+
const PBS_PREFIXES = [
|
|
87
|
+
"/media/",
|
|
88
|
+
"/ext_tw_video_thumb/",
|
|
89
|
+
"/amplify_video_thumb/",
|
|
90
|
+
"/tweet_video_thumb/",
|
|
91
|
+
"/profile_images/",
|
|
92
|
+
] as const;
|
|
93
|
+
const packageVersion = (
|
|
94
|
+
JSON.parse(
|
|
95
|
+
readFileSync(new URL("../../package.json", import.meta.url), "utf8"),
|
|
96
|
+
) as { version?: string }
|
|
97
|
+
).version;
|
|
98
|
+
|
|
99
|
+
function defaultSleep(ms: number) {
|
|
100
|
+
return new Promise<void>((resolve) => setTimeout(resolve, ms));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function fileSize(filePath: string) {
|
|
104
|
+
try {
|
|
105
|
+
return statSync(filePath).size;
|
|
106
|
+
} catch {
|
|
107
|
+
return 0;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function basenameKey(url: URL) {
|
|
112
|
+
return path.posix.parse(path.posix.basename(url.pathname)).name;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function imageExtension(url: URL) {
|
|
116
|
+
const ext = path.posix.extname(url.pathname).toLowerCase();
|
|
117
|
+
if (ext === ".jpeg" || ext === ".jpg") return ".jpg";
|
|
118
|
+
if (ext === ".png" || ext === ".webp" || ext === ".gif" || ext === ".svg")
|
|
119
|
+
return ext;
|
|
120
|
+
const format = url.searchParams.get("format")?.toLowerCase();
|
|
121
|
+
return format === "png" || format === "webp" || format === "gif"
|
|
122
|
+
? `.${format}`
|
|
123
|
+
: ".jpg";
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function imageCandidate(
|
|
127
|
+
urlValue: string,
|
|
128
|
+
dir: string,
|
|
129
|
+
tweetId: string,
|
|
130
|
+
): Candidate | null {
|
|
131
|
+
let url: URL;
|
|
132
|
+
try {
|
|
133
|
+
url = new URL(urlValue);
|
|
134
|
+
} catch {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
if (
|
|
138
|
+
url.protocol !== "https:" ||
|
|
139
|
+
url.hostname !== "pbs.twimg.com" ||
|
|
140
|
+
!PBS_PREFIXES.some((prefix) => url.pathname.startsWith(prefix))
|
|
141
|
+
) {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
const mediaKey = basenameKey(url);
|
|
145
|
+
const ext = imageExtension(url);
|
|
146
|
+
return {
|
|
147
|
+
kind: "image",
|
|
148
|
+
mediaKey,
|
|
149
|
+
tweetId,
|
|
150
|
+
url: url.toString(),
|
|
151
|
+
path: path.join(dir, `${mediaKey}${ext}`),
|
|
152
|
+
tmpPath: path.join(dir, `${mediaKey}${ext}.tmp`),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function record(value: unknown) {
|
|
157
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
158
|
+
? (value as Record<string, unknown>)
|
|
159
|
+
: null;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function variantUrl(value: unknown) {
|
|
163
|
+
const item = record(value);
|
|
164
|
+
if (!item) return null;
|
|
165
|
+
const contentType = String(item.content_type ?? item.contentType ?? "");
|
|
166
|
+
if (contentType !== "video/mp4" || typeof item.url !== "string") return null;
|
|
167
|
+
const bitrate = item.bitRate ?? item.bit_rate ?? item.bitrate;
|
|
168
|
+
return {
|
|
169
|
+
url: item.url,
|
|
170
|
+
bitrate: Number.isFinite(Number(bitrate)) ? Number(bitrate) : 0,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function videoCandidate(
|
|
175
|
+
item: Record<string, unknown>,
|
|
176
|
+
dir: string,
|
|
177
|
+
tweetId: string,
|
|
178
|
+
): Candidate | null {
|
|
179
|
+
const rawType = String(item.type ?? "");
|
|
180
|
+
const kind: MediaKind | null =
|
|
181
|
+
rawType === "video"
|
|
182
|
+
? "video"
|
|
183
|
+
: rawType === "animated_gif" || rawType === "gif"
|
|
184
|
+
? "gif"
|
|
185
|
+
: null;
|
|
186
|
+
if (!kind) return null;
|
|
187
|
+
const variants = Array.isArray(item.variants)
|
|
188
|
+
? item.variants
|
|
189
|
+
: Array.isArray(record(item.video_info)?.variants)
|
|
190
|
+
? (record(item.video_info)?.variants as unknown[])
|
|
191
|
+
: [];
|
|
192
|
+
const best = variants
|
|
193
|
+
.map(variantUrl)
|
|
194
|
+
.filter(
|
|
195
|
+
(variant): variant is { url: string; bitrate: number } =>
|
|
196
|
+
variant !== null,
|
|
197
|
+
)
|
|
198
|
+
.sort((left, right) => right.bitrate - left.bitrate)[0];
|
|
199
|
+
if (!best) return null;
|
|
200
|
+
|
|
201
|
+
let url: URL;
|
|
202
|
+
try {
|
|
203
|
+
url = new URL(best.url);
|
|
204
|
+
} catch {
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
if (url.protocol !== "https:" || url.hostname !== "video.twimg.com")
|
|
208
|
+
return null;
|
|
209
|
+
const mediaKey = basenameKey(url);
|
|
210
|
+
return {
|
|
211
|
+
kind,
|
|
212
|
+
mediaKey,
|
|
213
|
+
tweetId,
|
|
214
|
+
url: url.toString(),
|
|
215
|
+
path: path.join(dir, `${mediaKey}.mp4`),
|
|
216
|
+
tmpPath: path.join(dir, `${mediaKey}.mp4.tmp`),
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function archiveTweetDirs(dir: string, tweetId: string) {
|
|
221
|
+
const archiveRoot = path.join(dir, "archive");
|
|
222
|
+
try {
|
|
223
|
+
return readdirSync(archiveRoot, { withFileTypes: true })
|
|
224
|
+
.filter((entry) => entry.isDirectory())
|
|
225
|
+
.map((entry) => path.join(archiveRoot, entry.name, tweetId))
|
|
226
|
+
.filter((tweetDir) => existsSync(tweetDir));
|
|
227
|
+
} catch {
|
|
228
|
+
return [];
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function archiveVideoCandidates(
|
|
233
|
+
item: Record<string, unknown>,
|
|
234
|
+
dir: string,
|
|
235
|
+
tweetId: string,
|
|
236
|
+
) {
|
|
237
|
+
const rawType = String(item.type ?? "");
|
|
238
|
+
const kind: MediaKind | null =
|
|
239
|
+
rawType === "video"
|
|
240
|
+
? "video"
|
|
241
|
+
: rawType === "animated_gif" || rawType === "gif"
|
|
242
|
+
? "gif"
|
|
243
|
+
: null;
|
|
244
|
+
if (!kind) return [];
|
|
245
|
+
|
|
246
|
+
const candidates: Candidate[] = [];
|
|
247
|
+
for (const tweetDir of archiveTweetDirs(dir, tweetId)) {
|
|
248
|
+
let entries;
|
|
249
|
+
try {
|
|
250
|
+
entries = readdirSync(tweetDir, { withFileTypes: true });
|
|
251
|
+
} catch {
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
for (const entry of entries) {
|
|
255
|
+
const ext = path.extname(entry.name).toLowerCase();
|
|
256
|
+
if (!entry.isFile() || ext !== ".mp4") continue;
|
|
257
|
+
const archivePath = path.join(tweetDir, entry.name);
|
|
258
|
+
const prefix = `${tweetId}-`;
|
|
259
|
+
const rawKey = path.basename(entry.name, ext);
|
|
260
|
+
const mediaKey = rawKey.startsWith(prefix)
|
|
261
|
+
? rawKey.slice(prefix.length)
|
|
262
|
+
: rawKey;
|
|
263
|
+
if (!mediaKey) continue;
|
|
264
|
+
candidates.push({
|
|
265
|
+
kind,
|
|
266
|
+
mediaKey,
|
|
267
|
+
tweetId,
|
|
268
|
+
url: `archive:${archivePath}`,
|
|
269
|
+
path: path.join(dir, `${mediaKey}${ext}`),
|
|
270
|
+
tmpPath: path.join(dir, `${mediaKey}${ext}.tmp`),
|
|
271
|
+
archivePath,
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return candidates;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function rowCandidates(row: Row, dir: string, includeVideo: boolean) {
|
|
279
|
+
let items: unknown;
|
|
280
|
+
try {
|
|
281
|
+
items = JSON.parse(row.media_json);
|
|
282
|
+
} catch {
|
|
283
|
+
return [];
|
|
284
|
+
}
|
|
285
|
+
if (!Array.isArray(items)) return [];
|
|
286
|
+
|
|
287
|
+
const candidates: Candidate[] = [];
|
|
288
|
+
for (const value of items) {
|
|
289
|
+
const item = record(value);
|
|
290
|
+
if (!item) continue;
|
|
291
|
+
if (typeof item.url === "string") {
|
|
292
|
+
const image = imageCandidate(item.url, dir, row.id);
|
|
293
|
+
if (image) candidates.push(image);
|
|
294
|
+
}
|
|
295
|
+
if (includeVideo) {
|
|
296
|
+
const archiveVideos = archiveVideoCandidates(item, dir, row.id);
|
|
297
|
+
if (archiveVideos.length > 0) {
|
|
298
|
+
candidates.push(...archiveVideos);
|
|
299
|
+
continue;
|
|
300
|
+
}
|
|
301
|
+
const video = videoCandidate(item, dir, row.id);
|
|
302
|
+
if (video) candidates.push(video);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return candidates;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function queryRows(options: MediaFetchOptions) {
|
|
309
|
+
const params: Array<string | number> = [];
|
|
310
|
+
const account =
|
|
311
|
+
options.account && options.account !== "all" ? options.account : undefined;
|
|
312
|
+
const kind = normalizeKind(options.kind);
|
|
313
|
+
let sql = `
|
|
314
|
+
select t.id, t.media_json
|
|
315
|
+
from tweets t
|
|
316
|
+
where t.media_json not in ('', '[]', 'null')
|
|
317
|
+
`;
|
|
318
|
+
const scopeClause = buildScopeClause(params, account, kind);
|
|
319
|
+
if (scopeClause) sql += ` and (${scopeClause})`;
|
|
320
|
+
if (options.since) {
|
|
321
|
+
params.push(options.since);
|
|
322
|
+
sql += " and t.created_at >= ?";
|
|
323
|
+
}
|
|
324
|
+
sql += " order by t.created_at desc, t.id desc";
|
|
325
|
+
if (options.limit !== undefined) {
|
|
326
|
+
params.push(Math.max(0, Math.floor(options.limit)));
|
|
327
|
+
sql += " limit ?";
|
|
328
|
+
}
|
|
329
|
+
return getNativeDb().prepare(sql).all(params) as Row[];
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function normalizeKind(kind?: string) {
|
|
333
|
+
const value = kind?.trim().toLowerCase();
|
|
334
|
+
if (!value || value === "all") return undefined;
|
|
335
|
+
if (value === "likes") return "like";
|
|
336
|
+
if (value === "bookmarks") return "bookmark";
|
|
337
|
+
return value;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function collectionKind(kind?: string) {
|
|
341
|
+
if (kind === "like") return "likes";
|
|
342
|
+
if (kind === "bookmark") return "bookmarks";
|
|
343
|
+
return undefined;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function buildScopeClause(
|
|
347
|
+
params: Array<string | number>,
|
|
348
|
+
account?: string,
|
|
349
|
+
kind?: string,
|
|
350
|
+
) {
|
|
351
|
+
const clauses: string[] = [];
|
|
352
|
+
const accountClause = (alias: string) =>
|
|
353
|
+
account ? ` and ${alias}.account_id = ?` : "";
|
|
354
|
+
const pushAccount = () => {
|
|
355
|
+
if (account) params.push(account);
|
|
356
|
+
};
|
|
357
|
+
if (kind) {
|
|
358
|
+
params.push(kind);
|
|
359
|
+
pushAccount();
|
|
360
|
+
clauses.push(
|
|
361
|
+
`exists (select 1 from tweet_account_edges edge where edge.tweet_id = t.id and edge.kind = ?${accountClause("edge")})`,
|
|
362
|
+
);
|
|
363
|
+
const savedKind = collectionKind(kind);
|
|
364
|
+
if (savedKind) {
|
|
365
|
+
params.push(savedKind);
|
|
366
|
+
pushAccount();
|
|
367
|
+
clauses.push(
|
|
368
|
+
`exists (select 1 from tweet_collections collection where collection.tweet_id = t.id and collection.kind = ?${accountClause("collection")})`,
|
|
369
|
+
);
|
|
370
|
+
const legacyColumn = savedKind === "likes" ? "liked" : "bookmarked";
|
|
371
|
+
pushAccount();
|
|
372
|
+
clauses.push(
|
|
373
|
+
`t.${legacyColumn} = 1${account ? " and t.account_id = ?" : ""}`,
|
|
374
|
+
);
|
|
375
|
+
}
|
|
376
|
+
params.push(kind);
|
|
377
|
+
pushAccount();
|
|
378
|
+
clauses.push(`t.kind = ?${account ? " and t.account_id = ?" : ""}`);
|
|
379
|
+
return clauses.join(" or ");
|
|
380
|
+
}
|
|
381
|
+
if (account) {
|
|
382
|
+
params.push(account, account, account);
|
|
383
|
+
clauses.push(
|
|
384
|
+
"exists (select 1 from tweet_account_edges edge where edge.tweet_id = t.id and edge.account_id = ?)",
|
|
385
|
+
);
|
|
386
|
+
clauses.push(
|
|
387
|
+
"exists (select 1 from tweet_collections collection where collection.tweet_id = t.id and collection.account_id = ?)",
|
|
388
|
+
);
|
|
389
|
+
clauses.push("t.account_id = ?");
|
|
390
|
+
}
|
|
391
|
+
return clauses.join(" or ");
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function collect(options: MediaFetchOptions, dir: string) {
|
|
395
|
+
const seen = new Set<string>();
|
|
396
|
+
const candidates: Candidate[] = [];
|
|
397
|
+
const would_fetch: NonNullable<MediaFetchResult["would_fetch"]> = [];
|
|
398
|
+
let skipped_cached = 0;
|
|
399
|
+
|
|
400
|
+
for (const row of queryRows(options)) {
|
|
401
|
+
for (const item of rowCandidates(row, dir, options.includeVideo ?? true)) {
|
|
402
|
+
const identity = `${item.kind}:${item.mediaKey}`;
|
|
403
|
+
if (seen.has(identity)) continue;
|
|
404
|
+
seen.add(identity);
|
|
405
|
+
if (existsSync(item.path)) {
|
|
406
|
+
skipped_cached += 1;
|
|
407
|
+
} else if (options.dryRun) {
|
|
408
|
+
would_fetch.push({
|
|
409
|
+
media_key: item.mediaKey,
|
|
410
|
+
tweet_id: item.tweetId,
|
|
411
|
+
kind: item.kind,
|
|
412
|
+
url: item.url,
|
|
413
|
+
path: item.path,
|
|
414
|
+
});
|
|
415
|
+
} else {
|
|
416
|
+
candidates.push(item);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
return { candidates, skipped_cached, would_fetch };
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function fail(
|
|
424
|
+
item: Candidate,
|
|
425
|
+
reason: string,
|
|
426
|
+
rateLimited = false,
|
|
427
|
+
): FetchOneResult {
|
|
428
|
+
return {
|
|
429
|
+
fetched: 0,
|
|
430
|
+
bytes: 0,
|
|
431
|
+
rateLimited,
|
|
432
|
+
failure: { media_key: item.mediaKey, url: item.url, reason },
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* Archive reuse consumes files extracted by the sibling
|
|
438
|
+
* `feat/import-archive-followers-following` branch into
|
|
439
|
+
* `media/originals/archive/<kind>/<tweet_id>/...`.
|
|
440
|
+
*
|
|
441
|
+
* This fetcher intentionally does not extract archive ZIP media itself; it only
|
|
442
|
+
* reuses that layout when it is already present.
|
|
443
|
+
*/
|
|
444
|
+
function archivePathFor(item: Candidate, mediaOriginalsDir: string) {
|
|
445
|
+
if (item.archivePath) return item.archivePath;
|
|
446
|
+
if (!item.tweetId || !item.mediaKey) return null;
|
|
447
|
+
const ext = path.extname(item.path);
|
|
448
|
+
if (!ext) return null;
|
|
449
|
+
const fileName = `${item.tweetId}-${item.mediaKey}${ext}`;
|
|
450
|
+
return (
|
|
451
|
+
archiveTweetDirs(mediaOriginalsDir, item.tweetId)
|
|
452
|
+
.map((tweetDir) => path.join(tweetDir, fileName))
|
|
453
|
+
.find((archivePath) => existsSync(archivePath)) ?? null
|
|
454
|
+
);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
async function reuseFromArchive(
|
|
458
|
+
item: Candidate,
|
|
459
|
+
mediaOriginalsDir: string,
|
|
460
|
+
maxBytes: number,
|
|
461
|
+
) {
|
|
462
|
+
const archivePath = archivePathFor(item, mediaOriginalsDir);
|
|
463
|
+
if (!archivePath || !existsSync(archivePath)) return null;
|
|
464
|
+
const bytes = fileSize(archivePath);
|
|
465
|
+
if (bytes > maxBytes) return fail(item, "max-bytes");
|
|
466
|
+
await copyFile(archivePath, item.tmpPath);
|
|
467
|
+
await rename(item.tmpPath, item.path);
|
|
468
|
+
return {
|
|
469
|
+
fetched: 1,
|
|
470
|
+
bytes,
|
|
471
|
+
rateLimited: false,
|
|
472
|
+
kind: item.kind,
|
|
473
|
+
reusedFromArchive: true,
|
|
474
|
+
} satisfies FetchOneResult;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function contentLength(response: Response) {
|
|
478
|
+
const value = Number(response.headers.get("content-length"));
|
|
479
|
+
return Number.isFinite(value) && value >= 0 ? value : null;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function contentRangeTotal(response: Response) {
|
|
483
|
+
const total = /\/(\d+)\s*$/.exec(
|
|
484
|
+
response.headers.get("content-range") ?? "",
|
|
485
|
+
)?.[1];
|
|
486
|
+
return total ? Number(total) : null;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
async function writeResponseBody(
|
|
490
|
+
response: Response,
|
|
491
|
+
tmpPath: string,
|
|
492
|
+
append: boolean,
|
|
493
|
+
maxBytes: number,
|
|
494
|
+
initialBytes: number,
|
|
495
|
+
) {
|
|
496
|
+
if (!response.body) throw new Error("missing response body");
|
|
497
|
+
let bytes = 0;
|
|
498
|
+
if (!append) {
|
|
499
|
+
await writeFile(tmpPath, Buffer.alloc(0));
|
|
500
|
+
}
|
|
501
|
+
const reader = response.body.getReader();
|
|
502
|
+
try {
|
|
503
|
+
for (;;) {
|
|
504
|
+
const { done, value } = await reader.read();
|
|
505
|
+
if (done) {
|
|
506
|
+
break;
|
|
507
|
+
}
|
|
508
|
+
const chunk = Buffer.from(value);
|
|
509
|
+
bytes += chunk.length;
|
|
510
|
+
if (initialBytes + bytes > maxBytes) {
|
|
511
|
+
throw new Error("max-bytes");
|
|
512
|
+
}
|
|
513
|
+
await appendFile(tmpPath, chunk);
|
|
514
|
+
}
|
|
515
|
+
} catch (error) {
|
|
516
|
+
if (error instanceof Error && error.message === "max-bytes") {
|
|
517
|
+
await rm(tmpPath, { force: true });
|
|
518
|
+
}
|
|
519
|
+
try {
|
|
520
|
+
await reader.cancel(error);
|
|
521
|
+
} catch {
|
|
522
|
+
// The stream may already be errored; preserving the original failure matters.
|
|
523
|
+
}
|
|
524
|
+
throw error;
|
|
525
|
+
} finally {
|
|
526
|
+
reader.releaseLock();
|
|
527
|
+
}
|
|
528
|
+
return bytes;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
async function fetchOne({
|
|
532
|
+
item,
|
|
533
|
+
fetchImpl,
|
|
534
|
+
sleep,
|
|
535
|
+
retryMax,
|
|
536
|
+
userAgent,
|
|
537
|
+
maxBytes,
|
|
538
|
+
}: {
|
|
539
|
+
item: Candidate;
|
|
540
|
+
fetchImpl: FetchLike;
|
|
541
|
+
sleep: (ms: number) => Promise<void>;
|
|
542
|
+
retryMax: number;
|
|
543
|
+
userAgent: string;
|
|
544
|
+
maxBytes: number;
|
|
545
|
+
}): Promise<FetchOneResult> {
|
|
546
|
+
let rateLimited = false;
|
|
547
|
+
for (let attempt = 0; attempt <= retryMax; attempt += 1) {
|
|
548
|
+
const partialBytes = item.kind === "image" ? 0 : fileSize(item.tmpPath);
|
|
549
|
+
if (partialBytes > maxBytes) {
|
|
550
|
+
await rm(item.tmpPath, { force: true });
|
|
551
|
+
return fail(item, "max-bytes");
|
|
552
|
+
}
|
|
553
|
+
let response: Response;
|
|
554
|
+
try {
|
|
555
|
+
response = await fetchImpl(item.url, {
|
|
556
|
+
headers: {
|
|
557
|
+
"user-agent": userAgent,
|
|
558
|
+
...(partialBytes > 0 ? { range: `bytes=${partialBytes}-` } : {}),
|
|
559
|
+
},
|
|
560
|
+
});
|
|
561
|
+
} catch (error) {
|
|
562
|
+
return fail(
|
|
563
|
+
item,
|
|
564
|
+
error instanceof Error ? error.message : String(error),
|
|
565
|
+
rateLimited,
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
if (response.status === 429) {
|
|
569
|
+
rateLimited = true;
|
|
570
|
+
if (attempt < retryMax) {
|
|
571
|
+
await sleep(1000 * 2 ** attempt);
|
|
572
|
+
continue;
|
|
573
|
+
}
|
|
574
|
+
return fail(item, "429", true);
|
|
575
|
+
}
|
|
576
|
+
if (!response.ok && response.status !== 206) {
|
|
577
|
+
return fail(item, String(response.status), rateLimited);
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
const expectedTotal =
|
|
581
|
+
contentRangeTotal(response) ??
|
|
582
|
+
(contentLength(response) ?? 0) +
|
|
583
|
+
(response.status === 206 ? partialBytes : 0);
|
|
584
|
+
if (expectedTotal > maxBytes) {
|
|
585
|
+
await rm(item.tmpPath, { force: true });
|
|
586
|
+
return fail(item, "max-bytes");
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
const append = partialBytes > 0 && response.status === 206;
|
|
590
|
+
let bytes = 0;
|
|
591
|
+
try {
|
|
592
|
+
bytes = await writeResponseBody(
|
|
593
|
+
response,
|
|
594
|
+
item.tmpPath,
|
|
595
|
+
append,
|
|
596
|
+
maxBytes,
|
|
597
|
+
append ? partialBytes : 0,
|
|
598
|
+
);
|
|
599
|
+
} catch (error) {
|
|
600
|
+
if (error instanceof Error && error.message === "max-bytes") {
|
|
601
|
+
return fail(item, "max-bytes", rateLimited);
|
|
602
|
+
}
|
|
603
|
+
return fail(
|
|
604
|
+
item,
|
|
605
|
+
error instanceof Error ? error.message : String(error),
|
|
606
|
+
rateLimited,
|
|
607
|
+
);
|
|
608
|
+
}
|
|
609
|
+
await rename(item.tmpPath, item.path);
|
|
610
|
+
return { fetched: 1, bytes, rateLimited, kind: item.kind };
|
|
611
|
+
}
|
|
612
|
+
return fail(item, "retry exhausted", rateLimited);
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
function applyFetched(result: MediaFetchResult, fetched: FetchOneResult) {
|
|
616
|
+
result.fetched += fetched.fetched;
|
|
617
|
+
result.bytes += fetched.bytes;
|
|
618
|
+
if (fetched.kind === "image") {
|
|
619
|
+
result.images_fetched += 1;
|
|
620
|
+
result.image_bytes += fetched.bytes;
|
|
621
|
+
}
|
|
622
|
+
if (fetched.kind === "video") {
|
|
623
|
+
result.videos_fetched += 1;
|
|
624
|
+
result.video_bytes += fetched.bytes;
|
|
625
|
+
}
|
|
626
|
+
if (fetched.kind === "gif") {
|
|
627
|
+
result.gifs_fetched += 1;
|
|
628
|
+
result.gif_bytes += fetched.bytes;
|
|
629
|
+
}
|
|
630
|
+
if (fetched.reusedFromArchive) result.reused_from_archive += 1;
|
|
631
|
+
if (fetched.rateLimited) result.rate_limited += 1;
|
|
632
|
+
if (fetched.failure) result.failures.push(fetched.failure);
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
async function runGroup(
|
|
636
|
+
items: Candidate[],
|
|
637
|
+
parallel: number,
|
|
638
|
+
pacingMs: number,
|
|
639
|
+
now: () => number,
|
|
640
|
+
sleep: (ms: number) => Promise<void>,
|
|
641
|
+
worker: (item: Candidate) => Promise<void>,
|
|
642
|
+
) {
|
|
643
|
+
let next = 0;
|
|
644
|
+
let lastStart: number | null = null;
|
|
645
|
+
let pace = Promise.resolve();
|
|
646
|
+
const runPaced = async (item: Candidate) => {
|
|
647
|
+
const previous = pace;
|
|
648
|
+
let release = () => {};
|
|
649
|
+
pace = new Promise<void>((resolve) => {
|
|
650
|
+
release = resolve;
|
|
651
|
+
});
|
|
652
|
+
await previous;
|
|
653
|
+
let work: Promise<void>;
|
|
654
|
+
try {
|
|
655
|
+
const waitMs =
|
|
656
|
+
lastStart !== null ? Math.max(0, lastStart + pacingMs - now()) : 0;
|
|
657
|
+
if (waitMs > 0) await sleep(waitMs);
|
|
658
|
+
lastStart = now();
|
|
659
|
+
work = worker(item);
|
|
660
|
+
} finally {
|
|
661
|
+
release();
|
|
662
|
+
}
|
|
663
|
+
await work;
|
|
664
|
+
};
|
|
665
|
+
await Promise.all(
|
|
666
|
+
Array.from({ length: Math.min(parallel, items.length) }, async () => {
|
|
667
|
+
for (;;) {
|
|
668
|
+
const item = items[next++];
|
|
669
|
+
if (!item) return;
|
|
670
|
+
await runPaced(item);
|
|
671
|
+
}
|
|
672
|
+
}),
|
|
673
|
+
);
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
export async function fetchTweetMedia(options: MediaFetchOptions = {}) {
|
|
677
|
+
const now = options.now ?? Date.now;
|
|
678
|
+
const startedAt = now();
|
|
679
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
680
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
681
|
+
const retryMax = Math.max(0, Math.floor(options.retryMax ?? 3));
|
|
682
|
+
const parallel = Math.min(5, Math.max(1, Math.floor(options.parallel ?? 1)));
|
|
683
|
+
const pacingMs = Math.max(0, Math.floor(options.pacingMs ?? 250));
|
|
684
|
+
const videoPacingMs = Math.max(
|
|
685
|
+
0,
|
|
686
|
+
Math.floor(options.videoPacingMs ?? pacingMs),
|
|
687
|
+
);
|
|
688
|
+
const maxBytes = Math.max(
|
|
689
|
+
0,
|
|
690
|
+
Math.floor(options.maxBytes ?? DEFAULT_MAX_BYTES),
|
|
691
|
+
);
|
|
692
|
+
const userAgent =
|
|
693
|
+
options.userAgent ??
|
|
694
|
+
`birdclaw/${packageVersion ?? "0.0.0"} (https://github.com/steipete/birdclaw)`;
|
|
695
|
+
const { mediaOriginalsDir } = getBirdclawPaths();
|
|
696
|
+
mkdirSync(mediaOriginalsDir, { recursive: true });
|
|
697
|
+
|
|
698
|
+
const { candidates, skipped_cached, would_fetch } = collect(
|
|
699
|
+
options,
|
|
700
|
+
mediaOriginalsDir,
|
|
701
|
+
);
|
|
702
|
+
const result: MediaFetchResult = {
|
|
703
|
+
ok: true,
|
|
704
|
+
fetched: 0,
|
|
705
|
+
images_fetched: 0,
|
|
706
|
+
videos_fetched: 0,
|
|
707
|
+
gifs_fetched: 0,
|
|
708
|
+
reused_from_archive: 0,
|
|
709
|
+
skipped_cached,
|
|
710
|
+
failed: 0,
|
|
711
|
+
rate_limited: 0,
|
|
712
|
+
bytes: 0,
|
|
713
|
+
image_bytes: 0,
|
|
714
|
+
video_bytes: 0,
|
|
715
|
+
gif_bytes: 0,
|
|
716
|
+
duration_ms: 0,
|
|
717
|
+
failures: [],
|
|
718
|
+
...(options.dryRun ? { dry_run: true as const, would_fetch } : {}),
|
|
719
|
+
};
|
|
720
|
+
|
|
721
|
+
if (!options.dryRun) {
|
|
722
|
+
const httpCandidates: Candidate[] = [];
|
|
723
|
+
for (const item of candidates) {
|
|
724
|
+
const reused = await reuseFromArchive(item, mediaOriginalsDir, maxBytes);
|
|
725
|
+
if (reused) {
|
|
726
|
+
applyFetched(result, reused);
|
|
727
|
+
} else {
|
|
728
|
+
httpCandidates.push(item);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
const fetchCandidate = async (item: Candidate) =>
|
|
732
|
+
applyFetched(
|
|
733
|
+
result,
|
|
734
|
+
await fetchOne({
|
|
735
|
+
item,
|
|
736
|
+
fetchImpl,
|
|
737
|
+
sleep,
|
|
738
|
+
retryMax,
|
|
739
|
+
userAgent,
|
|
740
|
+
maxBytes,
|
|
741
|
+
}),
|
|
742
|
+
);
|
|
743
|
+
await runGroup(
|
|
744
|
+
httpCandidates.filter((item) => item.kind === "image"),
|
|
745
|
+
parallel,
|
|
746
|
+
pacingMs,
|
|
747
|
+
now,
|
|
748
|
+
sleep,
|
|
749
|
+
fetchCandidate,
|
|
750
|
+
);
|
|
751
|
+
await runGroup(
|
|
752
|
+
httpCandidates.filter((item) => item.kind !== "image"),
|
|
753
|
+
1,
|
|
754
|
+
videoPacingMs,
|
|
755
|
+
now,
|
|
756
|
+
sleep,
|
|
757
|
+
fetchCandidate,
|
|
758
|
+
);
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
result.failed = result.failures.length;
|
|
762
|
+
result.duration_ms = Math.max(0, Math.round(now() - startedAt));
|
|
763
|
+
return result;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
export function formatMediaFetchResult(result: MediaFetchResult) {
|
|
767
|
+
if (result.dry_run) {
|
|
768
|
+
return [
|
|
769
|
+
...(result.would_fetch ?? []).map(
|
|
770
|
+
(item) => `${item.kind}\t${item.media_key}\t${item.url}\t${item.path}`,
|
|
771
|
+
),
|
|
772
|
+
`would_fetch=${result.would_fetch?.length ?? 0} skipped_cached=${result.skipped_cached}`,
|
|
773
|
+
].join("\n");
|
|
774
|
+
}
|
|
775
|
+
return [
|
|
776
|
+
`fetched=${result.fetched}`,
|
|
777
|
+
`images=${result.images_fetched}`,
|
|
778
|
+
`videos=${result.videos_fetched}`,
|
|
779
|
+
`gifs=${result.gifs_fetched}`,
|
|
780
|
+
`reused_from_archive=${result.reused_from_archive}`,
|
|
781
|
+
`skipped_cached=${result.skipped_cached}`,
|
|
782
|
+
`failed=${result.failed}`,
|
|
783
|
+
`rate_limited=${result.rate_limited}`,
|
|
784
|
+
`bytes=${result.bytes}`,
|
|
785
|
+
`duration_ms=${result.duration_ms}`,
|
|
786
|
+
].join(" ");
|
|
787
|
+
}
|