views.py 11.4 KB
Newer Older
1 2 3 4
#!/usr/bin/env python3
"""
    Routes
"""
5
import copy
6
import json
7 8
import subprocess
import time
9
from datetime import datetime
10
from io import BytesIO
11 12
from pathlib import Path
from urllib.parse import quote_plus
13

Pierre Dittgen's avatar
Pierre Dittgen committed
14
from commonmark import commonmark
15
from flask import make_response, redirect, render_template, request, url_for
16

17
import tabulator
Pierre Dittgen's avatar
Pierre Dittgen committed
18 19
from validata_core import csv_helpers
from validata_core.loaders import custom_loaders
20
from validata_ui import app
Pierre Dittgen's avatar
Pierre Dittgen committed
21
from validata_ui.ui_util import flash_error, flash_warning
22
from validata_ui.validata_util import ValidataSource
23
from validata_ui.validate_helper import ValidatorHelper
24

25 26

def extract_source_data(source: ValidataSource, preview_rows_nb=5):
27
    """ Computes table preview """
28 29 30

    def stringify(val):
        """ Transform value into string """
Pierre Dittgen's avatar
Pierre Dittgen committed
31
        return '' if val is None else str(val)
32

33 34
    header = None
    rows = []
Pierre Dittgen's avatar
Pierre Dittgen committed
35
    nb_rows = 0
36

37
    options = {}
38
    if source.format == "csv":
39
        options['delimiter'] = csv_helpers.detect_dialect(source.source, format=source.format, scheme=source.scheme,
40
                                                          custom_loaders=custom_loaders).delimiter
41
    with tabulator.Stream(source.source, format=source.format, scheme=source.scheme, custom_loaders=custom_loaders,
42
                          **options) as stream:
43 44
        for row in stream:
            if header is None:
45
                header = ['' if v is None else v for v in row]
46
            else:
47
                rows.append(list(map(stringify, row)))
Pierre Dittgen's avatar
Pierre Dittgen committed
48
                nb_rows += 1
49
    preview_rows_nb = min(preview_rows_nb, nb_rows)
50 51
    return {'header': header,
            'rows_nb': nb_rows,
52 53 54
            'data_rows': rows,
            'preview_rows_nb': preview_rows_nb,
            'preview_rows': rows[:preview_rows_nb]}
55 56


Pierre Dittgen's avatar
Pierre Dittgen committed
57 58
def improve_errors(errors):
    """Add context to errors, converts markdown content to HTML"""
59

Pierre Dittgen's avatar
Pierre Dittgen committed
60 61
    def improve_err(err):
        """Adds context info based on row-nb presence and converts content to HTML"""
62

Pierre Dittgen's avatar
Pierre Dittgen committed
63 64 65 66
        # Context
        update_keys = {
            'context': 'body' if 'row-number' in err and not err['row-number'] is None else 'table',
        }
Pierre Dittgen's avatar
Pierre Dittgen committed
67

Pierre Dittgen's avatar
Pierre Dittgen committed
68
        # markdown to HTML (with default values for 'title' and 'content')
Pierre Dittgen's avatar
Pierre Dittgen committed
69

Pierre Dittgen's avatar
Pierre Dittgen committed
70 71 72
        # Set default title if no title
        if not 'title' in err:
            update_keys['title'] = '[{}]'.format(err['code'])
Pierre Dittgen's avatar
Pierre Dittgen committed
73

Pierre Dittgen's avatar
Pierre Dittgen committed
74 75 76 77
        # Convert message to markdown only if no content
        # => for pre-checks errors
        if 'message' in err and not 'content' in err:
            update_keys['message'] = commonmark(err['message'])
Pierre Dittgen's avatar
Pierre Dittgen committed
78

Pierre Dittgen's avatar
Pierre Dittgen committed
79 80 81
        # Else, default message
        elif not 'message' in err or err['message'] is None:
            update_keys['message'] = '[{}]'.format(err['code'])
Pierre Dittgen's avatar
Pierre Dittgen committed
82

Pierre Dittgen's avatar
Pierre Dittgen committed
83 84 85
        # Message content
        md_content = '*content soon available*' if not 'content' in err else err['content']
        update_keys['content'] = commonmark(md_content)
86

Pierre Dittgen's avatar
Pierre Dittgen committed
87
        return {**err, **update_keys}
88

Pierre Dittgen's avatar
Pierre Dittgen committed
89
    return list(map(improve_err, errors))
90 91


92
def create_validata_report(goodtables_report, schema):
93 94 95 96 97 98
    """ Creates an error report easier to handle and display in templates:
        - only one table
        - errors are contextualized
        - error-counts is ok
        - errors are grouped by lines
        - errors are separated into "structure" and "body"
99
        - error messages are improved
100 101 102 103 104 105 106 107 108 109 110
    """
    report = copy.deepcopy(goodtables_report)

    # One table is enough
    del report['table-count']
    report['table'] = report['tables'][0]
    del report['tables']
    del report['table']['error-count']
    del report['table']['time']
    del report['table']['valid']
    del report['valid']
