def do_portlet_resource(self, request, response, **kwargs):
     theme = kwargs.get("theme", "default")
     res_path = os.path.join\
         (self._template_dir, "themes", theme, request.path)
     if os.path.exists(res_path):
         return tools.serve_file(request, response, res_path)
     res_path = os.path.join (self._template_dir, request.path)
     if os.path.exists(res_path):
         return tools.serve_file(request, response, res_path)
     return notfound(request, response)
 def do_portlet_resource(self, request, response, **kwargs):
     theme = kwargs.get("theme", "default")
     res_path = os.path.join\
         (self._template_dir, "themes", theme, request.path)
     if os.path.exists(res_path):
         return tools.serve_file(request, response, res_path)
     res_path = os.path.join(self._template_dir, request.path)
     if os.path.exists(res_path):
         return tools.serve_file(request, response, res_path)
     return notfound(request, response)
    def _on_request_1(self, event, request, response, peer_cert=None):
        """
        First request handler. This handler handles resource requests
        directed at the portal or a portlet.
        """
        if not self._is_portal_request(request):
            return

        if peer_cert:
            event.peer_cert = peer_cert
            
        # Decode query parameters and body
        event.kwargs = parse_qs(request.qs)
        parse_body(request, response, event.kwargs)
        session = request.session
        # Is this a portal portal request?
        if request.path.startswith(self._portal_resource):
            res = os.path.join(os.path.join\
                (self._portal_resource_dir, 
                 request.path[len(self._portal_resource):]))
            if os.path.exists(res):
                event.stop()
                return tools.serve_file(request, response, res)
            return
        # Is this a portal theme resource request?
        if request.path.startswith(self._theme_resource):
            for directory in self._portal._templates_dir:
                res = os.path.join \
                    (directory, "themes", 
                     ThemeSelection.selected(session), 
                     request.path[len(self._theme_resource):])
                if os.path.exists(res):
                    event.stop()
                    return tools.serve_file(request, response, res)
            return
        # Is this a portlet resource request?
        if request.path.startswith(self._portlet_resource):
            segs = request.path[len(self._portlet_resource):].split("/")
            if len(segs) >= 2:
                request.path = "/".join(segs[1:])
                event.kwargs.update\
                    ({ "theme": ThemeSelection.selected(session),
                       "locales": LanguagePreferences.preferred(session)})
                return self.fire (portlet_resource(*event.args, 
                                                   **event.kwargs), segs[0])
Exemple #4
0
    def _on_request_1(self, event, request, response, peer_cert=None):
        """
        First request handler. This handler handles resource requests
        directed at the portal or a portlet.
        """
        if not self._is_portal_request(request):
            return

        if peer_cert:
            event.peer_cert = peer_cert
            
        # Decode query parameters and body
        event.kwargs = parse_qs(request.qs)
        parse_body(request, response, event.kwargs)
        session = request.session
        # Is this a portal portal request?
        if request.path.startswith(self._portal_resource):
            res = os.path.join(os.path.join\
                (self._portal_resource_dir, 
                 request.path[len(self._portal_resource):]))
            if os.path.exists(res):
                event.stop()
                return tools.serve_file(request, response, res)
            return
        # Is this a portal theme resource request?
        if request.path.startswith(self._theme_resource):
            for directory in self._portal._templates_dir:
                res = os.path.join \
                    (directory, "themes", 
                     ThemeSelection.selected(session), 
                     request.path[len(self._theme_resource):])
                if os.path.exists(res):
                    event.stop()
                    return tools.serve_file(request, response, res)
            return
        # Is this a portlet resource request?
        if request.path.startswith(self._portlet_resource):
            segs = request.path[len(self._portlet_resource):].split("/")
            if len(segs) >= 2:
                request.path = "/".join(segs[1:])
                event.kwargs.update\
                    ({ "theme": ThemeSelection.selected(session),
                       "locales": LanguagePreferences.preferred(session)})
                return self.fire (portlet_resource(*event.args, 
                                                   **event.kwargs), segs[0])
    def raster(self, event):
        request, response = event.args[:2]
        try:
            filename, url = self._split_cache_url(request.path, 'raster')
        except UrlError as e:
            self.log('Rastertile cache url error:', e, exc=True, lvl=warn)
            return

        # self.log("RASTER QUERY:", filename, lvl=error)
        if os.path.exists(filename):
            return serve_file(request, response, filename)
        else:
            self.log('Non-existing raster tile request:',
                     filename,
                     lvl=verbose)
