From b820cfb740b715c07cbf6e8892650fd2995ebefd Mon Sep 17 00:00:00 2001 From: Christian Moser Date: Sat, 27 Dec 2025 13:18:56 +0100 Subject: [PATCH] 2025.12.27 13:18:56 (cachyos.cmoser.eu) --- tinywiki/management/commands/twimport.py | 81 ++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 tinywiki/management/commands/twimport.py diff --git a/tinywiki/management/commands/twimport.py b/tinywiki/management/commands/twimport.py new file mode 100644 index 0000000..dec5881 --- /dev/null +++ b/tinywiki/management/commands/twimport.py @@ -0,0 +1,81 @@ +from django.core.management.base import BaseCommand, CommandError # noqa +from django.contrib.auth import get_user_model +import zipfile +import json + +from pathlib import Path + +from ...utils import ( + import_builtin_pages, + import_builtin_pages_from_zip, + import_builtin_images, + import_builtin_images_from_zip +) + + +class Command(BaseCommand): + help = "Export wiki content for an app" + + def add_arguments(self, parser): + parser.add_argument("file", nargs=1, type=str) + parser.add_argument("--username", type=str) + parser.add_argument("--email", type=str) + + def handle(self, *args, **options): + if not options['file']: + raise CommandError("No file to import specified") + + file = Path(options['file'][0]).resolve() + + if not file.exists(): + raise CommandError("File does not exist!") + if not file.is_file(): + raise CommandError("Not a file!") + + username = options['username'] + email = options['email'] + + user = None + UserModel = get_user_model() + if username: + try: + user = UserModel.objects.get(username=username) + except UserModel.DoesNotExist: + raise CommandError(f"No user with username {username} exists.") + elif email: + try: + user = UserModel.objects.get(email=email) + except UserModel.DoesNotExist: + raise CommandError(f"No user with email {email} exists.") + + + if zipfile.is_zipfile(file): + with zipfile.ZipFile(file, "r") as zf: + znames = zf.namelist() + has_pages = 'pages.json' in znames + has_images = 'images.json' in znames + + if not has_images and not has_pages: + raise CommandError("Not a valid zipfile!") + + if has_pages: + import_builtin_pages_from_zip(zip, user) + if has_images: + import_builtin_images_from_zip(zip, user) + else: + with open(file, "rt", encoding="utf-8") as json_file: + try: + json_data = json.loads(json_file.read()) + except Exception: + raise CommandError("Given file is not a zip file or json file!") + + has_images = 'images' in json_data + has_pages = 'pages' in json_data + + if not has_images and not has_pages: + raise CommandError("Not a valid json file!") + + if has_images: + import_builtin_images(file) + if has_pages: + import_builtin_pages(file)