Beispiel #1
0
    def getChild(self, name, request):
        # Python2.6/3.0
        #log.debug("{0} getting child {1} for {2}".format(
        #          self, name, request))
        log.debug("%r getting child %s for %r" % (self, name, request))

        try:
            sizeDesc, suffix = name.split(".")
            size = int(sizeDesc)

        except (TypeError, ValueError):
            child = Resource.getChild(self, name, request)

        else:
            suffix = suffix.upper()

            if suffix == "B":
                child = Junk(size, self._chunkSize)

            elif suffix == "KB":
                child = Junk(size * 1024, self._chunkSize)

            elif suffix == "MB":
                child = Junk(size * 1024 * 1024, self._chunkSize)

            else:
                child = Resource.getChild(self, name, request)

        return child
Beispiel #2
0
Datei: api.py Projekt: pdh/diablo
    def getChild(self, path, request):
        """ Implement URL routing.

        todo: add memoization
        """

        def potential_match(match, route):
            """ returns route if match is not None """
            if match:
                args = match.groups() or []
                kw = match.groupdict() or {}
                return route[1](*args, **kw)
            return None

        def try_to_match(url, route):
            """ returns route if match found, None otherwise """
            matching_route = potential_match(route[0].match(url), route)
            if not matching_route:
                # no match, now try toggling the ending slash
                newpath = self._toggleTrailingSlash(request.path)
                matching_route = potential_match(route[0].match(newpath), route)
            return matching_route

        for route in self._routes:
            match = try_to_match(request.path, route)
            if match:
                return match

        # let the base class handle 404
        return Resource.getChild(self, path, request)
Beispiel #3
0
    def getChild(self, path, request):
        """
        If path is an empty string or index, render_GET should be called,
        if not, we just look at the templates loaded from the view templates
        directory. If we find a template with the same name than the path
        then we render that template.

        .. caution::

            If there is a controller with the same path than the path
            then it will be hidden and the template in templates path
            should be rendered instead

        :param path: the path
        :type path: str
        :param request: the Twisted request object
        """

        if path == '' or path is None or path == 'index':
            return self

        for template in self.environment.list_templates():
            if path == template.rsplit('.', 1)[0]:
                return self

        return TwistedResource.getChild(self, path, request)
 def getChild(self, name, request):
     port = request.getHost().port
     if name == 'valid-mirror':
         leaf = DistributionMirrorTestHTTPServer()
         leaf.isLeaf = True
         return leaf
     elif name == 'timeout':
         return NeverFinishResource()
     elif name == 'error':
         return FiveHundredResource()
     elif name == 'redirect-to-valid-mirror':
         assert request.path != name, (
             'When redirecting to a valid mirror the path must have more '
             'than one component.')
         remaining_path = request.path.replace('/%s' % name, '')
         leaf = RedirectingResource('http://localhost:%s/valid-mirror%s' %
                                    (port, remaining_path))
         leaf.isLeaf = True
         return leaf
     elif name == 'redirect-infinite-loop':
         return RedirectingResource(
             'http://localhost:%s/redirect-infinite-loop' % port)
     elif name == 'redirect-unknown-url-scheme':
         return RedirectingResource(
             'ssh://localhost/redirect-unknown-url-scheme')
     else:
         return Resource.getChild(self, name, request)
Beispiel #5
0
    def getChild(self, path, request):
        """
        If path is an empty string or index, render_GET should be called,
        if not, we just look at the templates loaded from the view templates
        directory. If we find a template with the same name than the path
        then we render that template.

        .. caution::

            If there is a controller with the same path than the path
            parameter then it will be hidden and the template in templates
            path should be rendered instead

        :param path: the path
        :type path: str
        :param request: the Twisted request object
        """

        if path == '' or path is None or path == 'index':
            return self

        for template in self.environment.list_templates():
            if path == template.rsplit('.', 1)[0]:
                return self

        return TwistedResource.getChild(self, path, request)
