示例#1
0
def getCaptionInfoDict(self):
    d = {}

    file_url_list = []
    file_label_list = []
    preset_label = ""

    counter = 0

    filelist, filelist2 = getFilelist(self, fieldname='.*captions.*')

    for filenode in filelist2:
        if filenode.getType() in ["u_other", "u_xml"]:
            filename = filenode.getName()
            file_ext = filename.split('.')[-1]
            if file_ext in ['srt', 'xml']:
                counter += 1
                file_url = "/file/%s/%s" % (self.id, filename)
                file_url_list.append(file_url)

                x = filename[0:-len(file_ext) + 1].split('-')
                if len(x) > 1 and len(x[-1]):
                    file_label = x[-1]
                else:
                    file_label = "Track %s" % counter
                file_label_list.append(file_label)

                if filename.find('preset') >= 0:
                    preset_label = file_label

    if file_url_list:
        d['file_list'] = ",".join([x.strip() for x in file_url_list])
        d['label_list'] = ",".join([x.strip() for x in file_label_list])
        d['preset_label'] = preset_label
    return d
示例#2
0
文件: video.py 项目: hibozzy/mediatum
def getCaptionInfoDict(self):
    d = {}

    file_url_list = []
    file_label_list = []
    preset_label = ""

    counter = 0

    filelist, filelist2 = getFilelist(self, fieldname='.*captions.*')

    for filenode in filelist2:
        if filenode.getType() in ["u_other", "u_xml"]:
            filename = filenode.getName()
            file_ext = filename.split('.')[-1]
            if file_ext in ['srt', 'xml']:
                counter += 1
                file_url = "/file/%s/%s" % (self.id, filename)
                file_url_list.append(file_url)

                x = filename[0:-len(file_ext) + 1].split('-')
                if len(x) > 1 and len(x[-1]):
                    file_label = x[-1]
                else:
                    file_label = "Track %s" % counter
                file_label_list.append(file_label)

                if filename.find('preset') >= 0:
                    preset_label = file_label

    if file_url_list:
        d['file_list'] = ",".join([x.strip() for x in file_url_list])
        d['label_list'] = ",".join([x.strip() for x in file_label_list])
        d['preset_label'] = preset_label
    return d