Exemple #6
0
    def tilecache(self, event, *args, **kwargs):
        """Checks and caches a requested tile to disk, then delivers it to
        client"""
        request, response = event.args[:2]
        try:
            filename, url = self._splitURL(request.path)
        except UrlError:
            return

        # Do we have the tile already?
        if os.path.isfile(filename):
            hfoslog("Tile exists in cache", emitter="MTS")
            # Don't set cookies for static content
            response.cookie.clear()
            try:
                yield serve_file(request, response, filename)
            finally:
                event.stop()
        else:
            # We will have to get it first.
            hfoslog("Tile not cached yet. Tile data: ", filename, url,
                    emitter="MTS")
            if url in self._tilelist:
                hfoslog("Getting a tile for the second time?!", lvl=error,
                        emitter="MTS")
            else:
                self._tilelist += url
            try:
                tile, log = yield self.call(task(get_tile, url), "tcworkers")
                if log:
                    hfoslog("Thread error: ", log, emitter="MTS")
            except Exception as e:
                hfoslog("[MTS]", e, type(e))
                tile = None

            tilepath = os.path.dirname(filename)

            if tile:
                try:
                    os.makedirs(tilepath)
                except OSError as e:
                    if e.errno != errno.EEXIST:
                        hfoslog("Couldn't create path: %s (%s)" % (e, type(e)),
                                exc=True, emitter="MTS")

                hfoslog("Caching tile.", lvl=verbose, emitter="MTS")
                try:
                    with open(filename, "wb") as tilefile:
                        try:
                            tilefile.write(bytes(tile))
                        except Exception as e:
                            hfoslog("Writing error: %s" % str([type(e), e]),
                                    emitter="MTS")

                except Exception as e:
                    hfoslog("Open error: %s" % str([type(e), e]),
                            emitter="MTS")
                    return
                finally:
                    event.stop()

                try:
                    hfoslog("Delivering tile.", lvl=verbose, emitter="MTS")
                    yield serve_file(request, response, filename)
                except Exception as e:
                    hfoslog("Couldn't deliver tile: ", e, lvl=error,
                            emitter="MTS")
                    event.stop()
                hfoslog("Tile stored and delivered.", lvl=verbose,
                        emitter="MTS")
            else:
                hfoslog("Got no tile, serving defaulttile: %s" % url,
                        emitter="MTS")
                if self.defaulttile:
                    try:
                        yield serve_file(request, response, self.defaulttile)
                    finally:
                        event.stop()
                else:
                    yield
    def index(self, event, *args, **kwargs):
        """Checks and caches a requested tile to disk, then delivers it to
        client"""
        request, response = event.args[:2]

        cookie = request.cookie.get('isomer-client',
                                    request.cookie.get('isomer-dev', None))

        if cookie is None:
            self.log('Client not authorized by cookie.', lvl=warn)
            return

        # self.log(request.path, lvl=verbose)
        try:
            filename, url = self._split_cache_url(request.path, 'tilecache')
        except UrlError:
            return

        # self.log('CACHE QUERY:', filename, url)

        # Do we have the tile already?
        if os.path.isfile(filename):
            self.log("Tile exists in cache", lvl=verbose)
            # Don't set cookies for static content
            response.cookie.clear()
            try:
                yield serve_file(request, response, filename)
            finally:
                event.stop()
        else:
            # We will have to get it first.
            self.log("Tile not cached yet. Tile data: ",
                     filename,
                     url,
                     lvl=verbose)
            if url in self._tiles:
                self.log("Getting a tile for the second time?!", lvl=error)
            else:
                self._tiles += url
            try:
                tile, log = yield self.call(task(get_tile, url), "tcworkers")
                if log:
                    self.log("Thread error: ", log, lvl=error)
            except Exception as e:
                self.log("[MTS]", e, type(e))
                tile = None

            tile_path = os.path.dirname(filename)

            if tile:
                try:
                    os.makedirs(tile_path)
                except OSError as e:
                    if e.errno != errno.EEXIST:
                        self.log("Couldn't create path: %s (%s)" %
                                 (e, type(e)),
                                 lvl=error)

                self.log("Caching tile.", lvl=verbose)
                try:
                    with open(filename, "wb") as tile_file:
                        try:
                            tile_file.write(bytes(tile))
                        except Exception as e:
                            self.log("Writing error: %s" % str([type(e), e]),
                                     lvl=error)

                except Exception as e:
                    self.log("Open error on %s - %s" %
                             (filename, str([type(e), e])),
                             lvl=error)
                    return
                finally:
                    event.stop()

                try:
                    self.log("Delivering tile.", lvl=verbose)
                    yield serve_file(request, response, filename)
                except Exception as e:
                    self.log("Couldn't deliver tile: ", e, lvl=error)
                    event.stop()
                self.log("Tile stored and delivered.", lvl=verbose)
            else:
                self.log("Got no tile, serving default tile: %s" % url)
                if self.default_tile:
                    try:
                        yield serve_file(request, response, self.default_tile)
                    except Exception as e:
                        self.log('Cannot deliver default tile:',
                                 e,
                                 type(e),
                                 exc=True,
                                 lvl=error)
                    finally:
                        event.stop()
                else:
                    yield