Beispiel #6
0
 def getChild(self, name, request):
     mode = request.args.get('hub.mode', [None])[0]
     if mode in ['subscribe', 'unsubscribe']:
         return pubsub.SubscribeResource()
     elif mode == 'publish':
         return pubsub.PublishResource()
     return Resource.getChild(self, name, request)
 def getChild(self, name, request):
     port = request.getHost().port
     if name == 'valid-mirror':
         leaf = DistributionMirrorTestHTTPServer()
         leaf.isLeaf = True
         return leaf
     elif name == 'timeout':
         return NeverFinishResource()
     elif name == 'error':
         return FiveHundredResource()
     elif name == 'redirect-to-valid-mirror':
         assert request.path != name, (
             'When redirecting to a valid mirror the path must have more '
             'than one component.')
         remaining_path = request.path.replace('/%s' % name, '')
         leaf = RedirectingResource(
             'http://localhost:%s/valid-mirror%s' % (port, remaining_path))
         leaf.isLeaf = True
         return leaf
     elif name == 'redirect-infinite-loop':
         return RedirectingResource(
             'http://localhost:%s/redirect-infinite-loop' % port)
     elif name == 'redirect-unknown-url-scheme':
         return RedirectingResource(
             'ssh://localhost/redirect-unknown-url-scheme')
     else:
         return Resource.getChild(self, name, request)
Beispiel #8
0
 def getChild(self, name, request):
     mode = request.args.get("hub.mode", [None])[0]
     if mode in ["subscribe", "unsubscribe"]:
         return pubsub.SubscribeResource()
     elif mode == "publish":
         return pubsub.PublishResource()
     return Resource.getChild(self, name, request)
Beispiel #9
0
 def getChild(self, name, request):
     """
     should override.
     """
     if name == "":
         return self
     return Resource.getChild(self, name, request)
Beispiel #10
0
 def getChild(self, name, request):
     """
     Try and find the child for the name given
     """
     if name == "":
         return self
     else:
         return Resource.getChild(self, name, request)
Beispiel #11
0
 def getChild(self, path, request):
     if path == '':
         return self
     
     if len(request.postpath) >= 1:
         return APITMSID(path)
     
     return Resource.getChild(self, path, request)
Beispiel #12
0
 def getChild(self, name, request):
     """
     Try and find the child for the name given
     """
     if name == "":
         return self
     else:
         return Resource.getChild(self, name, request)
Beispiel #13
0
 def getChild(self, name, request):
     """
     Get the child page for the name given
     """
     if name == '':
         return self
     else:
         return Resource.getChild(self, name, request)
Beispiel #14
0
 def getChild(self, name, request):
     """
     Get the child page for the name given
     """
     if name == '':
         return self
     else:
         return Resource.getChild(self, name, request)
Beispiel #15
0
 def getChild(self, action, request):
     if action == '':
         return self
     else:
         if action in VIEWS.keys():
             return Resource.getChild(self, action, request)
         else:
             return NotFound()
Beispiel #16
0
 def getChild(self, name, request):
     if self.DEBUG:
         print("{}.getChild: ".format(self.name), name, request)
         print("  Children: ", self.listNames())
         print("  Headers: ", request.requestHeaders)
     child = Resource.getChild(self, name, request)
     if self.DEBUG:
         print("{}.getChild -> ".format(self.name), child)
     return child
Beispiel #17
0
    def getChild(self, name, request):
        out = Resource.getChild(self, name, request)
        print name

        if name and out.code == 404 and os.path.exists(os.path.join(self.pdfdir, name)):
            c = self.add_child(name)
            return c
        else:
            return out
Beispiel #18
0
    def getChild(self, name, request):
        if name.lower() == "valid":
            child = ValidMD5()
        elif name.lower() == "invalid":
            child = InvalidMD5()
        else:
            child = Resource.getChild(self, name, request)

        return child
Beispiel #19
0
Datei: ws.py Projekt: olix0r/pub
    def _getDeferredChild(self, name, request):
        try:
            entity = yield self.pubSvc.getEntity(name)

        except KeyError:
            baseName, sfx = self.splitResourceSuffix(name)
            try:
                entity = yield self.pubSvc.getEntity(baseName)
            except KeyError:
                resource = Resource.getChild(self, name, request)
            else:
                resource = self.buildEntityResource(baseName, entity, sfx)
                if not resource.suffixIsSupported(sfx):
                    resource = Resource.getChild(self, name, request)
        else:
            resource = self.buildEntityResource(name, entity)

        returnValue(resource)
