예제 #1
0
파일: webui.py 프로젝트: BigBlueHat/redbot
def standalone_main(port, static_dir):
    """Run RED as a standalone Web server."""
    static_files = {}
    for file in os.listdir(static_dir):
        sys.stderr.write("Loading %s...\n" % file)
        try:
            # FIXME: need to load icons
            static_files["/static/%s" % file] = open(
                os.path.join(static_dir, file)
            ).read()
        except IOError:
            sys.stderr.write("failed.\n")
    def red_handler(method, uri, req_hdrs, res_start, req_pause):
        p_uri = urlsplit(uri)
        if static_files.has_key(p_uri.path):
            res_body, res_done = res_start("200", "OK", [], nbhttp.dummy)
            res_body(static_files[p_uri.path])
            res_done(None)
        elif p_uri.path == "/":
            query = cgi.parse_qs(p_uri.query)
            test_uri = query.get('uri', [""])[0]
            test_hdrs = [] #FIXME
            base_uri = "/"
            descend = query.has_key('descend')
            res_hdrs = [('Content-Type', 'text/html; charset=utf-8')] 
            #FIXME: need to send proper content-type back, caching headers
            res_body, res_done = res_start(
                "200", "OK", res_hdrs, nbhttp.dummy
            )
            sys.stderr.write("%s %s %s\n" % (
                str(descend), test_uri, test_hdrs
            ))
            RedWebUi(test_uri, test_hdrs, base_uri, 
                res_body, output_hdr, descend
            )
            res_done(None)
        else:
            res_body, res_done = res_start(
                "404", "Not Found", [], nbhttp.dummy
            )
            res_done(None)
        return nbhttp.dummy, nbhttp.dummy
    nbhttp.Server("", port, red_handler)
    nbhttp.run() # FIXME: catch errors
예제 #2
0
파일: red_fetcher.py 프로젝트: acdha/redbot
 def _makeRequest(self):
     """
     Make an asynchronous HTTP request to uri, calling status_cb as it's updated and
     done_cb when it's done. Reason is used to explain what the request is in the
     status callback.
     """
     global outstanding_requests
     global total_requests
     outstanding_requests.append(self)
     total_requests += 1
     self._client = RedHttpClient(self._response_start)
     if self.status_cb and self.type:
         self.status_cb("fetching %s (%s)" % (self.uri, self.type))
     req_body, req_done = self._client.req_start(
         self.method, self.uri.encode('utf-8', 'replace'), self.req_hdrs, nbhttp.dummy)
     if self.req_body != None:
         req_body(self.req_body)
     req_done(None)
     if len(outstanding_requests) == 1:
         nbhttp.run()
예제 #3
0
파일: unicorn_ui.py 프로젝트: nunnun/redbot
    def __init__(self, test_uri):
        """
        Constractor
        @param test_uri: Test Uri
        """
        self.test_uri = test_uri
        try:
            self.red = InspectingResourceExpertDroid(self.test_uri)
            self.result = ""
            self.done = False
            self.groups = []
            logger = logging.getLogger()
            logger.setLevel(logging.DEBUG)