111 112 113
    # use _ instead of - to ease information picking in jinja2 template
    report['table']['row_count'] = report['table']['row-count']

Pierre Dittgen's avatar
Pierre Dittgen committed
114 115 116 117
    # Handy col_count info
    headers = report['table'].get('headers', [])
    report['table']['col_count'] = len(headers)

Pierre Dittgen's avatar
Pierre Dittgen committed
118
    # Computes column info
119
    schema_fields = schema.get('fields', [])
Pierre Dittgen's avatar
Pierre Dittgen committed
120 121 122 123
    fields_dict = {f['name']: (f.get('title', 'titre non défini'), f.get('description', '')) for f in schema_fields}
    report['table']['headers_title'] = [fields_dict[h][0] if h in fields_dict else 'colonne inconnue' for h in headers]
    report['table']['headers_description'] = [fields_dict[h][1]
                                              if h in fields_dict else 'Cette colonne n\'est pas définie dans le schema' for h in headers]
124

125
    # Provide better (french) messages
Pierre Dittgen's avatar
Pierre Dittgen committed
126 127
    errors = improve_errors(report['table']['errors'])
    del report['table']['errors']
128

129 130 131 132 133 134 135 136 137 138 139 140
    # Count errors
    report['error_count'] = len(errors)
    del report['error-count']

    # Then group them in 2 groups : structure and body
    report['table']['errors'] = {'structure': [], 'body': []}
    for err in errors:
        if err['context'] != 'body':
            report['table']['errors']['structure'].append(err)
        else:
            report['table']['errors']['body'].append(err)

Pierre Dittgen's avatar
Pierre Dittgen committed
141
    # Checks if there are structure errors different to invalid-column-delimiter
Pierre Dittgen's avatar
Pierre Dittgen committed
142 143 144
    structure_errors = report['table']['errors']['structure']
    report['table']['do_display_body_errors'] = len(structure_errors) == 0 or \
        all(err['code'] == 'invalid-column-delimiter' for err in structure_errors)
145

Pierre Dittgen's avatar
Pierre Dittgen committed
146 147 148 149
    # Group body errors by row id
    rows = []
    current_row_id = 0
    for err in report['table']['errors']['body']:
150 151
        if not 'row-number' in err:
            print('ERR', err)
Pierre Dittgen's avatar
Pierre Dittgen committed
152 153 154 155 156 157 158 159 160 161 162 163 164
        row_id = err['row-number']
        del err['row-number']
        del err['context']
        if row_id != current_row_id:
            current_row_id = row_id
            rows.append({'row_id': current_row_id, 'errors': {}})

        column_id = err.get('column-number')
        if column_id is not None:
            del err['column-number']
            rows[-1]['errors'][column_id] = err
        else:
            rows[-1]['errors']['row'] = err
Pierre Dittgen's avatar
Pierre Dittgen committed
165
    report['table']['errors']['body_by_rows'] = rows
Pierre Dittgen's avatar
Pierre Dittgen committed
166 167 168 169

    return report


170
def validate(schema_code, source: ValidataSource):
171 172
    """ Validate source and display report """

Pierre Dittgen's avatar
Pierre Dittgen committed
173
    try:
174 175 176 177 178
        goodtables_report = ValidatorHelper.validate(
            schema_code=schema_code,
            force_strings=True,
            **source.get_tabulator_params(),
        )
Pierre Dittgen's avatar
Pierre Dittgen committed
179 180 181
    except tabulator.exceptions.FormatError:
        flash_error('Erreur : format de fichier non supporté')
        return redirect(url_for('scdl_validator', val_code=schema_code))
182 183

    source_data = extract_source_data(source)
184

Pierre Dittgen's avatar
Pierre Dittgen committed
185 186 187
    # handle report date
    date_str = goodtables_report['date']
    report_date = datetime.strptime(date_str[:date_str.find('.')], '%Y-%m-%dT%H:%M:%S')
188

Pierre Dittgen's avatar
Pierre Dittgen committed
189
    # Enhance goodtables_report
190
    validata_report = create_validata_report(goodtables_report, ValidatorHelper.schema(schema_code).descriptor)
Pierre Dittgen's avatar
Pierre Dittgen committed
191

Pierre Dittgen's avatar
Pierre Dittgen committed
192
    # Display report to the user
Pierre Dittgen's avatar
Pierre Dittgen committed
193
    val_info = ValidatorHelper.schema_info(schema_code)