Beispiel #20
0
 def getChild(self, path, request):
     """override Resource"""
     # TODO: Either add a cache here or throw out the cache in BlockResource which this is defeating, depending on a performance comparison
     path = path.decode('utf-8')  # TODO centralize this 'urls are utf-8'
     if path in self.__cap_table:
         return IResource(self.__resource_factory(self.__cap_table[path]))
     else:
         # old-style-class super call
         return Resource.getChild(self, path, request)
Beispiel #21
0
 def getChild(self, path, request):
     """override Resource"""
     # TODO: Either add a cache here or throw out the cache in BlockResource which this is defeating, depending on a performance comparison
     path = path.decode('utf-8')  # TODO centralize this 'urls are utf-8'
     if path in self.__cap_table:
         return IResource(self.__resource_factory(self.__cap_table[path]))
     else:
         # old-style-class super call
         return Resource.getChild(self, path, request)
Beispiel #22
0
 def getChild(self, name, request):
     """Follow the web tree to find the correct resource according to the URL
     
     name    The path specified by the URL
     request A twisted.web.server.Request specifying meta-information about
             the request
     """
     if name == '':
         return self
     return Resource.getChild(self, name, request)
Beispiel #23
0
    def getChild(self, name, request):
        """Overwrite the get child function so that we can handle invalid requests."""

        if name == '':
            return self
        else:
            if name in VIEWS.keys():
                return Resource.getChild(self, name, request)
            else:
                return PageNotFoundError()
Beispiel #24
0
  def getChild(self, path, request):
	if "media" in path or "favicon.ico" in path:
		return Resource.getChild(self, path, request)
	if len(path) == 0:
		path = "redirect.html"
	template = self.env.get_template(path)
	context = self.contexts.get(path, lambda x,y: {})(self, request)
	context["pairing_supported"]=bluetooth.isPairingSupported()
	context["version"] = __version__
	return TemplateResource(template, context)
Beispiel #25
0
  def getChild(self, name, request):
    """Overwrite the get child function so that we can handle invalid requests."""

    if name == '':
      return self
    else:
      if name in VIEWS.keys():
        return Resource.getChild(self, name, request)
      else:
        return PageNotFoundError()
Beispiel #26
0
	def getChild(self,name,request):
		if name == '':
			return self
		elif name == 'verify':
			return Verify()
		elif name == 'getip':
			return GetIp()
		else:
			return NotFount()
		return Resource.getChild(self,name,request)
Beispiel #27
0
    def getChild(self, name, request):
        if name == '':
            return self

        if name == 'announce':
            return AnnounceResource(self._peer_manager)

        if name == 'utility':
            return UtilityFactorResource(self._peer_manager)

        return Resource.getChild(self, name, request)
Beispiel #28
0
    def getChild(self, name, req):
        _cors(req)

        if req.method=='PUT' and len(name) > 0:
            # db creation
            return self
        elif req.method=='GET' and len(name) == 0:
            # db info (XXX: why do I need this to be explicit?)
            # Shouldn't the render_GET be called by default?
            return self
        return Resource.getChild(self, name, req)
Beispiel #29
0
 def getChild(self, path, req):
     uid = path.split('.')[0]
     t_dir = self.transcriber.out_dir(uid)
     if os.path.exists(t_dir):
         # TODO: Check that "status" is complete and only create a LazyZipper if so
         # Otherwise, we could have incomplete transcriptions that get permanently zipped.
         # For now, a solution will be hiding the button in the client until it's done.
         lz = LazyZipper(self.cachedir, self.transcriber, uid)
         self.putChild(path, lz)
         return lz
     else:
         return Resource.getChild(self, path, req)
