Exemplo n.º 1
0
    def moveFile(self, at, importPath):
        """Copies file at p_at into the ODT file at p_importPath."""
        # Has this image already been imported ?
        for imagePath, imageAt in self.fileNames.items():
            if imageAt == at:
                # Yes!
                i = importPath.rfind(self.pictFolder) + 1
                return importPath[:i] + imagePath
        # The image has not already been imported: copy it.
        if not at.startswith("http"):
            shutil.copy(at, importPath)
            return importPath
        # The image must be retrieved via a URL. Try to perform a HTTP GET.
        response = Resource(at).get()
        if response.code == 200:
            # At last, I can get the file format.
            self.format = mimeTypesExts[response.headers["Content-Type"]]
            importPath += self.format
            f = file(importPath, "wb")
            f.write(response.body)
            f.close()
            return importPath
        # The HTTP GET did not work, maybe for security reasons (we probably
        # have no permission to get the file). But maybe the URL was a local
        # one, from an application server running this POD code. In this case,
        # if an image resolver has been given to POD, use it to retrieve the
        # image.
        imageResolver = self.renderer.imageResolver
        if not imageResolver:
            # Return some default image explaining that the image wasn't found.
            import appy.pod

            podFolder = os.path.dirname(appy.pod.__file__)
            img = os.path.join(podFolder, "imageNotFound.jpg")
            self.format = "jpg"
            importPath += self.format
            f = file(img)
            imageContent = f.read()
            f.close()
            f = file(importPath, "wb")
            f.write(imageContent)
            f.close()
        else:
            # The imageResolver is a Zope application. From it, we will
            # retrieve the object on which the image is stored and get
            # the file to download.
            urlParts = urllib.parse.urlsplit(at)
            path = urlParts[2][1:].split("/")[:-1]
            try:
                obj = imageResolver.unrestrictedTraverse(path)
            except KeyError:
                # Maybe a rewrite rule as added some prefix to all URLs?
                obj = imageResolver.unrestrictedTraverse(path[1:])
            zopeFile = getattr(obj, urlParts[3].split("=")[1])
            appyFile = FileWrapper(zopeFile)
            self.format = mimeTypesExts[appyFile.mimeType]
            importPath += self.format
            appyFile.dump(importPath)
        return importPath
Exemplo n.º 2
0
 def moveFile(self, at, importPath):
     '''Copies file at p_at into the ODT file at p_importPath.'''
     # Has this image already been imported ?
     for imagePath, imageAt in self.fileNames.iteritems():
         if imageAt == at:
             # Yes!
             i = importPath.rfind(self.pictFolder) + 1
             return importPath[:i] + imagePath
     # The image has not already been imported: copy it.
     if not at.startswith('http'):
         shutil.copy(at, importPath)
         return importPath
     # The image must be retrieved via a URL. Try to perform a HTTP GET.
     response = Resource(at).get()
     if response.code == 200:
         # At last, I can get the file format.
         self.format = mimeTypesExts[response.headers['Content-Type']]
         importPath += self.format
         f = file(importPath, 'wb')
         f.write(response.body)
         f.close()
         return importPath
     # The HTTP GET did not work, maybe for security reasons (we probably
     # have no permission to get the file). But maybe the URL was a local
     # one, from an application server running this POD code. In this case,
     # if an image resolver has been given to POD, use it to retrieve the
     # image.
     imageResolver = self.renderer.imageResolver
     if not imageResolver:
         # Return some default image explaining that the image wasn't found.
         import appy.pod
         podFolder = os.path.dirname(appy.pod.__file__)
         img = os.path.join(podFolder, 'imageNotFound.jpg')
         self.format = 'jpg'
         importPath += self.format
         f = file(img)
         imageContent = f.read()
         f.close()
         f = file(importPath, 'wb')
         f.write(imageContent)
         f.close()
     else:
         # The imageResolver is a Zope application. From it, we will
         # retrieve the object on which the image is stored and get
         # the file to download.
         urlParts = urlparse.urlsplit(at)
         path = urlParts[2][1:].split('/')[:-1]
         try:
             obj = imageResolver.unrestrictedTraverse(path)
         except KeyError:
             # Maybe a rewrite rule as added some prefix to all URLs?
             obj = imageResolver.unrestrictedTraverse(path[1:])
         zopeFile = getattr(obj, urlParts[3].split('=')[1])
         appyFile = FileWrapper(zopeFile)
         self.format = mimeTypesExts[appyFile.mimeType]
         importPath += self.format
         appyFile.dump(importPath)
     return importPath
