def get_pdf_for_notification(notification_id):
    _data = {"notification_id": notification_id}
    validate(_data, notification_by_id)
    notification = notifications_dao.get_notification_by_id(
        notification_id, authenticated_service.id, _raise=True)

    if notification.notification_type != LETTER_TYPE:
        raise BadRequestError(message="Notification is not a letter")

    if notification.status == NOTIFICATION_VIRUS_SCAN_FAILED:
        raise BadRequestError(message='Document did not pass the virus scan')

    if notification.status == NOTIFICATION_TECHNICAL_FAILURE:
        raise BadRequestError(
            message='PDF not available for letters in status {}'.format(
                notification.status))

    if notification.status == NOTIFICATION_PENDING_VIRUS_CHECK:
        raise PDFNotReadyError()

    try:
        pdf_data = get_letter_pdf(notification)
    except Exception:
        raise PDFNotReadyError()

    return send_file(filename_or_fp=BytesIO(pdf_data),
                     mimetype='application/pdf')
Пример #2
0
def test_get_letter_pdf_gets_pdf_from_correct_bucket(
        sample_precompiled_letter_notification_using_test_key,
        bucket_config_name, filename_format, aws_credentials):
    if bucket_config_name == 'LETTERS_PDF_BUCKET_NAME':
        sample_precompiled_letter_notification_using_test_key.key_type = KEY_TYPE_NORMAL

    bucket_name = current_app.config[bucket_config_name]
    filename = datetime.utcnow().strftime(filename_format)
    conn = boto3.resource('s3', region_name='us-east-1')
    conn.create_bucket(Bucket=bucket_name)
    s3 = boto3.client('s3', region_name='us-east-1')
    s3.put_object(Bucket=bucket_name, Key=filename, Body=b'pdf_content')

    ret = get_letter_pdf(sample_precompiled_letter_notification_using_test_key)

    assert ret == b'pdf_content'
Пример #3
0
def preview_letter_template_by_notification_id(service_id, notification_id,
                                               file_type):
    if file_type not in ('pdf', 'png'):
        raise InvalidRequest({'content': ["file_type must be pdf or png"]},
                             status_code=400)

    page = request.args.get('page')

    notification = get_notification_by_id(notification_id)

    template = dao_get_template_by_id(notification.template_id)

    if template.is_precompiled_letter:
        try:

            pdf_file = get_letter_pdf(notification)

        except botocore.exceptions.ClientError as e:
            raise InvalidRequest(
                'Error extracting requested page from PDF file for notification_id {} type {} {}'
                .format(notification_id, type(e), e),
                status_code=500)

        content = base64.b64encode(pdf_file).decode('utf-8')

        if file_type == 'png':
            try:
                page_number = page if page else "1"

                pdf_page = extract_page_from_pdf(BytesIO(pdf_file),
                                                 int(page_number) - 1)
                content = base64.b64encode(pdf_page).decode('utf-8')
            except PdfReadError as e:
                raise InvalidRequest(
                    'Error extracting requested page from PDF file for notification_id {} type {} {}'
                    .format(notification_id, type(e), e),
                    status_code=500)

            url = '{}/precompiled-preview.png{}'.format(
                current_app.config['TEMPLATE_PREVIEW_API_HOST'],
                '?hide_notify=true' if page_number == '1' else '')

            content = _get_png_preview(url,
                                       content,
                                       notification.id,
                                       json=False)
    else:

        template_for_letter_print = {
            "id": str(notification.template_id),
            "subject": template.subject,
            "content": template.content,
            "version": str(template.version)
        }

        service = dao_fetch_service_by_id(service_id)

        data = {
            'letter_contact_block': notification.reply_to_text,
            'template': template_for_letter_print,
            'values': notification.personalisation,
            'dvla_org_id': service.dvla_organisation_id,
        }

        url = '{}/preview.{}{}'.format(
            current_app.config['TEMPLATE_PREVIEW_API_HOST'], file_type,
            '?page={}'.format(page) if page else '')
        content = _get_png_preview(url, data, notification.id, json=True)

    return jsonify({"content": content})
