# Path: books/models.py
# class Author(models.Model):
#     a_author = models.CharField('atom:author', max_length=200, unique=True)
# 
#     def __unicode__(self):
#         return self.a_author
# 
#     def __str__(self):
#         return self.a_author
# 
# class Book(models.Model):
#     """
#     This model stores the book file, and all the metadata that is
#     needed to publish it in a OPDS atom feed.
# 
#     It also stores other information, like tags and downloads, so the
#     book can be listed in OPDS catalogs.
# 
#     """
#     book_file = models.FileField(upload_to='books')
#     file_sha256sum = models.CharField(max_length=64, unique=True)
#     mimetype = models.CharField(max_length=200, null=True)
#     time_added = models.DateTimeField(auto_now_add=True)
#     tags = TaggableManager(blank=True)
#     downloads = models.IntegerField(default=0)
#     a_id = UUIDField('atom:id')
#     a_status = models.ForeignKey(Status, blank=False, null=False, default=settings.DEFAULT_BOOK_STATUS)
#     a_title = models.CharField('atom:title', max_length=200)
#     a_author = models.ForeignKey(Author, blank=False, null=False)
#     a_updated = models.DateTimeField('atom:updated', auto_now=True)
#     a_summary = models.TextField('atom:summary', blank=True)
#     a_category = models.CharField('atom:category', max_length=200, blank=True)
#     a_rights = models.CharField('atom:rights', max_length=200, blank=True)
#     dc_language = models.ForeignKey(Language, blank=True, null=True)
#     dc_publisher = models.CharField('dc:publisher', max_length=200, blank=True)
#     dc_issued = models.CharField('dc:issued', max_length=100, blank=True)
#     dc_identifier = models.CharField('dc:identifier', max_length=50, \
#     help_text='Use ISBN for this', blank=True)
#     cover_img = models.FileField(blank=True, upload_to='covers')
# 
#     def validate_unique(self, *args, **kwargs):
#         if not self.file_sha256sum:
#             self.file_sha256sum = sha256_sum(self.book_file)
#         unicity = self.__class__.objects.filter(file_sha256sum=self.file_sha256sum)
#         if self.pk is not None:
#             unicity = unicity.exclude(pk=self.pk)
#         if unicity.exists():
#             raise ValidationError({
#                 NON_FIELD_ERRORS:['The book already exists in the server.',]})
# 
#     def save(self, *args, **kwargs):
#         assert self.file_sha256sum
#         if not self.cover_img:
#             # FIXME: we should use mimetype
#             if self.book_file.name.endswith('.epub'):
#                 # get the cover path from the epub file
#                 epub_file = Epub(self.book_file)
#                 cover_path = epub_file.get_cover_image_path()
#                 if cover_path is not None and os.path.exists(cover_path):
#                     cover_file = File(open(cover_path, "rb"))
#                     self.cover_img.save(os.path.basename(cover_path), # pylint: disable=no-member
#                                         cover_file)
#                 epub_file.close()
# 
#         super(Book, self).save(*args, **kwargs)
# 
#     class Meta:
#         ordering = ('-time_added',)
#         get_latest_by = "time_added"
# 
#     def __unicode__(self):
#         return self.a_title
# 
#     def __str__(self):
#         return self.a_title
# 
#     @models.permalink
#     def get_absolute_url(self):
#         return ('book_detail', [self.pk])
# 
# class Status(models.Model):
#     status = models.CharField(max_length=200, blank=False)
# 
#     class Meta:
#         verbose_name_plural = "Status"
# 
#     def __unicode__(self):
#         return self.status
# 
#     def __str__(self):
#         return self.status


from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ValidationError
from django.core.files import File
from django.db import transaction
from django.db.utils import IntegrityError
from optparse import make_option
from books.models import Author, Book, Status
import csv
import json
import logging
import os
import sys
                continue

            # Skip unless there is book content
            if not os.path.exists(d['book_path']):
                stats['skipped'] += 1
                continue

            # Get a Django File from the given path:
            f = open(d['book_path'], 'rb')
            d['book_file'] = File(f)
            del d['book_path']

            if 'cover_path' in d:
                f_cover = open(d['cover_path'], 'rb')
                d['cover_img'] = File(f_cover)
                del d['cover_path']

            if 'a_status' in d:
                d['a_status'] = Status.objects.get(status=d['a_status'])
            else:
                d['a_status'] = status_published

            a_author = None
            if 'a_author' in d:
                d['a_author'] = Author.objects.get_or_create(a_author=d['a_author'])[0]

            tags = d.get('tags', [])
            if 'tags' in d:
                del d['tags']