示例#3
0
    def show_workflow_node(self, node, req, data=None):

        check_context()

        user = users.getUserFromRequest(req)

        current_workflow = getNodeWorkflow(node)
        current_workflow_step = getNodeWorkflowStep(node)

        FATAL_ERROR = False
        FATAL_ERROR_STR = ""

        if "gotrue" in req.params:

            if not PYPDF_MODULE_PRESENT:
                del req.params['gotrue']
                return self.show_workflow_node(node, req)

            radio_apply_reset_accept = req.params.get(
                'radio_apply_reset_accept', '')

            if radio_apply_reset_accept == 'reset':
                for f in node.files:
                    f_name = f.base_name
                    if f_name.startswith(
                            'addpic2pdf_%s_node_%s_' %
                        (unicode(current_workflow_step.id), unicode(
                            node.id))) and f.filetype.startswith('p_document'):
                        logg.info(
                            "workflow step addpic2pdf(%s): going to remove file '%s' from node '%s' (%s) for request from user '%s' (%s)",
                            current_workflow_step.id, f_name, node.name,
                            node.id, user.login_name, req.ip)
                        node.files.remove(f)
                        db.session.commit()
                        try:
                            os.remove(f.abspath)
                        except:
                            logg.exception(
                                "exception in workflow setep addpic2pdf, removing file failed, ignoring"
                            )

                del req.params['gotrue']
                return self.show_workflow_node(node, req)

            elif radio_apply_reset_accept == 'accept':

                p_document_files = [
                    f for f in node.files
                    if f.filetype == 'p_document' and f.base_name.startswith(
                        'addpic2pdf_%s_node_%s_' %
                        (unicode(current_workflow_step.id), unicode(node.id)))
                ]

                if len(p_document_files) > 0:

                    p_document_file = p_document_files[0]

                    document_file = [
                        f for f in node.files if f.filetype == 'document'
                    ][0]

                    o_document_file = File(document_file.path, 'o_document',
                                           document_file.mimetype)

                    node.files.remove(document_file)
                    node.files.append(o_document_file)
                    o_document_name = o_document_file.base_name

                    for f in node.files:
                        if f.filetype in [
                                'thumb', 'fileinfo', 'fulltext'
                        ] or f.filetype.startswith('present'):
                            if os.path.splitext(
                                    f.base_name)[0] == os.path.splitext(
                                        o_document_name)[0]:
                                new_f = File(f.path, 'o_' + f.filetype,
                                             f.mimetype)
                                node.files.remove(f)
                                node.files.append(new_f)

                    new_document_file = File(p_document_file.path, 'document',
                                             p_document_file.mimetype)
                    node.files.remove(p_document_file)
                    node.files.append(new_document_file)
                    db.session.commit()
                    node.event_files_changed()

                del req.params['gotrue']
                return self.forwardAndShow(node, True, req)

            elif radio_apply_reset_accept == 'apply':

                drag_logo_fullname = req.params.get("input_drag_logo_fullname",
                                                    None)

                if not drag_logo_fullname:
                    req.params["addpic2pdf_error"] = "%s: %s" % (
                        format_date().replace('T', ' - '),
                        t(lang(req),
                          "admin_wfstep_addpic2pdf_no_logo_selected"))
                    del req.params['gotrue']
                    return self.show_workflow_node(node, req)

                drag_logo_filepath = [
                    f.abspath for f in current_workflow_step.files
                    if f.base_name == drag_logo_fullname
                ][0]

                pos_cm = req.params.get("input_poffset_cm", "0, 0")
                x_cm, y_cm = [float(x.strip()) for x in pos_cm.split(",")]

                pdf_in_filepath = getPdfFilepathForProcessing(
                    current_workflow_step, node)

                current_pageno = int(
                    req.params.get("input_current_page", "0").strip())

                radio_select_targetpages = req.params.get(
                    "radio_select_targetpages", "").strip()
                input_select_targetpages = req.params.get(
                    "input_select_targetpages", "").strip()

                printer_range = []
                page_count = get_pdf_pagecount(pdf_in_filepath)
                _parser_error = False

                try:
                    if radio_select_targetpages == "current_page":
                        printer_range = [current_pageno]
                    elif radio_select_targetpages == "all":
                        printer_range = range(0, page_count)
                    elif radio_select_targetpages == "pair":
                        printer_range = [
                            x for x in range(0, page_count) if x % 2
                        ]
                        if input_select_targetpages:
                            printer_range = [
                                x for x in printer_range if x in
                                parse_printer_range(input_select_targetpages,
                                                    maximum=page_count + 1)
                            ]
                    elif radio_select_targetpages == "impair":
                        printer_range = [
                            x for x in range(0, page_count) if not x % 2
                        ]
                        if input_select_targetpages:
                            printer_range = [
                                x for x in printer_range if x in
                                parse_printer_range(input_select_targetpages,
                                                    maximum=page_count + 1)
                            ]
                    elif radio_select_targetpages == "range_only" and input_select_targetpages:
                        printer_range = parse_printer_range(
                            input_select_targetpages, maximum=page_count + 1)
                except ValueError as e:
                    _parser_error = True

                if _parser_error:
                    req.params["addpic2pdf_error"] = "%s: %s" % (
                        format_date().replace('T', ' - '),
                        t(lang(req),
                          "admin_wfstep_addpic2pdf_printer_range_error"))
                    del req.params['gotrue']
                    return self.show_workflow_node(node, req)

                printer_range = map(int, list(printer_range))

                if not printer_range:
                    req.params["addpic2pdf_error"] = "%s: %s" % (
                        format_date().replace('T', ' - '),
                        t(
                            lang(req),
                            "admin_wfstep_addpic2pdf_printer_range_selected_empty"
                        ))
                    del req.params['gotrue']
                    return self.show_workflow_node(node, req)

                x = x_cm * cm  # cm = 28.346456692913385
                y = y_cm * cm

                pic_dpi = get_pic_info(drag_logo_filepath).get('dpi', None)

                scale = 1.0

                if pic_dpi:
                    dpi_x, dpi_y = pic_dpi
                    if dpi_x != dpi_y:
                        req.params["addpic2pdf_error"] = "%s: %s" % (
                            format_date().replace('T', ' - '),
                            t(lang(req),
                              "admin_wfstep_addpic2pdf_logo_dpix_dpiy"))
                    dpi = int(dpi_x)
                    if dpi == 72:
                        scale = 1.0
                    else:
                        scale = 1.0 * 72.0 / dpi
                else:
                    dpi = 300
                    scale = 1.0 * 72.0 / dpi
                    #dpi = 72
                    #scale = 1.0

                tmppath = config.get("paths.datadir") + "tmp/"
                date_str = format_date().replace('T',
                                                 '-').replace(' ', '').replace(
                                                     ':', '-')
                filetempname = tmppath + \
                    "temp_addpic_pdf_wfs_%s_node_%s_%s_%s_.pdf" % (
                        unicode(current_workflow_step.id), unicode(node.id), date_str, unicode(random.random()))

                url = req.params.get('input_drag_logo_url', '')

                fn_out = filetempname

                build_logo_overlay_pdf(pdf_in_filepath,
                                       drag_logo_filepath,
                                       fn_out,
                                       x,
                                       y,
                                       scale=scale,
                                       mask='auto',
                                       pages=printer_range,
                                       follow_rotate=True,
                                       url=(" " * ADD_NBSP) + url)

                for f in node.files:
                    f_name = f.base_name
                    if f_name.startswith('addpic2pdf_%s_node_%s_' % (
                            unicode(current_workflow_step.id),
                            unicode(node.id),
                    )) and f.filetype.startswith('p_document'):
                        logg.info(
                            "workflow step addpic2pdf(%s): going to remove file '%s' from node '%s' (%s) for request from user '%s' (%s)",
                            current_workflow_step.id, f_name, node.name,
                            node.id, user.login_name, req.ip)
                        node.files.remove(f)
                        try:
                            os.remove(f.abspath)
                        except:
                            pass
                        break

                date_str = format_date().replace('T',
                                                 '-').replace(' ', '').replace(
                                                     ':', '-')
                nodeFile = importFileToRealname(
                    "_has_been_processed_%s.pdf" % (date_str),
                    filetempname,
                    prefix='addpic2pdf_%s_node_%s_' % (
                        unicode(current_workflow_step.id),
                        unicode(node.id),
                    ),
                    typeprefix="p_")
                node.files.append(nodeFile)
                db.session.commit()
                try:
                    os.remove(filetempname)
                except:
                    pass

                del req.params['gotrue']
                return self.show_workflow_node(node, req)

        if "gofalse" in req.params:
            return self.forwardAndShow(node, False, req)

        # part of show_workflow_node not handled by "gotrue" and "gofalse"

        try:
            pdf_filepath = [
                f.abspath for f in node.files
                if f.filetype.startswith('document')
            ][0]
            error_no_pdf = False
        except:
            error_no_pdf = t(
                lang(req),
                "admin_wfstep_addpic2pdf_no_pdf_document_for_this_node")

        if not PYPDF_MODULE_PRESENT or error_no_pdf:
            error = ""
            if not PYPDF_MODULE_PRESENT:
                error += t(lang(req), "admin_wfstep_addpic2pdf_no_pypdf")
            if error_no_pdf:
                error += error_no_pdf
            pdf_dimensions = {
                'd_pageno2size': {
                    0: [595.275, 841.889]
                },
                'd_pageno2rotate': {
                    0: 0
                }
            }  # A4
            keep_params = copyDictValues(req.params, {}, KEEP_PARAMS)
            context = {
                "key": req.params.get("key", req.session.get("key", "")),
                "error": error,
                "node": node,
                "files": node.files,
                "wfs": current_workflow_step,
                "wfs_files": [],
                "logo_info": {},
                "logo_info_list": [],
                "getImageSize": lambda x: (0, 0),
                "pdf_page_count": 0,
                "pdf_dimensions": pdf_dimensions,
                "json_pdf_dimensions": json.dumps(pdf_dimensions),
                "keep_params": json.dumps(keep_params),
                "startpageno": 0,
                "FATAL_ERROR": 'true',
                "user": users.getUserFromRequest(req),
                "prefix": self.get("prefix"),
                "buttons": self.tableRowButtons(node)
            }

            return req.getTAL("workflow/addpic2pdf.html",
                              context,
                              macro="workflow_addpic2pdf")
        try:
            pdf_dimensions = get_pdf_dimensions(pdf_filepath)
            pdf_pagecount = get_pdf_pagecount(pdf_filepath)
        except Exception as e:
            logg.exception("exception in workflow step addpic2pdf(%s)",
                           current_workflow_step.id)
            pdf_dimensions = {
                'd_pages': 0,
                'd_pageno2size': (0, 0),
                'd_pageno2rotate': 0
            }
            pdf_pagecount = 0
            FATAL_ERROR = True
            FATAL_ERROR_STR += " - %s" % (unicode(e))

        #wfs_files = [f for f in current_workflow_step.getFiles() if os.path.isfile(f.retrieveFile())]

        wfs_files0, wfs_files = getFilelist(current_workflow_step,
                                            'logoupload')

        url_mapping = [
            line.strip()
            for line in current_workflow_step.get("url_mapping").splitlines()
            if line.strip() and line.find("|") > 0
        ]
        url_mapping = dict(
            map(lambda x: (x[0].strip(), x[1].strip()),
                [line.split("|", 1) for line in url_mapping]))

        logo_info = {}
        logo_info_list = []
        for f in [
                f for f in wfs_files
                if f.base_name.startswith('m_upload_logoupload')
        ]:
            f_path = f.abspath

            try:
                _size = list(get_pic_size(f_path))
                _dpi = get_pic_dpi(f_path)
            except Exception as e:
                logg.exception("exception in workflow step addpic2pdf(%s)",
                               current_workflow_step.id)
                FATAL_ERROR = True
                FATAL_ERROR_STR += (" - ERROR loading logo '%s'" %
                                    f_path) + unicode(e)
                continue

            logo_filename = f.base_name

            logo_url = ""
            for key in url_mapping:
                if logo_filename.find(key) >= 0:
                    logo_url = url_mapping[key]
                    break

            logo_info[logo_filename.encode('utf-8')] = {
                'size': _size,
                'dpi': _dpi,
                'url': logo_url.encode('utf-8')
            }
            if _dpi == 'no-info':
                _dpi = 72.0
            logo_info_list.append({
                'size': _size,
                'dpi': _dpi,
                'url': logo_url.encode('utf-8')
            })

        if len(logo_info) == 0:
            logg.error(
                "workflow step addpic2pdf(%s): Error: no logo images found",
                current_workflow_step.id)
            FATAL_ERROR = True
            FATAL_ERROR_STR += " - Error: no logo images found"

        keep_params = copyDictValues(req.params, {}, KEEP_PARAMS)

        context = {
            "key": req.params.get("key", req.session.get("key", "")),
            "error": req.params.get('addpic2pdf_error', ''),
            "node": node,
            "files": node.files,
            "wfs": current_workflow_step,
            "wfs_files": wfs_files,
            "logo_info": logo_info,
            "logo_info_list": logo_info_list,
            "getImageSize": get_pic_size,
            "pdf_page_count": pdf_pagecount,
            "pdf_dimensions": pdf_dimensions,
            "json_pdf_dimensions": json.dumps(pdf_dimensions),
            "keep_params": json.dumps(keep_params),
            "startpageno": startpageno,
            "FATAL_ERROR": {
                False: 'false',
                True: 'true'
            }[bool(FATAL_ERROR)],
            "user": users.getUserFromRequest(req),
            "prefix": self.get("prefix"),
            "buttons": self.tableRowButtons(node)
        }

        if FATAL_ERROR:
            context["error"] += " - %s" % (FATAL_ERROR_STR)

        return req.getTAL("workflow/addpic2pdf.html",
                          context,
                          macro="workflow_addpic2pdf")