194
    return render_template('validation_report.html', title='Rapport de validation',
195
                           val_info=ValidatorHelper.schema_info(schema_code), report=validata_report,
Pierre Dittgen's avatar
Pierre Dittgen committed
196
                           validation_date=report_date.strftime('le %d/%m/%Y à %Hh%M'),
197
                           source=source, source_type=source.type, source_data=source_data,
198
                           print_mode=request.args.get('print', 'false') == 'true',
199
                           report_str=json.dumps(validata_report, sort_keys=True, indent=2),
Pierre Dittgen's avatar
Pierre Dittgen committed
200
                           breadcrumbs=[{'url': url_for('home'), 'title': 'Accueil'},
Pierre Dittgen's avatar
Pierre Dittgen committed
201 202
                                        {'url': url_for('scdl_validator', val_code=schema_code),
                                         'title': val_info['title']}])
203 204


205 206 207 208 209 210 211 212
def bytes_data(f):
    """ Gets bytes data from Werkzeug FileStorage instance """
    iob = BytesIO()
    f.save(iob)
    iob.seek(0)
    return iob.getvalue()


213 214 215 216 217 218
# Routes


@app.route('/')
def home():
    """ Home page """
Pierre Dittgen's avatar
Pierre Dittgen committed
219
    validators = ValidatorHelper.schema_info_list()
Pierre Dittgen's avatar
Pierre Dittgen committed
220
    flash_warning('Ce service est fourni en mode beta - certains problèmes peuvent subsister - nous mettons tout en œuvre pour améliorer son fonctionnement en continu')
221 222 223 224 225 226 227 228 229
    return render_template('home.html', title='Accueil', validators=validators)


@app.route('/validators')
def validators():
    """ No validators page """
    return redirect(url_for('home'))


230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
@app.route('/pdf/<val_code>')
def pdf_report(val_code):
    """PDF report generation"""
    err_prefix = 'Erreur de génération du rapport PDF: '

    if not ValidatorHelper.schema_exist(val_code):
        flash_error(err_prefix + 'schéma inconnu')
        return redirect(url_for('home'))

    url_param = request.args.get('url')
    if not url_param:
        flash_error(err_prefix+'url non fournie')
        return redirect(url_for('home'))

    validation_url = '{}?input=url&print=true&url={}'.format(url_for('scdl_validator', val_code=val_code, _external=True),
                                                             quote_plus(url_param))

    # temporary pdf_report.pdf filename
    tmp_pdf_report = Path('/tmp') / 'validata_{}_{}_pdf_report.pdf'.format(val_code, str(time.time()))

    cmd = ['chromium', '--headless', '--disable-gpu',
           '--print-to-pdf={}'.format(str(tmp_pdf_report)), validation_url]
    result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    if result.returncode != 0:
        flash_error(err_prefix + result.stdout)
        if tmp_pdf_report.exists():
            tmp_pdf_report.unlink()
        return redirect(url_for('home'))

    response = make_response(tmp_pdf_report.open('rb').read())
    response.headers.set('Content-disposition', 'attachment', filename='report.pdf')
    response.headers.set('Content-type', 'application/pdf')
    response.headers.set('Content-length', tmp_pdf_report.stat().st_size)

    tmp_pdf_report.unlink()

    return response


269 270 271 272 273 274 275 276 277 278
@app.route('/validators/<val_code>', methods=['GET', 'POST'])
def scdl_validator(val_code):
    """ Validator page """

    if not ValidatorHelper.schema_exist(val_code):
        flash_error('Validateur [{}] inconnu'.format(val_code))
        return redirect(url_for('home'))

    if request.method == 'GET':

Pierre Dittgen's avatar
Pierre Dittgen committed
279
        val_info = ValidatorHelper.schema_info(val_code)
280 281 282 283
        input_param = request.args.get('input')

        # First form display
        if input_param is None or input_param not in ('url', 'example'):
284
            return render_template('validation_form.html', title=val_info['title'],
285 286 287 288 289
                                   val_info=val_info,
                                   breadcrumbs=[{'url': url_for('home'), 'title': 'Accueil'}, ])

        # Process URL
        else:
290 291
            url_param = request.args.get('url')
            if url_param is None or url_param == '':
292 293
                flash_error("Vous n'avez pas indiqué d'url à valider")
                return redirect(url_for('scdl_validator', val_code=val_code))
294
            return validate(val_code, ValidataSource('url', url_param, url_param))
295 296 297 298

    else:  # POST
        input_param = request.form.get('input')
        if input_param is None:
Pierre Dittgen's avatar
Pierre Dittgen committed
299
            flash_error('Aucun fichier à valider')
300 301 302 303 304 305 306 307
            return redirect(url_for('scdl_validator', val_code=val_code))

        # File validation
        if input_param == 'file':
            f = request.files.get('file')
            if f is None:
                flash_warning("Vous n'avez pas indiqué de fichier à valider")
                return redirect(url_for('scdl_validator', val_code=val_code))
308

309
            return validate(val_code, ValidataSource('file', f.filename, bytes_data(f)))
310 311

        return 'Bizarre, vous avez dit bizarre ?'