Ejemplo n.º 1
0
    def create_thumbnail(self, doc_url, doc):
        '''
        create document thumbnail
        '''

        # save thumbnail
        html_response = self.delayed_requests({
            'args': [doc_url],
            'kwargs': {
                'allow_redirects': True
            }
        })
        soup = BeautifulSoup(html_response.content, 'html.parser')
        elm_thumbnail = soup.find("img", {"id": "campaign-icon"})
        img_response = self.delayed_requests({
            'args':
            [urlparse.urljoin(html_response.url, elm_thumbnail.attrs['src'])],
            'kwargs': {
                'allow_redirects': True
            }
        })
        # img_response = requests.get(specialparams['thumbnail_url'], allow_redirects=True)
        if img_response.status_code == 200:
            doc = doc or KnowledgehubDocument.objects.get(doc_url=doc_url)
            doc.save_thumbnail(filename=self.thumb_name_tpl.format(doc.uuid),
                               image=generate_thumbnail_content(
                                   StringIO(img_response.content),
                                   size=(600, 450)))
        else:
            print 'img_response.status_code:', img_response.status_code
Ejemplo n.º 2
0
def create_document_thumbnail(self, object_id):
    """
    Create thumbnail for a document.
    """
    logger.debug("Generating thumbnail for document #{}.".format(object_id))

    try:
        document = Document.objects.get(id=object_id)
    except Document.DoesNotExist:
        logger.error("Document #{} does not exit.".format(object_id))
        return

    image_path = None

    if document.is_image():
        image_path = document.doc_file.path
    elif document.is_file():
        try:
            image_file = render_document(document.doc_file.path)
            image_path = image_file.name
        except ConversionError as e:
            logger.debug("Could not convert document #{}: {}.".format(
                object_id, e))

    try:
        if image_path:
            assert isfile(image_path) and access(
                image_path, R_OK) and os.stat(image_path).st_size > 0
    except (AssertionError, TypeError):
        image_path = None

    if not image_path:
        image_path = document.find_placeholder()

    if not image_path or not os.path.exists(image_path):
        logger.debug(
            "Could not find placeholder for document #{}".format(object_id))
        return

    thumbnail_content = None
    try:
        thumbnail_content = generate_thumbnail_content(image_path)
    except MissingPILError:
        logger.error('Pillow not installed, could not generate thumbnail.')
        return

    if not thumbnail_content:
        logger.warning("Thumbnail for document #{} empty.".format(object_id))
    filename = 'document-{}-thumb.png'.format(document.uuid)
    document.save_thumbnail(filename, thumbnail_content)
    logger.debug("Thumbnail for document #{} created.".format(object_id))
Ejemplo n.º 3
0
def create_document_thumbnail(self, object_id):
    """
    Create thumbnail for a document.
    """
    logger.debug("Generating thumbnail for document #{}.".format(object_id))

    try:
        document = Document.objects.get(id=object_id)
    except Document.DoesNotExist:
        logger.error("Document #{} does not exit.".format(object_id))
        return

    image_path = None

    if document.is_image():
        image_path = document.doc_file.path
    elif document.is_file():
        try:
            image_file = render_document(document.doc_file.path)
            image_path = image_file.name
        except ConversionError as e:
            logger.debug("Could not convert document #{}: {}."
                         .format(object_id, e))

    try:
        if image_path:
            assert isfile(image_path) and access(image_path, R_OK) and os.stat(image_path).st_size > 0
    except (AssertionError, TypeError):
        image_path = None

    if not image_path:
        image_path = document.find_placeholder()

    if not image_path or not os.path.exists(image_path):
        logger.debug("Could not find placeholder for document #{}"
                     .format(object_id))
        return

    thumbnail_content = None
    try:
        thumbnail_content = generate_thumbnail_content(image_path)
    except MissingPILError:
        logger.error('Pillow not installed, could not generate thumbnail.')
        return

    if not thumbnail_content:
        logger.warning("Thumbnail for document #{} empty.".format(object_id))
    filename = 'document-{}-thumb.png'.format(document.uuid)
    document.save_thumbnail(filename, thumbnail_content)
    logger.debug("Thumbnail for document #{} created.".format(object_id))
def create_thumbnail(doc_url, doc, external_thumbnail_url):
    '''
    create document thumbnail
    '''

    img_response = delayed_requests({'args':[external_thumbnail_url], 'kwargs':{'allow_redirects':True}}, module=sys.modules[__name__])
    if img_response.status_code == 200:
        doc = doc or Document.objects.get(doc_url=doc_url)
        doc.save_thumbnail(
            filename = thumb_name_tpl.format(doc.uuid),
            image = generate_thumbnail_content(StringIO(img_response.content), size=(600, 450))
        )
    else:
        print 'img_response.status_code:', img_response.status_code