Beispiel #30
0
 def getChild(self, path, request):
     if path == '': path = 'index'
     path = path.replace(".","_")
     cm = getattr(self, "wchild_"+path, None)
     if cm:
         p = cm(request)
         if isinstance(p, Deferred):
             return util.DeferredResource(p)
         adapter = components.getAdapter(p, IResource, None)
         if adapter is not None:
             return adapter
     return Resource.getChild(self, path, request)
Beispiel #31
0
 def getChild(self, path, req):
     uid = path.split('.')[0]
     t_dir = self.transcriber.out_dir(uid)
     if os.path.exists(t_dir):
         # TODO: Check that "status" is complete and only create a LazyZipper if so
         # Otherwise, we could have incomplete transcriptions that get permanently zipped.
         # For now, a solution will be hiding the button in the client until it's done.
         lz = LazyZipper(self.cachedir, self.transcriber, uid)
         self.putChild(path, lz)
         return lz
     else:
         return Resource.getChild(self, path, req)
Beispiel #32
0
 def getChild(self, name, request):
     if self._dynamic:
         curstate = self._block.state()
         if name in curstate:
             cell = curstate[name]
             if cell.type().is_reference():
                 return self.__getBlockChild(name, cell.get())
     else:
         if name in self._blockCells:
             return self.__getBlockChild(name, self._blockCells[name].get())
     # old-style-class super call
     return Resource.getChild(self, name, request)
Beispiel #33
0
 def getChild(self, name, request):
     if self._dynamic:
         curstate = self._block.state()
         if name in curstate:
             cell = curstate[name]
             if cell.isBlock():
                 return self.__getBlockChild(name, cell.get())
     else:
         if name in self._blockCells:
             return self.__getBlockChild(name, self._blockCells[name].get())
     # old-style-class super call
     return Resource.getChild(self, name, request)
Beispiel #34
0
 def getChild(self, path, request):
     if self._dynamic:
         curstate = self._block.state()
         if path in curstate:
             cell = curstate[path]
             if cell.type().is_reference():
                 return self.__getBlockChild(path, cell.get())
     else:
         if path in self._blockCells:
             return self.__getBlockChild(path, self._blockCells[path].get())
     # old-style-class super call
     return Resource.getChild(self, path, request)
Beispiel #35
0
    def getChild(self, name, request):

        if request.method == "GET":
            # Let's assume that all file are either empty (-> index.html) or have a period in them.
            if len(name) == 0 or "." in name:
                return self.file_resource.getChild(name, request)

            else:
                print 'making db', name

                dbdir = os.path.join(self.dbrootdir, name)

                subdir_resources = {}

                dbfactory = CommandDatabase(dbdir, subdir_resources)
                dbfactory.protocol = minidb.DBProtocol
                dbws_resource = WebSocketResource(dbfactory)
                subdir_resources['db'] = dbfactory

                factory = AudioConferenceFactory(subdir_resources, dbdir,
                                                 dbfactory)
                factory.protocol = AudioConferenceProtocol
                ws_resource = WebSocketResource(factory)
                subdir_resources['factory'] = factory

                attachdir = os.path.join(dbdir, "_attachments")
                attach = TranscodingAttachFactory(factory,
                                                  dbfactory,
                                                  attachdir=attachdir)
                attach.protocol = attachments.AttachProtocol
                subdir_resources['attach'] = attach

                attachhttp = File(attachdir)
                attws_resource = WebSocketResource(attach)

                zipper = DBZipper(dbfactory)

                root = File(self.webdir)
                dbhttp = File(dbdir)
                root.putChild('_ws', ws_resource)
                root.putChild('_db', dbws_resource)
                root.putChild('_attach', attws_resource)
                root.putChild('db', dbhttp)
                root.putChild('attachments', attachhttp)
                root.putChild('download.zip', zipper)

                self.putChild(name, root)
                return root

        return Resource.getChild(self, name, request)
    def getChild(self, name, request):
        out = Resource.getChild(self, name, request)
        LOGGER.warning("%s - %s", request.path, out.__class__.__name__)
        if isinstance(out, NoResource):
            # this matches the pre-existing behavior
            # of accepting any post as a message forward
            components = request.path.split('/')
            while components and components[0] == '':
                components.pop(0)
            LOGGER.warning("%s - %d", components, len(components))
            if len(components) > 0:
                out = ForwardPage(self.validator, components[0])

        return out
