示例#1
0
    def generate_document(self, template_id, field_data):
        """Return URL to the generated document - throw exception if not
        possible."""
        # Check user system is allowed to use template.
        ts = TemplateServer(TEMPLATE_URL)
        """
        templates = ts.get_templates(self._user_system_id)
        template_dict = {t[1]: t[2] for t in templates}
        do_pdf_dict = {t[1]: t[3] for t in templates}

        try:
            url = template_dict[template_id]
            do_pdf = do_pdf_dict[template_id]
        except KeyError:
            url = None
            raise RuntimeError(
                'Template {0} not available for client.'.format(
                    template_id)
            )
        """
        template = ts.get_template(self._user_system_id, template_id)
        if template is None:
            raise RuntimeError(
                "Template {0} not available for client.".format(template_id))
        url = template[0]
        do_pdf = template[1]
        # Retrieve template from template server.
        real_url = TEMPLATE_BASE_URL + url
        file_base, extension = os.path.splitext(url)
        file_base = file_base.split('/').pop()
        tmp_name = '/tmp/{0}{1}'.format(template_id, extension)
        (fn, headers) = urllib.urlretrieve(real_url, tmp_name)

        # Finally generate document, store in appropriate place and
        # return URL.

        # Get plugin.
        plugin_mapping = PluginMapping.objects.filter(
            extension=extension.strip('.').upper())[0]
        plugin = PluginManager.get_plugin(plugin_mapping.plugin)

        # Get fields from template system
        fields = ts.get_template_fields(template_id)
        # Get output file name
        unique_url = get_unique_token()
        output_dir = os.path.join(settings.MEDIA_ROOT, 'files')
        extension = 'pdf' if do_pdf else plugin_mapping.output_type
        output_file = '.'.join([unique_url, extension])
        output_path = os.path.join(output_dir, output_file)
        # TODO: Validate that fields in call exist in template, etc.
        output_url = settings.MEDIA_URL + 'files/' + output_file
        #raise RuntimeError("Not implemented: {0}".format(output_url))
        plugin.generate_document(tmp_name, output_path, field_data, do_pdf)
        # Calculate SHA1 hash of output file
        sha1 = hashlib.sha1()
        with open(output_path, 'rb') as f:
            sha1.update(f.read())
        hash = sha1.hexdigest()

        return (BROKER_BASE_URL + output_url, hash)
示例#2
0
    def generate_template_image(self, template_id, resolusion, image_type,
                                file_name):
        """
        Return a URL to the generated preview.
        """
        # Check user system is allowed to use template.
        ts = TemplateServer(TEMPLATE_URL)
        templates = ts.get_templates(self._user_system_id)
        template_dict = {t[1]: t[2] for t in templates}
        do_pdf_dict = {t[1]: t[3] for t in templates}

        try:
            url = template_dict[template_id]
            do_pdf = do_pdf_dict[template_id]
        except KeyError:
            url = None
            raise RuntimeError(
                'Template {0} not available for client.'.format(template_id))
        # Retrieve template from template server.
        real_url = TEMPLATE_BASE_URL + url
        file_base, extension = os.path.splitext(url)
        file_base = file_base.split('/').pop()
        tmp_name = '/tmp/{0}{1}'.format(template_id, extension)
        (fn, headers) = urllib.urlretrieve(real_url, tmp_name)

        # Finally generate document, store in appropriate place and
        # return URL.

        # Get plugin.
        plugin_mapping = PluginMapping.objects.filter(
            extension=extension.strip('.').upper())[0]
        plugin = PluginManager.get_plugin(plugin_mapping.plugin)

        # Get fields from template system
        fields = ts.get_template_fields(template_id)
        # Get output file name
        unique_url = get_unique_token()
        output_dir = os.path.join(settings.MEDIA_ROOT, 'files')
        extension = ".png"
        output_file = file_name[:file_name.rfind('.')] + "_" + image_type
        output_file += extension
        output_path = os.path.join(output_dir, output_file)
        # TODO: Validate that fields in call exist in template, etc.
        output_url = settings.MEDIA_URL + 'files/' + output_file
        print "generate_template_image IS RUN"
        plugin.generate_template_image(tmp_name, output_path, resolusion,
                                       image_type, fields)

        # Calculate SHA1 hash of output file
        sha1 = hashlib.sha1()
        with open(output_path, 'rb') as f:
            sha1.update(f.read())
        hash = sha1.hexdigest()
        return (BROKER_BASE_URL + output_url, hash)