Ejemplo n.º 5
0
def create_document_thumbnail(self, object_id):
    """
    Create thumbnail for a document.
    """
    logger.debug("Generating thumbnail for document #{}.".format(object_id))

    try:
        document = Document.objects.get(id=object_id)
    except Document.DoesNotExist:
        logger.error("Document #{} does not exit.".format(object_id))
        return

    image_path = None

    if document.is_image():
        image_path = document.doc_file.path
    elif document.is_file():
        try:
            image_file = render_document(document.doc_file.path)
            image_path = image_file.name
        except ConversionError as e:
            logger.debug(
                "Não foi possivel converte o documento #{}: {}.".format(
                    object_id, e))

    if not image_path:
        image_path = document.find_placeholder()

    if not image_path:
        logger.debug(
            "Não foi possivel encontrar o espaco reservado para o documento #{}"
            .format(object_id))
        return

    thumbnail_content = None
    try:
        thumbnail_content = generate_thumbnail_content(image_path)
    except MissingPILError:
        logger.error('Pillow not installed, could not generate thumbnail.')
        return

    if not thumbnail_content:
        logger.warning("Thumbnail for document #{} empty.".format(object_id))
    filename = 'document-{}-thumb.png'.format(document.uuid)
    document.save_thumbnail(filename, thumbnail_content)
    logger.debug("Thumbnail for document #{} created.".format(object_id))
Ejemplo n.º 6
0
def create_document_thumbnail(object_id):
    """
    Create thumbnail for a document.
    """
    logger.debug("Generating thumbnail for document #{}.".format(object_id))

    try:
        document = Document.objects.get(id=object_id)
    except Document.DoesNotExist:
        logger.error("Document #{} does not exit.".format(object_id))
        return

    image_path = None

    if document.is_image():
        image_path = document.doc_file.path
    elif document.is_file():
        try:
            image_file = render_document(document.doc_file.path)
            image_path = image_file.name
        except ConversionError as e:
            logger.debug("Could not convert document #{}: {}."
                         .format(object_id, e))

    if not image_path:
        image_path = document.find_placeholder()

    if not image_path:
        logger.debug("Could not find placeholder for document #{}"
                     .format(object_id))
        return

    try:
        thumbnail_content = generate_thumbnail_content(image_path)
    except MissingPILError:
        logger.error('Pillow not installed, could not generate thumbnail.')
        return

    filename = 'document-{}-thumb.png'.format(document.uuid)
    document.save_thumbnail(filename, thumbnail_content)
    logger.debug("Thumbnail for document #{} created.".format(object_id))
Ejemplo n.º 7
0
def create_document_thumbnail(object_id):
    """
    Create thumbnail for a document.
    """
    logger.debug("Generating thumbnail for document #{}.".format(object_id))

    try:
        document = Document.objects.get(id=object_id)
    except Document.DoesNotExist:
        logger.error("Document #{} does not exit.".format(object_id))
        return

    image_path = None

    if document.is_image():
        image_path = document.doc_file.path
    elif document.is_file():
        try:
            image_file = render_document(document.doc_file.path)
            image_path = image_file.name
        except ConversionError as e:
            logger.debug("Could not convert document #{}: {}."
                         .format(object_id, e))

    if not image_path:
        image_path = document.find_placeholder()

    if not image_path:
        logger.debug("Could not find placeholder for document #{}"
                     .format(object_id))
        return

    try:
        thumbnail_content = generate_thumbnail_content(image_path)
    except MissingPILError:
        logger.error('Pillow not installed, could not generate thumbnail.')
        return
Ejemplo n.º 8
0
def document_thumb_upload(request,
                          docid,
                          template='documents/document_thumb_upload.html'):
    document = None
    try:
        document = _resolve_document(request, docid,
                                     'base.change_resourcebase',
                                     _PERMISSION_MSG_MODIFY)

    except Http404:
        return HttpResponse(loader.render_to_string(
            '404.html', RequestContext(request, {})),
                            status=404)

    except PermissionDenied:
        return HttpResponse(loader.render_to_string(
            '401.html',
            RequestContext(request, {
                'error_message':
                _("You are not allowed to edit this document.")
            })),
                            status=403)

    if document is None:
        return HttpResponse('An unknown error has occured.',
                            content_type="text/plain",
                            status=401)

    if request.method == 'GET':
        return render_to_response(
            template,
            RequestContext(
                request, {
                    "resource": document,
                    "docid": docid,
                    'SITEURL': settings.SITEURL[:-1]
                }))
    elif request.method == 'POST':
        status_code = 401
        out = {'success': False}
        if docid and request.FILES:
            data = request.FILES.get('base_file')
            if data:
                filename = 'document-{}-thumb.png'.format(document.uuid)
                path = default_storage.save('tmp/' + filename,
                                            ContentFile(data.read()))
                f = os.path.join(settings.MEDIA_ROOT, path)
                try:
                    image_path = f
                except:
                    image_path = document.find_placeholder()

                thumbnail_content = None
                try:
                    thumbnail_content = generate_thumbnail_content(image_path)
                except MissingPILError:
                    logger.error(
                        'Pillow not installed, could not generate thumbnail.')

                document.save_thumbnail(filename, thumbnail_content)
                logger.debug(
                    "Thumbnail for document #{} created.".format(docid))
            status_code = 200
            out['success'] = True
            out['resource'] = docid
        else:
            out['success'] = False
            out['errors'] = 'An unknown error has occured.'
        out['url'] = reverse('document_detail', args=[docid])
        return HttpResponse(json.dumps(out),
                            content_type='application/json',
                            status=status_code)
