Files
django-tinywiki/tinywiki/management/commands/twimport.py

83 lines
2.6 KiB
Python

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 = "Import 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']).resolve()
print(f"Importing from {file} ...")
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)