Beispiel #1
0
class TestAuth(TestPanel):
    """
    Tests requests:
        * POST /auth/login
        * GET /auth/logout
    """
    @page('/auth/login', raises=True)
    def test_get_auth_login(self, error):
        self.assertEqual(error.value.status, '404')

    @page('/auth/logout', raises=True, method='POST')
    def test_post_auth_logout(self, error):
        self.assertEqual(error.value.status, '404')

    @page('/auth/login',
          raises=True,
          method='POST',
          postdata=json_encode({'passwd': '1234'}))
    def test_post_auth_login_fail(self, error):
        self.assertEqual(error.value.status, '401')

    test_post_auth_login_fail.skip = ('Must test invalid password from the'
                                      'outside.')

    @page('/auth/login',
          method='POST',
          postdata=json_encode({'passwd': sha256('None').hexdigest()}))
    def test_post_auth_login(self, response):
        self.assertEqual(json_decode(response), {'result': True})
Beispiel #2
0
class TestConfig(TestPanel):
    """
    Test requests:
        * GET /config
        * PUT /config {settings:{something}}
    """
    @page('/config')
    @json
    def test_get_config(self, response):
        self.assertTrue(
            all(config.custom[key] == value
                for key, value in response.iteritems()))

    @page('/config',
          method='PUT',
          headers={'settings': json_encode(dict(base_port=6666))})
    @json
    def test_put_config(self, response):
        self.assertEqual(response, {'result': True})

    @page('/config',
          method='PUT',
          headers={'settings': json_encode(dict(cheese='spam'))})
    @json
    def test_put_config_invalid_key(self, response):
        self.assertIn('error', response)

    @page('/config',
          method='PUT',
          headers={'settings': json_encode(dict(base_port='a string'))})
    @json
    def test_put_config_invalid_value(self, response):
        self.assertEqual(response, {'result': False})
Beispiel #3
0
 def test_rpc_request(self):
     response = Mock()
     response.code = 200
     response.body = escape.json_encode({"result": True})
     cyclone.httpclient.fetch.return_value = succeed(response)
     result = yield self.client.foo()
     self.assertTrue(result)
Beispiel #4
0
    def __rpcRequest(self, method, *args):
        q = escape.json_encode({"method": method, "params": args,
                                "id": self.__rpcId})
        self.__rpcId += 1
        r = defer.Deferred()
        d = fetch(
            self.__rpcUrl,
            method="POST",
            postdata=q,
            headers={
                "Content-Type": "application/json-rpc"
            }
        )

        def _success(response, deferred):
            if response.code == 200:
                data = escape.json_decode(response.body)
                error = data.get("error")
                if error:
                    deferred.errback(Exception(error))
                else:
                    deferred.callback(data.get("result"))
            else:
                deferred.errback(HTTPError(response.code, response.phrase))

        def _failure(failure, deferred):
            deferred.errback(failure)

        d.addCallback(_success, r)
        d.addErrback(_failure, r)
        return r
Beispiel #5
0
 def test_rpc_request_404(self):
     response = Mock()
     response.code = 404
     response.phrase = "Not found."
     response.body = escape.json_encode({"result": True})
     cyclone.httpclient.fetch.return_value = succeed(response)
     return self.assertFailure(self.client.foo(), HTTPError)
Beispiel #6
0
    def sendEvent(self, message, event=None, eid=None, retry=None):
        """
        sendEvent is the single method to send events to clients.

        Parameters:

        message: the event itself

        event: optional event name

        eid: optional event id to be used as Last-Event-ID header or
             e.lastEventId property

        retry: set the retry timeout in ms. default 3 secs.
        """
        if isinstance(message, dict):
            message = escape.json_encode(message)
        if isinstance(message, unicode):
            message = message.encode("utf-8")
        assert isinstance(message, str)

        if eid:
            self.transport.write("id: %s\n" % eid)
        if event:
            self.transport.write("event: %s\n" % event)
        if retry:
            self.transport.write("retry: %s\n" % retry)

        self.transport.write("data: %s\n\n" % message)
Beispiel #7
0
 def post(self):
     try:
         channel = str(self.get_argument('realChannel'))
         thirdparty_token = str(self.get_argument('thirdparty_token'))
     except Exception:
         raise web.HTTPError(400, 'Argument error')
     channels = yield self.sql.runQuery("SELECT id FROM core_channel WHERE slug=%s LIMIT 1", (channel, ))
     if channels:
         channel, = channels[0]
     else:
         raise web.HTTPError(400, 'Argument error')
     try:
         res = yield self.sql.runQuery("SELECT access_token FROM core_bindtoken WHERE channel_id=%s AND thirdparty_token=%s LIMIT 1",\
          (channel, thirdparty_token))
         if res:
             access_token, = res[0]
         else:
             access_token = yield self.redis.hget("bindtoken:%s" % channel, thirdparty_token)
             if not access_token:
                 access_token = ""
     except Exception:
         access_token = ""
     # access_token = yield self.redis.hget("bindtoken:%s" % channel, thirdparty_token)
     # if not access_token:
     #     access_token = ''
     ret = dict(access_token=access_token, timestamp=int(time.time())) 
     reb = zlib.compress(escape.json_encode(ret)) 
     self.write(ret)