# Path: books/models.py
# class Author(models.Model):
#     a_author = models.CharField('atom:author', max_length=200, unique=True)
# 
#     def __unicode__(self):
#         return self.a_author
# 
#     def __str__(self):
#         return self.a_author
# 
# class Book(models.Model):
#     """
#     This model stores the book file, and all the metadata that is
#     needed to publish it in a OPDS atom feed.
# 
#     It also stores other information, like tags and downloads, so the
#     book can be listed in OPDS catalogs.
# 
#     """
#     book_file = models.FileField(upload_to='books')
#     file_sha256sum = models.CharField(max_length=64, unique=True)
#     mimetype = models.CharField(max_length=200, null=True)
#     time_added = models.DateTimeField(auto_now_add=True)
#     tags = TaggableManager(blank=True)
#     downloads = models.IntegerField(default=0)
#     a_id = UUIDField('atom:id')
#     a_status = models.ForeignKey(Status, blank=False, null=False, default=settings.DEFAULT_BOOK_STATUS)
#     a_title = models.CharField('atom:title', max_length=200)
#     a_author = models.ForeignKey(Author, blank=False, null=False)
#     a_updated = models.DateTimeField('atom:updated', auto_now=True)
#     a_summary = models.TextField('atom:summary', blank=True)
#     a_category = models.CharField('atom:category', max_length=200, blank=True)
#     a_rights = models.CharField('atom:rights', max_length=200, blank=True)
#     dc_language = models.ForeignKey(Language, blank=True, null=True)
#     dc_publisher = models.CharField('dc:publisher', max_length=200, blank=True)
#     dc_issued = models.CharField('dc:issued', max_length=100, blank=True)
#     dc_identifier = models.CharField('dc:identifier', max_length=50, \
#     help_text='Use ISBN for this', blank=True)
#     cover_img = models.FileField(blank=True, upload_to='covers')
# 
#     def validate_unique(self, *args, **kwargs):
#         if not self.file_sha256sum:
#             self.file_sha256sum = sha256_sum(self.book_file)
#         unicity = self.__class__.objects.filter(file_sha256sum=self.file_sha256sum)
#         if self.pk is not None:
#             unicity = unicity.exclude(pk=self.pk)
#         if unicity.exists():
#             raise ValidationError({
#                 NON_FIELD_ERRORS:['The book already exists in the server.',]})
# 
#     def save(self, *args, **kwargs):
#         assert self.file_sha256sum
#         if not self.cover_img:
#             # FIXME: we should use mimetype
#             if self.book_file.name.endswith('.epub'):
#                 # get the cover path from the epub file
#                 epub_file = Epub(self.book_file)
#                 cover_path = epub_file.get_cover_image_path()
#                 if cover_path is not None and os.path.exists(cover_path):
#                     cover_file = File(open(cover_path, "rb"))
#                     self.cover_img.save(os.path.basename(cover_path), # pylint: disable=no-member
#                                         cover_file)
#                 epub_file.close()
# 
#         super(Book, self).save(*args, **kwargs)
# 
#     class Meta:
#         ordering = ('-time_added',)
#         get_latest_by = "time_added"
# 
#     def __unicode__(self):
#         return self.a_title
# 
#     def __str__(self):
#         return self.a_title
# 
#     @models.permalink
#     def get_absolute_url(self):
#         return ('book_detail', [self.pk])
# 
# class Status(models.Model):
#     status = models.CharField(max_length=200, blank=False)
# 
#     class Meta:
#         verbose_name_plural = "Status"
# 
#     def __unicode__(self):
#         return self.status
# 
#     def __str__(self):
#         return self.status


# Path: books/management/commands/addbooks.py
from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ValidationError
from django.core.files import File
from django.db import transaction
from django.db.utils import IntegrityError
from optparse import make_option
from books.models import Author, Book, Status
import csv
import json
import logging
import os
import sys

                continue

            # Skip unless there is book content
            if not os.path.exists(d['book_path']):
                stats['skipped'] += 1
                continue

            # Get a Django File from the given path:
            f = open(d['book_path'], 'rb')
            d['book_file'] = File(f)
            del d['book_path']

            if 'cover_path' in d:
                f_cover = open(d['cover_path'], 'rb')
                d['cover_img'] = File(f_cover)
                del d['cover_path']

            if 'a_status' in d:
                d['a_status'] = Status.objects.get(status=d['a_status'])
            else:
                d['a_status'] = status_published

            a_author = None
            if 'a_author' in d:
                d['a_author'] = Author.objects.get_or_create(a_author=d['a_author'])[0]

            tags = d.get('tags', [])
            if 'tags' in d:
                del d['tags']


            book = Book(**d)