def save(self, *args, **kwargs): if not self.cover_img: 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)) self.cover_img.save(os.path.basename(cover_path), cover_file) epub_file.close() super(Book, self).save(*args, **kwargs)
def clean_epub_file(self): """Perform basic validation of the epub_file by making sure: - no other existing models have the same sha256 hash. - it is parseable by `Epub`. TODO: This method is called twice during the wizard (at step 0, and at done()), by Django design. Still, we should look for alternatives in order to make sure epub validation only happens once. https://code.djangoproject.com/ticket/10810 """ data = self.cleaned_data["epub_file"] # Validate sha256 hash. sha256sum = models.sha256_sum(data) if models.Book.objects.filter(file_sha256sum=sha256sum).exists(): raise forms.ValidationError("The file is already on the database") # Validate parseability. epub = None try: # Fetch information from the epub, and set it as attributes. epub = Epub(data) info_dict, cover_path, tags = epub.as_model_dict() # TODO: pass this info via a cleaner way. self.cleaned_data["original_path"] = data.name self.cleaned_data["info_dict"] = info_dict self.cleaned_data["cover_path"] = cover_path self.cleaned_data["file_sha256sum"] = sha256sum except Exception as e: raise forms.ValidationError(str(e)) finally: # Try to remove the temp extracted epub folder. try: epub.close() except: pass return data
def clean_epub_file(self): """Perform basic validation of the epub_file by making sure: - no other existing models have the same sha256 hash. - it is parseable by `Epub`. TODO: This method is called twice during the wizard (at step 0, and at done()), by Django design. Still, we should look for alternatives in order to make sure epub validation only happens once. https://code.djangoproject.com/ticket/10810 """ data = self.cleaned_data['epub_file'] # Validate sha256 hash. sha256sum = models.sha256_sum(data) if models.Book.objects.filter(file_sha256sum=sha256sum).exists(): raise forms.ValidationError('The file is already on the database') # Validate parseability. epub = None try: # Fetch information from the epub, and set it as attributes. epub = Epub(data) info_dict, cover_path, tags = epub.as_model_dict() # TODO: pass this info via a cleaner way. self.cleaned_data['original_path'] = data.name self.cleaned_data['info_dict'] = info_dict self.cleaned_data['cover_path'] = cover_path self.cleaned_data['file_sha256sum'] = sha256sum except Exception as e: raise forms.ValidationError(str(e)) finally: # Try to remove the temp extracted epub folder. try: epub.close() except: pass return data