Ejemplo n.º 1
0
    def _set_cover(self, book, cover_image):
        """
        Assigns the specified cover.
        """

        validity = self.delegate.is_valid_cover(cover_image)

        if validity is None:
            # not checked by the assigned delegate
            is_valid, reason = is_valid_cover(cover_image)
        elif isinstance(validity, bool):
            is_valid, reason = validity, None
        else:
            is_valid, reason = validity

        if not is_valid:
            if reason:
                self.notifier.warning(
                    _("Not using {} as a cover image -- {}").format(
                        cover_image.file_name, reason))
            else:
                self.notifier.warning(
                    _("Not using {} as a cover image").format(
                        cover_image.file_name))
            return

        cover_file = ContentFile(cover_image.get_content())
        file_name = os.path.basename(cover_image.file_name)

        attName, attExt = os.path.splitext(file_name)
        file_name = '{}{}'.format(booktype_slugify(attName), attExt)

        created = datetime.datetime.now()
        title = ''

        h = hashlib.sha1()
        h.update(cover_image.file_name)
        h.update(title)
        h.update(str(created))

        cover = models.BookCover(
            book=book,
            user=book.owner,
            cid=h.hexdigest(),
            title=title,
            filename=file_name[:250],
            width=0,
            height=0,
            approved=False,
            is_book=False,
            is_ebook=True,
            is_pdf=False,
            created=created
        )
        cover.save()

        cover.attachment.save(file_name, cover_file, save=False)
        cover.save()

        self.notifier.info(_("Using {} as cover image").format(file_name))
Ejemplo n.º 2
0
def upload_cover(request, bookid, version=None):
    try:
        book = models.Book.objects.get(url_title__iexact=bookid)
    except models.Book.DoesNotExist:
        return views.ErrorPage(request, "errors/book_does_not_exist.html",
                               {"book_name": bookid})

    can_upload_cover = security.get_security_for_book(request.user, book).has_perm('edit.upload_cover')

    if (not request.user.is_superuser and not can_upload_cover and book.owner != request.user):
        raise PermissionDenied

    with transaction.atomic():
        file_data = request.FILES['files[]']
        title = request.POST.get('title', '')
        try:
            filename = unidecode.unidecode(file_data.name)
        except:
            filename = uuid.uuid1().hex

        h = hashlib.sha1()
        h.update(filename)
        h.update(title)
        h.update(str(datetime.datetime.now()))

        license = models.License.objects.get(
            abbrevation=request.POST.get('license', ''))

        cover = models.BookCover(
            book=book,
            user=request.user,
            cid=h.hexdigest(),
            title=title,
            filename=filename[:250],
            width=0,
            height=0,
            unit=request.POST.get('unit', 'mm'),
            booksize=request.POST.get('booksize', ''),
            cover_type=request.POST.get('type', ''),
            creator=request.POST.get('creator', '')[:40],
            license=license,
            notes=request.POST.get('notes', '')[:500],
            approved=False,
            is_book=False,
            is_ebook=True,
            is_pdf=False,
            created=datetime.datetime.now()
        )
        cover.save()

        # now save the attachment
        cover.attachment.save(filename, file_data, save=False)
        cover.save()

    response_data = {
        "files": [{
            "url": "http://127.0.0.1/",
            "thumbnail_url": "http://127.0.0.1/",
            "name": "boot.png",
            "type": "image/png",
            "size": 172728,
            "delete_url": "",
            "delete_type": "DELETE"
        }]
    }

    # add cliendID and sputnikID to request object
    # this will allow us to use sputnik and addMessageToChannel
    request.clientID = request.POST['clientID']
    request.sputnikID = "%s:%s" % (request.session.session_key, request.clientID)
    send_notification(request, book.id, book.get_version(version).get_version(),
                      "notification_new_cover_uploaded", cover.title)

    if "application/json" in request.META['HTTP_ACCEPT']:
        return HttpResponse(json.dumps(response_data),
                            content_type="application/json")
    else:
        return HttpResponse(json.dumps(response_data), content_type="text/html")
Ejemplo n.º 3
0
def upload_cover(request, bookid, version=None):
    """
    Uploades attachments. Used from Upload dialog.

    @param request: Django Request
    @param bookid: Book ID
    @param version: Book version or None
    """

    import datetime

    try:
        book = models.Book.objects.get(url_title__iexact=bookid)
    except models.Book.DoesNotExist:
        return pages.ErrorPage(request, "errors/book_does_not_exist.html",
                               {"book_name": bookid})

    book_version = book.getVersion(version)

    stat = models.BookStatus.objects.filter(book=book)[0]

    operationResult = True

    # check this for transactions
    try:

        for name, fileData in request.FILES.items():
            if True:
                print '>> ', name
                print request.FILES[name].name
                import hashlib

                h = hashlib.sha1()
                h.update(name)
                h.update(request.POST.get('format', ''))
                h.update(request.POST.get('license', ''))
                h.update(str(datetime.datetime.now()))

                license = models.License.objects.get(
                    name=request.POST.get('license', ''))

                frm = request.POST.get('format', '').split(',')

                try:
                    width = int(request.POST.get('width', '0'))
                except ValueError:
                    width = 0

                try:
                    height = int(request.POST.get('height', '0'))
                except ValueError:
                    height = 0

                try:
                    filename = request.FILES[name].name
                except:
                    filename = ''

                cov = models.BookCover(
                    book=book,
                    user=request.user,
                    cid=h.hexdigest(),
                    title=request.POST.get('title', '')[:250],
                    filename=filename[:250],
                    width=width,
                    height=height,
                    unit=request.POST.get('unit', 'mm'),
                    booksize=request.POST.get('booksize', ''),
                    cover_type=request.POST.get('type', ''),
                    creator=request.POST.get('creator', '')[:40],
                    license=license,
                    notes=request.POST.get('notes', '')[:500],
                    approved=False,
                    is_book='book' in frm,
                    is_ebook='ebook' in frm,
                    is_pdf='pdf' in frm,
                    created=datetime.datetime.now())
                cov.save()

                cov.attachment.save(request.FILES[name].name,
                                    fileData,
                                    save=False)
                cov.save()

        # TODO:
        # must write info about this to log!
    except IOError:
        operationResult = False
        transaction.rollback()
    except:
        from booki.utils import log
        log.printStack()
        oprerationResult = False
        transaction.rollback()
    else:
        # maybe check file name now and save with new name
        transaction.commit()

    return HttpResponse(
        '<html><body><script> parent.jQuery.booki.editor.showCovers(); </script></body></html>'
    )