@aronnaxlin/bgm-cli 1.0.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.
Files changed (46) hide show
  1. package/LICENSE +660 -0
  2. package/README.en.md +122 -0
  3. package/README.md +127 -0
  4. package/README.zh-TW.md +122 -0
  5. package/package.json +41 -0
  6. package/src/cli.js +993 -0
  7. package/src/commands/blog.js +213 -0
  8. package/src/commands/calendar.js +32 -0
  9. package/src/commands/character.js +291 -0
  10. package/src/commands/collection.js +418 -0
  11. package/src/commands/episode.js +379 -0
  12. package/src/commands/group.js +488 -0
  13. package/src/commands/index.js +362 -0
  14. package/src/commands/notify.js +74 -0
  15. package/src/commands/person.js +297 -0
  16. package/src/commands/status.js +74 -0
  17. package/src/commands/subject.js +537 -0
  18. package/src/commands/timeline.js +288 -0
  19. package/src/commands/trending.js +58 -0
  20. package/src/commands/tui.js +1537 -0
  21. package/src/commands/user.js +83 -0
  22. package/src/core/client.js +2065 -0
  23. package/src/core/config.js +450 -0
  24. package/src/core/http.js +144 -0
  25. package/src/core/output.js +3888 -0
  26. package/src/core/proxy.js +47 -0
  27. package/src/core/reactions.js +62 -0
  28. package/src/core/turnstile.js +526 -0
  29. package/src/data/bangumi-emotes.json +311 -0
  30. package/src/utils/args.js +113 -0
  31. package/src/utils/auth-flow.js +373 -0
  32. package/src/utils/auth.js +90 -0
  33. package/src/utils/calendar.js +23 -0
  34. package/src/utils/collection-ops.js +333 -0
  35. package/src/utils/collection.js +240 -0
  36. package/src/utils/formatters.js +157 -0
  37. package/src/utils/helpers.js +283 -0
  38. package/src/utils/hot.js +182 -0
  39. package/src/utils/install.js +40 -0
  40. package/src/utils/prompts.js +87 -0
  41. package/src/utils/relay.js +74 -0
  42. package/src/utils/status.js +68 -0
  43. package/src/utils/tui-interactive.js +197 -0
  44. package/src/utils/tui-render.js +86 -0
  45. package/src/utils/turnstile-flow.js +154 -0
  46. package/src/utils/validators.js +412 -0
