@irfanshadikrishad/anilist 1.9.8 → 2.0.0-forbidden.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.
@@ -10,19 +10,21 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  import { Cipher } from '@irfanshadikrishad/cipher';
11
11
  import fs from 'fs';
12
12
  import inquirer from 'inquirer';
13
+ import fetch from 'node-fetch';
13
14
  import open from 'open';
14
15
  import os from 'os';
15
16
  import path from 'path';
17
+ import { exit } from 'process';
16
18
  import Spinner from 'tiny-spinner';
17
- import { colorize } from '../lib/colorize.js';
18
19
  import { fetcher } from './fetcher.js';
20
+ import { colorize } from './lib/colorize.js';
19
21
  import { AniDB, AniList, MyAnimeList } from './lists.js';
20
- import { deleteActivityMutation, deleteMangaEntryMutation, deleteMediaEntryMutation, saveTextActivityMutation, toggleFollowMutation, } from './mutations.js';
21
- import { activityAllQuery, activityAnimeListQuery, activityMangaListQuery, activityMediaList, activityMessageQuery, activityTextQuery, currentUserAnimeList, currentUserMangaList, currentUserQuery, userActivityQuery, userFollowersQuery, userFollowingQuery, } from './queries.js';
22
+ import { deleteActivityMutation, deleteMangaEntryMutation, deleteMediaEntryMutation, likeActivityMutation, saveTextActivityMutation, toggleFollowMutation, } from './mutations.js';
23
+ import { activityAllQuery, activityAnimeListQuery, activityMangaListQuery, activityMediaList, activityMessageQuery, activityTextQuery, currentUserAnimeList, currentUserMangaList, currentUserQuery, followingActivitiesQuery, globalActivitiesQuery, specificUserActivitiesQuery, userActivityQuery, userFollowersQuery, userFollowingQuery, userQuery, } from './queries.js';
22
24
  import { responsiveOutput } from './truncate.js';
23
- import { aniListEndpoint, getTitle, redirectUri, timestampToTimeAgo, } from './workers.js';
25
+ import { activityBy, aniListEndpoint, getTitle, redirectUri, sleep, timestampToTimeAgo, } from './workers.js';
24
26
  const home_dir = os.homedir();
25
- const save_path = path.join(home_dir, '.anilist_tok3n');
27
+ const save_path = path.join(home_dir, '.anilist_token');
26
28
  const spinner = new Spinner();
27
29
  const vigenere = new Cipher.Vigenere('anilist');
28
30
  class Auth {
@@ -65,7 +67,7 @@ class Auth {
65
67
  }
66
68
  });
67
69
  }