Пример #4
0
def preview_letter_template_by_notification_id(service_id, notification_id, file_type):
    if file_type not in ('pdf', 'png'):
        raise InvalidRequest({'content': ["file_type must be pdf or png"]}, status_code=400)

    page = request.args.get('page')

    notification = get_notification_by_id(notification_id)

    template = dao_get_template_by_id(notification.template_id)

    if template.is_precompiled_letter:
        try:

            pdf_file = get_letter_pdf(notification)

        except botocore.exceptions.ClientError as e:
            raise InvalidRequest(
                'Error extracting requested page from PDF file for notification_id {} type {} {}'.format(
                    notification_id, type(e), e),
                status_code=500
            )

        content = base64.b64encode(pdf_file).decode('utf-8')
        overlay = request.args.get('overlay')
        page_number = page if page else "1"

        if overlay:
            path = '/precompiled/overlay.{}'.format(file_type)
            query_string = '?page_number={}'.format(page_number) if file_type == 'png' else ''
            content = pdf_file
        elif file_type == 'png':
            query_string = '?hide_notify=true' if page_number == '1' else ''
            path = '/precompiled-preview.png'
        else:
            path = None

        if file_type == 'png':
            try:
                pdf_page = extract_page_from_pdf(BytesIO(pdf_file), int(page_number) - 1)
                content = pdf_page if overlay else base64.b64encode(pdf_page).decode('utf-8')
            except PdfReadError as e:
                raise InvalidRequest(
                    'Error extracting requested page from PDF file for notification_id {} type {} {}'.format(
                        notification_id, type(e), e),
                    status_code=500
                )

        if path:
            url = current_app.config['TEMPLATE_PREVIEW_API_HOST'] + path + query_string
            response_content = _get_png_preview_or_overlaid_pdf(url, content, notification.id, json=False)
        else:
            response_content = content
    else:

        template_for_letter_print = {
            "id": str(notification.template_id),
            "subject": template.subject,
            "content": template.content,
            "version": str(template.version)
        }

        service = dao_fetch_service_by_id(service_id)
        letter_logo_filename = service.letter_branding and service.letter_branding.filename
        data = {
            'letter_contact_block': notification.reply_to_text,
            'template': template_for_letter_print,
            'values': notification.personalisation,
            'date': notification.created_at.isoformat(),
            'filename': letter_logo_filename,
        }

        url = '{}/preview.{}{}'.format(
            current_app.config['TEMPLATE_PREVIEW_API_HOST'],
            file_type,
            '?page={}'.format(page) if page else ''
        )
        response_content = _get_png_preview_or_overlaid_pdf(url, data, notification.id, json=True)

    return jsonify({"content": response_content})
Пример #5
0
def preview_letter_template_by_notification_id(service_id, notification_id,
                                               file_type):
    if file_type not in ("pdf", "png"):
        raise InvalidRequest({"content": ["file_type must be pdf or png"]},
                             status_code=400)

    page = request.args.get("page")

    notification = get_notification_by_id(notification_id)

    template = dao_get_template_by_id(notification.template_id)

    if template.is_precompiled_letter:
        try:

            pdf_file = get_letter_pdf(notification)

        except botocore.exceptions.ClientError as e:
            raise InvalidRequest(
                "Error extracting requested page from PDF file for notification_id {} type {} {}"
                .format(notification_id, type(e), e),
                status_code=500,
            )

        content = base64.b64encode(pdf_file).decode("utf-8")
        overlay = request.args.get("overlay")
        page_number = page if page else "1"

        if overlay:
            path = "/precompiled/overlay.{}".format(file_type)
            query_string = "?page_number={}".format(
                page_number) if file_type == "png" else ""
            content = pdf_file
        elif file_type == "png":
            query_string = "?hide_notify=true" if page_number == "1" else ""
            path = "/precompiled-preview.png"
        else:
            path = None

        if file_type == "png":
            try:
                pdf_page = extract_page_from_pdf(BytesIO(pdf_file),
                                                 int(page_number) - 1)
                content = pdf_page if overlay else base64.b64encode(
                    pdf_page).decode("utf-8")
            except PdfReadError as e:
                raise InvalidRequest(
                    "Error extracting requested page from PDF file for notification_id {} type {} {}"
                    .format(notification_id, type(e), e),
                    status_code=500,
                )

        if path:
            url = current_app.config[
                "TEMPLATE_PREVIEW_API_HOST"] + path + query_string
            response_content = _get_png_preview_or_overlaid_pdf(
                url, content, notification.id, json=False)
        else:
            response_content = content
    else:

        template_for_letter_print = {
            "id": str(notification.template_id),
            "subject": template.subject,
            "content": template.content,
            "version": str(template.version),
        }

        service = dao_fetch_service_by_id(service_id)
        letter_logo_filename = service.letter_branding and service.letter_branding.filename
        data = {
            "letter_contact_block": notification.reply_to_text,
            "template": template_for_letter_print,
            "values": notification.personalisation,
            "date": notification.created_at.isoformat(),
            "filename": letter_logo_filename,
        }

        url = "{}/preview.{}{}".format(
            current_app.config["TEMPLATE_PREVIEW_API_HOST"],
            file_type,
            "?page={}".format(page) if page else "",
        )
        response_content = _get_png_preview_or_overlaid_pdf(url,
                                                            data,
                                                            notification.id,
                                                            json=True)

    return jsonify({"content": response_content})