示例#4
0
    def show_workflow_node(self, node, req, data=None):

        check_context()

        user = users.getUserFromRequest(req)

        current_workflow = getNodeWorkflow(node)
        current_workflow_step = getNodeWorkflowStep(node)

        FATAL_ERROR = False
        FATAL_ERROR_STR = ""

        if "gotrue" in req.params:

            if not PYPDF_MODULE_PRESENT:
                del req.params['gotrue']
                return self.show_workflow_node(node, req)

            radio_apply_reset_accept = req.params.get('radio_apply_reset_accept', '')

            if radio_apply_reset_accept == 'reset':
                for f in node.files:
                    f_name = f.base_name
                    if f_name.startswith('addpic2pdf_%s_node_%s_' %
                                         (unicode(current_workflow_step.id), unicode(node.id))) and f.filetype.startswith('p_document'):
                        logg.info("workflow step addpic2pdf(%s): going to remove file '%s' from node '%s' (%s) for request from user '%s' (%s)",
                            current_workflow_step.id, f_name, node.name, node.id, user.login_name, req.ip)
                        node.files.remove(f)
                        db.session.commit()
                        try:
                            os.remove(f.abspath)
                        except:
                            logg.exception("exception in workflow setep addpic2pdf, removing file failed, ignoring")

                del req.params['gotrue']
                return self.show_workflow_node(node, req)

            elif radio_apply_reset_accept == 'accept':

                p_document_files = [f for f in node.files if f.filetype == 'p_document' and f.base_name.startswith(
                    'addpic2pdf_%s_node_%s_' % (unicode(current_workflow_step.id), unicode(node.id)))]

                if len(p_document_files) > 0:

                    p_document_file = p_document_files[0]

                    document_file = [f for f in node.files if f.filetype == 'document'][0]

                    o_document_file = File(document_file.path, 'o_document', document_file.mimetype)

                    node.files.remove(document_file)
                    node.files.append(o_document_file)
                    o_document_name = o_document_file.base_name

                    for f in node.files:
                        if f.filetype in ['thumb', 'fileinfo', 'fulltext'] or f.filetype.startswith('present'):
                            if os.path.splitext(f.base_name)[0] == os.path.splitext(o_document_name)[0]:
                                new_f = File(f.path, 'o_' + f.filetype, f.mimetype)
                                node.files.remove(f)
                                node.files.append(new_f)

                    new_document_file = File(p_document_file.path, 'document', p_document_file.mimetype)
                    node.files.remove(p_document_file)
                    node.files.append(new_document_file)
                    db.session.commit()
                    node.event_files_changed()

                del req.params['gotrue']
                return self.forwardAndShow(node, True, req)

            elif radio_apply_reset_accept == 'apply':

                drag_logo_fullname = req.params.get("input_drag_logo_fullname", None)

                if not drag_logo_fullname:
                    req.params["addpic2pdf_error"] = "%s: %s" % (
                        format_date().replace('T', ' - '), t(lang(req), "admin_wfstep_addpic2pdf_no_logo_selected"))
                    del req.params['gotrue']
                    return self.show_workflow_node(node, req)

                drag_logo_filepath = [f.abspath for f in current_workflow_step.files if f.base_name == drag_logo_fullname][0]

                pos_cm = req.params.get("input_poffset_cm", "0, 0")
                x_cm, y_cm = [float(x.strip()) for x in pos_cm.split(",")]

                pdf_in_filepath = getPdfFilepathForProcessing(current_workflow_step, node)

                current_pageno = int(req.params.get("input_current_page", "0").strip())

                radio_select_targetpages = req.params.get("radio_select_targetpages", "").strip()
                input_select_targetpages = req.params.get("input_select_targetpages", "").strip()

                printer_range = []
                page_count = get_pdf_pagecount(pdf_in_filepath)
                _parser_error = False

                try:
                    if radio_select_targetpages == "current_page":
                        printer_range = [current_pageno]
                    elif radio_select_targetpages == "all":
                        printer_range = range(0, page_count)
                    elif radio_select_targetpages == "pair":
                        printer_range = [x for x in range(0, page_count) if x % 2]
                        if input_select_targetpages:
                            printer_range = [x for x in printer_range if x in parse_printer_range(
                                input_select_targetpages, maximum=page_count + 1)]
                    elif radio_select_targetpages == "impair":
                        printer_range = [x for x in range(0, page_count) if not x % 2]
                        if input_select_targetpages:
                            printer_range = [x for x in printer_range if x in parse_printer_range(
                                input_select_targetpages, maximum=page_count + 1)]
                    elif radio_select_targetpages == "range_only" and input_select_targetpages:
                        printer_range = parse_printer_range(input_select_targetpages, maximum=page_count + 1)
                except ValueError as e:
                    _parser_error = True

                if _parser_error:
                    req.params["addpic2pdf_error"] = "%s: %s" % (
                        format_date().replace('T', ' - '), t(lang(req), "admin_wfstep_addpic2pdf_printer_range_error"))
                    del req.params['gotrue']
                    return self.show_workflow_node(node, req)

                printer_range = map(int, list(printer_range))

                if not printer_range:
                    req.params["addpic2pdf_error"] = "%s: %s" % (
                        format_date().replace('T', ' - '), t(lang(req), "admin_wfstep_addpic2pdf_printer_range_selected_empty"))
                    del req.params['gotrue']
                    return self.show_workflow_node(node, req)

                x = x_cm * cm  # cm = 28.346456692913385
                y = y_cm * cm

                pic_dpi = get_pic_info(drag_logo_filepath).get('dpi', None)

                scale = 1.0

                if pic_dpi:
                    dpi_x, dpi_y = pic_dpi
                    if dpi_x != dpi_y:
                        req.params["addpic2pdf_error"] = "%s: %s" % (
                            format_date().replace('T', ' - '), t(lang(req), "admin_wfstep_addpic2pdf_logo_dpix_dpiy"))
                    dpi = int(dpi_x)
                    if dpi == 72:
                        scale = 1.0
                    else:
                        scale = 1.0 * 72.0 / dpi
                else:
                    dpi = 300
                    scale = 1.0 * 72.0 / dpi
                    #dpi = 72
                    #scale = 1.0

                tmppath = config.get("paths.datadir") + "tmp/"
                date_str = format_date().replace('T', '-').replace(' ', '').replace(':', '-')
                filetempname = tmppath + \
                    "temp_addpic_pdf_wfs_%s_node_%s_%s_%s_.pdf" % (
                        unicode(current_workflow_step.id), unicode(node.id), date_str, unicode(random.random()))

                url = req.params.get('input_drag_logo_url', '')

                fn_out = filetempname

                build_logo_overlay_pdf(pdf_in_filepath, drag_logo_filepath, fn_out, x, y, scale=scale,
                                       mask='auto', pages=printer_range, follow_rotate=True, url=(" " * ADD_NBSP) + url)

                for f in node.files:
                    f_name = f.base_name
                    if f_name.startswith('addpic2pdf_%s_node_%s_' %
                                         (unicode(current_workflow_step.id), unicode(node.id), )) and f.filetype.startswith('p_document'):
                        logg.info("workflow step addpic2pdf(%s): going to remove file '%s' from node '%s' (%s) for request from user '%s' (%s)",
                            current_workflow_step.id, f_name, node.name, node.id, user.login_name, req.ip)
                        node.files.remove(f)
                        with suppress(Exception, warn=False):
                            os.remove(f.abspath)
                        break

                date_str = format_date().replace('T', '-').replace(' ', '').replace(':', '-')
                nodeFile = importFileToRealname("_has_been_processed_%s.pdf" % (date_str), filetempname, prefix='addpic2pdf_%s_node_%s_' % (
                    unicode(current_workflow_step.id), unicode(node.id), ), typeprefix="p_")
                node.files.append(nodeFile)
                db.session.commit()
                with suppress(Exception, warn=False):
                    os.remove(filetempname)
                del req.params['gotrue']
                return self.show_workflow_node(node, req)

        if "gofalse" in req.params:
            return self.forwardAndShow(node, False, req)

        # part of show_workflow_node not handled by "gotrue" and "gofalse"

        try:
            pdf_filepath = [f.abspath for f in node.files if f.filetype.startswith('document')][0]
            error_no_pdf = False
        except:
            error_no_pdf = t(lang(req), "admin_wfstep_addpic2pdf_no_pdf_document_for_this_node")

        if not PYPDF_MODULE_PRESENT or error_no_pdf:
            error = ""
            if not PYPDF_MODULE_PRESENT:
                error += t(lang(req), "admin_wfstep_addpic2pdf_no_pypdf")
            if error_no_pdf:
                error += error_no_pdf
            pdf_dimensions = {'d_pageno2size': {0: [595.275, 841.889]}, 'd_pageno2rotate': {0: 0}}  # A4
            keep_params = copyDictValues(req.params, {}, KEEP_PARAMS)
            context = {"key": req.params.get("key", req.session.get("key", "")),
                       "error": error,

                       "node": node,
                       "files": node.files,
                       "wfs": current_workflow_step,
                       "wfs_files": [],

                       "logo_info": {},
                       "logo_info_list": [],

                       "getImageSize": lambda x: (0, 0),
                       "pdf_page_count": 0,
                       "pdf_dimensions": pdf_dimensions,
                       "json_pdf_dimensions": json.dumps(pdf_dimensions),
                       "keep_params": json.dumps(keep_params),
                       "startpageno": 0,

                       "FATAL_ERROR": 'true',

                       "user": users.getUserFromRequest(req),
                       "prefix": self.get("prefix"),
                       "buttons": self.tableRowButtons(node),
                       "csrf": req.csrf_token.current_token,}

            return req.getTAL("workflow/addpic2pdf.html", context, macro="workflow_addpic2pdf")
        try:
            pdf_dimensions = get_pdf_dimensions(pdf_filepath)
            pdf_pagecount = get_pdf_pagecount(pdf_filepath)
        except Exception as e:
            logg.exception("exception in workflow step addpic2pdf(%s)", current_workflow_step.id)
            pdf_dimensions = {'d_pages': 0, 'd_pageno2size': (0, 0), 'd_pageno2rotate': 0}
            pdf_pagecount = 0
            FATAL_ERROR = True
            FATAL_ERROR_STR += " - %s" % (unicode(e))

        #wfs_files = [f for f in current_workflow_step.getFiles() if os.path.isfile(f.retrieveFile())]

        wfs_files0, wfs_files = getFilelist(current_workflow_step, 'logoupload')

        url_mapping = [line.strip()
                       for line in current_workflow_step.get("url_mapping").splitlines() if line.strip() and line.find("|") > 0]
        url_mapping = dict(map(lambda x: (x[0].strip(), x[1].strip()), [line.split("|", 1) for line in url_mapping]))

        logo_info = {}
        logo_info_list = []
        for f in [f for f in wfs_files if f.base_name.startswith('m_upload_logoupload')]:
            f_path = f.abspath

            try:
                _size = list(get_pic_size(f_path))
                _dpi = get_pic_dpi(f_path)
            except Exception as e:
                logg.exception("exception in workflow step addpic2pdf(%s)", current_workflow_step.id)
                FATAL_ERROR = True
                FATAL_ERROR_STR += (" - ERROR loading logo '%s'" % f_path) + unicode(e)
                continue

            logo_filename = f.base_name

            logo_url = ""
            for key in url_mapping:
                if logo_filename.find(key) >= 0:
                    logo_url = url_mapping[key]
                    break

            logo_info[logo_filename.encode('utf-8')] = {'size': _size, 'dpi': _dpi, 'url': logo_url.encode('utf-8')}
            if _dpi == 'no-info':
                _dpi = 72.0
            logo_info_list.append({'size': _size, 'dpi': _dpi, 'url': logo_url.encode('utf-8')})

        if len(logo_info) == 0:
            logg.error("workflow step addpic2pdf(%s): Error: no logo images found", current_workflow_step.id)
            FATAL_ERROR = True
            FATAL_ERROR_STR += " - Error: no logo images found"

        keep_params = copyDictValues(req.params, {}, KEEP_PARAMS)

        context = {"key": req.params.get("key", req.session.get("key", "")),
                   "error": req.params.get('addpic2pdf_error', ''),

                   "node": node,
                   "files": node.files,
                   "wfs": current_workflow_step,
                   "wfs_files": wfs_files,

                   "logo_info": logo_info,
                   "logo_info_list": logo_info_list,

                   "getImageSize": get_pic_size,
                   "pdf_page_count": pdf_pagecount,
                   "pdf_dimensions": pdf_dimensions,
                   "json_pdf_dimensions": json.dumps(pdf_dimensions),
                   "keep_params": json.dumps(keep_params),
                   "startpageno": startpageno,

                   "FATAL_ERROR": {False: 'false', True: 'true'}[bool(FATAL_ERROR)],

                   "user": users.getUserFromRequest(req),
                   "prefix": self.get("prefix"),
                   "buttons": self.tableRowButtons(node),
                   "csrf": req.csrf_token.current_token,}

        if FATAL_ERROR:
            context["error"] += " - %s" % (FATAL_ERROR_STR)

        return req.getTAL("workflow/addpic2pdf.html", context, macro="workflow_addpic2pdf")