68
- static RetrieveAccessToken() {
70
+ static RetriveAccessToken() {
69
71
  return __awaiter(this, void 0, void 0, function* () {
70
72
  try {
71
73
  if (fs.existsSync(save_path)) {
@@ -76,7 +78,7 @@ class Auth {
76
78
  }
77
79
  }
78
80
  catch (error) {
79
- console.error(`\nError retrieving access token. ${error.message}`);
81
+ console.error(`\nError retriving acess-token. ${error.message}`);
80
82
  return null;
81
83
  }
82
84
  });
@@ -124,12 +126,12 @@ class Auth {
124
126
  }
125
127
  static Myself() {
126
128
  return __awaiter(this, void 0, void 0, function* () {
127
- 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, _3, _4, _5;
129
+ 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;
128
130
  try {
129
131
  if (yield Auth.isLoggedIn()) {
130
132
  const headers = {
131
133
  'Content-Type': 'application/json',
132
- 'Authorization': `Bearer ${yield Auth.RetrieveAccessToken()}`,
134
+ 'Authorization': `Bearer ${yield Auth.RetriveAccessToken()}`,
133
135
  };
134
136
  const request = yield fetch(aniListEndpoint, {
135
137
  method: 'POST',
@@ -164,34 +166,34 @@ activityMergeTime: ${(_l = user === null || user === void 0 ? void 0 : user
164
166
  donatorTier: ${user === null || user === void 0 ? void 0 : user.donatorTier}
165
167
  donatorBadge: ${user === null || user === void 0 ? void 0 : user.donatorBadge}
166
168
  unreadNotificationCount:${user === null || user === void 0 ? void 0 : user.unreadNotificationCount}
167
- Account Created: ${new Date(((_m = user === null || user === void 0 ? void 0 : user.createdAt) !== null && _m !== void 0 ? _m : 0) * 1000).toUTCString()}
168
- Account Updated: ${new Date(((_o = user === null || user === void 0 ? void 0 : user.updatedAt) !== null && _o !== void 0 ? _o : 0) * 1000).toUTCString()}
169
+ Account Created: ${new Date((user === null || user === void 0 ? void 0 : user.createdAt) * 1000).toUTCString()}
170
+ Account Updated: ${new Date((user === null || user === void 0 ? void 0 : user.updatedAt) * 1000).toUTCString()}
169
171
 
170
172
  Followers: ${followersCount}
171
173
  Following: ${followingCount}
172
174
 
173
175
  Statistics (Anime):
174
- Count: ${(_q = (_p = user === null || user === void 0 ? void 0 : user.statistics) === null || _p === void 0 ? void 0 : _p.anime) === null || _q === void 0 ? void 0 : _q.count}
175
- Mean Score: ${(_s = (_r = user === null || user === void 0 ? void 0 : user.statistics) === null || _r === void 0 ? void 0 : _r.anime) === null || _s === void 0 ? void 0 : _s.meanScore}
176
- Minutes Watched: ${(_u = (_t = user === null || user === void 0 ? void 0 : user.statistics) === null || _t === void 0 ? void 0 : _t.anime) === null || _u === void 0 ? void 0 : _u.minutesWatched}
177
- Episodes Watched: ${(_w = (_v = user === null || user === void 0 ? void 0 : user.statistics) === null || _v === void 0 ? void 0 : _v.anime) === null || _w === void 0 ? void 0 : _w.episodesWatched}
176
+ Count: ${(_o = (_m = user === null || user === void 0 ? void 0 : user.statistics) === null || _m === void 0 ? void 0 : _m.anime) === null || _o === void 0 ? void 0 : _o.count}
177
+ Mean Score: ${(_q = (_p = user === null || user === void 0 ? void 0 : user.statistics) === null || _p === void 0 ? void 0 : _p.anime) === null || _q === void 0 ? void 0 : _q.meanScore}
178
+ Minutes Watched: ${(_s = (_r = user === null || user === void 0 ? void 0 : user.statistics) === null || _r === void 0 ? void 0 : _r.anime) === null || _s === void 0 ? void 0 : _s.minutesWatched}
179
+ Episodes Watched: ${(_u = (_t = user === null || user === void 0 ? void 0 : user.statistics) === null || _t === void 0 ? void 0 : _t.anime) === null || _u === void 0 ? void 0 : _u.episodesWatched}
178
180
 
179
181
  Statistics (Manga):
180
- Count: ${(_y = (_x = user === null || user === void 0 ? void 0 : user.statistics) === null || _x === void 0 ? void 0 : _x.manga) === null || _y === void 0 ? void 0 : _y.count}
181
- Mean Score: ${(_0 = (_z = user === null || user === void 0 ? void 0 : user.statistics) === null || _z === void 0 ? void 0 : _z.manga) === null || _0 === void 0 ? void 0 : _0.meanScore}
182
- Chapters Read: ${(_2 = (_1 = user === null || user === void 0 ? void 0 : user.statistics) === null || _1 === void 0 ? void 0 : _1.manga) === null || _2 === void 0 ? void 0 : _2.chaptersRead}
183
- Volumes Read: ${(_4 = (_3 = user === null || user === void 0 ? void 0 : user.statistics) === null || _3 === void 0 ? void 0 : _3.manga) === null || _4 === void 0 ? void 0 : _4.volumesRead}
182
+ Count: ${(_w = (_v = user === null || user === void 0 ? void 0 : user.statistics) === null || _v === void 0 ? void 0 : _v.manga) === null || _w === void 0 ? void 0 : _w.count}
183
+ Mean Score: ${(_y = (_x = user === null || user === void 0 ? void 0 : user.statistics) === null || _x === void 0 ? void 0 : _x.manga) === null || _y === void 0 ? void 0 : _y.meanScore}
184
+ Chapters Read: ${(_0 = (_z = user === null || user === void 0 ? void 0 : user.statistics) === null || _z === void 0 ? void 0 : _z.manga) === null || _0 === void 0 ? void 0 : _0.chaptersRead}
185
+ Volumes Read: ${(_2 = (_1 = user === null || user === void 0 ? void 0 : user.statistics) === null || _1 === void 0 ? void 0 : _1.manga) === null || _2 === void 0 ? void 0 : _2.volumesRead}
184
186
  `);
185
187
  console.log(`\nRecent Activities:`);
186
- if (activities === null || activities === void 0 ? void 0 : activities.length) {
187
- activities === null || activities === void 0 ? void 0 : activities.map(({ status, progress, media, createdAt }) => {
188
+ if (activities.length > 0) {
189
+ activities.map(({ status, progress, media, createdAt }) => {
188
190
  responsiveOutput(`${timestampToTimeAgo(createdAt)}\t${status} ${progress ? `${progress} of ` : ''}${getTitle(media === null || media === void 0 ? void 0 : media.title)}`);
189
191
  });
190
192
  }
191
193
  return user;
192
194
  }
193
195
  else {
194
- console.error(`\nSomething went wrong. Please log in again. ${(_5 = errors === null || errors === void 0 ? void 0 : errors[0]) === null || _5 === void 0 ? void 0 : _5.message}`);
196
+ console.error(`\nSomething went wrong. Please log in again. ${errors[0].message}`);
195
197
  return null;
196
198
  }
197
199
  }
@@ -208,7 +210,7 @@ Statistics (Manga):
208
210
  static isLoggedIn() {
209
211
  return __awaiter(this, void 0, void 0, function* () {
210
212
  try {
211
- const token = yield Auth.RetrieveAccessToken();
213
+ const token = yield Auth.RetriveAccessToken();
212
214
  return token !== null;
213
215
  }
214
216
  catch (error) {
@@ -241,24 +243,24 @@ Statistics (Manga):
241
243
  }
242
244
  static MyUserId() {
243
245
  return __awaiter(this, void 0, void 0, function* () {
244
- var _a, _b, _c;
246
+ var _a, _b;
245
247
  if (!(yield Auth.isLoggedIn())) {
246
248
  console.warn(`\nUser not logged in.`);
247
249
  return null;
248
250
  }
249
- const response = yield fetcher(currentUserQuery, {});
250
- return (_c = (_b = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.Viewer) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : null;
251
+ const { data } = yield fetcher(currentUserQuery, {});
252
+ return (_b = (_a = data === null || data === void 0 ? void 0 : data.Viewer) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : null;
251
253
  });
252
254
  }
253
255
  static MyUserName() {
254
256
  return __awaiter(this, void 0, void 0, function* () {
255
- var _a, _b, _c;
257
+ var _a, _b;
256
258
  if (!(yield Auth.isLoggedIn())) {
257
259
  console.log(`\nUser not logged in.`);
258
260
  return null;
259
261
  }
260
- const response = yield fetcher(currentUserQuery, {});
261
- return (_c = (_b = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.Viewer) === null || _b === void 0 ? void 0 : _b.name) !== null && _c !== void 0 ? _c : null;
262
+ const { data } = yield fetcher(currentUserQuery, {});
263
+ return (_b = (_a = data === null || data === void 0 ? void 0 : data.Viewer) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : null;
262
264
  });
263
265
  }
264
266
  static DeleteMyActivities() {
@@ -284,18 +286,6 @@ Statistics (Manga):
284
286
  ],
285
287
  },
286
288
  ]);
287
- const { confirmed } = yield inquirer.prompt([
288
- {
289
- type: 'confirm',
290
- name: 'confirmed',
291
- message: `Delete all activities of this type? This cannot be undone.`,
292
- default: false,
293
- },
294
- ]);
295
- if (!confirmed) {
296
- console.log(`\nAborted.`);
297
- return;
298
- }
299
289
  const queryMap = {
300
290
  0: activityAllQuery,
301
291
  1: activityTextQuery,
@@ -329,9 +319,9 @@ Statistics (Manga):
329
319
  const isDeleted = (_f = (_e = deleteResponse === null || deleteResponse === void 0 ? void 0 : deleteResponse.data) === null || _e === void 0 ? void 0 : _e.DeleteActivity) === null || _f === void 0 ? void 0 : _f.deleted;
330
320
  count++;
331
321
  totalCount++;
332
- console.log(`[${count}/${activities.length}/${totalCount}]\t${act === null || act === void 0 ? void 0 : act.id} ${isDeleted ? '✔' : '✘'}`);
322
+ console.log(`[${count}/${activities.length}/${totalCount}]\t${act === null || act === void 0 ? void 0 : act.id} ${isDeleted ? colorize.Green('✔') : colorize.Red('✘')}`);
333
323
  // Avoiding rate-limit
334
- yield new Promise((resolve) => setTimeout(resolve, 1100));
324
+ yield sleep(1100);
335
325
  }
336
326
  }
337
327
  }
@@ -348,174 +338,97 @@ Statistics (Manga):
348
338
  }
349
339
  });
350
340
  }
351
- static DeleteMyAnimeList() {
352
- return __awaiter(this, void 0, void 0, function* () {
353
- var _a, _b, _c, _d;
354
- if (!(yield Auth.isLoggedIn())) {
355
- console.error(`\nPlease log in first to delete your lists.`);
356
- return;
357
- }
358
- const userId = yield Auth.MyUserId();
359
- if (!userId) {
360
- console.log(`\nFailed getting current user Id.`);
361
- return;
362
- }
363
- const response = yield fetcher(currentUserAnimeList, { id: userId });
364
- if (response !== null) {
365
- const lists = (_c = (_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) !== null && _c !== void 0 ? _c : [];
366
- if (lists.length > 0) {
367
- const { selectedList } = yield inquirer.prompt([
368
- {
369
- type: 'select',
370
- name: 'selectedList',
371
- message: 'Select an anime list:',
372
- choices: lists.map((list) => list.name),
373
- pageSize: 10,
374
- },
375
- ]);
376
- const selectedEntries = lists.find((list) => list.name === selectedList);
377
- if (selectedEntries) {
378
- const { confirmed } = yield inquirer.prompt([
379
- {
380
- type: 'confirm',
381
- name: 'confirmed',
382
- message: `Delete all ${selectedEntries.entries.length} entries from '${selectedEntries.name}'? This cannot be undone.`,
383
- default: false,
384
- },
385
- ]);
386
- if (!confirmed) {
387
- console.log(`\nAborted.`);
388
- return;
389
- }
390
- console.log(`\nDeleting entries of '${selectedEntries.name}':`);
391
- for (const [, entry] of selectedEntries.entries.entries()) {
392
- if (entry === null || entry === void 0 ? void 0 : entry.id) {
393
- yield Auth.DeleteAnimeById(entry === null || entry === void 0 ? void 0 : entry.id, (_d = entry === null || entry === void 0 ? void 0 : entry.media) === null || _d === void 0 ? void 0 : _d.title);
394
- yield new Promise((resolve) => setTimeout(resolve, 1100));
395
- }
396
- else {
397
- console.log(`No id in entry.`);
398
- console.log(entry);
399
- }
400
- }
401
- }
402
- else {
403
- console.log('No entries found.');
404
- }
405
- }
406
- else {
407
- console.log(`\nNo anime(s) found in any list.`);
408
- }
409
- }
410
- else {
411
- console.log(`\nSomething went wrong fetching anime list.`);
412
- }
413
- });
414
- }
415
- static DeleteAnimeById(id, title) {
341
+ static DeleteMediaEntryById(mutation, id, title) {
416
342
  return __awaiter(this, void 0, void 0, function* () {
417
343
  var _a, _b, _c, _d;
418
344
  try {
419
- const response = yield fetcher(deleteMediaEntryMutation, { id: id });
345
+ const response = yield fetcher(mutation, { id });
420
346
  if (response === null || response === void 0 ? void 0 : response.data) {
421
347
  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;
422
- console.log(`del ${title ? getTitle(title) : ''} ${deleted ? '✔' : '✘'}`);
348
+ console.log(`del ${title ? getTitle(title) : ''} ${deleted ? colorize.Green('✔') : colorize.Red('✘')}`);
423
349
  }
424
350
  else {
425
- console.log(`\nError deleting anime. ${(_d = (_c = response === null || response === void 0 ? void 0 : response.errors) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.message}`);
426
- console.log(response);
351
+ console.error(`\nError deleting entry. ${(_d = (_c = response === null || response === void 0 ? void 0 : response.errors) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.message}`);
427
352
  }
428
353
  }
429
354
  catch (error) {
430
- console.log(`\nError deleting anime. ${id} ${error.message}`);
355
+ console.error(`\nError deleting entry. ${id} ${error.message}`);
431
356
  }
432
357
  });
433
358
  }
434
- static DeleteMyMangaList() {
359
+ static DeleteAnimeById(id, title) {
435
360
  return __awaiter(this, void 0, void 0, function* () {
436
- var _a, _b, _c, _d, _e, _f;
361
+ return Auth.DeleteMediaEntryById(deleteMediaEntryMutation, id, title);
362
+ });
363
+ }
364
+ static DeleteMangaById(id, title) {
365
+ return __awaiter(this, void 0, void 0, function* () {
366
+ return Auth.DeleteMediaEntryById(deleteMangaEntryMutation, id, title);
367
+ });
368
+ }
369
+ static DeleteMyMediaList(listQuery, deleteByIdFn, mediaLabel) {
370
+ return __awaiter(this, void 0, void 0, function* () {
371
+ var _a, _b, _c, _d, _e;
437
372
  try {
438
373
  if (!(yield Auth.isLoggedIn())) {
439
374
  console.error(`\nPlease log in first to delete your lists.`);
440
375
  return;
441
376
  }
442
- const userId = yield Auth.MyUserId();
443
- if (!userId) {
377
+ if (!(yield Auth.MyUserId())) {
444
378
  console.error(`\nFailed getting current user Id.`);
445
379
  return;
446
380
  }
447
- const response = yield fetcher(currentUserMangaList, { id: userId });
381
+ const response = yield fetcher(listQuery, {
382
+ id: yield Auth.MyUserId(),
383
+ });
448
384
  if (!(response === null || response === void 0 ? void 0 : response.data)) {
449
385
  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}`);
450
386
  return;
451
387
  }
452
- const lists = (_e = (_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) !== null && _e !== void 0 ? _e : [];
453
- if (lists.length > 0) {
454
- const { selectedList } = yield inquirer.prompt([
455
- {
456
- type: 'select',
457
- name: 'selectedList',
458
- message: 'Select a manga list:',
459
- choices: lists.map((list) => list.name),
460
- pageSize: 10,
461
- },
462
- ]);
463
- const selectedEntries = lists.find((list) => list.name === selectedList);
464
- if (selectedEntries) {
465
- const { confirmed } = yield inquirer.prompt([
466
- {
467
- type: 'confirm',
468
- name: 'confirmed',
469
- message: `Delete all ${selectedEntries.entries.length} entries from '${selectedEntries.name}'? This cannot be undone.`,
470
- default: false,
471
- },
472
- ]);
473
- if (!confirmed) {
474
- console.log(`\nAborted.`);
475
- return;
476
- }
477
- console.log(`\nDeleting entries of '${selectedEntries.name}':`);
478
- for (const [, entry] of selectedEntries.entries.entries()) {
479
- if (entry === null || entry === void 0 ? void 0 : entry.id) {
480
- yield Auth.DeleteMangaById(entry === null || entry === void 0 ? void 0 : entry.id, (_f = entry === null || entry === void 0 ? void 0 : entry.media) === null || _f === void 0 ? void 0 : _f.title);
481
- yield new Promise((resolve) => setTimeout(resolve, 1100));
482
- }
483
- else {
484
- console.log(`No id in entry.`);
485
- console.log(entry);
486
- }
487
- }
388
+ 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;
389
+ if (!lists || lists.length === 0) {
390
+ console.error(`\nNo ${mediaLabel}(s) found in any list.`);
391
+ return;
392
+ }
393
+ const { selectedList } = yield inquirer.prompt([
394
+ {
395
+ type: 'list',
396
+ name: 'selectedList',
397
+ message: `Select a${mediaLabel === 'anime' ? 'n' : ''} ${mediaLabel} list:`,
398
+ choices: lists.map((list) => list.name),
399
+ pageSize: 10,
400
+ },
401
+ ]);
402
+ const selectedEntries = lists.find((list) => list.name === selectedList);
403
+ if (!selectedEntries) {
404
+ console.error('\nNo entries found.');
405
+ return;
406
+ }
407
+ console.log(`\nDeleting entries of '${selectedEntries.name}':`);
408
+ for (const [, entry] of selectedEntries.entries.entries()) {
409
+ if (entry === null || entry === void 0 ? void 0 : entry.id) {
410
+ yield deleteByIdFn(entry === null || entry === void 0 ? void 0 : entry.id, (_e = entry === null || entry === void 0 ? void 0 : entry.media) === null || _e === void 0 ? void 0 : _e.title);
411
+ yield sleep(1100);
488
412
  }
489
413
  else {
490
- console.error('\nNo entries found.');
414
+ console.log(`No id in entry.`);
415
+ console.log(entry);
491
416
  }
492
417
  }
493
- else {
494
- console.error(`\nNo manga(s) found in any list.`);
495
- }
496
418
  }
497
419
  catch (error) {
498
- console.error(`\nError deleting manga. ${error.message}`);
420
+ console.error(`\nError deleting ${mediaLabel}. ${error.message}`);
499
421
  }
500
422
  });
501
423
  }
502
- static DeleteMangaById(id, title) {
424
+ static DeleteMyAnimeList() {
503
425
  return __awaiter(this, void 0, void 0, function* () {
504
- var _a, _b, _c, _d;
505
- try {
506
- const response = yield fetcher(deleteMangaEntryMutation, { id });
507
- const statusMessage = title ? getTitle(title) : '';
508
- if (response === null || response === void 0 ? void 0 : response.data) {
509
- 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;
510
- console.log(`del ${statusMessage} ${deleted ? '✔' : '✘'}`);
511
- }
512
- else {
513
- console.error(`Error deleting manga. ${(_d = (_c = response === null || response === void 0 ? void 0 : response.errors) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.message}`);
514
- }
515
- }
516
- catch (error) {
517
- console.error(`Error deleting manga. ${id} ${error instanceof Error ? error.message : error}`);
518
- }
426
+ return Auth.DeleteMyMediaList(currentUserAnimeList, Auth.DeleteAnimeById, 'anime');
427
+ });
428
+ }
429
+ static DeleteMyMangaList() {
430
+ return __awaiter(this, void 0, void 0, function* () {
431
+ return Auth.DeleteMyMediaList(currentUserMangaList, Auth.DeleteMangaById, 'manga');
519
432
  });
520
433
  }
521
434
  static Write(status) {
@@ -525,15 +438,15 @@ Statistics (Manga):
525
438
  console.error(`\nPlease login to use this feature.`);
526
439
  return;
527
440
  }
528
- const response = yield fetcher(saveTextActivityMutation, {
441
+ const { data } = yield fetcher(saveTextActivityMutation, {
529
442
  status: status,
530
443
  });
531
- if (!(response === null || response === void 0 ? void 0 : response.data)) {
532
- console.error(`\nSomething went wrong.`);
444
+ if (!data) {
445
+ console.error(`\nSomething went wrong. ${data}.`);
533
446
  return;
534
447
  }
535
- if (response.data.SaveTextActivity.id) {
536
- console.log(`\n[${response.data.SaveTextActivity.id}] status saved successfully!`);
448
+ if (data.SaveTextActivity.id) {
449
+ console.log(`\n[${data.SaveTextActivity.id}] status saved successfully!`);
537
450
  }
538
451
  }
539
452
  catch (error) {
@@ -546,7 +459,7 @@ Statistics (Manga):
546
459
  try {
547
460
  const { source } = yield inquirer.prompt([
548
461
  {
549
- type: 'select',
462
+ type: 'list',
550
463
  name: 'source',
551
464
  message: 'Select a source:',
552
465
  choices: [
@@ -582,7 +495,7 @@ Statistics (Manga):
582
495
  try {
583
496
  const { source } = yield inquirer.prompt([
584
497
  {
585
- type: 'select',
498
+ type: 'list',
586
499
  name: 'source',
587
500
  message: 'Select a source:',
588
501
  choices: [
@@ -609,60 +522,405 @@ Statistics (Manga):
609
522
  }
610
523
  });
611
524
  }
612
- }
613
- class Social {
614
525
  /**
615
- * Follow the users that follows you
526
+ * Attempt to like a single activity, respecting activities that are already liked.
527
+ * Printing/counting is left to the caller since labeling conventions differ per flow.
616
528
  */
617
- static follow() {
529
+ static attemptLikeActivity(activ) {
530
+ return __awaiter(this, void 0, void 0, function* () {
531
+ if (activ.isLiked || !activ.id) {
532
+ return 'skipped';
533
+ }
534
+ try {
535
+ const like = yield fetcher(likeActivityMutation, {
536
+ activityId: activ.id,
537
+ });
538
+ return (like === null || like === void 0 ? void 0 : like.data) ? 'liked' : 'failed';
539
+ }
540
+ catch (error) {
541
+ console.error(`Activity possibly deleted. ${error.message}`);
542
+ return 'error';
543
+ }
544
+ });
545
+ }
546
+ static LikeFollowing() {
547
+ return __awaiter(this, void 0, void 0, function* () {
548
+ var _a, _b, _c, _d, _e, _f;
549
+ try {
550
+ let page = 1;
551
+ let hasMoreActivities = true;
552
+ let retryCount = 0;
553
+ const maxRetries = 5;
554
+ let likedCount = 0;
555
+ while (hasMoreActivities) {
556
+ const activities = yield fetcher(followingActivitiesQuery, {
557
+ page,
558
+ perPage: 50,
559
+ });
560
+ if (activities && ((_b = (_a = activities === null || activities === void 0 ? void 0 : activities.data) === null || _a === void 0 ? void 0 : _a.Page) === null || _b === void 0 ? void 0 : _b.activities.length) > 0) {
561
+ spinner.success(`Got ${(_d = (_c = activities === null || activities === void 0 ? void 0 : activities.data) === null || _c === void 0 ? void 0 : _c.Page) === null || _d === void 0 ? void 0 : _d.activities.length} activities..`);
562
+ retryCount = 0; // Reset retry count on successful fetch
563
+ const activiti = (_f = (_e = activities === null || activities === void 0 ? void 0 : activities.data) === null || _e === void 0 ? void 0 : _e.Page) === null || _f === void 0 ? void 0 : _f.activities;
564
+ for (let activ of activiti) {
565
+ const result = yield Auth.attemptLikeActivity(activ);
566
+ if (result === 'liked') {
567
+ likedCount++;
568
+ }
569
+ if (result === 'liked' || result === 'failed') {
570
+ responsiveOutput(`${result === 'liked' ? colorize.Green('✔') : colorize.Red('✘')} ${activityBy(activ, likedCount)}`);
571
+ }
572
+ else if (result === 'skipped') {
573
+ responsiveOutput(`${colorize.Yellow('⚉')} ${activityBy(activ, likedCount)}`);
574
+ }
575
+ // avoiding rate-limit
576
+ yield sleep(2000);
577
+ }
578
+ page++;
579
+ }
580
+ else {
581
+ if (retryCount < maxRetries) {
582
+ spinner.start('Getting activities...');
583
+ retryCount++;
584
+ spinner.update(`Empty activities returned. Retrying... (${retryCount}/${maxRetries})`);
585
+ yield sleep(2000);
586
+ }
587
+ else {
588
+ spinner.error(`Probably the end of activities after ${maxRetries} retries.`);
589
+ hasMoreActivities = false;
590
+ }
591
+ }
592
+ }
593
+ }
594
+ catch (error) {
595
+ console.error(`\nError from likeFollowing. ${error.message}`);
596
+ }
597
+ });
598
+ }
599
+ static LikeGlobal() {
600
+ return __awaiter(this, void 0, void 0, function* () {
601
+ var _a, _b, _c, _d, _e, _f;
602
+ try {
603
+ let page = 1;
604
+ let hasMoreActivities = true;
605
+ let likedCount = 0;
606
+ spinner.start(`Getting global activities...`);
607
+ while (hasMoreActivities) {
608
+ const activities = yield fetcher(globalActivitiesQuery, {
609
+ page,
610
+ perPage: 50,
611
+ });
612
+ if (activities && ((_b = (_a = activities === null || activities === void 0 ? void 0 : activities.data) === null || _a === void 0 ? void 0 : _a.Page) === null || _b === void 0 ? void 0 : _b.activities.length) > 0) {
613
+ const activiti = (_d = (_c = activities === null || activities === void 0 ? void 0 : activities.data) === null || _c === void 0 ? void 0 : _c.Page) === null || _d === void 0 ? void 0 : _d.activities;
614
+ spinner.success(`Got ${activiti.length} activities...`);
615
+ for (let activ of activiti) {
616
+ const result = yield Auth.attemptLikeActivity(activ);
617
+ if (result === 'liked' || result === 'failed') {
618
+ likedCount++;
619
+ responsiveOutput(`${result === 'liked' ? colorize.Green('✔') : colorize.Red('✘')} ${activityBy(activ, likedCount)}`);
620
+ }
621
+ else if (result === 'skipped') {
622
+ responsiveOutput(`${colorize.Yellow('⚉')} ${activityBy(activ, likedCount)}`);
623
+ }
624
+ // avoiding rate-limit
625
+ yield sleep(1500);
626
+ }
627
+ page++;
628
+ }
629
+ else {
630
+ // No more activities to like
631
+ spinner.error(`Probably the end of activities. ${(_f = (_e = activities === null || activities === void 0 ? void 0 : activities.data) === null || _e === void 0 ? void 0 : _e.Page) === null || _f === void 0 ? void 0 : _f.activities}`);
632
+ hasMoreActivities = false;
633
+ }
634
+ }
635
+ }
636
+ catch (error) {
637
+ console.error(`\nError from likeFollowing. ${error.message}`);
638
+ }
639
+ });
640
+ }
641
+ static LikeSpecificUser() {
642
+ return __awaiter(this, void 0, void 0, function* () {
643
+ var _a, _b, _c, _d;
644
+ try {
645
+ const { username } = yield inquirer.prompt([
646
+ {
647
+ type: 'input',
648
+ name: 'username',
649
+ message: 'Username of the user:',
650
+ },
651
+ ]);
652
+ const { toLikeAmount } = yield inquirer.prompt([
653
+ {
654
+ type: 'number',
655
+ name: 'toLikeAmount',
656
+ message: 'Likes to give:',
657
+ },
658
+ ]);
659
+ const userDetails = yield fetcher(userQuery, { username: username });
660
+ spinner.start(`Getting activities by ${username}`);
661
+ if ((_b = (_a = userDetails === null || userDetails === void 0 ? void 0 : userDetails.data) === null || _a === void 0 ? void 0 : _a.User) === null || _b === void 0 ? void 0 : _b.id) {
662
+ let page = 1;
663
+ const perPage = 50;
664
+ const userId = userDetails.data.User.id;
665
+ let likedCount = 0;
666
+ while (likedCount < toLikeAmount) {
667
+ const activities = yield fetcher(specificUserActivitiesQuery, {
668
+ page,
669
+ perPage,
670
+ userId,
671
+ });
672
+ const activiti = (_d = (_c = activities === null || activities === void 0 ? void 0 : activities.data) === null || _c === void 0 ? void 0 : _c.Page) === null || _d === void 0 ? void 0 : _d.activities;
673
+ if (!activiti || activiti.length === 0) {
674
+ spinner.error('No more activities found.');
675
+ break;
676
+ }
677
+ spinner.success(`Got ${activiti.length} activities...`);
678
+ for (let activ of activiti) {
679
+ const result = yield Auth.attemptLikeActivity(activ);
680
+ if (result === 'liked' || result === 'failed') {
681
+ likedCount++;
682
+ responsiveOutput(`${result === 'liked' ? colorize.Green('✔') : colorize.Red('✘')} ${activityBy(activ, likedCount)}`);
683
+ if (likedCount >= toLikeAmount) {
684
+ spinner.success(`Finished liking ${likedCount} activities of ${username}.`);
685
+ return;
686
+ }
687
+ }
688
+ else if (result === 'skipped') {
689
+ responsiveOutput(`${colorize.Yellow('⚉')} ${activityBy(activ, likedCount)}`);
690
+ }
691
+ }
692
+ page += 1;
693
+ }
694
+ }
695
+ else {
696
+ spinner.error(`User ${username} does not exist.`);
697
+ exit(1);
698
+ }
699
+ }
700
+ catch (error) {
701
+ console.error(`\nError from LikeSpecificUser. ${error.message}`);
702
+ }
703
+ });
704
+ }
705
+ static LikeFollowingActivityV2(perPage) {
618
706
  return __awaiter(this, void 0, void 0, function* () {
619
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
707
+ var _a, _b, _c, _d, _e;
620
708
  try {
621
- let pager = 1;
709
+ if (!(yield Auth.isLoggedIn())) {
710
+ console.error(`\nPlease log in to use this feature.`);
711
+ return;
712
+ }
713
+ const allFollowingUsers = [];
622
714
  let hasNextPage = true;
623
- const allFollowerUsers = [];
624
- let followedBack = 0;
625
- spinner.start('Fetching all the followers...');
715
+ let page = 1;
716
+ let liked = 0;
717
+ // ------------------------
718
+ // Fetch all following users
719
+ // ------------------------
720
+ spinner.start(`Gathering following information...`);
626
721
  while (hasNextPage) {
627
- const followerUsers = yield fetcher(userFollowersQuery, {
722
+ spinner.update(`Fetched page ${page}...`);
723
+ const followingUsers = yield fetcher(userFollowingQuery, {
628
724
  userId: yield Auth.MyUserId(),
629
- page: pager,
725
+ page,
630
726
  });
631
- spinner.update(`Fetched page ${pager} of ${(_c = (_b = (_a = followerUsers === null || followerUsers === void 0 ? void 0 : followerUsers.data) === null || _a === void 0 ? void 0 : _a.Page) === null || _b === void 0 ? void 0 : _b.pageInfo) === null || _c === void 0 ? void 0 : _c.lastPage}...`);
632
- if (!((_f = (_e = (_d = followerUsers === null || followerUsers === void 0 ? void 0 : followerUsers.data) === null || _d === void 0 ? void 0 : _d.Page) === null || _e === void 0 ? void 0 : _e.pageInfo) === null || _f === void 0 ? void 0 : _f.hasNextPage)) {
633
- hasNextPage = false;
727
+ if (!((_b = (_a = followingUsers === null || followingUsers === void 0 ? void 0 : followingUsers.data) === null || _a === void 0 ? void 0 : _a.Page) === null || _b === void 0 ? void 0 : _b.following)) {
728
+ console.error(`\nFailed to fetch following users.`);
729
+ return;
730
+ }
731
+ allFollowingUsers.push(...followingUsers.data.Page.following);
732
+ hasNextPage = followingUsers.data.Page.pageInfo.hasNextPage;
733
+ page++;
734
+ }
735
+ spinner.stop(`Got ${allFollowingUsers.length} following user.`);
736
+ // Extract the IDs of all following users
737
+ const followingUserIds = allFollowingUsers.map((user) => user.id);
738
+ // --------------------
739
+ // APPROXIMATE TIME
740
+ // --------------------
741
+ const totalActivities = followingUserIds.length * perPage;
742
+ const perActivityTimeInSec = 1;
743
+ const rateLimitTimeInSec = 60;
744
+ const batchSize = 29;
745
+ const batches = Math.floor(totalActivities / batchSize);
746
+ const remaining = totalActivities % batchSize;
747
+ const processingTime = batches * batchSize * perActivityTimeInSec +
748
+ remaining * perActivityTimeInSec;
749
+ const waitTime = (batches - 1) * rateLimitTimeInSec;
750
+ const totalWaitTimeInSec = processingTime + (batches > 0 ? waitTime : 0);
751
+ const hours = Math.floor(totalWaitTimeInSec / 3600);
752
+ const minutes = Math.floor((totalWaitTimeInSec % 3600) / 60);
753
+ const seconds = totalWaitTimeInSec % 60;
754
+ const time = `${String(hours).padStart(2, '0')}h ${String(minutes).padStart(2, '0')}m ${String(seconds).padStart(2, '0')}s`;
755
+ console.log(`\nTotal following: ${followingUserIds.length}\nApproximately ${totalActivities} to like.\nWill take around ${time}`);
756
+ // -------------------
757
+ // Traverse the array and
758
+ // fetch users' activities one by one
759
+ // -------------------
760
+ let userNumber = 0;
761
+ for (const userId of followingUserIds) {
762
+ userNumber++;
763
+ console.log(`\n[${userNumber}]\tID: ${userId}`);
764
+ // Fetch `perPage` activities for the current user
765
+ const activities = yield fetcher(specificUserActivitiesQuery, {
766
+ userId,
767
+ page: 1, // Always fetch from the first page
768
+ perPage,
769
+ });
770
+ if (!((_e = (_d = (_c = activities === null || activities === void 0 ? void 0 : activities.data) === null || _c === void 0 ? void 0 : _c.Page) === null || _d === void 0 ? void 0 : _d.activities) === null || _e === void 0 ? void 0 : _e.length)) {
771
+ console.log(`[${userNumber}] No activities found for User ID: ${userId}`);
772
+ continue;
773
+ }
774
+ const activiti = activities.data.Page.activities;
775
+ for (let i = 0; i < activiti.length; i++) {
776
+ const activ = activiti[i];
777
+ const result = yield Auth.attemptLikeActivity(activ);
778
+ if (result === 'liked' || result === 'failed') {
779
+ responsiveOutput(`${result === 'liked' ? colorize.Green('✔') : colorize.Red('✘')} ${activityBy(activ, i + 1)}`);
780
+ if (result === 'liked') {
781
+ liked++;
782
+ }
783
+ }
784
+ else if (result === 'skipped') {
785
+ responsiveOutput(`${colorize.Yellow('⚉')} ${activityBy(activ, i + 1)}`);
786
+ }
787
+ // Avoid rate-limiting
788
+ yield sleep(1200);
634
789
  }
635
- allFollowerUsers.push(...(((_h = (_g = followerUsers === null || followerUsers === void 0 ? void 0 : followerUsers.data) === null || _g === void 0 ? void 0 : _g.Page) === null || _h === void 0 ? void 0 : _h.followers) || []));
636
- pager++;
637
790
  }
791
+ console.log(`\n${colorize.Green('✔')} All ${liked} activities liked successfully.`);
792
+ }
793
+ catch (error) {
794
+ console.error(`\nError in LikeFollowingActivityV2: ${error.message}`);
795
+ }
796
+ });
797
+ }
798
+ static AutoLike() {
799
+ return __awaiter(this, void 0, void 0, function* () {
800
+ try {
801
+ if (!(yield Auth.isLoggedIn())) {
802
+ console.error(`\nPlease login to use this feature.`);
803
+ return;
804
+ }
805
+ const { activityType } = yield inquirer.prompt([
806
+ {
807
+ type: 'list',
808
+ name: 'activityType',
809
+ message: 'Select activity type:',
810
+ choices: [
811
+ { name: 'Following • v1', value: 1 },
812
+ { name: 'Following • v2', value: 2 },
813
+ { name: 'Global', value: 3 },
814
+ { name: 'Specific User', value: 4 },
815
+ ],
816
+ pageSize: 10,
817
+ },
818
+ ]);
819
+ switch (activityType) {
820
+ case 1:
821
+ yield this.LikeFollowing();
822
+ break;
823
+ case 2: {
824
+ const { count } = yield inquirer.prompt([
825
+ {
826
+ type: 'number',
827
+ name: 'count',
828
+ message: 'Likes to give:',
829
+ },
830
+ ]);
831
+ yield this.LikeFollowingActivityV2(count);
832
+ break;
833
+ }
834
+ case 3:
835
+ yield this.LikeGlobal();
836
+ break;
837
+ case 4:
838
+ yield this.LikeSpecificUser();
839
+ break;
840
+ default:
841
+ console.error(`\nInvalid choice. (${activityType})`);
842
+ }
843
+ }
844
+ catch (error) {
845
+ console.error(`\nError from autolike. ${error.message}`);
846
+ }
847
+ });
848
+ }
849
+ }
850
+ class Social {
851
+ /**
852
+ * Fetch every page of a followers/following listing for the current user.
853
+ */
854
+ static fetchAllUsers(query, extractPage) {
855
+ return __awaiter(this, void 0, void 0, function* () {
856
+ let pager = 1;
857
+ let hasNextPage = true;
858
+ const allUsers = [];
859
+ const userId = yield Auth.MyUserId();
860
+ while (hasNextPage) {
861
+ const response = yield fetcher(query, {
862
+ userId,
863
+ page: pager,
864
+ });
865
+ const page = extractPage(response);
866
+ spinner.update(`Fetched page ${pager} of ${page.lastPage}...`);
867
+ allUsers.push(...page.list);
868
+ hasNextPage = page.hasNextPage;
869
+ pager++;
870
+ }
871
+ return allUsers;
872
+ });
873
+ }
874
+ /**
875
+ * Toggle-follow a batch of users, logging the outcome of each.
876
+ */
877
+ static toggleFollowBatch(users) {
878
+ return __awaiter(this, void 0, void 0, function* () {
879
+ var _a, _b, _c, _d, _e, _f;
880
+ let toggled = 0;
881
+ const maxIdLength = Math.max(...users.map(({ id }) => String(id).length));
882
+ const maxNameLength = Math.max(...users.map(({ name }) => name.length));
883
+ for (const user of users) {
884
+ try {
885
+ const response = yield fetcher(toggleFollowMutation, { userId: user.id });
886
+ console.log(`${String(`[${user.id}]`).padEnd(maxIdLength)}\t${String(`[${(_b = (_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.ToggleFollow) === null || _b === void 0 ? void 0 : _b.name}]`).padEnd(maxNameLength)}\t${((_d = (_c = response === null || response === void 0 ? void 0 : response.data) === null || _c === void 0 ? void 0 : _c.ToggleFollow) === null || _d === void 0 ? void 0 : _d.id) ? colorize.Green('✔') : colorize.Red('✘')}`);
887
+ if ((_f = (_e = response === null || response === void 0 ? void 0 : response.data) === null || _e === void 0 ? void 0 : _e.ToggleFollow) === null || _f === void 0 ? void 0 : _f.id) {
888
+ toggled++;
889
+ }
890
+ }
891
+ catch (error) {
892
+ console.log(`toggle_follow: ${error.message}`);
893
+ }
894
+ }
895
+ return toggled;
896
+ });
897
+ }
898
+ /**
899
+ * Follow the users that follows you
900
+ */
901
+ static follow() {
902
+ return __awaiter(this, void 0, void 0, function* () {
903
+ try {
904
+ spinner.start('Fetching all the followers...');
905
+ const allFollowerUsers = yield Social.fetchAllUsers(userFollowersQuery, (response) => {
906
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
907
+ return ({
908
+ list: ((_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.followers) || [],
909
+ hasNextPage: (_f = (_e = (_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.pageInfo) === null || _e === void 0 ? void 0 : _e.hasNextPage) !== null && _f !== void 0 ? _f : false,
910
+ lastPage: (_j = (_h = (_g = response === null || response === void 0 ? void 0 : response.data) === null || _g === void 0 ? void 0 : _g.Page) === null || _h === void 0 ? void 0 : _h.pageInfo) === null || _j === void 0 ? void 0 : _j.lastPage,
911
+ });
912
+ });
638
913
  spinner.stop('Fetched all the followers. Starting follow back.');
639
914
  // Filter users that do no follow me
640
915
  const notFollowing = allFollowerUsers
641
916
  .filter(({ isFollowing }) => !isFollowing)
642
- .map(({ id, name }) => ({ id: id, name: name !== null && name !== void 0 ? name : '' }));
917
+ .map(({ id, name }) => ({ id, name }));
643
918
  console.log(`\nTotal follower ${allFollowerUsers.length}.\nNot followed back ${notFollowing.length}\n`);
644
919
  if (notFollowing.length <= 0) {
645
920
  console.log(`Probably followed back all the users.`);
646
921
  return;
647
922
  }
648
- // Traverse and follow back
649
- const maxIdLength = Math.max(...notFollowing.map(({ id }) => String(id).length));
650
- const maxNameLength = Math.max(...notFollowing.map(({ name }) => name.length));
651
- for (const nf of notFollowing) {
652
- try {
653
- const follow = yield fetcher(toggleFollowMutation, { userId: nf.id });
654
- console.log(`${String(`[${nf.id}]`).padEnd(maxIdLength)}` +
655
- `\t${String(`[${(_k = (_j = follow === null || follow === void 0 ? void 0 : follow.data) === null || _j === void 0 ? void 0 : _j.ToggleFollow) === null || _k === void 0 ? void 0 : _k.name}]`).padEnd(maxNameLength)}` +
656
- `\t${((_m = (_l = follow === null || follow === void 0 ? void 0 : follow.data) === null || _l === void 0 ? void 0 : _l.ToggleFollow) === null || _m === void 0 ? void 0 : _m.id) ? colorize.Green('✔') : colorize.Red('✘')}`);
657
- // Count the followed back users
658
- if ((_p = (_o = follow === null || follow === void 0 ? void 0 : follow.data) === null || _o === void 0 ? void 0 : _o.ToggleFollow) === null || _p === void 0 ? void 0 : _p.id) {
659
- followedBack++;
660
- }
661
- }
662
- catch (error) {
663
- console.log(`automate_follow_toggle_follow: ${error.message}`);
664
- }
665
- }
923
+ const followedBack = yield Social.toggleFollowBatch(notFollowing);
666
924
  console.log(`\n${colorize.Green('✔')} Followed back ${followedBack} users.`);
667
925
  }
668
926
  catch (error) {
@@ -675,57 +933,83 @@ class Social {
675
933
  */
676
934
  static unfollow() {
677
935
  return __awaiter(this, void 0, void 0, function* () {
678
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
679
936
  try {
680
- let pager = 1;
681
- let hasNextPage = true;
682
- const allFollowingUsers = [];
683
- let unfollowedUsers = 0;
684
937
  spinner.start('Fetching all following users...');
685
- while (hasNextPage) {
686
- const followingUsers = yield fetcher(userFollowingQuery, {
687
- userId: yield Auth.MyUserId(),
688
- page: pager,
938
+ const allFollowingUsers = yield Social.fetchAllUsers(userFollowingQuery, (response) => {
939
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
940
+ return ({
941
+ list: ((_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.following) || [],
942
+ hasNextPage: (_f = (_e = (_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.pageInfo) === null || _e === void 0 ? void 0 : _e.hasNextPage) !== null && _f !== void 0 ? _f : false,
943
+ lastPage: (_j = (_h = (_g = response === null || response === void 0 ? void 0 : response.data) === null || _g === void 0 ? void 0 : _g.Page) === null || _h === void 0 ? void 0 : _h.pageInfo) === null || _j === void 0 ? void 0 : _j.lastPage,
689
944
  });
690
- spinner.update(`Fetched page ${pager} of ${(_c = (_b = (_a = followingUsers === null || followingUsers === void 0 ? void 0 : followingUsers.data) === null || _a === void 0 ? void 0 : _a.Page) === null || _b === void 0 ? void 0 : _b.pageInfo) === null || _c === void 0 ? void 0 : _c.lastPage}...`);
691
- if (!((_f = (_e = (_d = followingUsers === null || followingUsers === void 0 ? void 0 : followingUsers.data) === null || _d === void 0 ? void 0 : _d.Page) === null || _e === void 0 ? void 0 : _e.pageInfo) === null || _f === void 0 ? void 0 : _f.hasNextPage)) {
692
- hasNextPage = false;
693
- }
694
- allFollowingUsers.push(...(((_h = (_g = followingUsers === null || followingUsers === void 0 ? void 0 : followingUsers.data) === null || _g === void 0 ? void 0 : _g.Page) === null || _h === void 0 ? void 0 : _h.following) || []));
695
- pager++;
696
- }
697
- spinner.update(`${colorize.Green('✔')} Fetching complete. Total got ${allFollowingUsers.length} users.`);
945
+ });
946
+ spinner.update(`Fetching complete. Total got ${allFollowingUsers.length} users.`);
698
947
  // Filter users that do no follow me
699
948
  const notFollowingMe = allFollowingUsers
700
949
  .filter((user) => !user.isFollower)
701
- .map((u3r) => { var _a; return ({ id: u3r.id, name: (_a = u3r.name) !== null && _a !== void 0 ? _a : '' }); });
950
+ .map(({ id, name }) => ({ id, name }));
702
951
  if (notFollowingMe.length <= 0) {
703
952
  spinner.stop(`No users to unfollow. Exiting operation...`);
704
953
  return;
705
954
  }
706
955
  spinner.stop(`Unfollow process activated with ${notFollowingMe.length} users.`);
707
- let nfmCount = 0;
708
956
  console.log(`\n`);
709
- for (const nfm of notFollowingMe) {
710
- nfmCount++;
711
- try {
712
- const unfollow = yield fetcher(toggleFollowMutation, {
713
- userId: nfm.id,
714
- });
715
- console.log(`[${nfm.id}]\t[${(_k = (_j = unfollow === null || unfollow === void 0 ? void 0 : unfollow.data) === null || _j === void 0 ? void 0 : _j.ToggleFollow) === null || _k === void 0 ? void 0 : _k.name}]\t${((_m = (_l = unfollow === null || unfollow === void 0 ? void 0 : unfollow.data) === null || _l === void 0 ? void 0 : _l.ToggleFollow) === null || _m === void 0 ? void 0 : _m.id) ? colorize.Green('✔') : colorize.Red('✘')}`);
716
- // Count the unfollowed users
717
- if ((_p = (_o = unfollow === null || unfollow === void 0 ? void 0 : unfollow.data) === null || _o === void 0 ? void 0 : _o.ToggleFollow) === null || _p === void 0 ? void 0 : _p.id) {
718
- unfollowedUsers++;
719
- }
720
- }
721
- catch (error) {
722
- console.log(`unfollow_toggle_follow. ${error.message}`);
957
+ const unfollowedUsers = yield Social.toggleFollowBatch(notFollowingMe);
958
+ console.log(`\n${colorize.Green('✔')} Total Unfollowed: ${unfollowedUsers} of ${notFollowingMe.length} users.`);
959
+ }
960
+ catch (error) {
961
+ console.error(`\nautomate_unfollow: ${error.message}`);
962
+ }
963
+ });
964
+ }
965
+ /**
966
+ * Unfollow the users you follow who haven't posted any activity in the
967
+ * given number of months, to help clear out stale/inactive accounts.
968
+ */
969
+ static unfollowInactive(months) {
970
+ return __awaiter(this, void 0, void 0, function* () {
971
+ var _a, _b, _c, _d;
972
+ try {
973
+ if (!Number.isFinite(months) || months <= 0) {
974
+ console.error(`\nMust provide a positive number of months.`);
975
+ return;
976
+ }
977
+ spinner.start('Fetching all following users...');
978
+ const allFollowingUsers = yield Social.fetchAllUsers(userFollowingQuery, (response) => {
979
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
980
+ return ({
981
+ list: ((_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.following) || [],
982
+ hasNextPage: (_f = (_e = (_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.pageInfo) === null || _e === void 0 ? void 0 : _e.hasNextPage) !== null && _f !== void 0 ? _f : false,
983
+ lastPage: (_j = (_h = (_g = response === null || response === void 0 ? void 0 : response.data) === null || _g === void 0 ? void 0 : _g.Page) === null || _h === void 0 ? void 0 : _h.pageInfo) === null || _j === void 0 ? void 0 : _j.lastPage,
984
+ });
985
+ });
986
+ spinner.stop(`Fetched ${allFollowingUsers.length} following user(s). Checking their last activity...`);
987
+ const cutoff = Math.floor(Date.now() / 1000) - months * 30 * 24 * 60 * 60;
988
+ const staleUsers = [];
989
+ let checked = 0;
990
+ for (const user of allFollowingUsers) {
991
+ checked++;
992
+ const activityResponse = yield fetcher(specificUserActivitiesQuery, { userId: user.id, page: 1, perPage: 1 });
993
+ const lastActiveAt = (_d = (_c = (_b = (_a = activityResponse === null || activityResponse === void 0 ? void 0 : activityResponse.data) === null || _a === void 0 ? void 0 : _a.Page) === null || _b === void 0 ? void 0 : _b.activities) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.createdAt;
994
+ responsiveOutput(`[${checked}/${allFollowingUsers.length}]\t${user.name}\t${lastActiveAt
995
+ ? timestampToTimeAgo(lastActiveAt)
996
+ : 'no activity found'}`);
997
+ if (!lastActiveAt || lastActiveAt < cutoff) {
998
+ staleUsers.push({ id: user.id, name: user.name });
723
999
  }
1000
+ // avoiding rate-limit
1001
+ yield sleep(1100);
1002
+ }
1003
+ console.log(`\nFound ${staleUsers.length} user(s) inactive for ${months}+ month(s).`);
1004
+ if (staleUsers.length <= 0) {
1005
+ console.log(`No stale accounts to unfollow.`);
1006
+ return;
724
1007
  }
725
- console.log(`\nTotal Unfollowed: ${unfollowedUsers} of ${nfmCount} users.`);
1008
+ const unfollowedUsers = yield Social.toggleFollowBatch(staleUsers);
1009
+ console.log(`\n${colorize.Green('✔')} Unfollowed ${unfollowedUsers} of ${staleUsers.length} inactive user(s).`);
726
1010
  }
727
1011
  catch (error) {
728
- console.error(`\nautomate_unfollow: ${error.message}`);
1012
+ console.error(`\nautomate_unfollow_inactive: ${error.message}`);
729
1013
  }
730
1014
  });
731
1015
  }