Beispiel #8
0
    def get(self):
        logging.info("/lgpay/notify/ start")
        try:
            serial_no = self.get_argument("serial_no")
            transaction_id = self.get_argument("transaction_id")
            result_code = self.get_argument("result_code")
            fee = self.get_argument("fee")           
        except Exception:
            raise web.HTTPError(400, "Argument error")

        r,zoneid = serial_no.split('_')
        logging.info("/lgpay/notify/ zoneid:",zoneid)
        res = yield self.sql.runQuery("SELECT domain FROM core_zone WHERE zoneid=%s", (zoneid, ))
        if res:
            domain, = res[0] 
        if int(result_code) == 120:
            url = "%s/lgpay/notify/" % domain
            logging.info("/lgpay/notify/ url:",url)

            params = dict(serial_no=serial_no, transaction_id=transaction_id, fee=fee)
            yield httpclient.fetch(httputil.url_concat(url, params))
            ret = dict(serial_no=serial_no)
            reb = zlib.compress(escape.json_encode(ret))
            self.write(ret)
            logging.info("/lgpay/lgpay/ end")
Beispiel #9
0
    def sendEvent(self, message, event=None, eid=None, retry=None):
        """
        sendEvent is the single method to send events to clients.

        Parameters:

        message: the event itself

        event: optional event name

        eid: optional event id to be used as Last-Event-ID header or
             e.lastEventId property

        retry: set the retry timeout in ms. default 3 secs.
        """
        if isinstance(message, dict):
            message = escape.json_encode(message)
        if isinstance(message, unicode):
            message = message.encode("utf-8")
        assert isinstance(message, str)

        if eid:
            self.transport.write("id: %s\n" % eid)
        if event:
            self.transport.write("event: %s\n" % event)
        if retry:
            self.transport.write("retry: %s\n" % retry)

        self.transport.write("data: %s\n\n" % message)
Beispiel #10
0
    def post(self, name):
        if Project(name).exists():
            self.write(escape.json_encode({"status":  "Project already exists"}))
            return

        try:
            project = Project()
            project.name = name
            project.git_url = self.get_argument('git_url')[0]
            project.group_name = self.get_argument('group_name')
            project.save()
            self.write(escape.json_encode({"status": "ok"}))
            log.msg('Project created:', project.name)
        except Exception, e:
            log.err()
            self.write(escape.json_encode({"status": "fail"}))
Beispiel #11
0
 def post(self):
     try:
         channel = str(self.get_argument('realChannel'))
         thirdparty_token = str(self.get_argument('thirdparty_token'))
     except Exception:
         raise web.HTTPError(400, 'Argument error')
     channels = yield self.sql.runQuery(
         "SELECT id FROM core_channel WHERE slug=%s LIMIT 1", (channel, ))
     if channels:
         channel, = channels[0]
     else:
         raise web.HTTPError(400, 'Argument error')
     try:
         res = yield self.sql.runQuery(
             "SELECT access_token FROM core_bindtoken WHERE channel_id=%s AND thirdparty_token=%s LIMIT 1", \
             (channel, thirdparty_token))
         if res:
             access_token, = res[0]
         else:
             access_token = yield self.redis.hget("bindtoken:%s" % channel,
                                                  thirdparty_token)
             if not access_token:
                 access_token = ""
     except Exception:
         access_token = ""
     # access_token = yield self.redis.hget("bindtoken:%s" % channel, thirdparty_token)
     # if not access_token:
     #     access_token = ''
     ret = dict(access_token=access_token, timestamp=int(time.time()))
     reb = zlib.compress(escape.json_encode(ret))
     self.write(ret)
Beispiel #12
0
    def get(self):
        try:
            cpOrderId = self.get_argument("cpOrderId")
            orderStatus = self.get_argument("orderStatus")
            payFee = self.get_argument("payFee")
            payTime = self.get_argument("payTime")
            signature = self.get_argument("signature")  
            cpUserInfo = self.get_argument("cpUserInfo")             
        except Exception:
            raise web.HTTPError(400, "Argument error")
        params = self.request.arguments.copy()
        params.pop('signature')
        for x, y in params.items():
            params[x] = y[0]
        params = yield self.format_params(params, False)
        m = hashlib.md5()   
        m.update(params) 
        _sign = m.hexdigest()  
        if signature != _sign:
            url = "%s/xmpay/notify/" % cpUserInfo
            params = dict(cpOrderId=cpOrderId, orderStatus=orderStatus, payFee=payFee, payTime=payTime)
            yield httpclient.fetch(httputil.url_concat(url, params))

            ret = dict(error_code=200)
        else:
            ret = dict(error_code=1525, errMsg=E.errmsg(E.ERR_SIGN))
        reb = zlib.compress(escape.json_encode(ret))
        self.write(ret)