Exemple #8
0
    def _on_request(self, event, request, response):
        if self.path is not None and not request.path.startswith(self.path):
            return

        path = request.path

        if self.path is not None:
            path = path[len(self.path):]

        path = unquote(path.strip("/"))

        if path:
            location = os.path.abspath(os.path.join(self.docroot, path))
        else:
            location = os.path.abspath(os.path.join(self.docroot, "."))

        if not os.path.exists(location):
            return

        if not location.startswith(os.path.dirname(self.docroot)):
            return  # hacking attemp e.g. /foo/../../../../../etc/shadow

        # Is it a file we can serve directly?
        if os.path.isfile(location):
            # Don't set cookies for static content
            response.cookie.clear()
            try:
                return serve_file(request, response, location)
            finally:
                event.stop()

        # Is it a directory?
        elif os.path.isdir(location):

            # Try to serve one of default files first..
            for default in self.defaults:
                location = os.path.abspath(
                    os.path.join(self.docroot, path, default)
                )
                if os.path.exists(location):
                    # Don't set cookies for static content
                    response.cookie.clear()
                    try:
                        return serve_file(request, response, location)
                    finally:
                        event.stop()

            # .. serve a directory listing if allowed to.
            if self.dirlisting:
                directory = os.path.abspath(os.path.join(self.docroot, path))
                cur_dir = os.path.join(self.path, path) if self.path else ""

                if not path:
                    url_up = ""
                else:
                    if self.path is None:
                        url_up = os.path.join("/", os.path.split(path)[0])
                    else:
                        url_up = os.path.join(cur_dir, "..")
                    url_up = '<li><a href="%s">%s</a></li>' % (url_up, "..")

                listing = []
                for item in os.listdir(directory):
                    if not item.startswith("."):
                        url = os.path.join("/", path, cur_dir, item)
                        location = os.path.abspath(
                            os.path.join(self.docroot, path, item)
                        )
                        if os.path.isdir(location):
                            li = '<li><a href="%s/">%s/</a></li>' % (
                                quote(url), item
                            )
                        else:
                            li = '<li><a href="%s">%s</a></li>' % (
                                quote(url), item
                            )
                        listing.append(li)

                ctx = {}
                ctx["directory"] = cur_dir or os.path.join("/", cur_dir, path)
                ctx["url_up"] = url_up
                ctx["listing"] = "\n".join(listing)
                try:
                    return _dirlisting_template.safe_substitute(ctx)
                finally:
                    event.stop()
Exemple #9
0
 def download(self):
     path = self.storage._file_path(self.name)
     expires(self.request, self.response, 60*60*24*30, force=True)
     return serve_file(self.request, self.response, path, type=self.mime)
Exemple #10
0
 def view(self):
     path = self.storage._file_path(self.name)
     return serve_file(self.request, self.response, path, type=self.mime)
