prune.d 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. /*
  2. * pixiv_down - CLI-based downloading tool for https://www.pixiv.net.
  3. * Copyright (C) 2024 Mio
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, version 3 of the License.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. module app.cmds.prune;
  18. import pd.configuration: Config;
  19. import pd.pixiv;
  20. public void displayPruneHelp()
  21. {
  22. import std.stdio : stderr;
  23. stderr.writefln(
  24. "pixiv_down prune - Prune previously followed accounts.\n" ~
  25. "usage: pixiv_down prune [options]\n" ~
  26. "\n" ~
  27. "The prune command walks through all existing directories containing\n"~
  28. "content from followed accounts. It then checks if you are still\n"~
  29. "following that account (or if the account still exists). If either\n"~
  30. "of these are not true, pixiv_down will prompt to move the directory\n"~
  31. "to the recycle bin.\n" ~
  32. "\n" ~
  33. "Options:\n" ~
  34. " -n, --dry-run \tPrint the directories that would be moved,\n" ~
  35. " \tbut do not actually move them.\n" ~
  36. " -q, --quiet \tDo not prompt to confirm deleting of files.\n" ~
  37. " -s, --silent \tSynonym of --quiet.\n" ~
  38. " -h, --help \tDisplay this help message and exit.\n");
  39. }
  40. public int pruneHandle(string[] args, in Config config)
  41. {
  42. import std.experimental.logger;
  43. import std.getopt : getopt, GetOptException, GetOptOption = config;
  44. import std.stdio : stderr;
  45. Options options;
  46. try {
  47. auto helpInformation = getopt(args,
  48. GetOptOption.bundling,
  49. "quiet|q|silent|s", &options.quiet,
  50. "dry-run|n", &options.dry_run);
  51. if (helpInformation.helpWanted) {
  52. displayPruneHelp();
  53. return 0;
  54. }
  55. } catch (GetOptException e) {
  56. stderr.writefln("pixiv_down prune: %s", e.msg);
  57. stderr.writefln("Run 'pixiv_down help prune' for more information.");
  58. return 1;
  59. }
  60. if (options.dry_run && options.quiet) {
  61. return 0;
  62. }
  63. infof("running `prune` quietly? %s", options.quiet);
  64. return runPrune(config, options);
  65. }
  66. private:
  67. // TODO: use std.sumtype
  68. struct Result(T)
  69. {
  70. ErrorKind error;
  71. T result;
  72. }
  73. enum ErrorKind
  74. {
  75. None,
  76. UserNotFound,
  77. UserNotFollowed,
  78. PixivError,
  79. UnknownError
  80. }
  81. struct Options
  82. {
  83. bool quiet;
  84. bool dry_run;
  85. }
  86. void reportProgress(long total, long current)
  87. {
  88. import mlib.term: Term;
  89. import std.format: format;
  90. import std.stdio: stdout;
  91. Term.clearCurrentLine();
  92. const ratioCompleted = cast(double)current / total;
  93. const prefix = format!"%d ["(current);
  94. const suffix = format!"] %3.0f%%"(ratioCompleted * 100);
  95. const barLength = Term.getColumnCount() - prefix.length - suffix.length;
  96. stdout.write(prefix);
  97. foreach(i; 0..barLength) {
  98. stdout.write(i < (ratioCompleted * barLength) ? '#' : ' ');
  99. }
  100. stdout.write(suffix);
  101. stdout.flush();
  102. }
  103. Result!(User[]) fetchFollowing(bool forPrivate, in Config config)
  104. {
  105. import pd.pixiv : p_fetchFolloing = fetchFollowing;
  106. import std.experimental.logger;
  107. User[] users;
  108. long total;
  109. const visibility = forPrivate ? "private" : "public";
  110. // Fetch public accounts.
  111. long offset = 0;
  112. do {
  113. try {
  114. User[] page = p_fetchFolloing(forPrivate, offset, total, config);
  115. if (page.length == 0) {
  116. tracef("early finish fetching %s followed accounts.", visibility);
  117. break;
  118. }
  119. offset += page.length;
  120. users ~= page;
  121. reportProgress(total, offset);
  122. } catch (PixivException e) {
  123. errorf("Failed to fetch %s following: %s", visibility, e.msg);
  124. return Result!(User[])(ErrorKind.PixivError);
  125. } catch (Exception e) {
  126. errorf("Unknown error when fetching %s following: %s", visibility, e.msg);
  127. return Result!(User[])(ErrorKind.UnknownError);
  128. }
  129. } while (offset < total);
  130. return Result!(User[])(ErrorKind.None, users);
  131. }
  132. /// adhoc set implementation using assocArray.
  133. class Set(E)
  134. {
  135. private void[0][E] data;
  136. void add(E e)
  137. {
  138. data.require(e);
  139. }
  140. E[] toArray() const
  141. {
  142. return data.keys;
  143. }
  144. size_t length() const
  145. {
  146. return data.length;
  147. }
  148. }
  149. struct UserPair
  150. {
  151. string id;
  152. string displayName;
  153. bool valid;
  154. }
  155. Set!string findMissingIds(User[] users, string outputDirectory)
  156. {
  157. import std.algorithm : countUntil, map;
  158. import std.ascii : isDigit;
  159. import std.experimental.logger;
  160. import std.file : SpanMode, dirEntries;
  161. import std.path : baseName;
  162. import std.string : split;
  163. Set!string missingIds = new Set!string();
  164. auto userIds = users.map!(u => u.id);
  165. foreach(dir; dirEntries(outputDirectory, SpanMode.shallow)) {
  166. const bname = baseName(dir);
  167. if (bname.length <= 0 || false == isDigit(bname[0])) {
  168. continue;
  169. }
  170. const id = bname.split('_')[0];
  171. if (userIds.countUntil(id) == -1) {
  172. infof("adding missing ID %s", id);
  173. missingIds.add(id);
  174. }
  175. }
  176. return missingIds;
  177. }
  178. Set!UserPair retrieveAccountInfo(in Set!string userIds, in Config conf)
  179. {
  180. import app.util: sleep;
  181. import std.experimental.logger;
  182. import std.json : JSONException;
  183. import pd.pixiv;
  184. Set!UserPair pairs;
  185. string[] ids = userIds.toArray();
  186. pairs = new Set!UserPair();
  187. foreach(index, id; ids) {
  188. try {
  189. auto user = fetchUser(id, conf);
  190. pairs.add(UserPair(id, user.userName, true));
  191. } catch (JSONException e) {
  192. // User does not exist.
  193. pairs.add(UserPair(id, "", false));
  194. } catch (Exception e) {
  195. errorf("failed to fetch user ID %s: %s", id, e.msg);
  196. }
  197. displayProgress(index, ids.length, "Retrieving account information");
  198. sleep(2, 4, false);
  199. }
  200. return pairs;
  201. }
  202. void displayProgress(ulong through, ulong total, string message = "")
  203. {
  204. import std.stdio : stderr;
  205. auto percent = (cast(float)through / total) * 100.0;
  206. message = (message == "") ? "Progress" : message;
  207. stderr.writef("\r\033[2K%s: %d/%d (%3.2f%%)", message, through, total,
  208. percent);
  209. stderr.flush();
  210. }
  211. int runPrune(in Config config, in Options options)
  212. {
  213. import app.util: sleep;
  214. import mlib.term;
  215. import std.stdio: stdout, stderr;
  216. int success;
  217. if (options.quiet) {
  218. auto publicAccts = fetchFollowing(false, config);
  219. if (publicAccts.error != ErrorKind.None) {
  220. return 1;
  221. }
  222. auto privateAccts = fetchFollowing(true, config);
  223. if (privateAccts.error != ErrorKind.None) {
  224. return 1;
  225. }
  226. auto users = publicAccts.result ~ privateAccts.result;
  227. auto missingIds = findMissingIds(users, config.outputDirectory);
  228. foreach(id; missingIds.toArray()) {
  229. success |= remove(id, config.outputDirectory, options.dry_run);
  230. }
  231. return success;
  232. }
  233. stdout.writeln("Retrieving public following account list...");
  234. Result!(User[]) publicAccts = fetchFollowing(/* forPrivate */ false, config);
  235. if (publicAccts.error != ErrorKind.None) {
  236. stderr.writefln("Failed to retrieve public followed accounts: %s", publicAccts.error);
  237. return 1;
  238. }
  239. Term.clearCurrentLine();
  240. Term.goUpAndClearLine(1);
  241. stdout.writeln("Fetched public followed accounts.");
  242. sleep(1, 10, false);
  243. stdout.writeln("Retrieving private following account list...");
  244. Result!(User[]) privateAccts = fetchFollowing(/* forPrivate */ true, config);
  245. if (privateAccts.error != ErrorKind.None) {
  246. stderr.writefln("Failed to retrieve private followed accounts: %s", privateAccts.error);
  247. }
  248. Term.clearCurrentLine();
  249. Term.goUpAndClearLine(1);
  250. stdout.writeln("Fetched private followed accounts.");
  251. User[] users = publicAccts.result ~ privateAccts.result;
  252. auto missingIds = findMissingIds(users, config.outputDirectory);
  253. auto missingAccounts = retrieveAccountInfo(missingIds, config);
  254. Term.goUpAndClearLine(1);
  255. foreach(account; missingAccounts.toArray()) {
  256. auto result = removeAccount(account, config, options.dry_run);
  257. success |= result.success;
  258. /* Clear last two lines */
  259. Term.goUpAndClearLine(1, Yes.useStderr);
  260. Term.goUpAndClearLine(1, Yes.useStderr);
  261. if (result.accountRemoved && !options.dry_run) {
  262. if (account.valid) {
  263. stdout.writefln("Removed directories for %s", account.displayName);
  264. } else {
  265. stdout.writefln("Removed directories for ID %s", account.id);
  266. }
  267. } else if (result.accountRemoved && options.dry_run) {
  268. if (account.valid) {
  269. stdout.writefln("Would have removed directories for %s", account.displayName);
  270. } else {
  271. stdout.writefln("Would have removed directories for ID %s", account.id);
  272. }
  273. }
  274. }
  275. return success;
  276. }
  277. bool prompt(string msg)
  278. {
  279. import std.stdio : readln, writef;
  280. import std.string : toLower, strip;
  281. writef("%s [y/N]: ", msg);
  282. string res = readln.strip.toLower();
  283. if (res == "yes" || res == "y") {
  284. return true;
  285. }
  286. return false;
  287. }
  288. struct RemoveAccountReturn
  289. {
  290. /// Did the process execute successfully.
  291. bool success;
  292. /// Were any directories removed?
  293. bool accountRemoved;
  294. }
  295. RemoveAccountReturn removeAccount(UserPair user, in Config config, bool dryRun)
  296. {
  297. import std.experimental.logger;
  298. import std.stdio : writefln;
  299. bool removed = false;
  300. immutable promptMessage = dryRun ?
  301. "Would you want to remove their directories?" :
  302. "Do you want to remove their directories?";
  303. tracef("checkAndRemove(UserPair(%s, %s, %d))", user.id, user.displayName, user.valid);
  304. if (user.valid) {
  305. writefln("Not following %s (ID %s)", user.displayName, user.id);
  306. if (prompt(promptMessage)) {
  307. removed = remove(user.id, config.outputDirectory, dryRun) == 0;
  308. }
  309. return RemoveAccountReturn(true, removed);
  310. }
  311. writefln("User with ID %s has left pixiv.", user.id);
  312. if (prompt(promptMessage)) {
  313. removed = remove(user.id, config.outputDirectory, dryRun) == 0;
  314. }
  315. return RemoveAccountReturn(true, removed);
  316. }
  317. /// Remove all directories matching the pattern `id_` within the
  318. /// directory *baseDirectory*.
  319. ///
  320. /// If *dryRun* is `true`, no directories will be removed.
  321. int remove(string id, string baseDirectory, bool dryRun)
  322. {
  323. import std.file : SpanMode, dirEntries;
  324. import mlib.trash : trash;
  325. immutable pattern = id ~ "_*";
  326. if (dryRun) {
  327. return 0;
  328. }
  329. foreach(dir; dirEntries(baseDirectory, pattern, SpanMode.shallow)) {
  330. trash(dir);
  331. }
  332. return 0;
  333. }