Beispiel #13
0
    def get(self):
        logging.info("/xmpay/notify/ start")
        try:
            cpOrderId = self.get_argument("cpOrderId")
            orderStatus = self.get_argument("orderStatus")
            payFee = self.get_argument("payFee")
            payTime = self.get_argument("payTime")
            signature = self.get_argument("signature")  
            cpUserInfo = self.get_argument("cpUserInfo")             
        except Exception:
            raise web.HTTPError(400, "Argument error")

        params = self.request.arguments.copy()
        params.pop('signature')
        for x, y in params.items():
            params[x] = y[0]
        params = yield self.format_params(params, False)
        m = hashlib.md5()   
        m.update(params) 
        _sign = m.hexdigest()  
        if signature != _sign:
            url = "%s/xmpay/notify/" % cpUserInfo
            params = dict(cpOrderId=cpOrderId, orderStatus=orderStatus, payFee=payFee, payTime=payTime)
            yield httpclient.fetch(httputil.url_concat(url, params))

            ret = dict(error_code=200)
        else:
            ret = dict(error_code=1525, errMsg=E.errmsg(E.ERR_SIGN))
        reb = zlib.compress(escape.json_encode(ret))
        self.write(ret)
        logging.info("XmNotifyHandler /xmpay/notify/ end.")
Beispiel #14
0
    def __rpcRequest(self, method, *args):
        q = escape.json_encode({
            "method": method,
            "params": args,
            "id": self.__rpcId
        })
        self.__rpcId += 1
        r = defer.Deferred()
        d = fetch(self.__rpcUrl, method="POST", postdata=q)

        def _success(response, deferred):
            if response.code == 200:
                data = escape.json_decode(response.body)
                error = data.get("error")
                if error:
                    deferred.errback(Exception(error))
                else:
                    deferred.callback(data.get("result"))
            else:
                deferred.errback(HTTPError(response.code, response.phrase))

        def _failure(failure, deferred):
            deferred.errback(failure)

        d.addCallback(_success, r)
        d.addErrback(_failure, r)
        return r
Beispiel #15
0
 def get(self, name):
     project = name
     build_ids = BuildInfo(project, -1).builds()
     builds = []
     for bid in build_ids[-10:]:
         build = BuildInfo(project, bid)
         builds.append({'build': int(bid), 'log': os.path.basename(build.log()), 'version': build.version(), 'release': build.release(), 'date': build.time()})
     self.write(escape.json_encode(builds))
Beispiel #16
0
 def result(self, boolean):
     """
     Performs JSON response:
      * {"result" : true}
      * {"result": false}
     :param boolean: the boolean to be returned
     """
     return json_encode({'result': boolean})
Beispiel #17
0
    def error(self, msg):
        """
        Performs JSON response:
         * {"error" : error message }

        :param msg: error message
        """
        return json_encode({'error': str(msg)})
Beispiel #18
0
 def get(self):
     """
     Process GET requests:
         * /config
     Return a dictionary item:value for each item configurable from the
     panel.
     """
     return self.write(json_encode(self.controller.get()))
Beispiel #19
0
 def result(self, boolean):
     """
     Performs JSON response:
      * {"result" : true}
      * {"result": false}
     :param boolean: the boolean to be returned
     """
     return json_encode({'result':boolean})
Beispiel #20
0
    def error(self, msg):
        """
        Performs JSON response:
         * {"error" : error message }

        :param msg: error message
        """
        return json_encode({'error': str(msg)})
Beispiel #21
0
    def post(self, name):
        if Project(name).exists():
            self.write(escape.json_encode({"status":
                                           "Project already exists"}))
            return

        try:
            project = Project()
            project.name = name
            project.git_url = self.get_argument('git_url')[0]
            project.group_name = self.get_argument('group_name')
            project.save()
            self.write(escape.json_encode({"status": "ok"}))
            log.msg('Project created:', project.name)
        except Exception, e:
            log.err()
            self.write(escape.json_encode({"status": "fail"}))
Beispiel #22
0
 def get(self):
     """
     Process GET requests:
         * /config
     Return a dictionary item:value for each item configurable from the
     panel.
     """
     return self.write(json_encode(self.controller.get()))
Beispiel #23
0
 def post(self, *args):
     try:
         if len(args) > 0:
             name = args[0]
             group = Group(name)
             for key, value in self.request.arguments.iteritems():
                 if key in ("repo_addr", "repo_user", "repo_passwd"):
                     setattr(group, key, value[0])
             group.save()
         else:
             group = Group(self.get_argument('name'))
             group.repo_addr = self.get_argument('repo_addr')
             group.repo_user = self.get_argument('repo_user')
             group.repo_passwd = self.get_argument('repo_passwd')
             group.save()
         self.write(escape.json_encode({'status': 'ok'}))
     except Exception, e:
         self.write(escape.json_encode({'status': 'fail', 'error': str(e)}))
