-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcli.js
More file actions
483 lines (432 loc) · 19.7 KB
/
Copy pathcli.js
File metadata and controls
483 lines (432 loc) · 19.7 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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
#!/usr/bin/env node
/**
* Letterboxd Contribution Graph Generator - CLI Entry Point
*/
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { fetchProfileData, tryFetchMultipleYears, fetchSpecificYears, fetchAllDiaryEntries, fetchFilmDetails, imageToBase64, closeBrowser } from './fetcher.js';
import { generateSvg, generateMultiYearSvg } from './generator.js';
import { generateReviewCard, generateProfileCard, pickTopFilms, entriesForPeriod, POSTER_PIXEL_WIDTH, POSTER_PIXEL_HEIGHT, FAV_PIXEL_WIDTH, FAV_PIXEL_HEIGHT } from './cards.js';
import { svgToPng, imageBufferToThumbnail } from './exporter.js';
import { buildJsonExport, markRewatches } from './stats.js';
import { resolveReviewYears, resolveYears } from './years.js';
import { loadFilmCache, saveFilmCache, getCachedDetail, setCachedDetail } from './film-cache.js';
import { buildBadges, AVAILABLE_STYLES as BADGE_STYLES } from './badge.js';
import { buildAllTimeStats } from './stats.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
async function main() {
try {
const args = process.argv.slice(2);
let username = null;
let years = resolveYears(''); // Default to the current year, UTC like the diary
let weekStart = "sunday";
let outputBasePath = path.join("images", "github-letterboxd");
let usernameGradient = true;
let yearGradient = true;
let exportPng = false;
let mode = "count"; // 'count' or 'rating'
let animate = true; // CSS reveal animation for grid cells
let scope = "all"; // 'all' fetches the whole diary, 'years' only the -y years
let monthCards = 2; // recent months to also make review cards for
let topFilms = "watched"; // 'watched' or 'released' for the card's film list
let reviewYearsSpec = "all"; // 'all', a list, or a relative span for year cards
let badgeStyle = "dot"; // pill | card | dot | flat | flat-square | for-the-badge | plastic
let badgeStats = "films,rating,streak,days"; // comma list from AVAILABLE_STATS — days active now included by default
// Parse arguments
for (let i = 0; i < args.length; i++) {
if (args[i].startsWith('-')) {
const flag = args[i].replace(/^-+/, '').toLowerCase();
const value = args[i + 1] || "";
switch (flag) {
case 'y':
// A list ("2026,2025") or a relative span ("last 2")
years = resolveYears(value);
i++;
break;
case 'w':
weekStart = ['sunday', 'monday'].includes(value) ? value : 'sunday';
i++;
break;
case 'o':
outputBasePath = path.join(path.dirname(value), path.basename(value));
i++;
break;
case 'g': {
// Accepts the original true/false as well as naming the individual
// targets, so existing workflows keep working.
const targets = value.toLowerCase();
usernameGradient = ['true', 'both', 'name', ''].includes(targets);
yearGradient = ['true', 'both', 'year', ''].includes(targets);
i++;
break;
}
case 'p':
case 'png':
exportPng = true;
break;
case 'm':
mode = ['count', 'rating'].includes(value) ? value : 'count';
i++;
break;
case 'a':
animate = value.toLowerCase() !== 'false';
i++;
break;
case 's':
scope = ['all', 'years'].includes(value) ? value : 'all';
i++;
break;
case 'r':
topFilms = ['watched', 'released'].includes(value) ? value : 'watched';
i++;
break;
case 'review-years':
reviewYearsSpec = value || 'all';
i++;
break;
case 'c': {
const parsed = Number.parseInt(value, 10);
monthCards = Number.isInteger(parsed) && parsed >= 0 ? parsed : 2;
i++;
break;
}
case 'badge-style':
badgeStyle = BADGE_STYLES.includes(value) ? value : 'flat';
i++;
break;
case 'badge-stats':
badgeStats = value || 'films,rating,streak';
i++;
break;
default:
console.warn(`Unknown flag "${flag}", ignoring`);
}
} else if (i === 0 || !username) {
username = args[i];
}
}
if (!username) {
console.error("Error: No username provided.");
console.log("Usage: node src/cli.js <username> [options]");
console.log("Options:");
console.log(" -y <years> Year(s): a list like 2026,2025 or a span like \"last 2\"");
console.log(" -w <day> Week start: sunday or monday (default: sunday)");
console.log(" -o <path> Output path (default: images/github-letterboxd)");
console.log(" -g <targets> Gradient text: true, false, name or year (default: true)");
console.log(" -p Also export PNG files");
console.log(" -m <mode> Graph mode: count or rating (default: count)");
console.log(" -a <bool> Cell reveal animation: true or false (default: true)");
console.log(" -s <scope> Diary scope: all or years (default: all)");
console.log(" -c <count> Recent months to also make cards for, 0 to skip (default: 2)");
console.log(" -r <scope> Card film list: watched or released (default: watched)");
console.log(" --review-years <years> Year cards: all, a list, or last N (default: all)");
console.log(" --badge-style <style> Badge style: flat, flat-square, for-the-badge, plastic (default: flat)");
console.log(" --badge-stats <list> Badge stats: films,rating,streak,days,liked,rewatches (default: films,rating,streak)");
process.exit(1);
}
const outputPathDark = `${outputBasePath}-dark.svg`;
const outputPathLight = `${outputBasePath}-light.svg`;
const outputJsonPath = path.join(path.dirname(outputBasePath), 'letterboxd-data.json');
console.log(`\n🎬 Letterboxd Contribution Graph Generator\n`);
console.log(`Username: ${username}`);
console.log(`Years: ${years.join(', ')}`);
console.log(`Week starts on: ${weekStart}`);
console.log(`Mode: ${mode}`);
console.log(`Animation: ${animate ? '✓' : '✗'}`);
console.log(`Scope: ${scope === 'all' ? 'complete diary' : `only ${years.join(', ')}`}`);
console.log(`Review years: ${reviewYearsSpec}`);
console.log(`Month cards: ${monthCards === 0 ? '✗' : `last ${monthCards}`}`);
console.log(`Card films: ${topFilms === 'released' ? 'releases of that year' : 'everything watched'}`);
console.log(`Gradient: name ${usernameGradient ? '✓' : '✗'}, year ${yearGradient ? '✓' : '✗'}`);
console.log(`Badges: ${badgeStyle} (${badgeStats})`);
console.log(`PNG Export: ${exportPng ? '✓' : '✗'}`);
console.log(`Output: ${outputPathDark}, ${outputPathLight}, ${outputJsonPath}\n`);
// Fetch profile data
console.log("📋 Fetching profile data...");
const { profileImage, displayName, followers, following, totalEntries, memberStatus, favourites } = await fetchProfileData(username);
const profileImageBase64 = profileImage ? await imageToBase64(profileImage) : null;
console.log(` Display Name: ${displayName}`);
console.log(` Followers: ${followers}, Following: ${following}`);
console.log(` Total Films: ${totalEntries}, Member Status: ${memberStatus || 'None'}`);
console.log(` Profile Image: ${profileImageBase64 ? '✓' : '✗'}`);
console.log(` Favourites: ${favourites.length}\n`);
// Fetch Letterboxd logo
console.log("🎬 Fetching Letterboxd logo...");
const logoBase64 = await imageToBase64("https://a.ltrbxd.com/logos/letterboxd-decal-dots-pos-rgb-500px.png");
console.log(` Logo: ${logoBase64 ? '✓' : '✗'}\n`);
// Fetch diary entries. In 'all' scope the whole diary is fetched once and
// the graph years are filtered out of it, so the extra years cost nothing
// beyond the pages they live on.
console.log("📖 Fetching diary entries...");
let allEntries;
if (scope === 'all') {
allEntries = await fetchAllDiaryEntries(username);
} else if (years.length === 1) {
// Single year - use tryFetchMultipleYears logic (backwards compat) or direct fetch
// Using tryFetchMultipleYears to keep robustness if current year is empty
allEntries = await tryFetchMultipleYears(username, years[0]);
} else {
// Multiple specific years
allEntries = await fetchSpecificYears(username, years);
}
// Fill in the rewatches Letterboxd's hand-set flag missed, before anything
// reads the entries, so tooltips, stats, cards and the export agree.
allEntries = markRewatches(allEntries);
// The graph only shows the requested years. Review cards can cover every
// year from the same fetched diary without another Letterboxd request.
const reviewYears = resolveReviewYears(reviewYearsSpec, allEntries);
const filmEntries = scope === 'all'
? allEntries.filter(entry => years.includes(entry.date.getUTCFullYear()))
: allEntries;
console.log(`\n📊 Found ${allEntries.length} film entries`
+ (scope === 'all' ? `, ${filmEntries.length} in ${years.join(', ')}` : '') + '\n');
// Generate SVGs
console.log("🎨 Generating SVG graphs...");
const svgOptions = {
weekStart,
username,
profileImage: profileImageBase64,
displayName,
logoBase64,
usernameGradient,
yearGradient,
followers,
following,
totalEntries,
memberStatus,
mode,
animate,
topFilms
};
let svgDark, svgLight;
if (years.length > 1) {
// Multi-year generation
const multiOptions = { ...svgOptions, years };
svgDark = await generateMultiYearSvg(filmEntries, { ...multiOptions, theme: 'dark' });
svgLight = await generateMultiYearSvg(filmEntries, { ...multiOptions, theme: 'light' });
} else {
// Single year generation
const singleOptions = { ...svgOptions, year: years[0] };
svgDark = await generateSvg(filmEntries, { ...singleOptions, theme: 'dark' });
svgLight = await generateSvg(filmEntries, { ...singleOptions, theme: 'light' });
}
// Ensure output directory exists
const dir = path.dirname(outputPathDark);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
// Write SVG files
fs.writeFileSync(outputPathDark, svgDark);
fs.writeFileSync(outputPathLight, svgLight);
// Write JSON export for Glance custom-api and other consumers
const jsonExport = buildJsonExport(filmEntries, {
username,
year: years.length === 1 ? years[0] : null,
years,
weekStart,
recentLimit: 16,
// The graph and its cells stay scoped to the requested years; the all-time
// block covers whatever was fetched, which in 'all' scope is the lot.
allEntries,
totalFilms: totalEntries,
profileImage: profileImageBase64,
scope
});
fs.writeFileSync(outputJsonPath, JSON.stringify(jsonExport, null, 2));
// Write CSV export — one row per diary entry, stable sort, Excel-friendly
const csvPath = path.join(dir, 'letterboxd-diary.csv');
const csvHeader = ['date','title','year','rating','rewatch','liked','reviewed','url','reviewUrl','slug','filmUid','lid'];
const escapeCsv = (value) => {
if (value === null || value === undefined) return '';
const str = String(value);
if (/[",\n]/.test(str)) return `"${str.replace(/"/g, '""')}"`;
return str;
};
const csvRows = [...allEntries]
.sort((a, b) => b.date.getTime() - a.date.getTime())
.map(entry => [
entry.date.toISOString().split('T')[0],
entry.title,
entry.year || '',
entry.rating ?? '',
entry.rewatch ? '1' : '0',
entry.liked ? '1' : '0',
entry.reviewed ? '1' : '0',
entry.url || '',
entry.reviewUrl || '',
entry.slug || '',
entry.filmUid || '',
entry.lid || ''
].map(escapeCsv).join(','));
fs.writeFileSync(csvPath, [csvHeader.join(','), ...csvRows].join('\n') + '\n');
console.log(` ✓ ${outputPathDark}`);
console.log(` ✓ ${outputPathLight}`);
console.log(` ✓ ${outputJsonPath}`);
console.log(` ✓ ${csvPath}`);
// Review cards. A period is a year or a single month within one; the card
// is the same either way, so both come out of the same loop.
console.log("\n🃏 Generating review cards...");
const reviewCards = [];
const sortedYears = [...reviewYears].sort((a, b) => b - a);
// Years are named after themselves. Months are named by how recent they
// are, not by their date: a dated file would break every embed at the turn
// of the month, and nothing would ever delete the old ones.
const periods = sortedYears.map(year => ({ year, slug: String(year) }));
const now = new Date();
for (let back = 0; back < monthCards; back++) {
const cursor = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - back, 1));
const slug = back === 0 ? 'current-month' : back === 1 ? 'previous-month' : `month-minus-${back}`;
periods.push({ year: cursor.getUTCFullYear(), month: cursor.getUTCMonth() + 1, slug });
}
// Posters are only needed for the films that actually make a card, so they
// are resolved once here rather than per theme. A missing poster is not an
// error: the card falls back to a plain placeholder.
const posters = new Map();
const favouritePosters = new Map();
const details = new Map();
const filmCache = loadFilmCache(dir);
let cacheHits = 0;
let cacheMisses = 0;
// One request per film covers the poster, the runtime and the community
// rating, so details are cached across the year and profile cards. The
// persistent cache avoids re-fetching the same 30 films every daily run.
const loadFilm = async (films, target, width, height) => {
for (const film of films) {
if (!film.url || target.has(film.url)) continue;
let detail = details.get(film.url);
if (!detail) {
const cached = getCachedDetail(filmCache, film.url);
if (cached) {
detail = cached;
cacheHits++;
} else {
detail = await fetchFilmDetails(film.url);
setCachedDetail(filmCache, film.url, detail);
cacheMisses++;
}
details.set(film.url, detail);
}
if (!detail.poster) continue;
try {
const response = await fetch(detail.poster);
if (!response.ok) continue;
const thumbnail = await imageBufferToThumbnail(
Buffer.from(await response.arrayBuffer()),
width,
height
);
if (thumbnail) target.set(film.url, thumbnail);
} catch (error) {
console.warn(` Could not load poster for ${film.title}: ${error.message}`);
}
}
};
// Mirrors the card: the release filter is for year cards only.
const listFor = (period) => {
const inPeriod = entriesForPeriod(allEntries, period);
return topFilms === 'released' && period.month == null
? inPeriod.filter(entry => String(entry.year) === String(period.year))
: inPeriod;
};
const cardFilms = [
...periods.flatMap(period => pickTopFilms(listFor(period))),
...pickTopFilms(allEntries, 3)
];
await loadFilm(cardFilms, posters, POSTER_PIXEL_WIDTH, POSTER_PIXEL_HEIGHT);
await loadFilm(favourites, favouritePosters, FAV_PIXEL_WIDTH, FAV_PIXEL_HEIGHT);
saveFilmCache(dir, filmCache);
console.log(` Posters: ${posters.size}/${new Set(cardFilms.map(f => f.url)).size}`
+ `, favourites ${favouritePosters.size}/${favourites.length}`
+ `, cache ${cacheHits} hit / ${cacheMisses} miss`);
for (const period of periods) {
for (const theme of ['dark', 'light']) {
const cardPath = path.join(dir, `letterboxd-review-${period.slug}-${theme}.svg`);
const card = await generateReviewCard(allEntries, {
...svgOptions,
year: period.year,
month: period.month ?? null,
theme,
posters,
details
});
fs.writeFileSync(cardPath, card);
reviewCards.push({ path: cardPath, svg: card });
console.log(` ✓ ${cardPath}`);
}
}
// Anything matching the card naming scheme that this run did not write is
// left over from an earlier configuration: dated month files, or a year
// that has since been dropped from -y. Nothing else in the directory is
// touched.
const written = new Set(reviewCards.map(card => path.basename(card.path)));
for (const name of fs.readdirSync(dir)) {
if (!/^letterboxd-review-.+\.(svg|png)$/.test(name)) continue;
if (written.has(name) || written.has(name.replace(/\.png$/, '.svg'))) continue;
fs.unlinkSync(path.join(dir, name));
console.log(` ✗ removed stale ${name}`);
}
// Profile card, not tied to a single year
const profileCardPaths = ['dark', 'light'].map(theme =>
path.join(dir, `letterboxd-profile-${theme}.svg`));
for (const [index, theme] of ['dark', 'light'].entries()) {
const card = await generateProfileCard(allEntries, {
...svgOptions,
theme,
years: scope === 'all'
? [...new Set(allEntries.map(entry => entry.date.getUTCFullYear()))].sort((a, b) => a - b)
: years,
allTime: scope === 'all',
totalEntries,
favourites,
posters,
favouritePosters,
details
});
fs.writeFileSync(profileCardPaths[index], card);
reviewCards.push({ path: profileCardPaths[index], svg: card });
console.log(` ✓ ${profileCardPaths[index]}`);
}
// Badges — shields-style, one SVG per stat (no dark/light split)
console.log("\n🏷️ Generating badges...");
const allTimeForBadges = buildAllTimeStats(allEntries, { totalFilms: totalEntries, scope });
const wanted = badgeStats.split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
const badges = buildBadges(allTimeForBadges || { entries: allEntries.length, daysActive: 0, streak: { length: 0 }, averageRating: null, liked: 0, rewatches: 0 }, { style: badgeStyle, stats: wanted });
for (const badge of badges) {
const badgePath = path.join(dir, `${badge.slug}.svg`);
fs.writeFileSync(badgePath, badge.svg);
console.log(` ✓ ${badgePath} (${badge.label}: ${badge.value})`);
}
// Stale badges from a previous stat list are removed like review cards
const wantedSlugs = new Set(badges.map(b => `${b.slug}.svg`));
for (const name of fs.readdirSync(dir)) {
if (!/^badge-.+\.svg$/.test(name)) continue;
if (!wantedSlugs.has(name)) {
fs.unlinkSync(path.join(dir, name));
console.log(` ✗ removed stale ${name}`);
}
}
// Export PNGs if requested
if (exportPng) {
console.log("\n📸 Exporting PNG files...");
const pngPathDark = outputPathDark.replace('.svg', '.png');
const pngPathLight = outputPathLight.replace('.svg', '.png');
// Calculate scale - for multi-year we might want distinct scaling?
// Default scale 2 is fine
await svgToPng(svgDark, pngPathDark);
await svgToPng(svgLight, pngPathLight);
for (const card of reviewCards) {
await svgToPng(card.svg, card.path.replace('.svg', '.png'));
}
}
// Close the browser instance
await closeBrowser();
console.log(`\n✅ Done!\n`);
} catch (error) {
console.error("\n❌ Error:", error.message);
console.error(error.stack);
process.exit(1);
}
}
main();