#            self.formatter = find_formatter('txt', 'txt', False)(
#                self.test_uri, self.test_uri, [], 'en', None
#            )
#            self.formatter.set_red(self.red.state)
#            self.formatter.start_output()

            self.red.run(self.done)
            nbhttp.run()
            
            if self.red.state.res_complete:
                self.result = self._generate_output_xml(test_uri).toprettyxml()
            else:
                error_string = ""
                if self.red.state.res_error['desc'] == nbhttp.error.ERR_CONNECT['desc']:
                    error_string = "Could not connect to the server (%s)" % self.red.res_error.get('detail', "unknown")
                elif self.red.state.res_error['desc'] == nbhttp.error.ERR_URL['desc']:
                    error_string = self.red.res_error.get('detail', "RED can't fetch that URL.")
                elif self.red.state.res_error['desc'] == nbhttp.error.ERR_READ_TIMEOUT['desc']:
                    error_string = self.red.res_error['desc']
                elif self.red.state.res_error['desc'] == nbhttp.error.ERR_HTTP_VERSION['desc']:
                    error_string = "<code>%s</code> isn't HTTP." % e(self.red.res_error.get('detail', '')[:20])
                else:
                    raise AssertionError, "Unidentified incomplete response error."
                self.result = self._generate_error_xml(error_string).toprettyxml()
        except:
            import traceback
            logging.error(traceback.format_exc())
            self.result = """<?xml version="1.0" ?>
예제 #4
0
파일: webui.py 프로젝트: ylafon/redbot
def cgi_main():
    """Run RED as a CGI Script."""
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) 
    base_uri = "http://%s%s%s" % ( # TODO: only supports HTTP
      os.environ.get('HTTP_HOST'),
      os.environ.get('SCRIPT_NAME'),
      os.environ.get('PATH_INFO', '')
    )
    method = os.environ.get('REQUEST_METHOD')
    query_string = cgi.parse_qs(os.environ.get('QUERY_STRING', ""))
    
    def output_hdrs(status, res_hdrs):
        sys.stdout.write("Status: %s\n" % status)
        for k, v in res_hdrs:
            sys.stdout.write("%s: %s\n" % (k, v))
        sys.stdout.write("\n")
        return sys.stdout.write, nbhttp.stop
    try:
        RedWebUi(base_uri, method, query_string, output_hdrs)
        nbhttp.run()
    except:
        except_handler_factory(sys.stdout.write)()
예제 #5
0
파일: fetch.py 프로젝트: nunnun/redbot
            while True:
                s = content_l.pop()
                if not content_l or s == '\000':
                    break
        if flag & FCOMMENT:
            # Read and discard a null-terminated string containing a comment
            while True:
                s = content_l.pop()
                if not content_l or s == '\000':
                    break
        if flag & FHCRC:
            content_l = content_l[2:]   # Read & discard the 16-bit header CRC
        return "".join(content_l)



if "__main__" == __name__:
    import sys
    uri = sys.argv[1]
    test_req_hdrs = [('Accept-Encoding', 'gzip')]
    def status_p(msg):
        print msg
    class TestFetcher(RedFetcher):
        def done(self):
            print self.state.messages
    tf = TestFetcher(
        uri, req_hdrs=test_req_hdrs, status_cb=status_p, req_type='test'
    )
    tf.run()
    nbhttp.run()
예제 #6
0
파일: webui.py 프로젝트: ylafon/redbot
def standalone_main(port, static_dir):
    """Run RED as a standalone Web server."""
    
    # load static files
    static_files = {}
    def static_walker(arg, dirname, names):
        for name in names:
            try:
                path = os.path.join(dirname, name)
                if os.path.isdir(path):
                    continue
                uri = os.path.relpath(path, static_dir)
                static_files["/static/%s" % uri] = open(path).read()
            except IOError:
                sys.stderr.write(
                  "* Problem loading %s\n" % path
                )
    os.path.walk(static_dir, static_walker, "")
    sys.stderr.write("* Static files loaded.\n")

    def red_handler (method, uri, req_hdrs, res_start, req_pause):
        p_uri = urlsplit(uri)
        if static_files.has_key(p_uri.path):
            res_body, res_done = res_start("200", "OK", [], nbhttp.dummy)
            res_body(static_files[p_uri.path])
            res_done(None)
        elif p_uri.path == "/":
            query_string = cgi.parse_qs(p_uri.query)

            def output_hdrs (status, hdrs):
                code, phrase = status.split(None, 1)
                return res_start(code, phrase, hdrs, nbhttp.dummy)

            try:
                RedWebUi('/', method, query_string, output_hdrs)
            except:
                sys.stderr.write("""

*** FATAL ERROR
RED has encountered a fatal error which it really, really can't recover from
in standalone server mode. Details follow.

""")
                except_handler_factory(sys.stderr.write)()
                sys.stderr.write("\n")
                nbhttp.stop()
                sys.exit(1)
        else:
            res_body, res_done = res_start(
                "404", "Not Found", [], nbhttp.dummy
            )
            res_done(None)
        return nbhttp.dummy, nbhttp.dummy

    nbhttp.Server("", port, red_handler)
    
    try:
        nbhttp.run()
    except KeyboardInterrupt:
        sys.stderr.write("Stopping...\n")
        nbhttp.stop()