Beispiel #24
0
 def write(self, chunk):
     """
     XXX This is a patch that can be removed once
     https://github.com/fiorix/cyclone/pull/92 makes it into a release.
     """
     if isinstance(chunk, types.ListType):
         chunk = escape.json_encode(chunk)
         self.set_header("Content-Type", "application/json")
     web.RequestHandler.write(self, chunk)
Beispiel #25
0
 def write(self, chunk):
     """
     XXX This is a patch that can be removed once
     https://github.com/fiorix/cyclone/pull/92 makes it into a release.
     """
     if isinstance(chunk, types.ListType):
         chunk = escape.json_encode(chunk)
         self.set_header("Content-Type", "application/json")
     web.RequestHandler.write(self, chunk)
Beispiel #26
0
 def post(self, *args):
     try:
         if len(args) > 0:
             name = args[0]
             group = Group(name)
             for key, value in self.request.arguments.iteritems():
                 if key in ("repo_addr", "repo_user", "repo_passwd"):
                     setattr(group, key, value[0])
             group.save()
         else:
             group = Group(self.get_argument('name'))
             group.repo_addr = self.get_argument('repo_addr')
             group.repo_user = self.get_argument('repo_user')
             group.repo_passwd = self.get_argument('repo_passwd')
             group.save()
         self.write(escape.json_encode({'status': 'ok'}))
     except Exception, e:
         self.write(escape.json_encode({'status': 'fail', 'error': str(e)}))
Beispiel #27
0
    def write(self, chunk):
        """
        This is a monkey patch to RequestHandler to allow us to serialize also
        json list objects.
        """
        if isinstance(chunk, types.ListType):
            self.set_header("Content-Type", "application/json")
            chunk = escape.json_encode(chunk)

        RequestHandler.write(self, chunk)
Beispiel #28
0
    def write(self, chunk):
        """
        This is a monkey patch to RequestHandler to allow us to serialize also
        json list objects.
        """
        if isinstance(chunk, types.ListType):
            self.set_header("Content-Type", "application/json")
            chunk = escape.json_encode(chunk)

        RequestHandler.write(self, chunk)
Beispiel #29
0
    def __call__(self, *args):
        payload = escape.json_encode(dict(
            method=self.__service,
            params=args,
            id="jsonrpc",
        ))

        d = httpclient.fetch(self.__endpoint, method="POST", postdata=payload)
        d.addCallback(self.__cbResponse)
        return d
Beispiel #30
0
 def state(self, service):
     """
     Process GET request:
         * /services/<service>/
     Return a dictionary containig a summary of what the service is and on
     which url is running on.
     """
     try:
         return json_encode(self.controller.get(service))
     except ValueError:
         raise web.HTTPError(404)
Beispiel #31
0
 def state(self, service):
     """
     Process GET request:
         * /services/<service>/
     Return a dictionary containig a summary of what the service is and on
     which url is running on.
     """
     try:
         return json_encode(self.controller.get(service))
     except ValueError:
         raise web.HTTPError(404)
Beispiel #32
0
    def send_mails(self, sender, to_id, title, content, awards):
        query = "INSERT INTO core_mail(sender, to_id, title, content, jawards, comment, created_at) VALUES (%s, %s, %s, %s, %s, %s, %s) RETURNING id"
        params = (sender, to_id, title, content, escape.json_encode(awards), '', datetime.datetime.now())
        for i in range(5):
            try:
                yield self.sql.runQuery(query, params)
                break
            except storage.IntegrityError:
                log.msg("SQL integrity error, retry(%i): %s" % (i, (query % params)))
                continue

        defer.returnValue(None)
