regluit/distro/models.py

70 lines
2.7 KiB
Python
Raw Normal View History

2016-05-16 20:50:09 +00:00
import logging
import requests
2016-05-10 21:33:51 +00:00
from ftplib import FTP, FTP_TLS
2016-05-16 20:50:09 +00:00
from StringIO import StringIO
2016-05-10 21:33:51 +00:00
from django.db import models
2016-05-16 20:50:09 +00:00
logger = logging.getLogger(__name__)
2016-05-10 21:33:51 +00:00
class Target(models.Model):
name = models.CharField(max_length=30)
host = models.CharField(max_length=60)
pw = models.CharField(max_length=30)
user = models.CharField(max_length=30)
protocol = models.CharField(max_length=10, default='ftp')
2016-05-16 20:50:09 +00:00
formats = models.ManyToManyField('Format', related_name='targets')
2016-05-10 21:33:51 +00:00
def __unicode__(self):
return self.name
def get_ftp(self):
2016-05-16 20:50:09 +00:00
if self.protocol == 'secure':
_ftp = FTP_TLS(self.host, self.user, self.pw)
_ftp.prot_p()
else:
_ftp = FTP(self.host, self.user, self.pw)
return _ftp
2016-05-10 21:33:51 +00:00
2016-05-20 20:34:25 +00:00
def push(self, book, new=False):
2016-05-16 20:50:09 +00:00
pushed_formats = []
pushed_isbns = set()
2016-05-10 21:33:51 +00:00
for ebook in book.ebooks():
2016-05-20 20:34:25 +00:00
isbn = ebook.edition.isbn_13 if ebook.edition.isbn_13 else book.first_isbn_13()
2016-05-16 20:50:09 +00:00
if isbn and self.formats.filter(name=ebook.format).exists() and ebook.format not in pushed_formats:
2016-05-20 20:34:25 +00:00
dont_push = new and Deposit.objects.filter(isbn=isbn, target=self, format=ebook.format).exists()
if not dont_push:
ebfile = ebook.get_archive()
if ebfile:
self.push_file(u'{}.{}'.format(isbn,ebook.format), ebfile)
ebfile.close()
pushed_formats.append(ebook.format)
pushed_isbns.add(isbn)
Deposit.objects.create(target=self, isbn=isbn, format=ebook.format)
else:
logger.error('no file available for ebook {}'.format(ebook.id))
if pushed_isbns:
cover = book.cover_image_large()
if cover:
r = requests.get(cover)
for isbn in pushed_isbns:
self.push_file(u'{}.{}'.format(isbn,'jpg'), StringIO(r.content))
else:
logger.error('no cover available for {}'.format(book))
return pushed_isbns
2016-05-16 20:50:09 +00:00
def push_file(self, filename, file_to_push):
self.get_ftp().storbinary(u'STOR {}'.format(filename), file_to_push)
2016-05-10 21:33:51 +00:00
2016-05-16 20:50:09 +00:00
2016-05-10 21:33:51 +00:00
class Deposit(models.Model):
target = models.ForeignKey(Target, on_delete=models.CASCADE, related_name="deposits")
2016-05-10 21:33:51 +00:00
isbn = models.CharField(max_length=13)
format = models.CharField(max_length=30)
updated = models.DateTimeField(auto_now_add=True)
2016-05-16 20:50:09 +00:00
class Format(models.Model):
2016-05-10 21:33:51 +00:00
name = models.CharField(max_length=4)
def __unicode__(self):
return self.name