示例#5
0
    def runAction(self, node, op=""):
        fnode = None
        for fnode in node.files:
            if fnode.filetype == "document":
                break

        def reformatAuthors(s):
            authors = s.strip().split(";")
            if len(authors) > 1:
                authors = ", ".join(authors[:-1]) + " and " + authors[-1]
            else:
                authors = authors[0]
            return authors

        # get pdf form appended to this workflow step through upload field 'upload_pdfform'
        current_workflow = getNodeWorkflow(node)
        current_workflow_step = getNodeWorkflowStep(node)
        formfilelist, formfilelist2 = getFilelist(current_workflow_step,
                                                  'upload_pdfform')

        pdf_fields_editable = current_workflow_step.get("pdf_fields_editable")
        pdf_form_separate = current_workflow_step.get("pdf_form_separate")
        pdf_form_overwrite = current_workflow_step.get("pdf_form_overwrite")

        if pdf_fields_editable.lower() in ["1", "true"]:
            pdf_fields_editable = True
        else:
            pdf_fields_editable = False

        if pdf_form_separate.lower() in ["1", "true"]:
            pdf_form_separate = True
        else:
            pdf_form_separate = False

        fields = []
        f_retrieve_path = None

        schema = getMetaType(node.schema)

        if formfilelist:
            # take newest (mtime)
            f_mtime, f_name, f_mimetype, f_size, f_type, f_retrieve_path, f = formfilelist[
                -1]

            for field_dict in parse_pdftk_fields_dump(
                    get_pdftk_fields_dump(f_retrieve_path)):
                fieldname = field_dict.get('FieldName', None)
                if fieldname:
                    value = ''
                    if fieldname in dict(node.attrs.items()):
                        schemafield = schema.children.filter_by(
                            name=fieldname).first()
                        value = schemafield.getFormattedValue(node)[1]
                        if fieldname.find('author') >= 0:
                            value = reformatAuthors(value)
                    elif fieldname.lower() == 'node.schema':
                        value = getMetaType(node.schema).getLongName()
                    elif fieldname.lower() == 'node.id':
                        value = unicode(node.id)
                    elif fieldname.lower() == 'node.type':
                        value = node.type
                    elif fieldname.lower() == 'date()':
                        value = format_date(now(), format='%d.%m.%Y')
                    elif fieldname.lower() == 'time()':
                        value = format_date(now(), format='%H:%M:%S')
                    elif fieldname.find("+") > 0:
                        for _fn in fieldname.split('+'):
                            value = node.get(_fn)
                            if value:
                                break
                    elif '[att:' in fieldname:
                        value = fieldname
                        while '[att:' in value:
                            m = re.search('(?<=\[att:)([^&\]]+)', value)
                            if m:
                                if m.group(0) == 'id':
                                    v = unicode(node.id)
                                elif m.group(0) == 'type':
                                    v = node.type
                                elif m.group(0) == 'schema':
                                    v = getMetaType(node.schema).getLongName()
                                else:
                                    schemafield = schema.children.filter_by(
                                        name=m.group(0)).first()
                                    v = schemafield.getFormattedValue(node)[0]
                                value = value.replace(
                                    '[att:%s]' % (m.group(0)), v)
                    else:
                        logg.warning(
                            "workflowstep %s (%s): could not find attribute for pdf form field '%s' - node: '%s' (%s)",
                            current_workflow_step.name,
                            current_workflow_step.id, fieldname, node.name,
                            node.id)
                    fields.append((fieldname, remove_tags(desc(value))))

        if not pdf_form_separate and fnode and f_retrieve_path and os.path.isfile(
                f_retrieve_path):
            pages = fillPDFForm(f_retrieve_path,
                                fields,
                                input_is_fullpath=True,
                                editable=pdf_fields_editable)
            if pages == "":  # error in pdf creation -> forward to false operation
                logg.error(
                    "workflowstep %s (%s): could not create pdf file - node: '%s' (%s)"
                    % (current_workflow_step.name, current_workflow_step.id,
                       node.name, node.id))
                self.forward(node, False)
                return
            origname = fnode.abspath
            outfile = addPagesToPDF(pages, origname)

            for f in node.files:
                node.files.remove(f)
            fnode.path = outfile.replace(config.get("paths.datadir"), "")
            node.files.append(fnode)
            node.files.append(
                File(origname, 'upload',
                     'application/pdf'))  # store original filename
            node.event_files_changed()
            db.session.commit()
            logg.info(
                "workflow '%s' (%s), workflowstep '%s' (%s): added pdf form to pdf (node '%s' (%s)) fields: %s",
                current_workflow.name, current_workflow.id,
                current_workflow_step.name, current_workflow_step.id,
                node.name, node.id, fields)

        elif pdf_form_separate and f_retrieve_path and os.path.isfile(
                f_retrieve_path):
            pages = fillPDFForm(f_retrieve_path,
                                fields,
                                input_is_fullpath=True,
                                editable=pdf_fields_editable)
            if pages == "":  # error in pdf creation -> forward to false operation
                logg.error(
                    "workflowstep %s (%s): could not create pdf file - node: '%s' (%s)"
                    % (current_workflow_step.name, current_workflow_step.id,
                       node.name, node.id))
                self.forward(node, False)
                return
            importdir = getImportDir()
            try:
                new_form_path = join_paths(importdir,
                                           "%s_%s" % (node.id, f_name))
                counter = 0
                if not pdf_form_overwrite:  # build correct filename
                    while os.path.isfile(new_form_path):
                        counter += 1
                        new_form_path = join_paths(
                            importdir, "%s_%s_%s" % (node.id, counter, f_name))
                # copy new file and remove tmp
                shutil.copy(pages, new_form_path)
                if os.path.exists(pages):
                    os.remove(pages)
            except Exception:
                logg.exception(
                    "workflowstep %s (%s): could not copy pdf form to import directory - node: '%s' (%s), import directory: '%s'",
                    current_workflow_step.name, current_workflow_step.id,
                    node.name, node.id, importdir)
            found = 0
            for fn in node.files:
                if fn.abspath == new_form_path:
                    found = 1
                    break
            if found == 0 or (found == 1 and not pdf_form_overwrite):
                node.files.append(
                    File(new_form_path, 'pdf_form', 'application/pdf'))
                db.session.commit()

            logg.info(
                "workflow '%s' (%s), workflowstep '%s' (%s): added separate pdf form to node (node '%s' (%s)) fields: %s, path: '%s'",
                current_workflow.name, current_workflow.id,
                current_workflow_step.name, current_workflow_step.id,
                node.name, node.id, fields, new_form_path)
        else:
            logg.warning(
                "workflowstep %s (%s): could not process pdf form - node: '%s' (%s)",
                current_workflow_step.name, current_workflow_step.id,
                node.name, node.id)

        self.forward(node, True)