Beispiel #33
0
class BindHandler(ApiHandler):
    @storage.databaseSafe
    @defer.inlineCallbacks
    @api('Bind Token',
         '/bind/token/', [
             Param('channel', True, str, 'putaogame', 'putaogame', 'channel'),
             Param('thirdparty_token', True, str, '55526fcb3', '55526fcb3',
                   'thirdparty_token'),
             Param('access_token', True, str,
                   '55526fcb39ad4e0323d32837021655300f957edc',
                   '55526fcb39ad4e0323d32837021655300f957edc', 'access_token'),
         ],
         filters=[ps_filter],
         description="Bind Token")
    def post(self):
        try:
            channel = str(self.get_argument('realChannel'))
            thirdparty_token = str(self.get_argument('thirdparty_token'))
            access_token = str(self.get_argument('access_token'))
        except Exception:
            raise web.HTTPError(400, 'Argument error')
        channels = yield self.sql.runQuery(
            "SELECT id FROM core_channel WHERE slug=%s LIMIT 1", (channel, ))
        if channels:
            channel, = channels[0]
        else:
            raise web.HTTPError(404)
        try:
            res = yield self.sql.runQuery(
                "SELECT * FROM core_bindtoken WHERE channel_id=%s AND thirdparty_token=%s AND access_token=%s", \
                (channel, thirdparty_token, access_token))
            if not res:
                query = "INSERT INTO core_bindtoken(channel_id, thirdparty_token, access_token, timestamp) VALUES (%s, %s, %s, %s) RETURNING id"
                params = (channel, thirdparty_token, access_token,
                          int(time.time()))
                for i in range(5):
                    try:
                        yield self.sql.runQuery(query, params)
                        break
                    except storage.IntegrityError:
                        log.msg("SQL integrity error, retry(%i): %s" %
                                (i, (query % params)))
                        continue
                yield self.redis.hset("bindtoken:%s" % channel,
                                      thirdparty_token, access_token)
        except Exception, e:
            print e

        ret = dict(timestamp=int(time.time()))
        reb = zlib.compress(escape.json_encode(ret))
        self.write(ret)
Beispiel #34
0
 def _cbResult(self, result, jsonid):
     if isinstance(result, failure.Failure):
         if isinstance(result.value, RGError):
             error = result.value.message
         else:
             error = ErrorType.ServerErr("server error")
         result = None
     elif isinstance(result, AttributeError):
         error = ErrorType.NoMethod()
         result = None
     else:
         error = None
     data = {"result": result, "error": error, "id": jsonid}
     self.finish(cyclone_escape.json_encode(data))
Beispiel #35
0
    def post(self, name):
        project = Project(name)
        release = self.get_argument('tag')
        version = self.get_argument('version')
        commit  = self.get_argument('commit', default='HEAD')

        reactor.callInThread(build_project, {
            'project': project.name,
            'branch' : 'master',
            'release': release,
            'version': version,
            'commit' : commit,
        })

        self.write(escape.json_encode({'status': 'build of branch %s scheduled' % release}))
Beispiel #36
0
    def get(self, *args):
        groups_json = []
        groups = []

        if len(args) > 1:
            name = args[0]
            groups = [Group(name)]
        else:
            groups = Group.get_all()

        for group in groups:
            group_json = {}
            for attr in ('name', 'repo_addr', 'repo_user', 'repo_passwd'):
                group_json.update({attr: getattr(group, attr)})
            groups_json.append(group_json)
        self.write(escape.json_encode(groups_json))
Beispiel #37
0
    def get(self, *args):
        groups_json = []
        groups = []

        if len(args) > 1:
            name = args[0]
            groups = [Group(name)]
        else:
            groups = Group.get_all()

        for group in groups:
            group_json = {}
            for attr in ('name', 'repo_addr', 'repo_user', 'repo_passwd'):
                group_json.update({attr: getattr(group, attr)})
            groups_json.append(group_json)
        self.write(escape.json_encode(groups_json))
Beispiel #38
0
 def get(self):
     try:
         serial_no = self.get_argument("serial_no")
         transaction_id = self.get_argument("transaction_id")
         result_code = self.get_argument("result_code")
         fee = self.get_argument("fee")           
     except Exception:
         raise web.HTTPError(400, "Argument error")
     res = yield self.sql.runQuery("SELECT domain FROM core_zone WHERE zoneid=%s", (serial_no[10:], ))
     if res:
         domain, = res[0] 
     if int(result_code) == 120:
         url = "%s/lgpay/notify/" % domain
         params = dict(serial_no=serial_no, transaction_id=transaction_id, fee=fee)
         yield httpclient.fetch(httputil.url_concat(url, params))
         ret = dict(serial_no=serial_no)
         reb = zlib.compress(escape.json_encode(ret))
         self.write(ret)    
Beispiel #39
0
    def __rpcRequest(self, method, *args):
        q = escape.json_encode({
            "method": method,
            "params": args,
            "id": self.__rpcId
        })
        self.__rpcId += 1
        r = defer.Deferred()

        fetch_kwargs = {
            'method': "POST",
            'postdata': q,
            'headers': {
                "Content-Type": ["application/json-rpc"]
            },
        }
        fetch_kwargs.update(self.__fetch_kwargs)
        d = fetch(self.__rpcUrl, *self.__fetch_args, **fetch_kwargs)

        def _success(response, deferred):
            if response.code == 200:
                data = escape.json_decode(response.body)
                error = data.get("error")
                if error:
                    if isinstance(error, DictType) and 'message' in error:
                        # JSON-RPC spec is not very verbose about error schema,
                        # but it should look like {'code': 0, 'message': 'msg'}
                        deferred.errback(Exception(error['message']))
                    else:
                        # For backward compatibility with previous versions of
                        # cyclone.jsonrpc.JsonrpcRequestHandler
                        deferred.errback(Exception(error))
                else:
                    deferred.callback(data.get("result"))
            else:
                deferred.errback(HTTPError(response.code, response.phrase))

        def _failure(failure, deferred):
            deferred.errback(failure)

        d.addCallback(_success, r)
        d.addErrback(_failure, r)
        return r
