@irfanshadikrishad/anilist 1.0.0 → 1.0.1-forbidden.2

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.
@@ -7,372 +7,1102 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import fetch from "node-fetch";
10
+ import { XMLParser } from "fast-xml-parser";
11
+ import { readFile, writeFile } from "fs/promises";
11
12
  import inquirer from "inquirer";
12
- import { aniListEndpoint, getTitle } from "./workers.js";
13
- import { deleteMangaEntryMutation, deleteMediaEntryMutation, popularQuery, trendingQuery, } from "./queries.js";
14
- import { currentUserAnimeList, currentUserMangaList } from "./queries.js";
15
- import { isLoggedIn, currentUsersId, retriveAccessToken } from "./auth.js";
16
- function getTrending(count) {
17
- return __awaiter(this, void 0, void 0, function* () {
18
- var _a, _b, _c;
19
- try {
20
- const request = yield fetch(aniListEndpoint, {
21
- method: "POST",
22
- headers: {
23
- "content-type": "application/json",
13
+ import { jsonrepair } from "jsonrepair";
14
+ import open from "open";
15
+ import { join } from "path";
16
+ import { Auth } from "./auth.js";
17
+ import { fetcher } from "./fetcher.js";
18
+ import { addAnimeToListMutation, addMangaToListMutation, saveAnimeWithProgressMutation, saveMangaWithProgressMutation, } from "./mutations.js";
19
+ import { animeDetailsQuery, animeSearchQuery, currentUserAnimeList, currentUserMangaList, malIdToAnilistAnimeId, malIdToAnilistMangaId, mangaSearchQuery, popularQuery, trendingQuery, upcomingAnimesQuery, userActivityQuery, userFollowersQuery, userFollowingQuery, userQuery, } from "./queries.js";
20
+ import { AniListMediaStatus, } from "./types.js";
21
+ import { anidbToanilistMapper, createAnimeListXML, createMangaListXML, formatDateObject, getDownloadFolderPath, getFormattedDate, getNextSeasonAndYear, getTitle, removeHtmlAndMarkdown, saveJSONasCSV, saveJSONasJSON, selectFile, timestampToTimeAgo, } from "./workers.js";
22
+ class AniList {
23
+ static importAnime() {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ try {
26
+ const filename = yield selectFile(".json");
27
+ const filePath = join(getDownloadFolderPath(), filename);
28
+ const fileContent = yield readFile(filePath, "utf8");
29
+ const importedData = JSON.parse(fileContent);
30
+ let count = 0;
31
+ const batchSize = 1; // Number of requests in each batch
32
+ const delay = 1100; // delay to avoid rate-limiting
33
+ for (let i = 0; i < importedData.length; i += batchSize) {
34
+ const batch = importedData.slice(i, i + batchSize);
35
+ yield Promise.all(batch.map((anime) => __awaiter(this, void 0, void 0, function* () {
36
+ var _a, _b;
37
+ const query = saveAnimeWithProgressMutation;
38
+ const variables = {
39
+ mediaId: anime === null || anime === void 0 ? void 0 : anime.id,
40
+ progress: anime === null || anime === void 0 ? void 0 : anime.progress,
41
+ status: anime === null || anime === void 0 ? void 0 : anime.status,
42
+ hiddenFromStatusLists: false,
43
+ };
44
+ try {
45
+ const save = yield fetcher(query, variables);
46
+ if (save) {
47
+ const id = (_b = (_a = save === null || save === void 0 ? void 0 : save.data) === null || _a === void 0 ? void 0 : _a.SaveMediaListEntry) === null || _b === void 0 ? void 0 : _b.id;
48
+ count++;
49
+ console.log(`[${count}]\t${id}\t${anime === null || anime === void 0 ? void 0 : anime.id} ✅`);
50
+ }
51
+ else {
52
+ console.error(`\nError saving ${anime === null || anime === void 0 ? void 0 : anime.id}`);
53
+ }
54
+ }
55
+ catch (error) {
56
+ console.error(`\nError saving ${anime === null || anime === void 0 ? void 0 : anime.id}: ${error.message}`);
57
+ }
58
+ })));
59
+ // Avoid rate-limiting: Wait before sending the next batch
60
+ yield new Promise((resolve) => setTimeout(resolve, delay));
61
+ }
62
+ console.log(`\nTotal ${count} anime(s) imported successfully.`);
63
+ }
64
+ catch (error) {
65
+ console.error(`\n${error.message}`);
66
+ }
67
+ });
68
+ }
69
+ static importManga() {
70
+ return __awaiter(this, void 0, void 0, function* () {
71
+ try {
72
+ const filename = yield selectFile(".json");
73
+ const filePath = join(getDownloadFolderPath(), filename);
74
+ const fileContent = yield readFile(filePath, "utf8");
75
+ const importedData = JSON.parse(fileContent);
76
+ let count = 0;
77
+ const batchSize = 1; // Adjust batch size as per rate-limit constraints
78
+ const delay = 1100; // 2 seconds delay to avoid rate-limit
79
+ // Process in batches
80
+ for (let i = 0; i < importedData.length; i += batchSize) {
81
+ const batch = importedData.slice(i, i + batchSize);
82
+ yield Promise.all(batch.map((manga) => __awaiter(this, void 0, void 0, function* () {
83
+ var _a, _b;
84
+ const query = saveMangaWithProgressMutation;
85
+ const variables = {
86
+ mediaId: manga === null || manga === void 0 ? void 0 : manga.id,
87
+ progress: manga === null || manga === void 0 ? void 0 : manga.progress,
88
+ status: manga === null || manga === void 0 ? void 0 : manga.status,
89
+ hiddenFromStatusLists: false,
90
+ private: manga === null || manga === void 0 ? void 0 : manga.private,
91
+ };
92
+ try {
93
+ const save = yield fetcher(query, variables);
94
+ if (save) {
95
+ const id = (_b = (_a = save === null || save === void 0 ? void 0 : save.data) === null || _a === void 0 ? void 0 : _a.SaveMediaListEntry) === null || _b === void 0 ? void 0 : _b.id;
96
+ count++;
97
+ console.log(`[${count}]\t${id}\t${manga === null || manga === void 0 ? void 0 : manga.id} ✅`);
98
+ }
99
+ }
100
+ catch (err) {
101
+ console.error(`\nError saving ${manga === null || manga === void 0 ? void 0 : manga.id}: ${err.message}`);
102
+ }
103
+ })));
104
+ // Avoid rate-limit by adding delay after processing each batch
105
+ yield new Promise((resolve) => setTimeout(resolve, delay));
106
+ }
107
+ console.log(`\nTotal ${count} manga(s) imported successfully.`);
108
+ }
109
+ catch (error) {
110
+ console.error(`\nError: ${error.message}`);
111
+ }
112
+ });
113
+ }
114
+ static exportAnime() {
115
+ return __awaiter(this, void 0, void 0, function* () {
116
+ var _a, _b, _c;
117
+ if (!(yield Auth.isLoggedIn())) {
118
+ console.error(`\nMust login to use this feature.`);
119
+ return;
120
+ }
121
+ const { exportType } = yield inquirer.prompt([
122
+ {
123
+ type: "list",
124
+ name: "exportType",
125
+ message: "Choose export type:",
126
+ choices: [
127
+ { name: "CSV", value: 1 },
128
+ { name: "JSON", value: 2 },
129
+ { name: "XML (MyAnimeList/AniDB)", value: 3 },
130
+ ],
131
+ pageSize: 10,
24
132
  },
25
- body: JSON.stringify({
26
- query: trendingQuery,
27
- variables: { page: 1, perPage: count },
28
- }),
133
+ ]);
134
+ const animeList = yield fetcher(currentUserAnimeList, {
135
+ id: yield Auth.MyUserId(),
29
136
  });
30
- const response = yield request.json();
31
- if (request.status === 200) {
32
- const media = (_b = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.Page) === null || _b === void 0 ? void 0 : _b.media;
33
- if ((media === null || media === void 0 ? void 0 : media.length) > 0) {
34
- media.map((tr, idx) => {
35
- console.log(`${idx + 1}\t${getTitle(tr === null || tr === void 0 ? void 0 : tr.title)}`);
137
+ if (animeList) {
138
+ const lists = (_c = (_b = (_a = animeList === null || animeList === void 0 ? void 0 : animeList.data) === null || _a === void 0 ? void 0 : _a.MediaListCollection) === null || _b === void 0 ? void 0 : _b.lists) !== null && _c !== void 0 ? _c : [];
139
+ const mediaWithProgress = lists.flatMap((list) => list.entries.map((entry) => {
140
+ var _a, _b, _c, _d, _e;
141
+ return ({
142
+ id: (_a = entry === null || entry === void 0 ? void 0 : entry.media) === null || _a === void 0 ? void 0 : _a.id,
143
+ title: exportType === 1
144
+ ? getTitle((_b = entry === null || entry === void 0 ? void 0 : entry.media) === null || _b === void 0 ? void 0 : _b.title)
145
+ : (_c = entry === null || entry === void 0 ? void 0 : entry.media) === null || _c === void 0 ? void 0 : _c.title,
146
+ episodes: (_d = entry === null || entry === void 0 ? void 0 : entry.media) === null || _d === void 0 ? void 0 : _d.episodes,
147
+ siteUrl: (_e = entry === null || entry === void 0 ? void 0 : entry.media) === null || _e === void 0 ? void 0 : _e.siteUrl,
148
+ progress: entry.progress,
149
+ status: entry === null || entry === void 0 ? void 0 : entry.status,
150
+ hiddenFromStatusLists: entry.hiddenFromStatusLists,
36
151
  });
152
+ }));
153
+ switch (exportType) {
154
+ case 1:
155
+ yield saveJSONasCSV(mediaWithProgress, "anime");
156
+ break;
157
+ case 2:
158
+ yield saveJSONasJSON(mediaWithProgress, "anime");
159
+ break;
160
+ case 3:
161
+ yield MyAnimeList.exportAnime();
162
+ break;
163
+ default:
164
+ console.log(`\nInvalid export type. ${exportType}`);
165
+ break;
37
166
  }
38
167
  }
39
168
  else {
40
- console.log(`Something went wrong. ${(_c = response === null || response === void 0 ? void 0 : response.errors[0]) === null || _c === void 0 ? void 0 : _c.message}`);
169
+ console.error(`\nNo anime(s) found in your lists.`);
41
170
  }
42
- }
43
- catch (error) {
44
- console.log(`Something went wrong. ${error.message}`);
45
- }
46
- });
47
- }
48
- function getPopular(count) {
49
- return __awaiter(this, void 0, void 0, function* () {
50
- var _a, _b, _c;
51
- try {
52
- const request = yield fetch(aniListEndpoint, {
53
- method: "POST",
54
- headers: {
55
- "content-type": "application/json",
56
- },
57
- body: JSON.stringify({
58
- query: popularQuery,
59
- variables: { page: 1, perPage: count },
60
- }),
171
+ });
172
+ }
173
+ static exportManga() {
174
+ return __awaiter(this, void 0, void 0, function* () {
175
+ var _a, _b;
176
+ if (!(yield Auth.isLoggedIn())) {
177
+ console.error(`\nPlease login to use this feature.`);
178
+ return;
179
+ }
180
+ const mangaLists = yield fetcher(currentUserMangaList, {
181
+ id: yield Auth.MyUserId(),
61
182
  });
62
- const response = yield request.json();
63
- if (request.status === 200) {
64
- const media = (_b = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.Page) === null || _b === void 0 ? void 0 : _b.media;
65
- if ((media === null || media === void 0 ? void 0 : media.length) > 0) {
66
- media.map((tr, idx) => {
67
- console.log(`${idx + 1}\t${getTitle(tr === null || tr === void 0 ? void 0 : tr.title)}`);
183
+ if (!(mangaLists === null || mangaLists === void 0 ? void 0 : mangaLists.data)) {
184
+ console.error(`\nCould not get manga list.`);
185
+ return;
186
+ }
187
+ const lists = ((_b = (_a = mangaLists === null || mangaLists === void 0 ? void 0 : mangaLists.data) === null || _a === void 0 ? void 0 : _a.MediaListCollection) === null || _b === void 0 ? void 0 : _b.lists) || [];
188
+ if (lists.length > 0) {
189
+ const { exportType } = yield inquirer.prompt([
190
+ {
191
+ type: "list",
192
+ name: "exportType",
193
+ message: "Choose export type:",
194
+ choices: [
195
+ { name: "CSV", value: 1 },
196
+ { name: "JSON", value: 2 },
197
+ { name: "XML (MyAnimeList)", value: 3 },
198
+ ],
199
+ pageSize: 10,
200
+ },
201
+ ]);
202
+ const mediaWithProgress = lists.flatMap((list) => list.entries.map((entry) => {
203
+ var _a, _b, _c;
204
+ return ({
205
+ id: (_a = entry === null || entry === void 0 ? void 0 : entry.media) === null || _a === void 0 ? void 0 : _a.id,
206
+ title: exportType === 1
207
+ ? getTitle((_b = entry === null || entry === void 0 ? void 0 : entry.media) === null || _b === void 0 ? void 0 : _b.title)
208
+ : (_c = entry === null || entry === void 0 ? void 0 : entry.media) === null || _c === void 0 ? void 0 : _c.title,
209
+ private: entry.private,
210
+ chapters: entry.media.chapters,
211
+ progress: entry.progress,
212
+ status: entry === null || entry === void 0 ? void 0 : entry.status,
213
+ hiddenFromStatusLists: entry.hiddenFromStatusLists,
68
214
  });
215
+ }));
216
+ switch (exportType) {
217
+ case 1:
218
+ yield saveJSONasCSV(mediaWithProgress, "manga");
219
+ break;
220
+ case 2:
221
+ yield saveJSONasJSON(mediaWithProgress, "manga");
222
+ break;
223
+ case 3:
224
+ yield MyAnimeList.exportManga();
225
+ break;
226
+ default:
227
+ console.log(`\nInvalid export type. ${exportType}`);
228
+ break;
69
229
  }
70
230
  }
71
231
  else {
72
- console.log(`Something went wrong. ${(_c = response === null || response === void 0 ? void 0 : response.errors[0]) === null || _c === void 0 ? void 0 : _c.message}`);
232
+ console.log(`\nList seems to be empty.`);
73
233
  }
74
- }
75
- catch (error) {
76
- console.log(`Something went wrong. ${error.message}`);
77
- }
78
- });
79
- }
80
- function loggedInUsersAnimeLists() {
81
- return __awaiter(this, void 0, void 0, function* () {
82
- var _a, _b, _c;
83
- try {
84
- const loggedIn = yield isLoggedIn();
85
- if (loggedIn) {
86
- const userID = yield currentUsersId();
87
- if (userID) {
88
- const request = yield fetch(aniListEndpoint, {
89
- method: "POST",
90
- headers: {
91
- "content-type": "application/json",
92
- Authorization: `Bearer ${yield retriveAccessToken()}`,
93
- },
94
- body: JSON.stringify({
95
- query: currentUserAnimeList,
96
- variables: { id: userID },
234
+ });
235
+ }
236
+ static MyAnime() {
237
+ return __awaiter(this, void 0, void 0, function* () {
238
+ var _a, _b, _c, _d, _e;
239
+ try {
240
+ if (!(yield Auth.isLoggedIn())) {
241
+ return console.error(`\nPlease log in first to access your lists.`);
242
+ }
243
+ if (!(yield Auth.MyUserId())) {
244
+ return console.log(`\nFailed getting current user Id.`);
245
+ }
246
+ const data = yield fetcher(currentUserAnimeList, { id: yield Auth.MyUserId() });
247
+ if (data === null || data === void 0 ? void 0 : data.errors) {
248
+ return console.log(`\nSomething went wrong. ${(_b = (_a = data === null || data === void 0 ? void 0 : data.errors) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.message}`);
249
+ }
250
+ const lists = (_d = (_c = data === null || data === void 0 ? void 0 : data.data) === null || _c === void 0 ? void 0 : _c.MediaListCollection) === null || _d === void 0 ? void 0 : _d.lists;
251
+ if (!lists || lists.length === 0) {
252
+ return console.log(`\nYou seem to have no anime(s) in your lists.`);
253
+ }
254
+ const { selectedList } = yield inquirer.prompt([
255
+ {
256
+ type: "list",
257
+ name: "selectedList",
258
+ message: "Select an anime list:",
259
+ choices: lists.map((list) => list.name),
260
+ },
261
+ ]);
262
+ const selectedEntries = lists.find((list) => list.name === selectedList);
263
+ if (!selectedEntries || !selectedEntries.entries.length) {
264
+ return console.log(`\nNo entries found or not available at this moment.`);
265
+ }
266
+ console.log(`\nEntries for '${selectedEntries.name}':`);
267
+ const { selectedAnime } = yield inquirer.prompt([
268
+ {
269
+ type: "list",
270
+ name: "selectedAnime",
271
+ message: "Select anime to add to the list:",
272
+ choices: selectedEntries.entries.map((entry, idx) => ({
273
+ name: `[${idx + 1}] ${getTitle(entry.media.title)}`,
274
+ value: entry.media.id,
275
+ })),
276
+ pageSize: 10,
277
+ },
278
+ ]);
279
+ const { selectedListType } = yield inquirer.prompt([
280
+ {
281
+ type: "list",
282
+ name: "selectedListType",
283
+ message: "Select the list where you want to save this anime:",
284
+ choices: [
285
+ { name: "Planning", value: "PLANNING" },
286
+ { name: "Watching", value: "CURRENT" },
287
+ { name: "Completed", value: "COMPLETED" },
288
+ { name: "Paused", value: "PAUSED" },
289
+ { name: "Dropped", value: "DROPPED" },
290
+ ],
291
+ },
292
+ ]);
293
+ const saveResponse = yield fetcher(addAnimeToListMutation, {
294
+ mediaId: selectedAnime,
295
+ status: selectedListType,
296
+ });
297
+ if (saveResponse) {
298
+ const savedEntry = (_e = saveResponse.data) === null || _e === void 0 ? void 0 : _e.SaveMediaListEntry;
299
+ console.log(`\nEntry ${savedEntry === null || savedEntry === void 0 ? void 0 : savedEntry.id}. Saved as ${savedEntry === null || savedEntry === void 0 ? void 0 : savedEntry.status}.`);
300
+ }
301
+ else {
302
+ console.error(`\nPlease log in first to use this feature.`);
303
+ }
304
+ }
305
+ catch (error) {
306
+ console.log(`\nSomething went wrong. ${error.message}`);
307
+ }
308
+ });
309
+ }
310
+ static MyManga() {
311
+ return __awaiter(this, void 0, void 0, function* () {
312
+ var _a, _b, _c, _d, _e, _f, _g;
313
+ try {
314
+ if (!(yield Auth.isLoggedIn())) {
315
+ return console.error(`\nPlease log in first to access your lists.`);
316
+ }
317
+ const userId = yield Auth.MyUserId();
318
+ if (!userId) {
319
+ return console.error(`\nFailed to get the current user ID.`);
320
+ }
321
+ const response = yield fetcher(currentUserMangaList, { id: userId });
322
+ if (!(response === null || response === void 0 ? void 0 : response.data)) {
323
+ return console.error(`\nFailed to fetch manga lists. ${((_b = (_a = response === null || response === void 0 ? void 0 : response.errors) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.message) || "Unknown error"}`);
324
+ }
325
+ const lists = (_d = (_c = response === null || response === void 0 ? void 0 : response.data) === null || _c === void 0 ? void 0 : _c.MediaListCollection) === null || _d === void 0 ? void 0 : _d.lists;
326
+ if (!lists || lists.length === 0) {
327
+ return console.log("\nYou don't seem to have any manga in your lists.");
328
+ }
329
+ const { selectedList } = yield inquirer.prompt([
330
+ {
331
+ type: "list",
332
+ name: "selectedList",
333
+ message: "Select a manga list:",
334
+ choices: lists.map((list) => list.name),
335
+ },
336
+ ]);
337
+ const selectedEntries = lists.find((list) => list.name === selectedList);
338
+ if (!selectedEntries || selectedEntries.entries.length === 0) {
339
+ return console.log("\nNo manga entries found in the selected list.");
340
+ }
341
+ console.log(`\nEntries for '${selectedEntries.name}':`);
342
+ const { selectedManga } = yield inquirer.prompt([
343
+ {
344
+ type: "list",
345
+ name: "selectedManga",
346
+ message: "Select a manga to add to the list:",
347
+ choices: selectedEntries.entries.map((entry, idx) => {
348
+ var _a;
349
+ return ({
350
+ name: `[${idx + 1}] ${getTitle(entry.media.title)}`,
351
+ value: (_a = entry === null || entry === void 0 ? void 0 : entry.media) === null || _a === void 0 ? void 0 : _a.id,
352
+ });
97
353
  }),
98
- });
99
- const response = yield request.json();
100
- if (request.status === 200) {
101
- const lists = (_b = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.MediaListCollection) === null || _b === void 0 ? void 0 : _b.lists;
102
- const { selectedList } = yield inquirer.prompt([
354
+ pageSize: 10,
355
+ },
356
+ ]);
357
+ const { selectedListType } = yield inquirer.prompt([
358
+ {
359
+ type: "list",
360
+ name: "selectedListType",
361
+ message: "Select the list where you want to save this manga:",
362
+ choices: [
363
+ { name: "Planning", value: "PLANNING" },
364
+ { name: "Reading", value: "CURRENT" },
365
+ { name: "Completed", value: "COMPLETED" },
366
+ { name: "Paused", value: "PAUSED" },
367
+ { name: "Dropped", value: "DROPPED" },
368
+ ],
369
+ },
370
+ ]);
371
+ const saveResponse = yield fetcher(addMangaToListMutation, {
372
+ mediaId: selectedManga,
373
+ status: selectedListType,
374
+ });
375
+ const saved = (_e = saveResponse === null || saveResponse === void 0 ? void 0 : saveResponse.data) === null || _e === void 0 ? void 0 : _e.SaveMediaListEntry;
376
+ if (saved) {
377
+ console.log(`\nEntry ${saved.id}. Saved as ${saved.status}.`);
378
+ }
379
+ else {
380
+ console.error(`\nFailed to save the manga. ${((_g = (_f = saveResponse === null || saveResponse === void 0 ? void 0 : saveResponse.errors) === null || _f === void 0 ? void 0 : _f[0]) === null || _g === void 0 ? void 0 : _g.message) || "Unknown error"}`);
381
+ }
382
+ }
383
+ catch (error) {
384
+ console.error(`\nSomething went wrong. ${error.message}`);
385
+ }
386
+ });
387
+ }
388
+ static getTrendingAnime(count) {
389
+ return __awaiter(this, void 0, void 0, function* () {
390
+ var _a, _b, _c, _d, _e, _f, _g;
391
+ try {
392
+ let page = 1;
393
+ let allTrending = [];
394
+ while (true) {
395
+ const response = yield fetcher(trendingQuery, { page, perPage: count });
396
+ if (response === null || response === void 0 ? void 0 : response.errors) {
397
+ console.error(`\nSomething went wrong. ${((_b = (_a = response === null || response === void 0 ? void 0 : response.errors) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.message) || "Unknown error"}`);
398
+ return;
399
+ }
400
+ const media = (_d = (_c = response === null || response === void 0 ? void 0 : response.data) === null || _c === void 0 ? void 0 : _c.Page) === null || _d === void 0 ? void 0 : _d.media;
401
+ if (!media || media.length === 0) {
402
+ console.log(`\nNo more trending anime available.`);
403
+ break;
404
+ }
405
+ allTrending = [...allTrending, ...media];
406
+ const choices = allTrending.map((anime, idx) => ({
407
+ name: `[${idx + 1}] ${getTitle(anime === null || anime === void 0 ? void 0 : anime.title)}`,
408
+ value: String(anime === null || anime === void 0 ? void 0 : anime.id),
409
+ }));
410
+ choices.push({ name: "See more", value: "see_more" });
411
+ const { selectedAnime } = yield inquirer.prompt([
412
+ {
413
+ type: "list",
414
+ name: "selectedAnime",
415
+ message: "Select anime to add to the list:",
416
+ choices,
417
+ pageSize: choices.length + 1,
418
+ },
419
+ ]);
420
+ if (selectedAnime === "see_more") {
421
+ page++;
422
+ continue;
423
+ }
424
+ else {
425
+ const { selectedListType } = yield inquirer.prompt([
103
426
  {
104
427
  type: "list",
105
- name: "selectedList",
106
- message: "Select an anime list:",
107
- choices: lists.map((list) => list.name),
428
+ name: "selectedListType",
429
+ message: "Select the list where you want to save this anime:",
430
+ choices: [
431
+ { name: "Planning", value: "PLANNING" },
432
+ { name: "Watching", value: "CURRENT" },
433
+ { name: "Completed", value: "COMPLETED" },
434
+ { name: "Paused", value: "PAUSED" },
435
+ { name: "Dropped", value: "DROPPED" },
436
+ ],
108
437
  },
109
438
  ]);
110
- const selectedEntries = lists.find((list) => list.name === selectedList);
111
- if (selectedEntries) {
112
- console.log(`\nEntries for '${selectedEntries.name}':`);
113
- selectedEntries.entries.forEach((entry, idx) => {
114
- var _a;
115
- console.log(`${idx + 1}. ${getTitle((_a = entry === null || entry === void 0 ? void 0 : entry.media) === null || _a === void 0 ? void 0 : _a.title)}`);
116
- });
439
+ if (!(yield Auth.isLoggedIn())) {
440
+ console.error(`\nPlease log in first to use this feature.`);
441
+ return;
442
+ }
443
+ const variables = { mediaId: selectedAnime, status: selectedListType };
444
+ const saveResponse = yield fetcher(addAnimeToListMutation, variables);
445
+ const saved = (_e = saveResponse === null || saveResponse === void 0 ? void 0 : saveResponse.data) === null || _e === void 0 ? void 0 : _e.SaveMediaListEntry;
446
+ if (saved) {
447
+ console.log(`\nEntry ${saved.id}. Saved as ${saved.status}.`);
117
448
  }
118
449
  else {
119
- console.log("No entries found.");
450
+ console.error(`\nFailed to save the anime. ${((_g = (_f = saveResponse === null || saveResponse === void 0 ? void 0 : saveResponse.errors) === null || _f === void 0 ? void 0 : _f[0]) === null || _g === void 0 ? void 0 : _g.message) || "Unknown error"}`);
120
451
  }
121
- }
122
- else {
123
- console.log(`Something went wrong. ${(_c = response === null || response === void 0 ? void 0 : response.errors[0]) === null || _c === void 0 ? void 0 : _c.message}`);
452
+ break;
124
453
  }
125
454
  }
126
- else {
127
- console.log(`Failed getting current user Id.`);
128
- }
129
455
  }
130
- else {
131
- console.log(`Please log in first.`);
456
+ catch (error) {
457
+ console.error(`\nSomething went wrong. ${error.message}`);
132
458
  }
133
- }
134
- catch (error) {
135
- console.log(`Something went wrong. ${error.message}`);
136
- }
137
- });
138
- }
139
- function loggedInUsersMangaLists() {
140
- return __awaiter(this, void 0, void 0, function* () {
141
- var _a, _b, _c;
142
- try {
143
- const loggedIn = yield isLoggedIn();
144
- if (loggedIn) {
145
- const userID = yield currentUsersId();
146
- if (userID) {
147
- const request = yield fetch(aniListEndpoint, {
148
- method: "POST",
149
- headers: {
150
- "content-type": "application/json",
151
- Authorization: `Bearer ${yield retriveAccessToken()}`,
459
+ });
460
+ }
461
+ static getPopularAnime(count) {
462
+ return __awaiter(this, void 0, void 0, function* () {
463
+ var _a, _b, _c, _d, _e, _f, _g;
464
+ try {
465
+ let page = 1;
466
+ let allMedia = [];
467
+ while (true) {
468
+ const response = yield fetcher(popularQuery, { page, perPage: count });
469
+ if (!(response === null || response === void 0 ? void 0 : response.data)) {
470
+ console.error(`\nSomething went wrong. ${((_b = (_a = response === null || response === void 0 ? void 0 : response.errors) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.message) || "Unknown error"}`);
471
+ return;
472
+ }
473
+ const newMedia = (_d = (_c = response === null || response === void 0 ? void 0 : response.data) === null || _c === void 0 ? void 0 : _c.Page) === null || _d === void 0 ? void 0 : _d.media;
474
+ if (!newMedia || newMedia.length === 0) {
475
+ console.log(`\nNo more popular anime available.`);
476
+ break;
477
+ }
478
+ allMedia = [...allMedia, ...newMedia];
479
+ const choices = allMedia.map((anime, idx) => ({
480
+ name: `[${idx + 1}] ${getTitle(anime === null || anime === void 0 ? void 0 : anime.title)}`,
481
+ value: String(anime === null || anime === void 0 ? void 0 : anime.id),
482
+ }));
483
+ choices.push({ name: "See more", value: "see_more" });
484
+ const { selectedAnime } = yield inquirer.prompt([
485
+ {
486
+ type: "list",
487
+ name: "selectedAnime",
488
+ message: "Select anime to add to the list:",
489
+ choices,
490
+ pageSize: choices.length,
152
491
  },
153
- body: JSON.stringify({
154
- query: currentUserMangaList,
155
- variables: { id: userID },
156
- }),
157
- });
158
- const response = yield request.json();
159
- if (request.status === 200) {
160
- const lists = (_b = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.MediaListCollection) === null || _b === void 0 ? void 0 : _b.lists;
161
- const { selectedList } = yield inquirer.prompt([
492
+ ]);
493
+ if (selectedAnime === "see_more") {
494
+ page++;
495
+ continue;
496
+ }
497
+ else {
498
+ const { selectedListType } = yield inquirer.prompt([
162
499
  {
163
500
  type: "list",
164
- name: "selectedList",
165
- message: "Select a manga list:",
166
- choices: lists.map((list) => list.name),
501
+ name: "selectedListType",
502
+ message: "Select the list where you want to save this anime:",
503
+ choices: [
504
+ { name: "Planning", value: "PLANNING" },
505
+ { name: "Watching", value: "CURRENT" },
506
+ { name: "Completed", value: "COMPLETED" },
507
+ { name: "Paused", value: "PAUSED" },
508
+ { name: "Dropped", value: "DROPPED" },
509
+ ],
167
510
  },
168
511
  ]);
169
- const selectedEntries = lists.find((list) => list.name === selectedList);
170
- if (selectedEntries) {
171
- console.log(`\nEntries for '${selectedEntries.name}':`);
172
- selectedEntries.entries.forEach((entry, idx) => {
173
- var _a;
174
- console.log(`${idx + 1}. ${getTitle((_a = entry === null || entry === void 0 ? void 0 : entry.media) === null || _a === void 0 ? void 0 : _a.title)}`);
175
- });
512
+ if (!(yield Auth.isLoggedIn())) {
513
+ return console.error(`\nPlease log in first to use this feature.`);
514
+ }
515
+ const variables = { mediaId: selectedAnime, status: selectedListType };
516
+ const saveResponse = yield fetcher(addAnimeToListMutation, variables);
517
+ const saved = (_e = saveResponse === null || saveResponse === void 0 ? void 0 : saveResponse.data) === null || _e === void 0 ? void 0 : _e.SaveMediaListEntry;
518
+ if (saved) {
519
+ console.log(`\nEntry ${saved.id}. Saved as ${saved.status}.`);
176
520
  }
177
521
  else {
178
- console.log("No entries found.");
522
+ console.error(`\nFailed to save the anime. ${((_g = (_f = saveResponse === null || saveResponse === void 0 ? void 0 : saveResponse.errors) === null || _f === void 0 ? void 0 : _f[0]) === null || _g === void 0 ? void 0 : _g.message) || "Unknown error"}`);
179
523
  }
524
+ break;
525
+ }
526
+ }
527
+ }
528
+ catch (error) {
529
+ console.error(`\nSomething went wrong. ${error.message}`);
530
+ }
531
+ });
532
+ }
533
+ static getUpcomingAnime(count) {
534
+ return __awaiter(this, void 0, void 0, function* () {
535
+ var _a, _b, _c, _d, _e, _f;
536
+ try {
537
+ const { nextSeason, nextYear } = getNextSeasonAndYear();
538
+ let page = 1;
539
+ let allUpcoming = [];
540
+ while (true) {
541
+ const request = yield fetcher(upcomingAnimesQuery, {
542
+ nextSeason,
543
+ nextYear,
544
+ page,
545
+ perPage: count,
546
+ });
547
+ if (!request || !request.data) {
548
+ console.error(`\nSomething went wrong. ${((_b = (_a = request === null || request === void 0 ? void 0 : request.errors) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.message) || "Unknown error"}`);
549
+ return;
550
+ }
551
+ const newUpcoming = (_c = request.data.Page.media) !== null && _c !== void 0 ? _c : [];
552
+ if (newUpcoming.length === 0) {
553
+ console.log(`\nNo more upcoming anime available.`);
554
+ break;
555
+ }
556
+ allUpcoming = [...allUpcoming, ...newUpcoming];
557
+ const choices = allUpcoming.map((anime, idx) => ({
558
+ name: `[${idx + 1}] ${getTitle(anime === null || anime === void 0 ? void 0 : anime.title)}`,
559
+ value: String(anime === null || anime === void 0 ? void 0 : anime.id),
560
+ }));
561
+ choices.push({ name: "See more", value: "see_more" });
562
+ const { selectedAnime } = yield inquirer.prompt([
563
+ {
564
+ type: "list",
565
+ name: "selectedAnime",
566
+ message: "Select anime to add to the list:",
567
+ choices,
568
+ pageSize: choices.length + 2,
569
+ },
570
+ ]);
571
+ if (selectedAnime === "see_more") {
572
+ page++;
573
+ continue;
180
574
  }
181
575
  else {
182
- console.log(`Something went wrong. ${(_c = response === null || response === void 0 ? void 0 : response.errors[0]) === null || _c === void 0 ? void 0 : _c.message}`);
576
+ const { selectedListType } = yield inquirer.prompt([
577
+ {
578
+ type: "list",
579
+ name: "selectedListType",
580
+ message: "Select the list where you want to save this anime:",
581
+ choices: [
582
+ { name: "Planning", value: "PLANNING" },
583
+ { name: "Watching", value: "CURRENT" },
584
+ { name: "Completed", value: "COMPLETED" },
585
+ { name: "Paused", value: "PAUSED" },
586
+ { name: "Dropped", value: "DROPPED" },
587
+ ],
588
+ },
589
+ ]);
590
+ if (!(yield Auth.isLoggedIn())) {
591
+ return console.error(`\nPlease log in first to use this feature.`);
592
+ }
593
+ const variables = { mediaId: selectedAnime, status: selectedListType };
594
+ const saveResponse = yield fetcher(addAnimeToListMutation, variables);
595
+ const saved = (_d = saveResponse === null || saveResponse === void 0 ? void 0 : saveResponse.data) === null || _d === void 0 ? void 0 : _d.SaveMediaListEntry;
596
+ if (saved) {
597
+ console.log(`\nEntry ${saved.id}. Saved as ${saved.status}.`);
598
+ }
599
+ else {
600
+ console.error(`\nFailed to save the anime. ${((_f = (_e = saveResponse === null || saveResponse === void 0 ? void 0 : saveResponse.errors) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.message) || "Unknown error"}`);
601
+ }
602
+ break;
183
603
  }
184
604
  }
605
+ }
606
+ catch (error) {
607
+ console.error(`\nError getting upcoming animes. ${error.message}`);
608
+ }
609
+ });
610
+ }
611
+ static getUserByUsername(username) {
612
+ return __awaiter(this, void 0, void 0, function* () {
613
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2;
614
+ try {
615
+ const response = yield fetcher(userQuery, { username });
616
+ if (!((_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.User)) {
617
+ return console.error(`\n${((_c = (_b = response === null || response === void 0 ? void 0 : response.errors) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.message) || "Unknown error"}`);
618
+ }
619
+ const user = response.data.User;
620
+ const userActivityResponse = yield fetcher(userActivityQuery, {
621
+ id: user.id,
622
+ page: 1,
623
+ perPage: 10,
624
+ });
625
+ const activities = (_f = (_e = (_d = userActivityResponse === null || userActivityResponse === void 0 ? void 0 : userActivityResponse.data) === null || _d === void 0 ? void 0 : _d.Page) === null || _e === void 0 ? void 0 : _e.activities) !== null && _f !== void 0 ? _f : [];
626
+ // Get follower/following information
627
+ const req_followers = yield fetcher(userFollowersQuery, {
628
+ userId: user === null || user === void 0 ? void 0 : user.id,
629
+ });
630
+ const req_following = yield fetcher(userFollowingQuery, {
631
+ userId: user === null || user === void 0 ? void 0 : user.id,
632
+ });
633
+ const followersCount = ((_j = (_h = (_g = req_followers === null || req_followers === void 0 ? void 0 : req_followers.data) === null || _g === void 0 ? void 0 : _g.Page) === null || _h === void 0 ? void 0 : _h.pageInfo) === null || _j === void 0 ? void 0 : _j.total) || 0;
634
+ const followingCount = ((_m = (_l = (_k = req_following === null || req_following === void 0 ? void 0 : req_following.data) === null || _k === void 0 ? void 0 : _k.Page) === null || _l === void 0 ? void 0 : _l.pageInfo) === null || _m === void 0 ? void 0 : _m.total) || 0;
635
+ console.log(`\nID:\t\t${user.id}`);
636
+ console.log(`Name:\t\t${user.name}`);
637
+ console.log(`Site URL:\t${user.siteUrl}`);
638
+ console.log(`Donator Tier:\t${user.donatorTier}`);
639
+ console.log(`Donator Badge:\t${user.donatorBadge}`);
640
+ console.log(`Account Created:\t${user.createdAt ? new Date(user.createdAt * 1000).toUTCString() : "N/A"}`);
641
+ console.log(`Account Updated:\t${user.updatedAt ? new Date(user.updatedAt * 1000).toUTCString() : "N/A"}`);
642
+ console.log(`Blocked:\t${user.isBlocked}`);
643
+ console.log(`Follower:\t${user.isFollower}`);
644
+ console.log(`Following:\t${user.isFollowing}`);
645
+ console.log(`Profile Color:\t${(_o = user.options) === null || _o === void 0 ? void 0 : _o.profileColor}`);
646
+ console.log(`Timezone:\t${((_p = user.options) === null || _p === void 0 ? void 0 : _p.timezone) ? (_q = user.options) === null || _q === void 0 ? void 0 : _q.timezone : "N/A"}`);
647
+ console.log(`\nFollowers:\t${followersCount}`);
648
+ console.log(`Following:\t${followingCount}`);
649
+ console.log(`\nStatistics (Anime)\n\tCount: ${((_s = (_r = user.statistics) === null || _r === void 0 ? void 0 : _r.anime) === null || _s === void 0 ? void 0 : _s.count) || 0}\tEpisodes Watched: ${((_u = (_t = user.statistics) === null || _t === void 0 ? void 0 : _t.anime) === null || _u === void 0 ? void 0 : _u.episodesWatched) || 0}\tMinutes Watched: ${((_w = (_v = user.statistics) === null || _v === void 0 ? void 0 : _v.anime) === null || _w === void 0 ? void 0 : _w.minutesWatched) || 0}`);
650
+ console.log(`Statistics (Manga)\n\tCount: ${((_y = (_x = user.statistics) === null || _x === void 0 ? void 0 : _x.manga) === null || _y === void 0 ? void 0 : _y.count) || 0}\tChapters Read: ${((_0 = (_z = user.statistics) === null || _z === void 0 ? void 0 : _z.manga) === null || _0 === void 0 ? void 0 : _0.chaptersRead) || 0}\tVolumes Read: ${((_2 = (_1 = user.statistics) === null || _1 === void 0 ? void 0 : _1.manga) === null || _2 === void 0 ? void 0 : _2.volumesRead) || 0}`);
651
+ if (activities.length > 0) {
652
+ console.log(`\nRecent Activities:`);
653
+ activities.forEach(({ status, progress, media, createdAt }) => {
654
+ console.log(`${timestampToTimeAgo(createdAt)}\t${status} ${progress ? `${progress} of ` : ""}${getTitle(media === null || media === void 0 ? void 0 : media.title)}`);
655
+ });
656
+ }
185
657
  else {
186
- console.log(`Failed getting current user Id.`);
658
+ console.log("\nNo recent activities.");
187
659
  }
188
660
  }
189
- else {
190
- console.log(`Please log in first.`);
661
+ catch (error) {
662
+ console.error(`\nSomething went wrong. ${error.message}`);
191
663
  }
192
- }
193
- catch (error) {
194
- console.log(`Something went wrong. ${error.message}`);
195
- }
196
- });
197
- }
198
- function deleteAnimeCollection() {
199
- return __awaiter(this, void 0, void 0, function* () {
200
- var _a, _b, _c, _d;
201
- const loggedIn = yield isLoggedIn();
202
- if (loggedIn) {
203
- const userID = yield currentUsersId();
204
- if (userID) {
205
- const request = yield fetch(aniListEndpoint, {
206
- method: "POST",
207
- headers: {
208
- "content-type": "application/json",
209
- Authorization: `Bearer ${yield retriveAccessToken()}`,
210
- },
211
- body: JSON.stringify({
212
- query: currentUserAnimeList,
213
- variables: { id: userID },
214
- }),
215
- });
216
- const response = yield request.json();
217
- if (request.status === 200) {
218
- const lists = (_b = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.MediaListCollection) === null || _b === void 0 ? void 0 : _b.lists;
219
- const { selectedList } = yield inquirer.prompt([
664
+ });
665
+ }
666
+ static getAnimeDetailsByID(anilistID) {
667
+ return __awaiter(this, void 0, void 0, function* () {
668
+ var _a;
669
+ const details = yield fetcher(animeDetailsQuery, {
670
+ id: anilistID,
671
+ });
672
+ if ((_a = details === null || details === void 0 ? void 0 : details.data) === null || _a === void 0 ? void 0 : _a.Media) {
673
+ const { id, title, description, duration, startDate, endDate, countryOfOrigin, isAdult, status, season, format, genres, siteUrl, } = details.data.Media;
674
+ console.log(`\nID: ${id}`);
675
+ console.log(`Title: ${(title === null || title === void 0 ? void 0 : title.userPreferred) || getTitle(title)}`);
676
+ console.log(`Description: ${removeHtmlAndMarkdown(description)}`);
677
+ console.log(`Episode Duration: ${duration || "Unknown"} min`);
678
+ console.log(`Origin: ${countryOfOrigin || "N/A"}`);
679
+ console.log(`Status: ${status || "N/A"}`);
680
+ console.log(`Format: ${format || "N/A"}`);
681
+ console.log(`Genres: ${genres.length ? genres.join(", ") : "N/A"}`);
682
+ console.log(`Season: ${season || "N/A"}`);
683
+ console.log(`Url: ${siteUrl || "N/A"}`);
684
+ console.log(`isAdult: ${isAdult ? "Yes" : "No"}`);
685
+ console.log(`Released: ${formatDateObject(startDate) || "Unknown"}`);
686
+ console.log(`Finished: ${formatDateObject(endDate) || "Ongoing"}`);
687
+ }
688
+ });
689
+ }
690
+ static searchAnime(search, count) {
691
+ return __awaiter(this, void 0, void 0, function* () {
692
+ var _a, _b, _c;
693
+ const searchResults = yield fetcher(animeSearchQuery, {
694
+ search,
695
+ page: 1,
696
+ perPage: count,
697
+ });
698
+ if (searchResults) {
699
+ const results = (_b = (_a = searchResults === null || searchResults === void 0 ? void 0 : searchResults.data) === null || _a === void 0 ? void 0 : _a.Page) === null || _b === void 0 ? void 0 : _b.media;
700
+ if (results.length > 0) {
701
+ const { selectedAnime } = yield inquirer.prompt([
220
702
  {
221
703
  type: "list",
222
- name: "selectedList",
223
- message: "Select an anime list:",
224
- choices: lists.map((list) => list.name),
704
+ name: "selectedAnime",
705
+ message: "Select anime to add to your list:",
706
+ choices: results.map((res, idx) => ({
707
+ name: `[${idx + 1}] ${getTitle(res === null || res === void 0 ? void 0 : res.title)}`,
708
+ value: res === null || res === void 0 ? void 0 : res.id,
709
+ })),
710
+ pageSize: 10,
225
711
  },
226
712
  ]);
227
- const selectedEntries = lists.find((list) => list.name === selectedList);
228
- if (selectedEntries) {
229
- console.log(`\nDeleting entries of '${selectedEntries.name}':`);
230
- for (const [idx, entry] of selectedEntries.entries.entries()) {
231
- if (entry === null || entry === void 0 ? void 0 : entry.id) {
232
- yield deleteAnimeByAnimeId(entry === null || entry === void 0 ? void 0 : entry.id, (_c = entry === null || entry === void 0 ? void 0 : entry.media) === null || _c === void 0 ? void 0 : _c.title);
233
- yield new Promise((resolve) => setTimeout(resolve, 2000));
234
- }
235
- else {
236
- console.log(`No id in entry.`);
237
- console.log(entry);
238
- }
713
+ const { selectedListType } = yield inquirer.prompt([
714
+ {
715
+ type: "list",
716
+ name: "selectedListType",
717
+ message: "Select the list where you want to save this anime:",
718
+ choices: [
719
+ { name: "Planning", value: "PLANNING" },
720
+ { name: "Watching", value: "CURRENT" },
721
+ { name: "Completed", value: "COMPLETED" },
722
+ { name: "Paused", value: "PAUSED" },
723
+ { name: "Dropped", value: "DROPPED" },
724
+ ],
725
+ },
726
+ ]);
727
+ // Save selected anime to chosen list type
728
+ if (yield Auth.isLoggedIn()) {
729
+ const response = yield fetcher(addAnimeToListMutation, {
730
+ mediaId: selectedAnime,
731
+ status: selectedListType,
732
+ });
733
+ if (response) {
734
+ const saved = (_c = response === null || response === void 0 ? void 0 : response.data) === null || _c === void 0 ? void 0 : _c.SaveMediaListEntry;
735
+ console.log(`\nEntry ${saved === null || saved === void 0 ? void 0 : saved.id}. Saved as ${saved === null || saved === void 0 ? void 0 : saved.status}.`);
239
736
  }
240
737
  }
241
738
  else {
242
- console.log("No entries found.");
739
+ console.error(`\nPlease log in first to use this feature.`);
243
740
  }
244
741
  }
245
742
  else {
246
- console.log(`Something went wrong. ${(_d = response === null || response === void 0 ? void 0 : response.errors[0]) === null || _d === void 0 ? void 0 : _d.message}`);
743
+ console.log(`\nNo search results found.`);
247
744
  }
248
745
  }
249
746
  else {
250
- console.log(`Failed getting current user Id.`);
747
+ console.error(`\nSomething went wrong.`);
251
748
  }
252
- }
253
- else {
254
- console.log(`Please log in first.`);
255
- }
256
- });
257
- }
258
- function deleteAnimeByAnimeId(id, title) {
259
- return __awaiter(this, void 0, void 0, function* () {
260
- var _a, _b, _c;
261
- try {
262
- const request = yield fetch(aniListEndpoint, {
263
- method: "POST",
264
- headers: {
265
- "content-type": "application/json",
266
- Authorization: `Bearer ${yield retriveAccessToken()}`,
267
- },
268
- body: JSON.stringify({
269
- query: deleteMediaEntryMutation,
270
- variables: { id },
271
- }),
749
+ });
750
+ }
751
+ static searchManga(search, count) {
752
+ return __awaiter(this, void 0, void 0, function* () {
753
+ var _a, _b, _c;
754
+ const mangaSearchResult = yield fetcher(mangaSearchQuery, {
755
+ search,
756
+ page: 1,
757
+ perPage: count,
272
758
  });
273
- const response = yield request.json();
274
- if (request.status === 200) {
275
- const deleted = (_b = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.DeleteMediaListEntry) === null || _b === void 0 ? void 0 : _b.deleted;
276
- console.log(`del ${title ? getTitle(title) : ""} ${deleted ? "✅" : "❌"}`);
759
+ if (mangaSearchResult) {
760
+ const results = (_b = (_a = mangaSearchResult === null || mangaSearchResult === void 0 ? void 0 : mangaSearchResult.data) === null || _a === void 0 ? void 0 : _a.Page) === null || _b === void 0 ? void 0 : _b.media;
761
+ // List of manga search results
762
+ const { selectedMangaId } = yield inquirer.prompt([
763
+ {
764
+ type: "list",
765
+ name: "selectedMangaId",
766
+ message: "Select manga to add to your list:",
767
+ choices: results.map((res, idx) => ({
768
+ name: `[${idx + 1}] ${getTitle(res === null || res === void 0 ? void 0 : res.title)}`,
769
+ value: res === null || res === void 0 ? void 0 : res.id,
770
+ })),
771
+ pageSize: 10,
772
+ },
773
+ ]);
774
+ // Options to save to the list
775
+ const { selectedListType } = yield inquirer.prompt([
776
+ {
777
+ type: "list",
778
+ name: "selectedListType",
779
+ message: "Select the list where you want to save this manga:",
780
+ choices: [
781
+ { name: "Planning", value: "PLANNING" },
782
+ { name: "Reading", value: "CURRENT" },
783
+ { name: "Completed", value: "COMPLETED" },
784
+ { name: "Paused", value: "PAUSED" },
785
+ { name: "Dropped", value: "DROPPED" },
786
+ ],
787
+ },
788
+ ]);
789
+ // If logged in save to the list
790
+ if (yield Auth.isLoggedIn()) {
791
+ const response = yield fetcher(addMangaToListMutation, {
792
+ mediaId: selectedMangaId,
793
+ status: selectedListType,
794
+ });
795
+ if (response) {
796
+ const saved = (_c = response === null || response === void 0 ? void 0 : response.data) === null || _c === void 0 ? void 0 : _c.SaveMediaListEntry;
797
+ console.log(`\nEntry ${saved === null || saved === void 0 ? void 0 : saved.id}. Saved as ${saved === null || saved === void 0 ? void 0 : saved.status}.`);
798
+ }
799
+ }
800
+ else {
801
+ console.error(`\nPlease log in first to use this feature.`);
802
+ }
277
803
  }
278
804
  else {
279
- console.log(`Error deleting anime. ${(_c = response === null || response === void 0 ? void 0 : response.errors[0]) === null || _c === void 0 ? void 0 : _c.message}`);
280
- console.log(response);
805
+ console.error(`\nSomething went wrong.`);
281
806
  }
282
- }
283
- catch (error) {
284
- console.log(`Error deleting anime. ${id} ${error.message}`);
285
- }
286
- });
807
+ });
808
+ }
287
809
  }
288
- function deleteMangaCollection() {
289
- return __awaiter(this, void 0, void 0, function* () {
290
- var _a, _b, _c, _d;
291
- const loggedIn = yield isLoggedIn();
292
- if (loggedIn) {
293
- const userID = yield currentUsersId();
294
- if (userID) {
295
- const request = yield fetch(aniListEndpoint, {
296
- method: "POST",
297
- headers: {
298
- "content-type": "application/json",
299
- Authorization: `Bearer ${yield retriveAccessToken()}`,
300
- },
301
- body: JSON.stringify({
302
- query: currentUserMangaList,
303
- variables: { id: userID },
304
- }),
305
- });
306
- const response = yield request.json();
307
- if (request.status === 200) {
308
- const lists = (_b = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.MediaListCollection) === null || _b === void 0 ? void 0 : _b.lists;
309
- const { selectedList } = yield inquirer.prompt([
310
- {
311
- type: "list",
312
- name: "selectedList",
313
- message: "Select a manga list:",
314
- choices: lists.map((list) => list.name),
315
- },
316
- ]);
317
- const selectedEntries = lists.find((list) => list.name === selectedList);
318
- if (selectedEntries) {
319
- console.log(`\nDeleting entries of '${selectedEntries.name}':`);
320
- for (const [idx, entry] of selectedEntries.entries.entries()) {
321
- if (entry === null || entry === void 0 ? void 0 : entry.id) {
322
- yield deleteMangaByMangaId(entry === null || entry === void 0 ? void 0 : entry.id, (_c = entry === null || entry === void 0 ? void 0 : entry.media) === null || _c === void 0 ? void 0 : _c.title);
323
- yield new Promise((resolve) => setTimeout(resolve, 2000));
810
+ class MyAnimeList {
811
+ static importAnime() {
812
+ return __awaiter(this, void 0, void 0, function* () {
813
+ var _a, _b, _c, _d, _e;
814
+ try {
815
+ const filename = yield selectFile(".xml");
816
+ const filePath = join(getDownloadFolderPath(), filename);
817
+ const fileContent = yield readFile(filePath, "utf8");
818
+ const parser = new XMLParser();
819
+ if (fileContent) {
820
+ const XMLObject = parser.parse(fileContent);
821
+ const animeList = (_a = XMLObject === null || XMLObject === void 0 ? void 0 : XMLObject.myanimelist) === null || _a === void 0 ? void 0 : _a.anime;
822
+ if ((animeList === null || animeList === void 0 ? void 0 : animeList.length) > 0) {
823
+ let count = 0;
824
+ const statusMap = {
825
+ "On-Hold": AniListMediaStatus.PAUSED,
826
+ "Dropped": AniListMediaStatus.DROPPED,
827
+ "Completed": AniListMediaStatus.COMPLETED,
828
+ "Watching": AniListMediaStatus.CURRENT,
829
+ "Plan to Watch": AniListMediaStatus.PLANNING,
830
+ };
831
+ for (const anime of animeList) {
832
+ const malId = anime.series_animedb_id;
833
+ const progress = anime.my_watched_episodes;
834
+ const status = statusMap[anime.my_status];
835
+ try {
836
+ // Fetch AniList ID using MAL ID
837
+ const anilistResponse = yield fetcher(malIdToAnilistAnimeId, { malId });
838
+ const anilistId = (_c = (_b = anilistResponse === null || anilistResponse === void 0 ? void 0 : anilistResponse.data) === null || _b === void 0 ? void 0 : _b.Media) === null || _c === void 0 ? void 0 : _c.id;
839
+ if (anilistId) {
840
+ // Save anime entry with progress
841
+ const saveResponse = yield fetcher(saveAnimeWithProgressMutation, {
842
+ mediaId: anilistId,
843
+ progress,
844
+ status,
845
+ hiddenFromStatusLists: false,
846
+ private: false,
847
+ });
848
+ const entryId = (_e = (_d = saveResponse === null || saveResponse === void 0 ? void 0 : saveResponse.data) === null || _d === void 0 ? void 0 : _d.SaveMediaListEntry) === null || _e === void 0 ? void 0 : _e.id;
849
+ if (entryId) {
850
+ count++;
851
+ console.log(`[${count}] ${entryId} ✅`);
852
+ }
853
+ // Rate limit each API call to avoid server overload
854
+ yield new Promise((resolve) => setTimeout(resolve, 1100));
855
+ }
856
+ else {
857
+ console.error(`Could not retrieve AniList ID for MAL ID ${malId}`);
858
+ }
324
859
  }
325
- else {
326
- console.log(`No id in entry.`);
327
- console.log(entry);
860
+ catch (error) {
861
+ console.error(`Error processing MAL ID ${malId}: ${error.message}`);
328
862
  }
329
863
  }
864
+ console.log(`\nTotal Entries Processed: ${count}`);
330
865
  }
331
866
  else {
332
- console.log("No entries found.");
867
+ console.log(`\nNo anime list found in the file.`);
333
868
  }
334
869
  }
870
+ }
871
+ catch (error) {
872
+ console.error(`\nError in MAL import process: ${error.message}`);
873
+ }
874
+ });
875
+ }
876
+ static importManga() {
877
+ return __awaiter(this, void 0, void 0, function* () {
878
+ var _a, _b, _c, _d, _e;
879
+ try {
880
+ const filename = yield selectFile(".xml");
881
+ const filePath = join(getDownloadFolderPath(), filename);
882
+ const fileContent = yield readFile(filePath, "utf8");
883
+ const parser = new XMLParser();
884
+ if (fileContent) {
885
+ const XMLObject = parser.parse(fileContent);
886
+ const mangas = (_a = XMLObject === null || XMLObject === void 0 ? void 0 : XMLObject.myanimelist) === null || _a === void 0 ? void 0 : _a.manga;
887
+ if ((mangas === null || mangas === void 0 ? void 0 : mangas.length) > 0) {
888
+ let count = 0;
889
+ const statusMap = {
890
+ "On-Hold": AniListMediaStatus.PAUSED,
891
+ "Dropped": AniListMediaStatus.DROPPED,
892
+ "Completed": AniListMediaStatus.COMPLETED,
893
+ "Reading": AniListMediaStatus.CURRENT,
894
+ "Plan to Read": AniListMediaStatus.PLANNING,
895
+ };
896
+ for (const manga of mangas) {
897
+ const malId = manga.manga_mangadb_id;
898
+ const progress = manga.my_read_chapters;
899
+ const status = statusMap[manga.my_status];
900
+ try {
901
+ // Fetch AniList ID using MAL ID
902
+ const anilistResponse = yield fetcher(malIdToAnilistMangaId, { malId });
903
+ const anilistId = (_c = (_b = anilistResponse === null || anilistResponse === void 0 ? void 0 : anilistResponse.data) === null || _b === void 0 ? void 0 : _b.Media) === null || _c === void 0 ? void 0 : _c.id;
904
+ if (anilistId) {
905
+ // Save manga entry with progress
906
+ const saveResponse = yield fetcher(saveMangaWithProgressMutation, {
907
+ mediaId: anilistId,
908
+ progress,
909
+ status,
910
+ hiddenFromStatusLists: false,
911
+ private: false,
912
+ });
913
+ const entryId = (_e = (_d = saveResponse === null || saveResponse === void 0 ? void 0 : saveResponse.data) === null || _d === void 0 ? void 0 : _d.SaveMediaListEntry) === null || _e === void 0 ? void 0 : _e.id;
914
+ if (entryId) {
915
+ count++;
916
+ console.log(`[${count}] ${entryId} ✅`);
917
+ }
918
+ else {
919
+ console.error(`Failed to save entry for ${malId}`);
920
+ }
921
+ }
922
+ else {
923
+ console.error(`Could not retrieve AniList ID for MAL ID ${malId}`);
924
+ }
925
+ }
926
+ catch (error) {
927
+ console.error(`Error processing MAL ID ${malId}: ${error.message}`);
928
+ }
929
+ }
930
+ console.log(`\nTotal Entries Processed: ${count}`);
931
+ }
932
+ else {
933
+ console.log(`\nNo manga list seems to be found.`);
934
+ }
935
+ }
936
+ }
937
+ catch (error) {
938
+ console.error(`\nError from MAL import: ${error.message}`);
939
+ }
940
+ });
941
+ }
942
+ static exportAnime() {
943
+ return __awaiter(this, void 0, void 0, function* () {
944
+ var _a, _b, _c, _d;
945
+ try {
946
+ if (yield Auth.isLoggedIn()) {
947
+ const animeList = yield fetcher(currentUserAnimeList, {
948
+ id: yield Auth.MyUserId(),
949
+ });
950
+ if (((_b = (_a = animeList === null || animeList === void 0 ? void 0 : animeList.data) === null || _a === void 0 ? void 0 : _a.MediaListCollection) === null || _b === void 0 ? void 0 : _b.lists.length) > 0) {
951
+ const lists = (_d = (_c = animeList === null || animeList === void 0 ? void 0 : animeList.data) === null || _c === void 0 ? void 0 : _c.MediaListCollection) === null || _d === void 0 ? void 0 : _d.lists;
952
+ const mediaWithProgress = lists.flatMap((list) => list.entries.map((entry) => {
953
+ var _a, _b, _c, _d, _e;
954
+ return ({
955
+ id: (_a = entry === null || entry === void 0 ? void 0 : entry.media) === null || _a === void 0 ? void 0 : _a.id,
956
+ malId: (_b = entry === null || entry === void 0 ? void 0 : entry.media) === null || _b === void 0 ? void 0 : _b.idMal,
957
+ title: (_c = entry === null || entry === void 0 ? void 0 : entry.media) === null || _c === void 0 ? void 0 : _c.title,
958
+ episodes: (_d = entry === null || entry === void 0 ? void 0 : entry.media) === null || _d === void 0 ? void 0 : _d.episodes,
959
+ siteUrl: (_e = entry === null || entry === void 0 ? void 0 : entry.media) === null || _e === void 0 ? void 0 : _e.siteUrl,
960
+ progress: entry.progress,
961
+ status: entry === null || entry === void 0 ? void 0 : entry.status,
962
+ hiddenFromStatusLists: false,
963
+ });
964
+ }));
965
+ const xmlContent = createAnimeListXML(mediaWithProgress);
966
+ const path = join(getDownloadFolderPath(), `${yield Auth.MyUserName()}@irfanshadikrishad-anilist-myanimelist(anime)-${getFormattedDate()}.xml`);
967
+ yield writeFile(path, yield xmlContent, "utf8");
968
+ console.log(`Generated XML for MyAnimeList.`);
969
+ open(getDownloadFolderPath());
970
+ }
971
+ else {
972
+ console.log(`\nHey, ${yield Auth.MyUserName()}. Your anime list seems to be empty.`);
973
+ }
974
+ }
975
+ }
976
+ catch (error) {
977
+ console.error(`\nError from MALexport. ${error.message}`);
978
+ }
979
+ });
980
+ }
981
+ static exportManga() {
982
+ return __awaiter(this, void 0, void 0, function* () {
983
+ var _a, _b, _c, _d;
984
+ try {
985
+ if (!(yield Auth.isLoggedIn())) {
986
+ console.log(`\nPlease login to use this feature.`);
987
+ return;
988
+ }
989
+ const mangaList = yield fetcher(currentUserMangaList, {
990
+ id: yield Auth.MyUserId(),
991
+ });
992
+ if (mangaList && ((_b = (_a = mangaList === null || mangaList === void 0 ? void 0 : mangaList.data) === null || _a === void 0 ? void 0 : _a.MediaListCollection) === null || _b === void 0 ? void 0 : _b.lists.length) > 0) {
993
+ const lists = (_d = (_c = mangaList === null || mangaList === void 0 ? void 0 : mangaList.data) === null || _c === void 0 ? void 0 : _c.MediaListCollection) === null || _d === void 0 ? void 0 : _d.lists;
994
+ const mediaWithProgress = lists.flatMap((list) => list.entries.map((entry) => ({
995
+ id: entry.media.id,
996
+ malId: entry.media.idMal,
997
+ title: entry.media.title,
998
+ private: entry.private,
999
+ chapters: entry.media.chapters,
1000
+ progress: entry.progress,
1001
+ status: entry.status,
1002
+ hiddenFromStatusLists: entry.hiddenFromStatusLists,
1003
+ })));
1004
+ const XMLContent = createMangaListXML(mediaWithProgress);
1005
+ const path = join(getDownloadFolderPath(), `${yield Auth.MyUserName()}@irfanshadikrishad-anilist-myanimelist(manga)-${getFormattedDate()}.xml`);
1006
+ yield writeFile(path, yield XMLContent, "utf8");
1007
+ console.log(`Generated XML for MyAnimeList.`);
1008
+ open(getDownloadFolderPath());
1009
+ }
335
1010
  else {
336
- console.log(`Something went wrong. ${(_d = response === null || response === void 0 ? void 0 : response.errors[0]) === null || _d === void 0 ? void 0 : _d.message}`);
1011
+ console.log(`\nHey, ${yield Auth.MyUserName()}. Your anime list seems to be empty.`);
337
1012
  }
338
1013
  }
339
- else {
340
- console.log(`Failed getting current user Id.`);
1014
+ catch (error) {
1015
+ console.error(`\nError from MALexport. ${error.message}`);
341
1016
  }
342
- }
343
- else {
344
- console.log(`Please log in first.`);
345
- }
346
- });
1017
+ });
1018
+ }
347
1019
  }
348
- function deleteMangaByMangaId(id, title) {
349
- return __awaiter(this, void 0, void 0, function* () {
350
- var _a, _b, _c;
351
- try {
352
- const request = yield fetch(aniListEndpoint, {
353
- method: "POST",
354
- headers: {
355
- "content-type": "application/json",
356
- Authorization: `Bearer ${yield retriveAccessToken()}`,
357
- },
358
- body: JSON.stringify({
359
- query: deleteMangaEntryMutation,
360
- variables: { id },
361
- }),
362
- });
363
- const response = yield request.json();
364
- if (request.status === 200) {
365
- const deleted = (_b = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.DeleteMediaListEntry) === null || _b === void 0 ? void 0 : _b.deleted;
366
- console.log(`del ${title ? getTitle(title) : ""} ${deleted ? "✅" : "❌"}`);
1020
+ class AniDB {
1021
+ static importAnime() {
1022
+ return __awaiter(this, void 0, void 0, function* () {
1023
+ var _a, _b;
1024
+ try {
1025
+ const filename = yield selectFile(".json");
1026
+ const filePath = join(getDownloadFolderPath(), filename);
1027
+ const fileContent = yield readFile(filePath, "utf8");
1028
+ const js0n_repaired = jsonrepair(fileContent);
1029
+ if (fileContent) {
1030
+ const obj3ct = yield JSON.parse(js0n_repaired);
1031
+ const animeList = obj3ct === null || obj3ct === void 0 ? void 0 : obj3ct.anime;
1032
+ if ((animeList === null || animeList === void 0 ? void 0 : animeList.length) > 0) {
1033
+ let count = 0;
1034
+ let iteration = 0;
1035
+ let missed = [];
1036
+ for (const anime of animeList) {
1037
+ iteration++;
1038
+ const anidbId = anime.id;
1039
+ const released = anime.broadcastDate; // DD-MM-YYYY (eg: "23.07.2016")
1040
+ const status = anime.status;
1041
+ // const type = anime.type
1042
+ const totalEpisodes = anime.totalEpisodes;
1043
+ const ownEpisodes = anime.ownEpisodes;
1044
+ const romanjiName = anime.romanjiName;
1045
+ const englishName = anime.englishName;
1046
+ function getStatus(anidbStatus, episodesSeen) {
1047
+ if (anidbStatus === "complete") {
1048
+ return AniListMediaStatus.COMPLETED;
1049
+ }
1050
+ else if (anidbStatus === "incomplete" &&
1051
+ Number(episodesSeen) > 0) {
1052
+ return AniListMediaStatus.CURRENT;
1053
+ }
1054
+ else {
1055
+ return AniListMediaStatus.PLANNING;
1056
+ }
1057
+ }
1058
+ let anilistId = yield anidbToanilistMapper(romanjiName, Number(released.split(".")[2]), englishName);
1059
+ if (anilistId) {
1060
+ try {
1061
+ const saveResponse = yield fetcher(saveAnimeWithProgressMutation, {
1062
+ mediaId: anilistId,
1063
+ progress: ownEpisodes - 2,
1064
+ status: getStatus(status, ownEpisodes),
1065
+ hiddenFromStatusLists: false,
1066
+ private: false,
1067
+ });
1068
+ const entryId = (_b = (_a = saveResponse === null || saveResponse === void 0 ? void 0 : saveResponse.data) === null || _a === void 0 ? void 0 : _a.SaveMediaListEntry) === null || _b === void 0 ? void 0 : _b.id;
1069
+ if (entryId) {
1070
+ count++;
1071
+ console.log(`[${count}]\t${entryId} ✅\t${anidbId}\t${anilistId}\t(${ownEpisodes}/${totalEpisodes})\t${status}→${getStatus(status, ownEpisodes)}`);
1072
+ }
1073
+ // Rate limit each API call to avoid server overload
1074
+ // await new Promise((resolve) => setTimeout(resolve, 1100))
1075
+ }
1076
+ catch (error) {
1077
+ console.error(`Error processing AniDB ID ${anidbId}: ${error.message}`);
1078
+ }
1079
+ }
1080
+ else {
1081
+ missed.push({
1082
+ anidbId: anidbId,
1083
+ englishTitle: englishName,
1084
+ romajiTitle: romanjiName,
1085
+ });
1086
+ }
1087
+ }
1088
+ console.log(`\nAccuracy: ${(((animeList.length - missed.length) / animeList.length) * 100).toFixed(2)}%\tTotal Processed: ${iteration}\tMissed: ${missed.length}`);
1089
+ if (missed.length > 0) {
1090
+ console.log(`Exporting missed entries to JSON file, Please add them manually.`);
1091
+ yield saveJSONasJSON(missed, "anidb-missed");
1092
+ }
1093
+ }
1094
+ else {
1095
+ console.log(`\nNo anime list found in the file.`);
1096
+ }
1097
+ }
1098
+ else {
1099
+ console.log(`\nNo content found in the file or unable to read.`);
1100
+ }
367
1101
  }
368
- else {
369
- console.log(`Error deleting manga. ${(_c = response === null || response === void 0 ? void 0 : response.errors[0]) === null || _c === void 0 ? void 0 : _c.message}`);
370
- console.log(response);
1102
+ catch (error) {
1103
+ console.error(`\nError in AniDB import process: ${error.message}`);
371
1104
  }
372
- }
373
- catch (error) {
374
- console.log(`Error deleting manga. ${id} ${error.message}`);
375
- }
376
- });
1105
+ });
1106
+ }
377
1107
  }
378
- export { getTrending, getPopular, loggedInUsersAnimeLists, loggedInUsersMangaLists, deleteAnimeCollection, deleteMangaCollection, };
1108
+ export { AniDB, AniList, MyAnimeList };