Beispiel #37
0
    def getChild(self, path, request):
        self.log.debug('{kass}.getChild(path={path}, request={request}, prepath={prepath}, postpath={postpath})',
                       kass=self.__class__.__name__,
                       path=path,
                       prepath=request.prepath,
                       postpath=request.postpath,
                       request=request)

        search_path = b'/'.join([path] + request.postpath).decode('utf8')

        if search_path == '' or search_path.endswith('/') or search_path in ['pair', 'pair.html']:
            return self
        else:
            return Resource.getChild(self, path, request)
Beispiel #38
0
 def getChild(self, path, request):
     if path == '': path = 'index'
     path = path.replace(".","_")
     cm = getattr(self, "wchild_"+path, None)
     if cm:
         p = cm(request)
         if isinstance(p, Deferred):
             return util.DeferredResource(p)
         adapter = components.getAdapter(p, IResource, None)
         if adapter is not None:
             return adapter
     # maybe we want direct support for ModelLoader?
     # cl = getattr(self, "wload_"+path, None) #???
     return Resource.getChild(self, path, request)
Beispiel #39
0
 def getChild(self, path, request):
     if path == '': path = 'index'
     path = path.replace(".", "_")
     cm = getattr(self, "wchild_" + path, None)
     if cm:
         p = cm(request)
         if isinstance(p, Deferred):
             return util.DeferredResource(p)
         adapter = components.getAdapter(p, IResource, None)
         if adapter is not None:
             return adapter
     # maybe we want direct support for ModelLoader?
     # cl = getattr(self, "wload_"+path, None) #???
     return Resource.getChild(self, path, request)
Beispiel #40
0
    def getChild(self, name, request):
        out = Resource.getChild(self, name, request)
        LOGGER.warning("%s - %s", request.path, out.__class__.__name__)
        if isinstance(out, NoResource):
            # this matches the pre-existing behavior
            # of accepting any post as a message forward
            components = request.path.split('/')
            while components and components[0] == '':
                components.pop(0)
            LOGGER.warning("%s - %d", components, len(components))
            if len(components) > 0:
                out = ForwardPage(self.validator, components[0])

        return out
Beispiel #41
0
    def getChild(self, name, request):
        if name == '':
            return self

        child = Resource.getChild(self, name, request)

        if isinstance(child, NoResource):
            session_path = os.path.normpath(os.path.join(os.path.dirname(__file__),"../data/",name))
            if os.path.exists(session_path):
                theory_path = glob.glob(os.path.join(session_path,'*.als'))[0]
                theory = os.path.splitext(os.path.basename(theory_path))[0]
                child = self.init_session(name, theory)

        return child
    def getChild(self, name, request):
        # Python2.6/3.0
        # log.debug("{0} getting child {1} for {2}".format(
        #          self, name, request))
        log.debug("%r getting child %s for %r" % (self, name, request))

        try:
            sizeDesc, suffix = name.split(".")
            relativeSize = long(sizeDesc)
            size = normalizeBytes(relativeSize, suffix)

        except (TypeError, ValueError), e:
            log.debug("Failed to determine size for %r: %r" % (name, e.args))
            child = Resource.getChild(self, name, request)
Beispiel #43
0
    def getChild(self, name, request):
        child = Resource.getChild(self, name, request)
        if name == self.STATIC_NAME:
            f = File(STATIC_DIR_PATH)
            if f.exists():
                return f
            else:
                return child

        f = File(STATIC_DIR_PATH + "/" + INDEX_FILE_NAME)
        if f.exists():
            return f
        else:
            return child
Beispiel #44
0
    def getChild(self, name, request):
        child = Resource.getChild(self, name, request)
        if name == self.STATIC_NAME:
            f = File(STATIC_DIR_PATH)
            if f.exists():
                return f
            else:
                return child


        f = File(STATIC_DIR_PATH + "/" + INDEX_FILE_NAME)
        if f.exists():
            return f
        else:
            return child