Beispiel #40
0
    def get(self, sp_keyword='status/bootstrap-phase'):
        """
        Processes GET requests:
            * /tor/<sp_keyword>

        In case the GETINFO command returns a 552 error code, raise a 404.
        (controlspec.txt) «If some of the listed keywords can't be found,
        Tor replies with a "552 Unrecognized option" message.»

        In case tor is not yet started, return a error message in JSON format.
        """
        try:
            self.controller.get(sp_keyword).addCallback(
                lambda infos: self.finish(json_encode(infos)))
        except ValueError:
            raise web.HTTPError(404)
        except KeyError as exc:
            self.finish(self.error(exc))
        except RuntimeError as exc:
            return self.finish(self.error(exc))
Beispiel #41
0
    def get(self, sp_keyword='status/bootstrap-phase'):
        """
        Processes GET requests:
            * /tor/<sp_keyword>

        In case the GETINFO command returns a 552 error code, raise a 404.
        (controlspec.txt) «If some of the listed keywords can't be found,
        Tor replies with a "552 Unrecognized option" message.»

        In case tor is not yet started, return a error message in JSON format.
        """
        try:
            self.controller.get(sp_keyword).addCallback(
                    lambda infos: self.finish(json_encode(infos)))
        except ValueError:
            raise web.HTTPError(404)
        except KeyError as exc:
            self.finish(self.error(exc))
        except RuntimeError as exc:
            return self.finish(self.error(exc))
Beispiel #42
0
 def update_huntguard(self, uid, heros, formation):
     res = yield self.sql.runQuery("SELECT a.id, a.jheros, b.jguards, b.formation, a.xp, a.nickname, \
      a.avat FROM core_user AS a, core_hunt AS b WHERE a.id=b.user_id AND a.id=%s" % uid)
     if res:
         for r in res:
             jheros = r[1] and escape.json_decode(r[1]) or {}
             jguards = {}
             jguards_list = filter(lambda j:j in jheros, heros)
             for j in jguards_list:
                 jguards[j] = jheros[j]
             query = "UPDATE core_hunt SET jguards=%s, formation=%s WHERE user_id=%s RETURNING id"
             params = (escape.json_encode(jguards), formation, uid)
             for i in range(5):
                 try:
                     yield self.sql.runQuery(query, params)
                     break
                 except storage.IntegrityError:
                     log.msg("SQL integrity error, retry(%i): %s" % (i, (query % params)))
                     continue
     #yield self.set_arena(uid)
     defer.returnValue(jguards.keys())
Beispiel #43
0
    def __rpcRequest(self, method, *args):
        q = escape.json_encode({"method": method, "params": args,
                                "id": self.__rpcId})
        self.__rpcId += 1
        r = defer.Deferred()

        fetch_kwargs = {
            'method': "POST",
            'postdata': q,
            'headers': {"Content-Type": ["application/json-rpc"]},
        }
        fetch_kwargs.update(self.__fetch_kwargs)
        d = fetch(self.__rpcUrl, *self.__fetch_args, **fetch_kwargs)

        def _success(response, deferred):
            if response.code == 200:
                data = escape.json_decode(response.body)
                error = data.get("error")
                if error:
                    if isinstance(error, DictType) and 'message' in error:
                        # JSON-RPC spec is not very verbose about error schema,
                        # but it should look like {'code': 0, 'message': 'msg'}
                        deferred.errback(Exception(error['message']))
                    else:
                        # For backward compatibility with previous versions of
                        # cyclone.jsonrpc.JsonrpcRequestHandler
                        deferred.errback(Exception(error))
                else:
                    deferred.callback(data.get("result"))
            else:
                deferred.errback(HTTPError(response.code, response.phrase))

        def _failure(failure, deferred):
            deferred.errback(failure)

        d.addCallback(_success, r)
        d.addErrback(_failure, r)
        return r
Beispiel #44
0
 def test_json_encode(self):
     data = {"a": "b"}
     result = json_encode(data)
     self.assertEqual(result, '{"a": "b"}')
