From 3fbe3a0b9359b09a5f277cb2d27d5b6df13832b7 Mon Sep 17 00:00:00 2001 From: anbosuki Date: Mon, 4 Jul 2022 19:22:35 +0200 Subject: [PATCH] cli-delete-posts Added the possibility to delete single posts or a range of multiple posts at once using the command as following:
`docker-compose run server ./szuru-admin --delete posts 35 36 40-45`
Each space represents a single post id, using a `-` between two ids will delete all posts within range, including the first and the last one --- server/szuru-admin | 52 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/server/szuru-admin b/server/szuru-admin index 08ba1827..be743227 100755 --- a/server/szuru-admin +++ b/server/szuru-admin @@ -13,7 +13,7 @@ from getpass import getpass from sys import stderr from szurubooru import config, db, errors, model -from szurubooru.func import files, images +from szurubooru.func import files, images, snapshots from szurubooru.func import posts as postfuncs from szurubooru.func import users as userfuncs @@ -100,6 +100,48 @@ def regenerate_thumbnails() -> None: pass +def delete_posts(parameters: list) -> None: + verification: str = "y" + + while "" == verification: + verification = input("Do you really want to delete all posts with the given ID's [y/n]: ") + + if "y" != verification.lower(): + return + + def delete_one_post(post_id: int) -> None: + print("Deleting post %d" % post_id) + + try: + post: model.Post = postfuncs.get_post_by_id(post_id) + except postfuncs.PostNotFoundError: + print("Post with ID %d not found" % post_id) + return + + postfuncs.delete(post) + snapshots.delete(post, None) + + def delete_multiple_posts(start_id: int, end_id: int) -> None: + for post_id in range(start_id, end_id + 1): + delete_one_post(post_id) + + for parameter in parameters: + try: + if "-" not in parameter: + delete_one_post(int(parameter)) + continue + + post_range: list = [int(number) for number in parameter.split("-", 2)] + delete_multiple_posts(*post_range) + except ValueError: + print("One of the specified parameters is not a number") + return + + db.get_session().commit() + + print("All posts were deleted") + + def main() -> None: parser_top = ArgumentParser( description="Collection of CLI commands for an administrator to use", @@ -129,6 +171,12 @@ def main() -> None: help="regenerate the thumbnails for posts if the " "thumbnail files are missing", ) + parser.add_argument( + "--delete-posts", + metavar="", + nargs='+', + help="Will delete all posts with the given id's" + ) command = parser_top.parse_args() try: @@ -140,6 +188,8 @@ def main() -> None: reset_filenames() elif command.regenerate_thumbnails: regenerate_thumbnails() + elif command.delete_posts: + delete_posts(command.delete_posts) except errors.BaseError as e: print(e, file=stderr)