示例#3
0
    def generate_fo_template(self, template_id, fo_file):
        """
        Return a URL to the generated preview.
        """
        # Check user system is allowed to use template.
        ts = TemplateServer(TEMPLATE_URL)
        templates = ts.get_templates(self._user_system_id)
        template_dict = {t[1]: t[2] for t in templates}
        do_pdf_dict = {t[1]: t[3] for t in templates}
        print "TEMPLATE_ID: " + template_id
        print "TEMPLATES: " + str(template_dict)

        try:
            url = template_dict[template_id]
            do_pdf = do_pdf_dict[template_id]
        except KeyError:
            url = None
            raise RuntimeError(
                'Template {0} not available for client.'.format(template_id))
        # Retrieve template from template server.
        real_url = TEMPLATE_BASE_URL + url
        file_base, extension = os.path.splitext(url)
        file_base = file_base.split('/').pop()
        tmp_name = '/tmp/{0}{1}'.format(template_id, extension)
        (fn, headers) = urllib.urlretrieve(real_url, tmp_name)

        # Get plugin.
        plugin_mapping = PluginMapping.objects.filter(
            extension=extension.strip('.').upper())[0]
        plugin = PluginManager.get_plugin(plugin_mapping.plugin)

        # Get output file name
        unique_url = get_unique_token()
        output_dir = os.path.join(settings.MEDIA_ROOT, 'files')
        extension = "fo"
        output_file = '.'.join([unique_url, extension])
        output_path = os.path.join(output_dir, output_file)
        output_url = settings.MEDIA_URL + 'files/' + output_file
        plugin.generate_xsl_fo_ghost_document(tmp_name, output_path)

        # Calculate SHA1 hash of output file
        sha1 = hashlib.sha1()
        with open(output_path, 'rb') as f:
            sha1.update(f.read())
        hash = sha1.hexdigest()
        return (BROKER_BASE_URL + output_url, hash)
示例#4
0
    def save(self, *args, **kwargs):
        fo_file_path = ""
        bs = BrokerServer(document_broker_settings.BROKER_URL)
        set_broker_server(bs)
        # Before save
        if self.file != self._old_file:
            self.version = self.version + 1
            """
            We check if template contains HTML input fields.
            """
            file_contents = self.file.read()
            if not "#[HTML]" in file_contents:
                """
                Couldn't make the commit keyword work on the save method.
                pre_save=
                super(Template, self).save(commit=False, *args, **kwargs)
                Except: save() got an unexpected keyword argument 'commit'

                This is a dirty way to find the next file:
                """
                found = True
                i = 0
                while found:
                    """
                    We traverse the files with this name and set the fo output
                    file to be the next one in the row.
                    """
                    wo_ext = str(self.file.name)
                    wo_ext = wo_ext[:str(self.file.name).rfind(".")]
                    ext = str(self.file.name)[str(self.file.name).rfind("."):]
                    if i == 0:
                        file_name = "files/"
                        file_name += wo_ext
                    else:
                        file_name += wo_ext
                        file_name += "_" + str(i)
                    try:
                        the_file = os.path.join(
                            settings.MEDIA_ROOT,
                            file_name + ext
                        )
                        with open(the_file, 'r') as f:
                            file_name = "files/"
                            found = True
                    except Exception as e:
                        fo_file_path = file_name + ".fo"
                        found = False
                    i += 1
                self.precompiled_file = fo_file_path
        plugin_mappings = bs.get_plugin_mappings()
        # Actual save
        super(Template, self).save(*args, **kwargs)
        # After save - extract field if file changed.
        if self.file != self._old_file:
            # Get plugin name from mapping
            (_, extension) = os.path.splitext(self.file.path)
            extension = extension.strip('.').upper()
            db = DocumentBroker(document_broker_settings.BROKER_URL)
            plugin_mappings = db.get_plugin_mappings()
            plugin = PluginManager.get_plugin(plugin_mappings[extension])
            fields = plugin.extract_document_fields(str(self.file.path))
            existing_fields = Field.objects.filter(document=self)

            for name, content_type in fields:
                if name not in [f.name for f in existing_fields]:
                    """ We set the default input type to be text. """
                    input_type = "TEXT"
                    """
                    We check if the field take HTML input and declare the input
                    type alike.
                    """
                    if len(name) > 7:
                        if name[:6] == "[HTML]":
                            input_type = "HTML"
                            self.precompiled_file = None
                    Field.objects.create(
                        name=name, type=input_type,
                        content_type="string", document=self)