Beispiel #45
0
    def get(self):
        try:
            channel = self.get_argument('channel', 'putaogame')
            version = str(self.get_argument('version'))
        except Exception:
            # raise web.HTTPError(400, 'Argument error')
            emsg = "传入参数有误"
            logging.error(emsg)
            self.write(dict(err=E.ERR_PARAM, msg=emsg))
            return

        channels = yield self.sql.runQuery("SELECT id, version, version2, version3 FROM core_channel WHERE slug=%s LIMIT 1", (channel, ))
        if channels:
            channel, nversion, mversion, uversion = channels[0]
        else:
            # raise web.HTTPError(404,'Channel not find in DB core_channel.')
            emsg = "渠道在记录中不存在"
            logging.error(emsg)
            self.write(dict(err=E.ERR_PARAM, msg=emsg))
            return
        #最大版本号需要根据请求版本号和配置版本号来确认
        #请求版本号需要和最大版本号一致
        #确定最大版本号应该使用哪一列
        if version.split('.')[0] == nversion.split('.')[0]:
            max_version = nversion
        elif version.split('.')[0] == mversion.split('.')[0]:
            max_version = mversion
        else:
            max_version = uversion
        # try:
        #     assert version.split('.')[0] == nversion.split('.')[0]
        #     max_version = nversion
        # except Exception:
        #     max_version = mversion
        if cmp(version, max_version) == 0:
            ret = dict(code=0, timestamp=int(time.time())) 
            reb = zlib.compress(escape.json_encode(ret)) 
            self.write(ret)
            return
        FIND = False  
        res = yield self.sql.runQuery("SELECT cversion, tversion, url, sign FROM core_update WHERE channel_id=%s", (channel, ))
        if res: 
            for r in res:
                if version == str(r[0]) and max_version == str(r[1]):
                    FIND = True
                    code, target, url, md5 = 1, r[1], r[2], r[3]
                    ret = dict(code=code, msg='', targetVersion=target, upgrade=url, md5=md5, timestamp=int(time.time()))
                    reb = zlib.compress(escape.json_encode(ret))
                    self.write(ret)
                    return  
                else:continue
        if not FIND:
            res = yield self.sql.runQuery("SELECT version, url, md5 FROM core_upgrade WHERE channel_id=%s ORDER BY version DESC LIMIT 1", (channel, ))
            if res: 
                for r in res:
                    code, target, url, md5 = -1, r[0], r[1] or '', r[2] or ''
                    ret = dict(code=code, msg='', targetVersion=target, upgrade=url, md5=md5, timestamp=int(time.time()))  
                    reb = zlib.compress(escape.json_encode(ret))
                    self.write(ret)
                    return
            else:
                ret = dict(code=0, timestamp=int(time.time())) 
                reb = zlib.compress(escape.json_encode(ret)) 
                self.write(ret)
                return
Beispiel #46
0
 def test_json_encode(self):
     data = {"a": "b"}
     result = json_encode(data)
     self.assertEqual(result, '{"a": "b"}')
Beispiel #47
0
 def _response_json(self, value):
     self.set_header("Content-Type", "application/json")
     self.response = json_encode(value)
     self.finish(self.response)
Beispiel #48
0
    def get(self):
        if self.has_arg('channel'):
            channels = yield self.sql.runQuery(
                "SELECT id FROM core_channel WHERE slug=%s LIMIT 1",
                (self.arg("channel"), ))
            if channels:
                channel, = channels[0]
            else:
                self.write(dict(err=E.ERR_CHANNEL,
                                msg=E.errmsg(E.ERR_CHANNEL)))
                return

        else:
            self.write(dict(err=E.ERR_ARGUMENT, msg=E.errmsg(E.ERR_ARGUMENT)))
            return
        if channel:
            res = yield self.sql.runQuery(
                "SELECT a.id, a.zoneid, a.domain, a.maxnum, a.status, a.index FROM"
                " core_zone AS a, core_zone_channels AS b WHERE a.id=b.zone_id AND"
                " b.channel_id=%s", (channel, ))
            zone_dict = {}
            record = {}
            if res:
                for r in res:
                    zid, zoneid, domain, maxnum, status, index = r
                    notice_dict = {}
                    notices = yield self.sql.runQuery(
                        "SELECT notice_id, position FROM core_noticeship WHERE zone_id=%s",
                        (zid, ))
                    if notices:
                        for n in notices:
                            notices = yield self.sql.runQuery(
                                "SELECT id, title, content, screenshot, sign,\
                              created_at FROM core_notice WHERE id=%s",
                                (n[0], ))
                            nid, title, content, screenshot, sign, create_at = notices[
                                0]
                            if screenshot and FileObject(screenshot).exists():
                                url = FileObject(screenshot).url
                            else:
                                url = ''
                            create_at = time.mktime(create_at.timetuple())
                            position = n[1]
                            notice_dict[nid] = dict(title=title, content=content, url=url, sign=sign,
                                                    create_at=create_at, \
                                                    position=position)

                    try:
                        nownum = yield self.redis.get(
                            'zone:%s:%s' %
                            (zoneid,
                             datetime.datetime.now().strftime('%Y%m%d')))
                        if not nownum:
                            nownum = 0
                    except Exception:
                        nownum = 0

                    zone_dict[zoneid] = dict(domain=domain, maxnum=maxnum, nownum=nownum, status=status, index=index, \
                                             notices=notice_dict, title=D.ZONENAME.get(str(zoneid), ''))

                    if self.user_id:
                        idcard = yield self.redis.get('zone:%s:%s' %
                                                      (zoneid, self.user_id))
                        if idcard:
                            record[zoneid] = idcard
                            # if rec:
                            #     rec = pickle.loads(rec)
                            #     record = rec
                        else:
                            pass
                    #record[1] = '7he74dbd44fe7b43ef932ddc9ba612b0a7'
            ret = dict(zone=zone_dict,
                       record=record,
                       timestamp=int(time.time()))
            reb = zlib.compress(escape.json_encode(ret))
            self.write(ret)
        else:
            raise web.HTTPError(404)