@@ -0,0 +1,333 @@
1
+ /**
2
+ * Collection and episode mutation helpers.
3
+ */
4
+
5
+ import readline from "node:readline/promises";
6
+ import { BangumiClient } from "../core/client.js";
7
+ import { getConfig } from "../core/config.js";
8
+ import { BangumiApiError as ApiError } from "../core/http.js";
9
+ import { CommandError } from "../core/output.js";
10
+ import { askRequired } from "./prompts.js";
11
+ import { formatSubjectMenuLabel } from "./formatters.js";
12
+ import { delayMs, normalizeNonNegativeInteger, normalizeRateValue, parseOptionalBoolean, parseOptionalInteger } from "./helpers.js";
13
+ import { firstPositional, splitFilterValues } from "./args.js";
14
+ import { COLLECTION_STATUS_MAP, normalizeCollectionStatusValue } from "./validators.js";
15
+
16
+ export function buildCollectionActionResult({ action, actionLabel, subjectId, subject, collection }) {
17
+ return {
18
+ action,
19
+ actionLabel,
20
+ subjectId: Number(subjectId),
21
+ subjectName: subject?.name_cn || subject?.name,
22
+ subject,
23
+ collection,
24
+ };
25
+ }
26
+
27
+ export function buildEpisodeActionResult({ action, actionLabel, subjectId, episodeId, episode, collection, requestedType }) {
28
+ const resolvedEpisode = collection?.episode ?? episode ?? null;
29
+ return {
30
+ resource: "episode-mutation",
31
+ action,
32
+ actionLabel,
33
+ subjectId: subjectId !== undefined ? Number(subjectId) : (resolvedEpisode?.subject_id ?? null),
34
+ episodeId: Number(episodeId ?? resolvedEpisode?.id),
35
+ episode: resolvedEpisode,
36
+ collection,
37
+ status: requestedType,
38
+ };
39
+ }
40
+
41
+ export async function fetchMySubjectCollection(client, subjectId) {
42
+ const me = await client.getMe();
43
+ return client.getUserCollection(me.username, subjectId);
44
+ }
45
+
46
+ export async function fetchMyEpisodeCollection(client, episodeId) {
47
+ return client.getMyEpisodeCollection(episodeId);
48
+ }
49
+
50
+ export async function fetchMySubjectCollectionVerified(client, subjectId, { expected, actionLabel, mismatchMessage }) {
51
+ let latest = null;
52
+
53
+ for (let attempt = 0; attempt < 3; attempt += 1) {
54
+ latest = await fetchMySubjectCollection(client, subjectId);
55
+ if (collectionMatchesExpected(latest, expected)) {
56
+ return latest;
57
+ }
58
+ if (attempt < 2) {
59
+ await delayMs(350);
60
+ }
61
+ }
62
+
63
+ throw new CommandError(
64
+ typeof mismatchMessage === "function"
65
+ ? mismatchMessage(latest)
66
+ : `${actionLabel} did not persist on Bangumi.`,
67
+ );
68
+ }
69
+
70
+ export function collectionMatchesExpected(collection, expected = {}) {
71
+ return Object.entries(expected).every(([key, value]) => collection?.[key] === value);
72
+ }
73
+
74
+ export async function fetchMyEpisodeCollectionVerified(client, episodeId, { expected, actionLabel, mismatchMessage }) {
75
+ let latest = null;
76
+
77
+ for (let attempt = 0; attempt < 5; attempt += 1) {
78
+ try {
79
+ latest = await fetchMyEpisodeCollection(client, episodeId);
80
+ } catch (error) {
81
+ if (error instanceof ApiError && error.status === 404 && expected?.type === 0) {
82
+ return null;
83
+ }
84
+ throw error;
85
+ }
86
+
87
+ if (episodeCollectionMatchesExpected(latest, expected)) {
88
+ return latest;
89
+ }
90
+ if (attempt < 4) {
91
+ await delayMs(400 + attempt * 350);
92
+ }
93
+ }
94
+
95
+ throw new CommandError(
96
+ typeof mismatchMessage === "function"
97
+ ? mismatchMessage(latest)
98
+ : `${actionLabel} did not persist on Bangumi.`,
99
+ );
100
+ }
101
+
102
+ export function episodeCollectionMatchesExpected(collection, expected = {}) {
103
+ return Object.entries(expected).every(([key, value]) => {
104
+ if (key === "type" && value === 0) {
105
+ return collection === null || collection?.type === 0;
106
+ }
107
+ return collection?.[key] === value;
108
+ });
109
+ }
110
+
111
+ export function formatCollectionStatusForError(type) {
112
+ const labels = {
113
+ 1: "wish",
114
+ 2: "collect",
115
+ 3: "doing",
116
+ 4: "on_hold",
117
+ 5: "dropped",
118
+ };
119
+ return labels[type] ?? String(type ?? "-");
120
+ }
121
+
122
+ export function formatEpisodeCollectionStatusForError(type) {
123
+ const labels = {
124
+ 0: "remove",
125
+ 1: "queue",
126
+ 2: "watched",
127
+ 3: "drop",
128
+ };
129
+ return labels[type] ?? String(type ?? "-");
130
+ }
131
+
132
+ export function mapEpisodeMutationError(error, { action, episodeId, subjectId }) {
133
+ if (!(error instanceof ApiError)) {
134
+ return error;
135
+ }
136
+
137
+ const description = String(error.message ?? "").toLowerCase();
138
+
139
+ if (error.status === 400 && description.includes("need to add subject to your collection first")) {
140
+ return new CommandError(
141
+ `Failed to ${action}. Bangumi requires the parent subject to be in your collection before episode progress can be changed. Add subject #${subjectId ?? "-"} to your collection first, then retry.`,
142
+ );
143
+ }
144
+
145
+ if (error.status === 400 && description.includes("episode id not valid")) {
146
+ return new CommandError(`Failed to ${action}. Episode #${episodeId} is invalid or does not belong to a writable collected subject.`);
147
+ }
148
+
149
+ if (error.status === 401) {
150
+ return new CommandError(`Failed to ${action}. Save a valid Bangumi access token first with \`bgm auth set-token\`.`);
151
+ }
152
+
153
+ if (error.status === 403) {
154
+ return new CommandError(
155
+ `Failed to ${action}. Your Bangumi account is authenticated but does not currently have permission for this episode or subject. This can happen with NSFW/R18 content or account-level access restrictions.`,
156
+ );
157
+ }
158
+
159
+ if (error.status === 404) {
160
+ return new CommandError(
161
+ `Failed to ${action}. Episode #${episodeId} or its parent subject was not found, or Bangumi denied access to the subject. For NSFW/R18 content, make sure you are authenticated and your account is eligible to view it.`,
162
+ );
163
+ }
164
+
165
+ return error;
166
+ }
167
+
168
+ export function buildSubjectSearchArgs(keyword, options) {
169
+ const args = [String(keyword)];
170
+
171
+ if (options.type) {
172
+ args.push("--type", String(options.type));
173
+ }
174
+ if (options.sort) {
175
+ args.push("--sort", String(options.sort));
176
+ }
177
+ if (options.limit) {
178
+ args.push("--limit", String(options.limit));
179
+ } else {
180
+ args.push("--limit", "10");
181
+ }
182
+
183
+ return args;
184
+ }
185
+
186
+ export function buildCollectionMutationPayload(options, { defaultStatus } = {}) {
187
+ const payload = {};
188
+
189
+ if (defaultStatus !== undefined) {
190
+ payload.type = defaultStatus;
191
+ } else if (options.status !== undefined) {
192
+ payload.type = normalizeCollectionStatusValue(options.status);
193
+ }
194
+ if (options.rate !== undefined) {
195
+ payload.rate = normalizeRateValue(options.rate);
196
+ }
197
+ if (options.comment !== undefined) {
198
+ payload.comment = String(options.comment);
199
+ }
200
+ if (options.private !== undefined) {
201
+ payload.private = parseOptionalBoolean(options.private);
202
+ }
203
+ if (options.epStatus !== undefined) {
204
+ payload.ep_status = normalizeNonNegativeInteger(options.epStatus, "ep-status");
205
+ }
206
+ if (options.volStatus !== undefined) {
207
+ payload.vol_status = normalizeNonNegativeInteger(options.volStatus, "vol-status");
208
+ }
209
+ if (options.tags !== undefined) {
210
+ payload.tags = splitFilterValues(options.tags);
211
+ }
212
+
213
+ return payload;
214
+ }
215
+
216
+ export function buildCollectionTargetArgs(target) {
217
+ if (target?.mode === "id" && target.subjectId) {
218
+ return [String(target.subjectId)];
219
+ }
220
+ return [];
221
+ }
222
+
223
+ export async function resolveCollectionTarget(options, { client, usage, searchSubjects }) {
224
+ const explicitSubjectId = options.subjectId ?? firstPositional(options);
225
+
226
+ if (options.search) {
227
+ return selectSubjectFromSearch(options.search, options, { searchSubjects });
228
+ }
229
+
230
+ if (!explicitSubjectId) {
231
+ throw new CommandError(usage);
232
+ }
233
+
234
+ const subject = await client.getSubject(explicitSubjectId);
235
+ return {
236
+ subjectId: subject.id ?? Number(explicitSubjectId),
237
+ subject,
238
+ };
239
+ }
240
+
241
+ export async function selectSubjectFromSearch(keyword, options, { searchSubjects }) {
242
+ const result = await searchSubjects(buildSubjectSearchArgs(keyword, options));
243
+ const subjects = Array.isArray(result?.data) ? result.data : [];
244
+
245
+ if (subjects.length === 0) {
246
+ throw new CommandError(`No subject matched search keyword: ${keyword}`);
247
+ }
248
+
249
+ const pickedIndex = parseOptionalInteger(options.pick);
250
+ if (pickedIndex !== undefined) {
251
+ const subject = subjects[pickedIndex - 1];
252
+ if (!subject) {
253
+ throw new CommandError(`Search pick index out of range: ${pickedIndex}`);
254
+ }
255
+ return {
256
+ subjectId: subject.id,
257
+ subject,
258
+ };
259
+ }
260
+
261
+ if (subjects.length === 1) {
262
+ return {
263
+ subjectId: subjects[0].id,
264
+ subject: subjects[0],
265
+ };
266
+ }
267
+
268
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
269
+ throw new CommandError(
270
+ "Search returned multiple subjects. Re-run with --pick <n> or pass a subject ID directly.",
271
+ );
272
+ }
273
+
274
+ const rl = readline.createInterface({
275
+ input: process.stdin,
276
+ output: process.stdout,
277
+ });
278
+
279
+ try {
280
+ console.log("Search results");
281
+ subjects.forEach((subject, index) => {
282
+ console.log(` ${index + 1}. ${formatSubjectMenuLabel(subject)}`);
283
+ });
284
+ const selected = await askRequired(rl, "Choose target subject number");
285
+ const index = Number.parseInt(String(selected), 10);
286
+ if (Number.isNaN(index) || index < 1 || index > subjects.length) {
287
+ throw new CommandError(`Invalid number: ${selected}`);
288
+ }
289
+ return {
290
+ subjectId: subjects[index - 1].id,
291
+ subject: subjects[index - 1],
292
+ };
293
+ } finally {
294
+ rl.close();
295
+ }
296
+ }
297
+
298
+ export function getCollectionStatusKey(type) {
299
+ const map = {
300
+ [COLLECTION_STATUS_MAP.wish]: "wish",
301
+ [COLLECTION_STATUS_MAP.collect]: "collect",
302
+ [COLLECTION_STATUS_MAP.doing]: "doing",
303
+ [COLLECTION_STATUS_MAP.on_hold]: "on_hold",
304
+ [COLLECTION_STATUS_MAP.dropped]: "dropped",
305
+ };
306
+ return map[type];
307
+ }
308
+
309
+ export function handleEpisodeListError(error, subjectId) {
310
+ if (error instanceof ApiError && [401, 403, 404].includes(error.status)) {
311
+ const hasToken = Boolean(getConfig().accessToken);
312
+ const suggestion = hasToken
313
+ ? "If this subject is NSFW/R18, your Bangumi account may still lack permission to view it, for example because the account is too new or not eligible yet."
314
+ : "If this subject is NSFW/R18, save an access token first. Bangumi may return a misleading 404 when the request is unauthenticated.";
315
+ throw new CommandError(
316
+ `Failed to list episodes for subject ${subjectId}. ${suggestion} Original API response: ${error.message}`,
317
+ );
318
+ }
319
+
320
+ throw error;
321
+ }
322
+
323
+ export async function fetchTuiCollectionSnapshot(subjectId) {
324
+ const client = new BangumiClient(getConfig());
325
+ try {
326
+ return await fetchMySubjectCollection(client, subjectId);
327
+ } catch (error) {
328
+ if (error instanceof ApiError && error.status === 404) {
329
+ return null;
330
+ }
331
+ throw error;
332
+ }
333
+ }
@@ -0,0 +1,240 @@
1
+ /**
2
+ * Collection/subject/episode fetching and sorting utilities.
3
+ */
4
+
5
+ import { compareStrings } from "./helpers.js";
6
+
7
+ export async function fetchAllCollections(client, username, { query = {} } = {}) {
8
+ const pageSize = 100;
9
+
10
+ const first = await client.listCollections(username, {
11
+ limit: pageSize,
12
+ offset: 0,
13
+ ...query,
14
+ });
15
+
16
+ const firstData = Array.isArray(first.data) ? first.data : [];
17
+
18
+ // Only trust API total when it is a finite positive number.
19
+ // Fallback to sequential pagination otherwise to avoid truncating results.
20
+ const hasReliableTotal = Number.isFinite(first.total) && first.total > 0;
21
+ const total = hasReliableTotal ? first.total : firstData.length;
22
+
23
+ if (firstData.length === 0 || (hasReliableTotal && firstData.length >= total)) {
24
+ return {
25
+ data: firstData,
26
+ total,
27
+ limit: pageSize,
28
+ offset: 0,
29
+ };
30
+ }
31
+
32
+ if (!hasReliableTotal) {
33
+ // Sequential fallback: paginate until an empty or partial page signals the end.
34
+ const all = [...firstData];
35
+ let currentOffset = firstData.length;
36
+ while (true) {
37
+ const page = await client.listCollections(username, {
38
+ limit: pageSize,
39
+ offset: currentOffset,
40
+ ...query,
41
+ });
42
+ const pageData = Array.isArray(page.data) ? page.data : [];
43
+ if (pageData.length === 0) break;
44
+ all.push(...pageData);
45
+ currentOffset += pageData.length;
46
+ if (pageData.length < pageSize) break;
47
+ }
48
+ return {
49
+ data: all,
50
+ total: all.length,
51
+ limit: pageSize,
52
+ offset: 0,
53
+ };
54
+ }
55
+
56
+ // Parallel path with bounded concurrency to avoid rate limiting.
57
+ const CONCURRENCY = 8;
58
+ const offsets = [];
59
+ for (let off = firstData.length; off < total; off += pageSize) {
60
+ offsets.push(off);
61
+ }
62
+
63
+ const all = [...firstData];
64
+ for (let i = 0; i < offsets.length; i += CONCURRENCY) {
65
+ const batch = offsets.slice(i, i + CONCURRENCY);
66
+ const pages = await Promise.all(
67
+ batch.map((off) =>
68
+ client.listCollections(username, { limit: pageSize, offset: off, ...query })
69
+ )
70
+ );
71
+ for (const page of pages) {
72
+ const data = Array.isArray(page.data) ? page.data : [];
73
+ all.push(...data);
74
+ }
75
+ }
76
+
77
+ return {
78
+ data: all,
79
+ total: total || all.length,
80
+ limit: pageSize,
81
+ offset: 0,
82
+ };
83
+ }
84
+
85
+ export async function fetchAllSubjects(client, query) {
86
+ const pageSize = 100;
87
+ const requestedLimit = query.limit ?? pageSize;
88
+ const startOffset = query.offset ?? 0;
89
+
90
+ const first = await client.listSubjects({
91
+ ...query,
92
+ limit: pageSize,
93
+ offset: startOffset,
94
+ });
95
+
96
+ const firstData = Array.isArray(first.data) ? first.data : [];
97
+ const total = first.total ?? firstData.length;
98
+
99
+ const needed = Math.min(requestedLimit, total - startOffset);
100
+ if (firstData.length === 0 || firstData.length >= needed) {
101
+ return {
102
+ data: firstData.slice(0, needed),
103
+ total,
104
+ limit: requestedLimit,
105
+ offset: startOffset,
106
+ };
107
+ }
108
+
109
+ // Parallel path with bounded concurrency to avoid rate limiting.
110
+ const CONCURRENCY = 8;
111
+ const offsets = [];
112
+ for (let off = startOffset + firstData.length; off < startOffset + needed; off += pageSize) {
113
+ offsets.push(off);
114
+ }
115
+
116
+ const all = [...firstData];
117
+ for (let i = 0; i < offsets.length; i += CONCURRENCY) {
118
+ const batch = offsets.slice(i, i + CONCURRENCY);
119
+ const pages = await Promise.all(
120
+ batch.map((off) =>
121
+ client.listSubjects({
122
+ ...query,
123
+ limit: pageSize,
124
+ offset: off,
125
+ })
126
+ )
127
+ );
128
+ for (const page of pages) {
129
+ const data = Array.isArray(page.data) ? page.data : [];
130
+ all.push(...data);
131
+ if (all.length >= needed) break;
132
+ }
133
+ if (all.length >= needed) break;
134
+ }
135
+
136
+ return {
137
+ data: all.slice(0, needed),
138
+ total,
139
+ limit: requestedLimit,
140
+ offset: startOffset,
141
+ };
142
+ }
143
+
144
+ export function sortCollections(items, sort, order) {
145
+ const factor = order === "asc" ? 1 : -1;
146
+ const list = [...items];
147
+
148
+ list.sort((left, right) => {
149
+ const leftValue = getCollectionSortValue(left, sort);
150
+ const rightValue = getCollectionSortValue(right, sort);
151
+
152
+ if (leftValue < rightValue) {
153
+ return -1 * factor;
154
+ }
155
+ if (leftValue > rightValue) {
156
+ return 1 * factor;
157
+ }
158
+
159
+ return compareStrings(
160
+ left?.subject?.name_cn || left?.subject?.name || "",
161
+ right?.subject?.name_cn || right?.subject?.name || "",
162
+ ) * factor;
163
+ });
164
+
165
+ return list;
166
+ }
167
+
168
+ export function sortSubjectsByRank(subjects) {
169
+ return [...subjects].sort((left, right) => {
170
+ const leftRank = Number(left?.rating?.rank ?? left?.rank ?? Number.MAX_SAFE_INTEGER);
171
+ const rightRank = Number(right?.rating?.rank ?? right?.rank ?? Number.MAX_SAFE_INTEGER);
172
+
173
+ if (leftRank !== rightRank) {
174
+ return leftRank - rightRank;
175
+ }
176
+
177
+ const leftScore = Number(left?.rating?.score ?? -1);
178
+ const rightScore = Number(right?.rating?.score ?? -1);
179
+ if (leftScore !== rightScore) {
180
+ return rightScore - leftScore;
181
+ }
182
+
183
+ const leftName = String(left?.name_cn || left?.name || "");
184
+ const rightName = String(right?.name_cn || right?.name || "");
185
+ return leftName.localeCompare(rightName, "zh-Hans-CN");
186
+ });
187
+ }
188
+
189
+ export function getCollectionSortValue(item, sort) {
190
+ switch (sort) {
191
+ case "name":
192
+ return String(item?.subject?.name_cn || item?.subject?.name || "").toLowerCase();
193
+ case "rank":
194
+ return Number(item?.subject?.rank || Number.MAX_SAFE_INTEGER);
195
+ case "community_score":
196
+ return Number(item?.subject?.score || -1);
197
+ case "user_score":
198
+ return Number(item?.rate || -1);
199
+ case "date":
200
+ return String(item?.subject?.date || "");
201
+ case "updated":
202
+ default:
203
+ return String(item?.updated_at || "");
204
+ }
205
+ }
206
+
207
+ export async function fetchAllEpisodes(client, subjectId, query = {}) {
208
+ const pageSize = 200;
209
+ const first = await client.listEpisodes({
210
+ ...query,
211
+ subject_id: subjectId,
212
+ limit: pageSize,
213
+ offset: 0,
214
+ });
215
+
216
+ const firstData = Array.isArray(first.data) ? first.data : [];
217
+ const total = first.total ?? firstData.length;
218
+ if (firstData.length === 0 || firstData.length >= total) {
219
+ return firstData;
220
+ }
221
+
222
+ const remaining = [];
223
+ for (let offset = firstData.length; offset < total; offset += pageSize) {
224
+ remaining.push(
225
+ client.listEpisodes({
226
+ ...query,
227
+ subject_id: subjectId,
228
+ limit: pageSize,
229
+ offset,
230
+ })
231
+ );
232
+ }
233
+
234
+ const pages = await Promise.all(remaining);
235
+ const all = [...firstData];
236
+ for (const page of pages) {
237
+ all.push(...(Array.isArray(page.data) ? page.data : []));
238
+ }
239
+ return all;
240
+ }