示例#6
0
    def runAction(self, node, op=""):
        fnode = None
        for fnode in node.files:
            if fnode.filetype == "document":
                break

        def reformatAuthors(s):
            authors = s.strip().split(";")
            if len(authors) > 1:
                authors = ", ".join(authors[:-1]) + " and " + authors[-1]
            else:
                authors = authors[0]
            return authors

        # get pdf form appended to this workflow step through upload field 'upload_pdfform'
        current_workflow = getNodeWorkflow(node)
        current_workflow_step = getNodeWorkflowStep(node)
        formfilelist, formfilelist2 = getFilelist(current_workflow_step, 'upload_pdfform')

        pdf_fields_editable = current_workflow_step.get("pdf_fields_editable")
        pdf_form_separate = current_workflow_step.get("pdf_form_separate")
        pdf_form_overwrite = current_workflow_step.get("pdf_form_overwrite")

        if pdf_fields_editable.lower() in ["1", "true"]:
            pdf_fields_editable = True
        else:
            pdf_fields_editable = False

        if pdf_form_separate.lower() in ["1", "true"]:
            pdf_form_separate = True
        else:
            pdf_form_separate = False

        fields = []
        f_retrieve_path = None

        schema = getMetaType(node.schema)

        if formfilelist:
            # take newest (mtime)
            f_mtime, f_name, f_mimetype, f_size, f_type, f_retrieve_path, f = formfilelist[-1]

            for field_dict in parse_pdftk_fields_dump(get_pdftk_fields_dump(f_retrieve_path)):
                fieldname = field_dict.get('FieldName', None)
                if fieldname:
                    value = ''
                    if fieldname in dict(node.attrs.items()):
                        schemafield = schema.children.filter_by(name=fieldname).first()
                        value = schemafield.getFormattedValue(node)[1]
                        if fieldname.find('author') >= 0:
                            value = reformatAuthors(value)
                    elif fieldname.lower() == 'node.schema':
                        value = getMetaType(node.schema).getLongName()
                    elif fieldname.lower() == 'node.id':
                        value = unicode(node.id)
                    elif fieldname.lower() == 'node.type':
                        value = node.type
                    elif fieldname.lower() == 'date()':
                        value = format_date(now(), format='%d.%m.%Y')
                    elif fieldname.lower() == 'time()':
                        value = format_date(now(), format='%H:%M:%S')
                    elif fieldname.find("+") > 0:
                        for _fn in fieldname.split('+'):
                            value = node.get(_fn)
                            if value:
                                break
                    elif '[att:' in fieldname:
                        value = fieldname
                        while '[att:' in value:
                            m = re.search('(?<=\[att:)([^&\]]+)', value)
                            if m:
                                if m.group(0) == 'id':
                                    v = unicode(node.id)
                                elif m.group(0) == 'type':
                                    v = node.type
                                elif m.group(0) == 'schema':
                                    v = getMetaType(node.schema).getLongName()
                                else:
                                    schemafield = schema.children.filter_by(name=m.group(0)).first()
                                    v = schemafield.getFormattedValue(node)[0]
                                value = value.replace('[att:%s]' % (m.group(0)), v)
                    else:
                        logg.warning("workflowstep %s (%s): could not find attribute for pdf form field '%s' - node: '%s' (%s)",
                                       current_workflow_step.name, current_workflow_step.id, fieldname, node.name, node.id)
                    fields.append((fieldname, remove_tags(desc(value))))

        if not pdf_form_separate and fnode and f_retrieve_path and os.path.isfile(f_retrieve_path):
            pages = fillPDFForm(f_retrieve_path, fields, input_is_fullpath=True, editable=pdf_fields_editable)
            if pages == "":  # error in pdf creation -> forward to false operation
                logg.error("workflowstep %s (%s): could not create pdf file - node: '%s' (%s)" %
                           (current_workflow_step.name, current_workflow_step.id, node.name, node.id))
                self.forward(node, False)
                return
            origname = fnode.abspath
            outfile = addPagesToPDF(pages, origname)

            for f in node.files:
                node.files.remove(f)
            fnode.path = outfile.replace(config.get("paths.datadir"), "")
            node.files.append(fnode)
            node.files.append(File(origname, 'upload', 'application/pdf'))  # store original filename
            node.event_files_changed()
            db.session.commit()
            logg.info("workflow '%s' (%s), workflowstep '%s' (%s): added pdf form to pdf (node '%s' (%s)) fields: %s",
                current_workflow.name, current_workflow.id, current_workflow_step.name, current_workflow_step.id, node.name, node.id, fields)
            
        elif pdf_form_separate and f_retrieve_path and os.path.isfile(f_retrieve_path):
            pages = fillPDFForm(f_retrieve_path, fields, input_is_fullpath=True, editable=pdf_fields_editable)
            if pages == "":  # error in pdf creation -> forward to false operation
                logg.error("workflowstep %s (%s): could not create pdf file - node: '%s' (%s)" %
                           (current_workflow_step.name, current_workflow_step.id, node.name, node.id))
                self.forward(node, False)
                return
            importdir = getImportDir()
            try:
                new_form_path = join_paths(importdir, "%s_%s" % (node.id, f_name))
                counter = 0
                if not pdf_form_overwrite:  # build correct filename
                    while os.path.isfile(new_form_path):
                        counter += 1
                        new_form_path = join_paths(importdir, "%s_%s_%s" % (node.id, counter, f_name))
                # copy new file and remove tmp
                shutil.copy(pages, new_form_path)
                if os.path.exists(pages):
                    os.remove(pages)
            except Exception:
                logg.exception("workflowstep %s (%s): could not copy pdf form to import directory - node: '%s' (%s), import directory: '%s'",
                             current_workflow_step.name, current_workflow_step.id, node.name, node.id, importdir)
            found = 0
            for fn in node.files:
                if fn.abspath == new_form_path:
                    found = 1
                    break
            if found == 0 or (found == 1 and not pdf_form_overwrite):
                node.files.append(File(new_form_path, 'pdf_form', 'application/pdf'))
                db.session.commit()

            logg.info(
                "workflow '%s' (%s), workflowstep '%s' (%s): added separate pdf form to node (node '%s' (%s)) fields: %s, path: '%s'",
                current_workflow.name, current_workflow.id, current_workflow_step.name,
                current_workflow_step.id, node.name, node.id, fields, new_form_path)
        else:
            logg.warning("workflowstep %s (%s): could not process pdf form - node: '%s' (%s)",
                           current_workflow_step.name, current_workflow_step.id, node.name, node.id)

        self.forward(node, True)