Beispiel #49
0
    def post(self):
        if self.has_arg('channel'):
            channels = yield self.sql.runQuery("SELECT id FROM core_channel WHERE slug=%s LIMIT 1", (self.arg("channel"), ))
            if channels:
                channel, = channels[0]
            else:
                # raise web.HTTPError(404,'channel not find in DB.')
                emsg = "该渠道在记录中不存在"
                logging.error(emsg)
                self.write(dict(err=E.ERR_PARAM, msg=emsg))
                return
        else:
            emsg = "参数中不包括渠道"
            logging.error(emsg)
            self.write(dict(err=E.ERR_PARAM, msg=emsg))
            return
            # raise web.HTTPError('400', 'Argument error. not find channel!')

        if channel:
            #通过core_zone_channels里的channel_id拿到zoneid列表,得到zoneid列表每一个zoneid对应的信息
            res = yield self.sql.runQuery("SELECT a.id, a.zoneid, a.domain, a.maxnum, a.status, a.index FROM core_zone AS a")
            zone_dict = {}
            record = {}
            # print "home.py res: ",res
            if res:
                for r in res:
                    zid, zoneid, domain, maxnum, status, index = r
                    notice_dict = {}
                    # notices = yield self.sql.runQuery("SELECT notice_id, position FROM core_noticeship WHERE zone_id=%s", (zid, ))
                    # if notices:
                    #     for n in notices:
                    #         notices = yield self.sql.runQuery("SELECT id, title, content, screenshot, sign,\
                    #           created_at FROM core_notice WHERE id=%s", (n[0], ))
                    #         nid, title, content, screenshot, sign, create_at = notices[0]
                    #         if screenshot and FileObject(screenshot).exists():
                    #             url = FileObject(screenshot).url
                    #         else:
                    #             url = ''
                    #         create_at = time.mktime(create_at.timetuple())
                    #         position = n[1]
                    #         notice_dict[nid] = dict(title=title, content=content, url=url, sign=sign, create_at=create_at,\
                    #                                 position=position)

                    try:
                        nownum = yield self.redis.get('zone:%s:%s' % (zoneid, datetime.datetime.now().strftime('%Y%m%d')))
                    except Exception:
                        nownum = 0

                    zone_dict[zoneid] = dict(domain=domain, maxnum=maxnum, nownum=nownum, status=status, index=index,\
                                             notices=notice_dict, title=D.ZONENAME.get(str(zoneid), ''))

                    if self.has_arg('access_token'):
                        idcard = yield self.redis.get('zone:%s:%s' % (zoneid, self.arg('access_token')))

                        if idcard:
                            record[zoneid] = idcard
                # if rec:
                #     rec = pickle.loads(rec)
                #     record = rec            

            ret = dict(zone=zone_dict, record=record, timestamp=int(time.time()))
            reb = zlib.compress(escape.json_encode(ret))
            self.write(ret)
        else:
            # raise web.HTTPError(404,'channel not find in DB.')
            emsg = "渠道在记录中不存在"
            logging.error(emsg)
            self.write(dict(err=E.ERR_PARAM, msg=emsg))
            return
Beispiel #50
0
 def test_rpc_request_error1(self):
     response = Mock()
     response.code = 404
     response.body = escape.json_encode({"result": True})
     cyclone.httpclient.fetch.return_value = fail(HTTPError(404))
     return self.assertFailure(self.client.foo(), HTTPError)
Beispiel #51
0
 def test_rpc_request_error_old(self):
     response = Mock()
     response.code = 200
     response.body = escape.json_encode({"error": "some error"})
     cyclone.httpclient.fetch.return_value = succeed(response)
     return self.assertFailure(self.client.foo(), Exception)
Beispiel #52
0
 def post(self, project):
     try:
         self._clear_repo(Project(project))
         self.write(escape.json_encode({'status': 'ok'}))
     except Exception, e:
         self.write(escape.json_encode({'status': 'fail', 'error': str(e)}))
Beispiel #53
0
def recents(req):
    req.set_header("Content-Type", "application/json")
    req.write(json_encode({"recents":req.settings.cache.recents()}))
Beispiel #54
0
 def post(self, project):
     try:
         self._clear_repo(Project(project))
         self.write(escape.json_encode({'status': 'ok'}))
     except Exception, e:
         self.write(escape.json_encode({'status': 'fail', 'error': str(e)}))