Exemplo n.º 3
0
 def importPod(self,
               content=None,
               at=None,
               format='odt',
               context=None,
               pageBreakBefore=False,
               pageBreakAfter=False):
     '''Similar to m_importDocument, but allows to import the result of
        executing the POD template specified in p_content or p_at, and
        include it in the POD result.'''
     # Is there a pod template defined?
     if not content and not at:
         raise PodError(DOC_NOT_SPECIFIED)
     # If the POD template is specified as a Zope file, convert it into a
     # Appy FileWrapper.
     if content.__class__.__name__ == 'File':
         content = FileWrapper(content)
     imp = PodImporter(content, at, format, self)
     self.forceOoCall = True
     # Define the context to use: either the current context of the current
     # POD renderer, or p_context if given.
     if context:
         ctx = context
     else:
         ctx = self.contentParser.env.context
     imp.init(ctx, pageBreakBefore, pageBreakAfter)
     return imp.run()
Exemplo n.º 4
0
    def importDocument(self, content=None, at=None, format=None,
                       anchor='as-char', wrapInPara=True, size=None,
                       sizeUnit='cm', style=None,
                       pageBreakBefore=False, pageBreakAfter=False):
        '''If p_at is not None, it represents a path or url allowing to find
           the document. If p_at is None, the content of the document is
           supposed to be in binary format in p_content. The document
           p_format may be: odt or any format in imageFormats.

           p_anchor, p_wrapInPara and p_size, p_sizeUnit and p_style are only
           relevant for images:
           * p_anchor defines the way the image is anchored into the document;
                      Valid values are 'page','paragraph', 'char' and 'as-char';
           * p_wrapInPara, if true, wraps the resulting 'image' tag into a 'p'
                           tag;
           * p_size, if specified, is a tuple of float or integers
                     (width, height) expressing size in p_sizeUnit (see below).
                     If not specified, size will be computed from image info;
           * p_sizeUnit is the unit for p_size elements, it can be "cm"
             (centimeters) or "px" (pixels);
           * if p_style is given, it is the content of a "style" attribute,
             containing CSS attributes. If "width" and "heigth" attributes are
             found there, they will override p_size and p_sizeUnit.

           p_pageBreakBefore and p_pageBreakAfter are only relevant for import
           of external odt documents, and allows to insert a page break
           before/after the inserted document.
        '''
        importer = None
        # Is there someting to import?
        if not content and not at: raise PodError(DOC_NOT_SPECIFIED)
        # Convert Zope files into Appy wrappers.
        if content.__class__.__name__ in ('File', 'Image'):
            content = FileWrapper(content)
        # Guess document format
        if isinstance(content, FileWrapper):
            format = content.mimeType
        if not format:
            # It should be deduced from p_at
            if not at:
                raise PodError(DOC_FORMAT_ERROR)
            format = os.path.splitext(at)[1][1:]
        else:
            # If format is a mimeType, convert it to an extension
            if mimeTypesExts.has_key(format):
                format = mimeTypesExts[format]
        isImage = False
        isOdt = False
        if format in self.ooFormats:
            importer = OdtImporter
            self.forceOoCall = True
            isOdt = True
        elif (format in self.imageFormats) or not format:
            # If the format can't be guessed, we suppose it is an image.
            importer = ImageImporter
            isImage = True
        elif format == 'pdf':
            importer = PdfImporter
        elif format in self.convertibleFormats:
            importer = ConvertImporter
        else:
            raise PodError(DOC_WRONG_FORMAT % format)
        imp = importer(content, at, format, self)
        # Initialise image-specific parameters
        if isImage: imp.init(anchor, wrapInPara, size, sizeUnit, style)
        elif isOdt: imp.init(pageBreakBefore, pageBreakAfter)
        return imp.run()