Exemple #11
0
    def _on_request(self, event, request, response):
        if self.path is not None and not request.path.startswith(self.path):
            return

        path = request.path

        if self.path is not None:
            path = path[len(self.path):]

        path = unquote(path.strip("/"))

        if path:
            location = os.path.abspath(os.path.join(self.docroot, path))
        else:
            location = os.path.abspath(os.path.join(self.docroot, "."))

        if not os.path.exists(location):
            return

        if not location.startswith(os.path.dirname(self.docroot)):
            return  # hacking attemp e.g. /foo/../../../../../etc/shadow

        # Is it a file we can serve directly?
        if os.path.isfile(location):
            # Don't set cookies for static content
            response.cookie.clear()
            try:
                return serve_file(request, response, location)
            finally:
                event.stop()

        # Is it a directory?
        elif os.path.isdir(location):

            # Try to serve one of default files first..
            for default in self.defaults:
                location = os.path.abspath(
                    os.path.join(self.docroot, path, default))
                if os.path.exists(location):
                    # Don't set cookies for static content
                    response.cookie.clear()
                    try:
                        return serve_file(request, response, location)
                    finally:
                        event.stop()

            # .. serve a directory listing if allowed to.
            if self.dirlisting:
                directory = os.path.abspath(os.path.join(self.docroot, path))
                cur_dir = os.path.join(self.path, path) if self.path else ""

                if not path:
                    url_up = ""
                else:
                    if self.path is None:
                        url_up = os.path.join("/", os.path.split(path)[0])
                    else:
                        url_up = os.path.join(cur_dir, "..")
                    url_up = '<li><a href="%s">%s</a></li>' % (url_up, "..")

                listing = []
                for item in os.listdir(directory):
                    if not item.startswith("."):
                        url = os.path.join("/", path, cur_dir, item)
                        location = os.path.abspath(
                            os.path.join(self.docroot, path, item))
                        if os.path.isdir(location):
                            li = '<li><a href="%s/">%s/</a></li>' % (
                                quote(url), item)
                        else:
                            li = '<li><a href="%s">%s</a></li>' % (quote(url),
                                                                   item)
                        listing.append(li)

                ctx = {}
                ctx["directory"] = cur_dir or os.path.join("/", cur_dir, path)
                ctx["url_up"] = url_up
                ctx["listing"] = "\n".join(listing)
                try:
                    return _dirlisting_template.safe_substitute(ctx)
                finally:
                    event.stop()
Exemple #12
0
    def tilecache(self, event, *args, **kwargs):
        """Checks and caches a requested tile to disk, then delivers it to client"""
        request, response = event.args[:2]
        try:
            filename, url = self._splitURL(request.path)
        except UrlError:
            return

        # Do we have the tile already?
        if os.path.isfile(filename):
            hfoslog("[TC] Tile exists in cache")
            # Don't set cookies for static content
            response.cookie.clear()
            try:
                yield serve_file(request, response, filename)
            finally:
                event.stop()
        else:
            # We will have to get it first.
            hfoslog("[TC] Tile not cached yet. Tile data: ", filename, url)
            if url in self._tilelist:
                hfoslog("[TC] Getting a tile for the second time?!", lvl=error)
            else:
                self._tilelist += url
            try:
                tile, log = yield self.call(task(get_tile, url), "tcworkers")
                if log:
                    hfoslog("[TC] Thread error: ", log)
            except Exception as e:
                hfoslog("[TC]", e, type(e))
                tile = None

            tilepath = os.path.dirname(filename)

            if tile:
                try:
                    os.makedirs(tilepath)
                except OSError as e:
                    if e.errno != errno.EEXIST:
                        hfoslog("[TC] Couldn't create path: %s (%s)" %
                                (e, type(e)))

                hfoslog("[TC] Caching tile.", lvl=verbose)
                try:
                    with open(filename, "wb") as tilefile:
                        try:
                            tilefile.write(bytes(tile))
                        except Exception as e:
                            hfoslog("[TC] Writing error: %s" %
                                    str([type(e), e]))

                except Exception as e:
                    hfoslog("[TC] Open error: %s" % str([type(e), e]))
                    return
                finally:
                    event.stop()

                try:
                    hfoslog("[TC] Delivering tile.", lvl=verbose)
                    yield serve_file(request, response, filename)
                except Exception as e:
                    hfoslog("[TC] Couldn't deliver tile: ", e, lvl=error)
                    event.stop()
                hfoslog("[TC] Tile stored and delivered.", lvl=verbose)
            else:
                hfoslog("[TC] Got no tile, serving defaulttile: %s" % url)
                if self.defaulttile:
                    try:
                        yield serve_file(request, response, self.defaulttile)
                    finally:
                        event.stop()
                else:
                    yield