Ejemplo n.º 9
0
def create_document_thumbnail(self, object_id):
    """
    Create thumbnail for a document.
    """
    logger.debug("Generating thumbnail for document #{}.".format(object_id))

    try:
        document = Document.objects.get(id=object_id)
    except Document.DoesNotExist:
        logger.error("Document #{} does not exist.".format(object_id))
        return

    image_path = None
    image_file = None

    if document.is_image:
        if not os.path.exists(storage.path(document.doc_file.name)):
            from shutil import copyfile
            copyfile(document.doc_file.path,
                     storage.path(document.doc_file.name))
        image_file = storage.open(document.doc_file.name, 'rb')
    elif document.is_video or document.is_audio:
        image_file = open(document.find_placeholder(), 'rb')
    elif document.is_file:
        try:
            document_location = storage.path(document.doc_file.name)
        except NotImplementedError as e:
            logger.debug(e)
            document_location = storage.url(document.doc_file.name)

        try:
            image_path = render_document(document_location)
            if image_path is not None:
                try:
                    image_file = open(image_path, 'rb')
                except Exception as e:
                    logger.debug(e)
                    logger.debug(
                        "Failed to render document #{}".format(object_id))
            else:
                logger.debug("Failed to render document #{}".format(object_id))
        except ConversionError as e:
            logger.debug("Could not convert document #{}: {}.".format(
                object_id, e))
        except NotImplementedError as e:
            logger.debug("Failed to render document #{}: {}".format(
                object_id, e))

    thumbnail_content = None
    try:
        try:
            thumbnail_content = generate_thumbnail_content(image_file)
        except Exception as e:
            logger.error(
                "Could not generate thumbnail, falling back to 'placeholder': {}"
                .format(e))
            thumbnail_content = generate_thumbnail_content(
                document.find_placeholder())
    except Exception as e:
        logger.error("Could not generate thumbnail: {}".format(e))
        return
    finally:
        if image_file is not None:
            image_file.close()

        if image_path is not None:
            os.remove(image_path)

    if not thumbnail_content:
        logger.warning("Thumbnail for document #{} empty.".format(object_id))
    filename = 'document-{}-thumb.png'.format(document.uuid)
    document.save_thumbnail(filename, thumbnail_content)
    logger.debug("Thumbnail for document #{} created.".format(object_id))
Ejemplo n.º 10
0
def document_thumb_upload(
        request,
        docid,
        template='documents/document_thumb_upload.html'):
    document = None
    try:
        document = _resolve_document(
            request,
            docid,
            'base.change_resourcebase',
            _PERMISSION_MSG_MODIFY)

    except Http404:
        return HttpResponse(
            loader.render_to_string(
                '404.html', context={
                }, request=request), status=404)

    except PermissionDenied:
        return HttpResponse(
            loader.render_to_string(
                '401.html', context={
                    'error_message': _("You are not allowed to edit this document.")}, request=request), status=403)

    if document is None:
        return HttpResponse(
            'An unknown error has occured.',
            content_type="text/plain",
            status=401
        )

    site_url = settings.SITEURL.rstrip('/') if settings.SITEURL.startswith('http') else settings.SITEURL
    if request.method == 'GET':
        return render(request, template, context={
            "resource": document,
            "docid": docid,
            'SITEURL': site_url
        })
    elif request.method == 'POST':
        status_code = 401
        out = {'success': False}
        if docid and request.FILES:
            data = request.FILES.get('base_file')
            if data:
                filename = 'document-{}-thumb.png'.format(document.uuid)
                path = default_storage.save(
                    'tmp/' + filename, ContentFile(data.read()))
                f = os.path.join(settings.MEDIA_ROOT, path)
                try:
                    image_path = f
                except BaseException:
                    image_path = document.find_placeholder()

                thumbnail_content = None
                try:
                    thumbnail_content = generate_thumbnail_content(image_path)
                except MissingPILError:
                    logger.error(
                        'Pillow not installed, could not generate thumbnail.')

                if not thumbnail_content:
                    logger.warning("Thumbnail for document #{} empty.".format(docid))
                document.save_thumbnail(filename, thumbnail_content)
                logger.debug(
                    "Thumbnail for document #{} created.".format(docid))
            status_code = 200
            out['success'] = True
            out['resource'] = docid
        else:
            out['success'] = False
            out['errors'] = 'An unknown error has occured.'
        out['url'] = reverse(
            'document_detail', args=[
                docid])
        return HttpResponse(
            json.dumps(out),
            content_type='application/json',
            status=status_code)