Beispiel #45
0
 def getChild(self, path, request):
     if "media" in path or "favicon.ico" in path:
         return Resource.getChild(self, path, request)
     if len(path) == 0:
         path = "redirect.html"
     template = self.env.get_template(path)
     context = self.contexts.get(path, lambda x,y: {})(self, request)
     context["pairing_supported"] = bluetooth.isPairingSupported()
     context["l2cap_supported"] = bluetooth.L2CAP_SUPPORTED
     context["sco_supported"] = bluetooth.SCO_SUPPORTED
     context["version"] = __version__
     try:
         context["android"] = bluetooth.isAndroid()
     except:
         context["android"] = False
     return TemplateResource(template, context)
Beispiel #46
0
 def getChild(self, path, request):
     if "media" in path or "favicon.ico" in path:
         return Resource.getChild(self, path, request)
     if len(path) == 0:
         path = "redirect.html"
     template = self.env.get_template(path)
     context = self.contexts.get(path, lambda x, y: {})(self, request)
     context["pairing_supported"] = bluetooth.isPairingSupported()
     context["l2cap_supported"] = bluetooth.L2CAP_SUPPORTED
     context["sco_supported"] = bluetooth.SCO_SUPPORTED
     context["version"] = __version__
     try:
         context["android"] = bluetooth.isAndroid()
     except:
         context["android"] = False
     return TemplateResource(template, context)
Beispiel #47
0
 def getChild(self, path, req):
     if path == "download":
         self.asDownload = True
         return self
     if path == "download_with_headers":
         self.asDownload = True
         self.withHeaders = True
         return self
     if path == "plaintext":
         self.newWindow = True
         return self
     if path == "plaintext_with_headers":
         self.newWindow = True
         self.withHeaders = True
         return self
     if path == "iframe":
         self.iFrame = True
         return self
     return Resource.getChild(self, path, req)
Beispiel #48
0
    def getChild(self, name, request):
        _cors(request)

        if request.method == "GET":
            # Let's assume that all file are either empty (-> index.html) or have a period in them.
            if len(name) == 0 or "." in name:
                return self.file_resource.getChild(name, request)
            elif "_" in name:
                # Why *not* allow some of the db tracking APIs...
                return self
            else:
                # get_or_create db?
                db = self.create_db(name)

                self.on_db_create(db)

                # Return new ddoc _rewrite
                return db.docs[self.ddoc_name].rewrite_resource
        else:
            # Error? 
            return Resource.getChild(self, name, request)
Beispiel #49
0
 def getChild(self, path, request):
     if path == "":
         return self
     else:
         return Resource.getChild(self, path, request)
 def getChild(self, name, request):
     if name == b'':
         return self
     return Resource.getChild(self, name, request)
Beispiel #51
0
 def getChild(self, name, request):
     print name
     if name == '':
         return File(STATIC_ROOT + '/index.html')
     return Resource.getChild(self, name, request)
Beispiel #52
0
 def getChild(self, name, request):
     if name == b"" and self.ui_enabled:
         return self
     return Resource.getChild(self, name, request)
Beispiel #53
0
 def getChild(self, name, request):
     if not name:
         return Resource.getChild(self, name, request)
     if not self.isServiceName(str(request.URLPath())):
         return RESTDomain(self.dispatcher, name, self.noerrors)
     return RESTService(self.dispatcher, self.domain, name, self.noerrors)
Beispiel #54
0
 def getChild(self, name, request):
     if not name:
         return Resource.getChild(self, name, request)
     if len(request.postpath) > 1:
         return RESTDomain(self.dispatcher, name, self.noerrors)
     return RESTService(self.dispatcher, None, name, self.noerrors)
Beispiel #55
0
 def getChild(self, name, request):
     if name == '':
         return self
     child = Resource.getChild(self, name, request)
     if isinstance(child, NoResource):
         return self
Beispiel #56
0
 def getChild(self, path, req):
     if path == "text":
         self.asText = True
         return self
     return Resource.getChild(self, path, req)
 def getChild(self, path, request):  # NOQA: N802
     if path == '':
         return self
     else:
         return Resource.getChild(self, path, request)