mirror of
https://gitlab.crans.org/mediatek/med.git
synced 2024-11-27 02:13:07 +00:00
94 lines
3.4 KiB
Python
94 lines
3.4 KiB
Python
from argparse import FileType
|
|
from sys import stdin
|
|
|
|
from django.core.exceptions import ValidationError
|
|
from django.core.management import BaseCommand
|
|
|
|
from media.models import BD, FutureMedia, Manga, Roman
|
|
from media.validators import isbn_validator
|
|
|
|
|
|
class Command(BaseCommand):
|
|
def add_arguments(self, parser):
|
|
parser.add_argument('--media-type',
|
|
type=str,
|
|
default='bd',
|
|
choices=[
|
|
'bd',
|
|
'manga',
|
|
'roman',
|
|
],
|
|
help="Type of media to be "
|
|
"imported.")
|
|
parser.add_argument('input', nargs='?',
|
|
type=FileType('r'),
|
|
default=stdin,
|
|
help="ISBN to be imported.")
|
|
|
|
def handle(self, *args, **options):
|
|
type_str = options["media_type"]
|
|
|
|
media_classes = [BD, Manga, Roman, FutureMedia]
|
|
|
|
file = options["input"]
|
|
isbns = []
|
|
for line in file:
|
|
isbns.append(line[:-1])
|
|
|
|
print("Registering", len(isbns), "ISBN")
|
|
|
|
imported = 0
|
|
not_imported = []
|
|
|
|
for isbn in isbns:
|
|
if not isbn:
|
|
continue
|
|
|
|
try:
|
|
if not isbn_validator(isbn):
|
|
raise ValidationError(
|
|
"This ISBN is invalid for an unknown reason")
|
|
except ValidationError as e:
|
|
self.stderr.write(self.style.ERROR(
|
|
"The following ISBN is invalid:"
|
|
" {isbn}, reason: {reason}. Ignoring...".format(
|
|
isbn=isbn, reason=e.message)))
|
|
|
|
isbn_exists = False
|
|
for cl in media_classes:
|
|
if cl.objects.filter(isbn=isbn).exists():
|
|
isbn_exists = True
|
|
medium = cl.objects.get(isbn=isbn)
|
|
self.stderr.write(self.style.WARNING(
|
|
("Warning: ISBN {isbn} already exists, and is "
|
|
+ "registered as type {type}: {name}. Ignoring...")
|
|
.format(isbn=isbn,
|
|
name=str(medium),
|
|
type=str(cl._meta.verbose_name))))
|
|
not_imported.append(medium)
|
|
break
|
|
|
|
if isbn_exists:
|
|
continue
|
|
|
|
FutureMedia.objects.create(isbn=isbn, type=type_str)
|
|
self.stdout.write(self.style.SUCCESS("ISBN {isbn} imported"
|
|
.format(isbn=isbn)))
|
|
imported += 1
|
|
|
|
self.stdout.write(self.style.SUCCESS("{count} media imported"
|
|
.format(count=imported)))
|
|
|
|
with open('not_imported_media.csv', 'w') as f:
|
|
f.write("isbn|type|title\n")
|
|
for medium in not_imported:
|
|
if not hasattr(medium, 'title') or not medium.title:
|
|
medium.title = ''
|
|
f.write(medium.isbn + "|"
|
|
+ str(medium._meta.verbose_name)
|
|
+ "|" + medium.title + "\n")
|
|
|
|
self.stderr.write(self.style.WARNING(("{count} media already "
|
|
+ "imported").format(
|
|
count=len(not_imported))))
|