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, metadata = get_letter_pdf_and_metadata(notification)
    except Exception:
        raise PDFNotReadyError()

    return send_file(filename_or_fp=BytesIO(pdf_data),
                     mimetype='application/pdf')
def test_get_letter_pdf_gets_pdf_from_correct_bucket(
        sample_precompiled_letter_notification_using_test_key,
        bucket_config_name, filename_format):
    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='eu-west-1')
    conn.create_bucket(Bucket=bucket_name)
    s3 = boto3.client('s3', region_name='eu-west-1')
    s3.put_object(Bucket=bucket_name, Key=filename, Body=b'pdf_content')

    file_data, metadata = get_letter_pdf_and_metadata(
        sample_precompiled_letter_notification_using_test_key)

    assert file_data == b'pdf_content'
Ejemplo n.º 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,
                                      notification.template_version)
    metadata = {}

    if template.is_precompiled_letter:
        try:

            pdf_file, metadata = get_letter_pdf_and_metadata(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)

        page_number = page if page else "1"
        content = base64.b64encode(pdf_file).decode('utf-8')
        content_outside_printable_area = metadata.get(
            "message") == "content-outside-printable-area"
        page_is_in_invalid_pages = page_number in metadata.get(
            'invalid_pages', '[]')

        if content_outside_printable_area and (file_type == "pdf"
                                               or page_is_in_invalid_pages):
            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)
                if content_outside_printable_area and page_is_in_invalid_pages:
                    content = pdf_page
                else:
                    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)

        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),
            "template_type": template.template_type
        }

        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, "metadata": metadata})