Пример #1
0
    def test_session_manager_can_set_active_customer(self):

        self.session_manager = SessionManager()

        self.session_manager.set_active_customer()

        self.assertTrue(self.session_manager.get_active_customer())
Пример #2
0
  def evaluate_once(self):
    session_manager = SessionManager(self.config)
    global_step, sess = session_manager.restore(self.saver)  
    coord = tf.train.Coordinator()
    try:
      queue_runners = tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS)
      threads_per_qr = map(lambda qr: qr.create_threads(sess, coord=coord, daemon=True, start=True), queue_runners)
      threads = reduce(list.__add__, threads_per_qr)
      num_iter = math.ceil(self.config.dataset.set_sizes['test'] / self.config.training_params.batch_size)
      
      step = 0
      acc = []
      
      full_logits = []
      full_labels = []


      while step < num_iter and not coord.should_stop():
        logits, labels = sess.run([self.logits, self.labels])
        full_logits += [logits]
        full_labels += [labels]
        step += 1
      
      logits = np.vstack(full_logits)
      labels = np.vstack(full_labels)
      labels = np.array(labels, np.uint8).reshape((-1))
      
      good_logits = logits[np.arange(logits.shape[0]), labels]
      classirate = good_logits.sum() / logits.shape[0]
      
      print ('Classification rate:',  classirate)        
      coord.request_stop()
      coord.join(threads, stop_grace_period_secs=10)
    except Exception as e:
      coord.request_stop(e)
Пример #3
0
def validate_session(chat_id):
    # check if session is valid for current chat_id
    logger.info('Validando sessão de ' + str(chat_id))
    if not SessionManager.getInstance().checkSession(chat_id):
        session_id = create_session()
        logger.info('Sessão criada para ' + str(chat_id))
    else:
        session_id = SessionManager.getInstance().getSession(chat_id)
        logger.info('Sessão atualizada para ' + str(chat_id))

    SessionManager.getInstance().updateSession(chat_id, session_id)
Пример #4
0
    def loadSessionFromFile(self, fileName):
        sessionManager = SessionManager(self.app)
        file = open(fileName, "r")
        propertyDict = sessionManager.parseTextLines(file.readlines())

        self.volumeViewer.loadSessionInfo(sessionManager, propertyDict)
        self.skeletonViewer.loadSessionInfo(sessionManager, propertyDict)
        self.sseViewer.loadSessionInfo(sessionManager, propertyDict)
        self.calphaViewer.loadSessionInfo(sessionManager, propertyDict)

        self.mainCamera.loadSessionInfo(sessionManager, propertyDict)
        file.close()
Пример #5
0
    def POST(self):
        params = web.input()
        session_id = params.session_id
        userid = int(params.userid)
        device_id = params.device_id
        token = params.token
        sms_code = params.sms_code

        if not SessionManager.instance().check_session(session_id, device_id,
                                                       userid):
            resp = {'res': 401, 'msg': '登陆态异常'}
            return json.dumps(resp, ensure_ascii=False)

        ret = SMSCenter.instance().check_sms(token, sms_code)
        if ret is None:
            logger.info('check sms code failed!! token:%s, code:%s' %
                        (token, sms_code))
            resp = {'res': 1, 'msg': 'error'}
        else:
            action, data = ret
            #修改状态
            SMSCenter.instance().update_status(token, SMSStatus.SMS_CONFIRMED)

            if action != SMSAction.BIND_PHONE:
                resp = {'res': 1, 'msg': 'error'}
            else:
                resp = self.apply_bind_phone(json.loads(data))

                if resp['res'] == 0:
                    if userid == 0:
                        #绑定成功,需要进行帐号迁移
                        userid = resp['userid']
                        r = self.activate_account(userid, device_id)
                        if r['rtn'] == 0:
                            resp['balance'] = r['balance']
                            resp['income'] = r['income']
                            resp['outgo'] = r['outgo']
                            resp['shared_income'] = r['shared_income']

                        #修改cache中的userid
                        SessionManager.instance().update_session(
                            session_id, device_id, userid)
                    else:
                        #查询余额
                        r = self.query_balance(userid, device_id)
                        if r['rtn'] == 0:
                            resp['balance'] = r['balance']
                            resp['income'] = r['income']
                            resp['outgo'] = r['outgo']
                            resp['shared_income'] = r['shared_income']

        return json.dumps(resp)
Пример #6
0
  def run(self):
    files, labels, images = self.input_manager.get_inputs(type='submission', distorted = False, shuffle = False)

    with tf.variable_scope("inference"):    
      logits = self.config.inference(images, testing=True)
        
    # Restore the moving average version of the learned variables for eval.
    variable_averages = tf.train.ExponentialMovingAverage(self.config.training_params.moving_average_decay)
    variables_to_restore = variable_averages.variables_to_restore()
    self.saver = tf.train.Saver(variables_to_restore)
    
    session_manager = SessionManager(self.config)
    global_step, sess = session_manager.restore(self.saver)  
    coord = tf.train.Coordinator()
    try:
      queue_runners = tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS)
      threads_per_qr = map(lambda qr: qr.create_threads(sess, coord=coord, daemon=True, start=True), queue_runners)
      threads = reduce(list.__add__, threads_per_qr)
      num_iter = math.ceil(self.config.dataset.submission_size / self.config.training_params.batch_size)
      
      step = 0
      predictions_ids = []
      predictions = []
      while step < num_iter and not coord.should_stop():
        submission_files, submission_logits = sess.run([files, logits])
        submission_files = list(map(self.config.dataset.retrieve_file_id, submission_files))
        predictions += [submission_logits]
        predictions_ids += submission_files
        step += 1
        
      predictions = np.vstack(predictions)
      predictions = np.float32(predictions)
      predictions += 5e-2
      row_sums = np.reshape(predictions.sum(axis=1), [-1, 1])
      predictions /= row_sums
      
      df = pd.DataFrame(data=predictions)
      cols = list(map(lambda c: 'c' + str(c), range(10)))
      
      df.columns = cols
      df['img'] = predictions_ids
      
      df = df[['img'] + cols]
      df = df.drop_duplicates(subset = ['img'], keep='first')
      df.to_csv('submission.csv', index=False)
      
      coord.request_stop()
      coord.join(threads, stop_grace_period_secs=10)
    except Exception as e:
      coord.request_stop(e)
Пример #7
0
    def __init__(self, config_, ioloop, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.ioloop = ioloop
        self.logger = logging.getLogger('servicehub')
        self.logger.setLevel(config.LOGLEVEL)

        self.session_manager = SessionManager()
        self.docker = aiodocker.Docker()
        image_config = config_['image']
        self.image = image_config.get('name')
        self.image_label = image_config.get('label', 'latest')
        self.image_remove = image_config.getboolean('remove', False)
        self.session_lifetime = config_['session'].get('lifetime', 21600)
        self.remove_container = config_['session'].getboolean('remove', False)
    def POST(self):
        params = web.input()
        session_id = params.session_id
        userid = int(params.userid)
        device_id = params.device_id
        token = params.token
        sms_code = params.sms_code

        if not SessionManager.instance().check_session(session_id, device_id, userid):
            resp = {'res':401, 'msg':'登陆态异常'}
            return json.dumps(resp, ensure_ascii=False)

        ret = SMSCenter.instance().check_sms(token, sms_code)
        if ret is None:
            logger.info('check sms code failed!! token:%s, code:%s' %(token, sms_code))
            resp = {'res': 1, 'msg': 'error'}
        else:
            action, data = ret
            #修改状态
            SMSCenter.instance().update_status(token, SMSStatus.SMS_CONFIRMED)
            
            if action != SMSAction.BIND_PHONE:
                resp = {'res': 1, 'msg': 'error'}
            else:
                resp = self.apply_bind_phone(json.loads(data))

                if resp['res'] == 0:
                    if userid == 0:
                        #绑定成功,需要进行帐号迁移
                        userid = resp['userid']
                        r = self.activate_account(userid, device_id)
                        if r['rtn'] == 0:
                            resp['balance'] = r['balance']
                            resp['income'] = r['income']
                            resp['outgo'] = r['outgo']
                            resp['shared_income'] = r['shared_income']

                        #修改cache中的userid
                        SessionManager.instance().update_session(session_id, device_id, userid)
                    else:
                        #查询余额
                        r = self.query_balance(userid, device_id)
                        if r['rtn'] == 0:
                            resp['balance'] = r['balance']
                            resp['income'] = r['income']
                            resp['outgo'] = r['outgo']
                            resp['shared_income'] = r['shared_income']
                            
        return json.dumps(resp)
    def POST(self):
        req  = protocol.ExchangeCodeReq(web.input(), web.cookies())
        resp = protocol.ExchangeCodeResp()

        if not SessionManager.instance().check_session(req.session_id, req.device_id, req.userid):
            resp.res = 401
            resp.msg = '登陆态异常'
            return resp.dump_json()

        #userid不能为0
        if req.userid == 0:
            resp.res = 1
            return resp.dump_json()

        if req.exchange_type == 1:
            rtn, sn, code = self.get_exchange_code_jingdong(req.userid, req.device_id)
        elif req.exchange_type == 2:
            rtn, sn, code = self.get_exchange_code_xlvip(req.userid, req.device_id)
        else:
            resp.res = 1
            return resp.dump_json()

        if rtn != 0:
            resp.res = rtn
            return resp.dump_json()

        #成功,发送短信
        self.notify_exchange_code(req.userid, req.device_id, req.exchange_type, code)
        
        resp.order_id = sn
        resp.exchange_code = code
        return resp.dump_json()
Пример #10
0
class ServiceHubApplication(Application):
    '''Servicehub main application
    @param  dict config  The main application configuration.
    @option  dict images  The available images as: path => docker image name
    '''
    def __init__(self, config_, ioloop, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.ioloop = ioloop
        self.logger = logging.getLogger('servicehub')
        self.logger.setLevel(config.LOGLEVEL)

        self.session_manager = SessionManager()
        self.docker = aiodocker.Docker()
        image_config = config_['image']
        self.image = image_config.get('name')
        self.image_label = image_config.get('label', 'latest')
        self.image_remove = image_config.getboolean('remove', False)
        self.session_lifetime = config_['session'].get('lifetime', 21600)
        self.remove_container = config_['session'].getboolean('remove', False)

    async def shutdown(self):
        self.logger.debug("Running application shutdown")
        self.http_server.stop()
        await self._stop_containers()
        await self.docker.close()
        self.ioloop.stop()

    async def _stop_containers(self):
        self.logger.debug("Stopping containers.")
        for user, session in self.session_manager.items():
            container = session['container']
            self.logger.debug("Stopping container %s", container)
            await container.stop()
        self.logger.debug("Containers stopped.")
Пример #11
0
    def POST(self):
        req = protocol.CheckInReq(web.input(), web.cookies())
        resp = protocol.CheckInResp()

        if not SessionManager.instance().check_session(
                req.session_id, req.device_id, req.userid):
            resp.res = 401
            resp.msg = '登陆态异常'
            return resp.dump_json()

        data = {'userid': req.userid, 'device_id': req.device_id}

        url = 'http://' + TASK_BACKEND + '/check-in'

        r = http_request(url, data)
        if r['rtn'] == 0:
            resp.award = r['award']
        elif r['rtn'] == 1:
            resp.res = 1
            resp.msg = '您今天已抽奖,明天再来试试运气吧!'
        else:
            resp.res = 1
            resp.msg = 'error'

        return resp.dump_json()
Пример #12
0
def message(update, context):
    message_received = update.message.text

    assistant.validate_session(update.effective_chat.id)

    response_text = assistant.send_message(SessionManager.getInstance().getSession(update.effective_chat.id), update.message.text)
    context.bot.send_message(chat_id=update.effective_chat.id, text=response_text)
Пример #13
0
    def initialize(self):
        self.publish_queue = []
        self.options = options

        from models import engine, db_bootstrap
        self.db_session = scoped_session(sessionmaker(bind=engine))
        db_bootstrap(self.db_session)

        from session_manager import SessionManager
        self.session_manager = SessionManager(
            timeout_limit=self.options.session_timeout_limit)

        self.context = zmq.Context()
        self.input_socket = self.context.socket(zmq.REP)
        self.input_socket.bind(self.options.trade_in)

        self.publisher_socket = self.context.socket(zmq.PUB)
        self.publisher_socket.bind(self.options.trade_pub)

        input_log_file_handler = logging.handlers.TimedRotatingFileHandler(
            self.options.trade_log, when='MIDNIGHT')
        formatter = logging.Formatter('%(asctime)s - %(message)s')
        input_log_file_handler.setFormatter(formatter)

        self.replay_logger = logging.getLogger("REPLAY")
        self.replay_logger.setLevel(logging.INFO)
        self.replay_logger.addHandler(input_log_file_handler)
        self.replay_logger.info('START')

        self.log_start_data()
Пример #14
0
    def POST(self):
        req = protocol.ResendSmsCodeReq(web.input(), web.cookies())
        resp = protocol.ResendSmsCodeResp()

        if not SessionManager.instance().check_session(
                req.session_id, req.device_id, req.userid):
            resp.res = 401
            resp.msg = '登陆态异常'
            return resp.dump_json()

        sms = SMSCenter.instance()

        item = sms.find_item(req.token)
        if item is None:
            resp.res = 1
            resp.msg = 'error'
            return resp.dump_json()

        sms_code = sms.gen_sms_code(req.code_len)
        logger.debug('new sms code: %s' % sms_code)

        sms.update_sms_code(req.token, sms_code)

        ret = sms.send_sms_code(item['phone_num'], sms_code)
        if ret:
            sms.update_status(req.token, SMSStatus.SMS_SUCC)
            resp.token = req.token
        else:
            sms.update_status(req.token, SMSStatus.SMS_FAIL)
            resp.res = 1
            resp.msg = '短信发送数量已超过限额'

        return resp.dump_json()
Пример #15
0
    def GET(self):
        params = web.input()

        if not SessionManager.instance().check_session(params.session_id, params.device_id, int(params.userid)):
            resp = {'res':401, 'msg':'登陆态异常'}
            return json.dumps(resp, ensure_ascii=False)

        data = {'device_id': params.device_id, 'userid': int(params.userid)}
        url = 'http://' + ACCOUNT_BACKEND + '/user_info?' + urllib.urlencode(data)

        r = http_request(url)
        if r.has_key('rtn') and r['rtn'] == 0:
            resp = {
                'res': 0,
                'msg': '',
                'userid': int(r['userid']),
                'phone': r['phone_num'],
#                'nickname': r['nickname'],
                'sex': int(r['sex']),
                'age': int(r['age']),
                'interest': r['interest']
            }
        else:
            resp = {'res': 1, 'msg': 'error'}

        return json.dumps(resp)
Пример #16
0
    def GET(self):
        req  = protocol.ReportPollReq(web.input(), web.cookies())
        resp = protocol.ReportPollResp()

        if not SessionManager.instance().check_session(req.session_id, req.device_id, req.userid):
            resp.res = 401
            resp.msg = '登陆态异常'
            return resp.dump_json()

        data = {
            'userid': req.userid,
            'device_id': req.device_id
        }

        url = 'http://' + BILLING_BACKEND + '/query_balance?' + urllib.urlencode(data)

        logger.debug('[POLL] billing request, url = %s' %(url))

        r = http_request(url)

        if r['rtn'] == 0:
            resp.res = 0
            resp.msg = '成功'
            resp.offerwall_income = r['offerwall_income']
        else:
            resp.res = 589
            resp.msg = '查询余额错误'
            return resp.dump_json()

        return resp.dump_json()
    def POST(self):
        req = protocol.ResendSmsCodeReq(web.input(), web.cookies())
        resp = protocol.ResendSmsCodeResp()

        if not SessionManager.instance().check_session(req.session_id, req.device_id, req.userid):
            resp.res = 401
            resp.msg = '登陆态异常'
            return resp.dump_json()

        sms = SMSCenter.instance()

        item = sms.find_item(req.token)
        if item is None:
            resp.res = 1
            resp.msg = 'error'
            return resp.dump_json()
            
        sms_code = sms.gen_sms_code(req.code_len)
        logger.debug('new sms code: %s' %sms_code)

        sms.update_sms_code(req.token, sms_code)

        ret = sms.send_sms_code(item['phone_num'], sms_code)
        if ret:
            sms.update_status(req.token, SMSStatus.SMS_SUCC)
            resp.token = req.token
        else:
            sms.update_status(req.token, SMSStatus.SMS_FAIL)
            resp.res = 1
            resp.msg = 'error'

        return resp.dump_json()
Пример #18
0
def receive_voice(update, context):
    assistant.validate_session(update.effective_chat.id)

    audio_file = BytesIO(update.message.voice.get_file().download_as_bytearray())
    text = voice.convert_voice(audio_file)
    response_text = assistant.send_message(SessionManager.getInstance().getSession(update.effective_chat.id), text)
    context.bot.send_voice(chat_id=update.effective_chat.id, voice=voice.convert_text(response_text))
Пример #19
0
    def GET(self):
        params = web.input()

        if not SessionManager.instance().check_session(
                params.session_id, params.device_id, int(params.userid)):
            resp = {'res': 401, 'msg': '登陆态异常'}
            return json.dumps(resp, ensure_ascii=False)

        data = {'device_id': params.device_id, 'userid': int(params.userid)}
        url = 'http://' + ACCOUNT_BACKEND + '/user_info?' + urllib.urlencode(
            data)

        r = http_request(url)
        if r.has_key('rtn') and r['rtn'] == 0:
            resp = {
                'res': 0,
                'msg': '',
                'userid': int(r['userid']),
                'phone': r['phone_num'],
                #                'nickname': r['nickname'],
                'sex': int(r['sex']),
                'age': int(r['age']),
                'interest': r['interest']
            }
        else:
            resp = {'res': 1, 'msg': 'error'}

        return json.dumps(resp)
Пример #20
0
    def POST(self):
        req  = protocol.CheckInReq(web.input(), web.cookies())
        resp = protocol.CheckInResp()

        if not SessionManager.instance().check_session(req.session_id, req.device_id, req.userid):
            resp.res = 401
            resp.msg = '登陆态异常'
            return resp.dump_json()

        data = {
            'userid': req.userid,
            'device_id': req.device_id
        }

        url = 'http://' + TASK_BACKEND + '/check-in'

        r = http_request(url, data)
        if r['rtn'] == 0:
            resp.award = r['award']
        elif r['rtn'] == 1:
            resp.res = 1
            resp.msg = '您今天已抽奖,明天再来试试运气吧!'
        else:
            resp.res = 1
            resp.msg = 'error'
        
        return resp.dump_json()
Пример #21
0
 def __init__(self,
              handlers=None,
              default_host=None,
              transforms=None,
              **settings):
     super(WSAplication, self).__init__(handlers, default_host, transforms,
                                        **settings)
     self.session_manager = SessionManager()
Пример #22
0
class TestChooseActiveCustomer(unittest.TestCase):
    '''
	    Purpose:
	        This class tests that a customer can be set as active

	    Methods:
	        def test_superuser_can_choose_active_customer(self):

	    Author:
	        @rtwhitfield84
	'''
    def test_session_manager_can_set_active_customer(self):

        self.session_manager = SessionManager()

        self.session_manager.set_active_customer()

        self.assertTrue(self.session_manager.get_active_customer())
Пример #23
0
def queue_process_new_users():
    task_id = 'unique_process-new-users'
    if task_in_queue(task_id, 'celery@worker_q_selenium'):
        logger.info('Task %s already in queue' % task_id)
        return False

    from session_manager import SessionManager
    if SessionManager.whatsapp_web_connection_okay():
        return process_new_users.apply_async(queue='process_message',
                                             task_id=task_id)
    else:
        return False
Пример #24
0
    def saveSessionToFile(self, fileName):
        sessionManager = SessionManager(self.app)
        file = open(fileName, "w")
        textLines = []
        textLines.extend(self.getSessionHeader(sessionManager))
        textLines.extend(self.mainCamera.getSessionInfo(sessionManager))
        textLines.extend(self.volumeViewer.getSessionInfo(sessionManager))
        textLines.extend(self.skeletonViewer.getSessionInfo(sessionManager))
        textLines.extend(self.sseViewer.getSessionInfo(sessionManager))
        textLines.extend(self.calphaViewer.getSessionInfo(sessionManager))

        file.writelines(textLines)
        file.close()
Пример #25
0
def signup_user():

    userhash = str(request.headers.get("authorization"))

    if not userhash == "None":
        userhash = userhash.replace("Basic ", "")
        jsondata = json.dumps(request.json)

        session = SessionManager.create_user(jsondata, userhash)
        application_cache.add_session_to_cache({"sessiontoken": session, "userid": session.iduser})
        if session:
            profile = SloachObjectProvider.create_profile(session.iduser, {"firstname": "", "lastname": "", "address": "", "email": json.loads(jsondata)['email']})
            return jsonify({'iduser': session.iduser, 'token': str(session.sessiontoken), 'profile': {"firstname": profile.firstname, "lastname": profile.lastname, "email": profile.email}})
    return make_response("Username already exists", 400)
Пример #26
0
    def __init__(self, name, s_size, a_size, trainer, model_path, global_episodes, env_name, seed, test, cell_units, params, testing_trial=False):
        self.name = "worker_" + str(name)
        self.number = name
        self.model_path = model_path
        self.trainer = trainer
        self.global_episodes = global_episodes
        self.increment = self.global_episodes.assign_add(1)
        self.episode_rewards = []
        self.episode_lengths = []
        self.episode_mean_values = []
        self.summary_writer = tf.summary.FileWriter("train_" + str(self.number))
        self.is_test = test
        self.a_size = a_size
        self.params = params

        # Create the local copy of the network and the tensorflow op to copy global parameters to local network
        self.local_AC = AC_Network(s_size, a_size, cell_units, self.name, trainer)
        self.update_local_ops = update_target_graph('global', self.name)

        self.testing_trial = testing_trial
        if not self.testing_trial:
            self.scenario_name = params['train_scenario_name']
            self.attempt_limit = params['train_attempt_limit']
        else:
            self.scenario_name = params['test_scenario_name']
            self.attempt_limit = params['test_attempt_limit']

        self.scenario = select_scenario(self.scenario_name, params['use_physics'])
        env = gym.make(env_name)

        self.manager = SessionManager(env, params, human=False)
        self.manager.update_scenario(self.scenario)
        self.manager.env.reward_mode = params['reward_mode']

        self.trial_count = 0
        self.manager.env.seed(seed)
	def process(self, app, event):
		done = False

		credentials = self.ask("Name")
		pieces = credentials.split(",")
		if len(pieces) == 2:
			username = pieces[0]
			password = pieces[1]
			
			sm = SessionManager()
			if sm.validateCredentials(username, password):
				app.pressed = []
				app.isButtonUp = False
				self.clearView()
				
				#app.buildHitDataSource()
				#self.myThread = ThreadedSerialReader(1, "Thread-1", self.workQueue, None, serialBuilder, port, baud, serial_port, False)
				#self.myThread.start()

				app.dispatcher.setCurrentController(MenuController.ID)
			else:
				time.sleep(0.1)
		
		return done
Пример #28
0
    def initialize(self, options, instance_name):
        self.publish_queue = []
        self.options = options
        self.instance_name = instance_name

        self.order_matcher_disabled = False
        if options.has_option('order_matcher_disabled'):
            self.order_matcher_disabled = True

        from models import Base, db_bootstrap
        db_engine = options.sqlalchemy_engine + ':///' + \
                    os.path.expanduser(options.sqlalchemy_connection_string)
        engine = create_engine(db_engine, echo=options.db_echo)
        Base.metadata.create_all(engine)

        self.db_session = scoped_session(sessionmaker(bind=engine))
        db_bootstrap(self.db_session)

        from session_manager import SessionManager
        self.session_manager = SessionManager(
            timeout_limit=self.options.session_timeout_limit)

        self.context = zmq.Context()
        self.input_socket = self.context.socket(zmq.REP)
        self.input_socket.bind(self.options.trade_in)

        self.publisher_socket = self.context.socket(zmq.PUB)
        self.publisher_socket.bind(self.options.trade_pub)

        input_log_file_handler = logging.handlers.TimedRotatingFileHandler(
            os.path.expanduser(self.options.trade_log), when='MIDNIGHT')
        input_log_file_handler.setFormatter(
            logging.Formatter('%(asctime)s - %(message)s'))

        self.replay_logger = logging.getLogger(self.instance_name)
        self.replay_logger.setLevel(logging.INFO)
        self.replay_logger.addHandler(input_log_file_handler)

        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.DEBUG)
        ch.setFormatter(
            logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
        self.replay_logger.addHandler(ch)

        self.replay_logger.info('START')

        self.log_start_data()
Пример #29
0
def login_user():
    hash = str(request.headers.get("authorization"))

    if not hash == 'None':
        hash = str.replace(hash, "Basic ", "")
        session = SessionManager.create_session(hash, request.remote_addr)
        if session is None:
            return make_response("User not found or password is invalid", 404)
        application_cache.add_session_to_cache(session)
        profile = SloachObjectProvider.get_profile(session.iduser)
        if profile is None:
            return make_response("Couldn't find your profile", 500)
        loginResult = {'iduser': session.iduser, 'token': str(session.sessiontoken), 'profile': {"firstname": profile.firstname, "lastname": profile.lastname, "email": profile.email, "clubkey": profile.clubkey}}

        return jsonify(loginResult)
    return make_response("",401)
Пример #30
0
def check_auth(request):
    if request.headers.get('sessiontoken') is None:
        return False

    sessiontoken = request.headers.get('sessiontoken')
    if sessiontoken in application_cache.session_cache:
        return True
    #Query the database for the user session
    user_session = SessionManager.get_session(sessiontoken)
    if user_session is None:
        application_cache.remove_session_from_cache(sessiontoken)
        return False
    else:
        if application_cache.session_cache[sessiontoken] is None:
            application_cache.session_cache[sessiontoken] = user_session.userid
        return True
Пример #31
0
class TestSessionManager(unittest.TestCase):
    def setUp(self):
        self.__sessionManager = SessionManager()

    def test_next_session(self):
        session = self.__sessionManager.current_session
        self.__sessionManager.next()
        next_session = self.__sessionManager.current_session

        self.assertNotEqual(session.session_id, next_session.session_id)

    def test_get_first_session(self):
        self.__sessionManager.first()
        session = self.__sessionManager.current_session
        self.__sessionManager.next()
        self.__sessionManager.first()
        first_session = self.__sessionManager.current_session

        self.assertEqual(session.session_id, first_session.session_id)
Пример #32
0
    def POST(self):
        req = protocol.UpdateInviterReq(web.input(), web.cookies())
        resp = protocol.UpdateInviterResp()

        if not SessionManager.instance().check_session(
                req.session_id, req.device_id, req.userid):
            resp.res = 401
            resp.msg = '登陆态异常'
            return resp.dump_json()

        url = 'http://' + ACCOUNT_BACKEND + '/update_inviter'
        data = {
            'device_id': req.device_id,
            'userid': req.userid,
            'invite_code': req.inviter.upper()
        }

        r = http_request(url, data)
        if r['rtn'] == 2:
            resp.res = 1
            resp.msg = '不能邀请自己'
            return resp.dump_json()
        elif r['rtn'] != 0:
            resp.res = 1
            resp.msg = '邀请码错误'
            return resp.dump_json()

        inviter_id = int(r['inviter'])

        #在任务系统进行记录
        url = 'http://' + TASK_BACKEND + '/report_invite'
        data = {
            'userid': inviter_id,
            'invite_code': req.inviter,
            'invitee': req.userid
        }

        r = http_request(url, data)
        if r['rtn'] == 0:
            return resp.dump_json()
        else:
            resp.res = 1
            resp.msg = 'error'
            return resp.dump_json()
    def POST(self):
        req = protocol.UpdateInviterReq(web.input(), web.cookies())
        resp = protocol.UpdateInviterResp()

        if not SessionManager.instance().check_session(req.session_id, req.device_id, req.userid):
            resp.res = 401
            resp.msg = '登陆态异常'
            return resp.dump_json()

        url = 'http://' + ACCOUNT_BACKEND + '/update_inviter'
        data = {
            'device_id': req.device_id,
            'userid': req.userid,
            'invite_code': req.inviter.upper()
        }

        r = http_request(url, data)
        if r['rtn'] == 2:
            resp.res = 1
            resp.msg = '不能邀请自己'
            return resp.dump_json()
        elif r['rtn'] != 0:
            resp.res = 1
            resp.msg = 'error'
            return resp.dump_json()
            
        inviter_id = int(r['inviter'])

        #在任务系统进行记录
        url = 'http://' + TASK_BACKEND + '/report_invite'
        data = {
            'userid': inviter_id,
            'invite_code': req.inviter,
            'invitee': req.userid
        }

        r = http_request(url, data)
        if r['rtn'] == 0:
            return resp.dump_json()
        else:
            resp.res = 1
            resp.msg = 'error'
            return resp.dump_json()
Пример #34
0
def main():
    host = input('Hostname: ')
    port = input('Port: ')
    username = input('Username: '******'Password: '******'',
        username,
        password,
    ]

    with paramiko.SSHClient() as ssh:
        try:
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(host,
                        port=int(port),
                        username=username,
                        password=password)
        except Exception as ex:
            print(ex)
            sys.exit(1)

        session = ssh.invoke_shell()
        dir_path = os.getcwd() + os.sep + time.strftime(
            '%Y-%m-%d_%H:%M') + '_output'
        if not os.path.exists(dir_path):
            os.mkdir(dir_path)
        csv_writer = CSVWriter(
            dir_path, ['HOSTNAME', 'TELNET', 'SSH', 'VERSION', 'SERIALNUMBER'])
        session_manager = SessionManager(session, auth_list, csv_writer,
                                         dir_path)

        try:
            with open('hostnames.txt') as file:
                hostnames = [hostname.rstrip('\n') for hostname in file]
        except Exception as ex:
            print(ex)
            sys.exit(1)

        with concurrent.futures.ThreadPoolExecutor() as executor:
            executor.map(session_manager.manage, hostnames)
        csv_writer.close()
Пример #35
0
    def emit(self, record):
        """
        Overwrite the logging.handlers.SMTPHandler.emit function with SMTP_SSL.
        Emit a record.
        Format the record and send it to the specified addressees.
        """
        try:
            import smtplib
            import ssl
            from email.utils import formatdate
            # context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
            port = self.mailport
            if not port:
                port = smtplib.SMTP_SSL_PORT
            smtp = smtplib.SMTP_SSL(self.mailhost, port, timeout=5)

            msg = MIMEMultipart()
            msg['Subject'] = self.getSubject(record)
            msg['From'] = self.fromaddr
            msg['To'] = self.toaddrs[0]
            msg['Date'] = formatdate()

            text = MIMEText('Screenshot attached')
            msg.attach(text)

            image_data = SessionManager.get_screenshot()
            if image_data:
                image = MIMEImage(image_data, 'screenshot.png')
                msg.attach(image)

            if self.username:
                # smtp.ehlo()
                # smtp.starttls()  # for tls add this line context=context
                smtp.ehlo()
                smtp.login(self.username, self.password)
            smtp.sendmail(self.fromaddr, [self.toaddrs], msg.as_string())

            smtp.quit()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)
Пример #36
0
    def POST(self):
        req = protocol.ReportCommentReq(web.input(), web.cookies())
        resp = protocol.ReportCommentResp()

        if not SessionManager.instance().check_session(
                req.session_id, req.device_id, req.userid):
            resp.res = 401
            resp.msg = '登陆态异常'
            return resp.dump_json()

        url = 'http://' + TASK_BACKEND + '/report_comment'
        data = {'userid': req.userid, 'device_id': req.device_id}

        r = http_request(url, data)
        if r['rtn'] == 0:
            resp.income = r.get('income', 0)
        else:
            resp.res = 1
            resp.msg = 'error'

        return resp.dump_json()
Пример #37
0
    def POST(self):
        logger = logging.getLogger('root')
        params = web.input()
        session_id = params.session_id
        device_id = params.device_id
        userid = int(params.userid)
        phone_num = params.phone

        if not SessionManager.instance().check_session(session_id, device_id,
                                                       userid):
            resp = {'res': 401, 'msg': '登陆态异常'}
            return json.dumps(resp, ensure_ascii=False)

        data = {
            'userid': int(params.userid),
            'device_id': params.device_id,
            'phone': params.phone
        }

        logger.debug('userid: ' + params.userid)
        logger.debug('device_id: ' + params.device_id)
        logger.debug('phone: ' + params.phone)

        sms = SMSCenter.instance()

        #创建短信任务,写数据库
        token, code = sms.create_sms_task(phone_num, SMSAction.BIND_PHONE,
                                          json.dumps(data))

        #发送短信
        ret = sms.send_sms_code(phone_num, code)
        if ret:
            sms.update_status(token, SMSStatus.SMS_SUCC)
            resp = {'res': 0, 'msg': '', 'token': token}
        else:
            sms.update_status(token, SMSStatus.SMS_FAIL)
            resp = {'res': 1, 'msg': 'error'}

        return json.dumps(resp)
Пример #38
0
    def POST(self):
        req = protocol.ReportOfferWallPointReq(web.input(), web.cookies())
        resp = protocol.ReportOfferWallPointResp()

        logger.debug(
            "domob point: %d, youmi point: %d, userid:%d, device_id:%s"
            % (req.domob_point, req.youmi_point, req.userid, req.device_id)
        )

        if not SessionManager.instance().check_session(req.session_id, req.device_id, req.userid):
            resp.res = 401
            resp.msg = "登陆态异常"
            return resp.dump_json()

        if req.userid != 0:
            inviter = self.query_inviter(req.userid)
        else:
            inviter = 0

        if req.domob_point > 0:
            income = self.report_domob_point(req.userid, req.device_id, inviter, req.domob_point)
            if income < 0:
                logger.error("report_domob_point failed!! rtn:%d" % income)
                resp.res = -income
                resp.msg = "report_domob_point failed!!"
                return resp.dump_json()
            resp.income += income

        if req.youmi_point > 0:
            income = self.report_youmi_point(req.userid, req.device_id, inviter, req.youmi_point)
            if income < 0:
                logger.error("report_youmi_point failed!! rtn:%d" % income)
                resp.res = -income
                resp.msg = "report_youmi_point failed!!"
                return resp.dump_json()
            resp.income += income

        return resp.dump_json()
Пример #39
0
    def POST(self):
        req = protocol.ReportCommentReq(web.input(), web.cookies())
        resp = protocol.ReportCommentResp()

        if not SessionManager.instance().check_session(req.session_id, req.device_id, req.userid):
            resp.res = 401
            resp.msg = '登陆态异常'
            return resp.dump_json()
            
        url = 'http://' + TASK_BACKEND + '/report_comment'
        data = {
            'userid': req.userid,
            'device_id': req.device_id
        }

        r = http_request(url, data)
        if r['rtn'] == 0:
            resp.income = r.get('income', 0)
        else:
            resp.res = 1
            resp.msg = 'error'

        return resp.dump_json()
Пример #40
0
    def __init__(self):
        self.configDb = sqlite3.connect('../userdata.db')
        configDb = self.configDb
        configDb.row_factory = sqlite3.Row
        cursor = configDb.cursor()

        # Ensure settings table exists and create it if not
        cursor.execute(
            "SELECT name FROM sqlite_master WHERE Type='table' and name = 'settings'"
        )
        if cursor.fetchone() is None:
            self.createSettingsTable()

        app = QtGui.QApplication(sys.argv)
        mainApplicationWindow = MainApplicationWindow(configDb)
        mainApplicationWindow.hide()
        sessionManager = SessionManager(mainApplicationWindow, configDb)
        # sessionManager.show()

        self.mainApplicationWindow = mainApplicationWindow
        self.sessionManager = sessionManager

        app.exec_()
Пример #41
0
    def POST(self):
        logger = logging.getLogger('root')
        params = web.input()
        session_id = params.session_id
        device_id = params.device_id
        userid = int(params.userid)
        phone_num = params.phone

        if not SessionManager.instance().check_session(session_id, device_id, userid):
            resp = {'res':401, 'msg':'登陆态异常'}
            return json.dumps(resp, ensure_ascii=False)

        data = {
            'userid': int(params.userid),
            'device_id': params.device_id,
            'phone': params.phone
        }

        logger.debug('userid: ' + params.userid )
        logger.debug('device_id: ' + params.device_id)
        logger.debug('phone: ' + params.phone)

        sms = SMSCenter.instance()

        #创建短信任务,写数据库
        token, code = sms.create_sms_task(phone_num, SMSAction.BIND_PHONE, json.dumps(data))
        
        #发送短信
        ret = sms.send_sms_code(phone_num, code)
        if ret:
            sms.update_status(token, SMSStatus.SMS_SUCC)
            resp = {'res': 0, 'msg': '', 'token': token}
        else:
            sms.update_status(token, SMSStatus.SMS_FAIL)
            resp = {'res': 1, 'msg': 'error'}

        return json.dumps(resp)
Пример #42
0
    def POST(self):
        req  = protocol.ReportOfferWallPointReq(web.input(), web.cookies())
        resp = protocol.ReportOfferWallPointResp()

        logger.debug('domob point: %d, youmi point: %d, userid:%d, device_id:%s' \
                    %(req.domob_point, req.youmi_point, req.userid, req.device_id))

        if not SessionManager.instance().check_session(req.session_id, req.device_id, req.userid):
            resp.res = 401
            resp.msg = '登陆态异常'
            return resp.dump_json()

        if req.userid != 0:
            inviter = self.query_inviter(req.userid)
        else:
            inviter = 0

        if req.domob_point > 0:
            income = self.report_domob_point(req.userid, req.device_id, inviter, req.domob_point)
            if income < 0:
                logger.error('report_domob_point failed!! rtn:%d' %income)
                resp.res = -income
                resp.msg = 'report_domob_point failed!!'
                return resp.dump_json()
            resp.income += income

        if req.youmi_point > 0:
            income = self.report_youmi_point(req.userid, req.device_id, inviter, req.youmi_point)
            if income < 0:
                logger.error('report_youmi_point failed!! rtn:%d' %income)
                resp.res = -income
                resp.msg = 'report_youmi_point failed!!'
                return resp.dump_json()
            resp.income += income

        return resp.dump_json()
Пример #43
0
    def POST(self):
        req = protocol.ExchangeCodeReq(web.input(), web.cookies())
        resp = protocol.ExchangeCodeResp()

        if not SessionManager.instance().check_session(
                req.session_id, req.device_id, req.userid):
            resp.res = 401
            resp.msg = '登陆态异常'
            return resp.dump_json()

        #userid不能为0
        if req.userid == 0:
            resp.res = 1
            return resp.dump_json()

        if req.exchange_type == 1:
            rtn, sn, code = self.get_exchange_code_jingdong(
                req.userid, req.device_id)
        elif req.exchange_type == 2:
            rtn, sn, code = self.get_exchange_code_xlvip(
                req.userid, req.device_id)
        else:
            resp.res = 1
            return resp.dump_json()

        if rtn != 0:
            resp.res = rtn
            return resp.dump_json()

        #成功,发送短信
        self.notify_exchange_code(req.userid, req.device_id, req.exchange_type,
                                  code)

        resp.order_id = sn
        resp.exchange_code = code
        return resp.dump_json()
Пример #44
0
    def POST(self):
        req = protocol.RegisterReq(web.input(), web.cookies())
        resp = protocol.RegisterResp()

        if not self.re_idfa.match(req.idfa) or not self.re_mac.match(req.mac):
            resp.res = 1
            resp.msg = '参数错误'
            return resp.dump_json()

        cookies = web.cookies()
        logger.debug('cookies: platform=%s, version=%s%s, network=%s' \
                %(cookies.get('p', ''),
                    cookies.get('app', ''),
                    cookies.get('ver', ''),
                    cookies.get('net', '')))
        logger.debug('client ip: %s' % web.ctx.ip)

        #服务器维护
        if SWITCH_SERVER_DOWN == 1:
            resp.res = 511
            resp.msg = SWITCH_SERVER_DOWN_MSG
            return resp.dump_json()

        #配置提现开关
        if SWITCH_NO_WITHDRAW == 1:
            resp.no_withdraw = 1

        #配置TIPS
        if SWITCH_SERVER_TIPS == 1:
            resp.tips = SWITCH_SERVER_TIPS_CONTENT

        #配置积分墙开关(已废弃)
        resp.offerwall = {'domob': 0, 'youmi': 0}

        #配置积分墙列表
        resp.offerwall_list = [{
            'icon': 'task_icon_punchbox',
            'name': '触控应用任务',
            'type': 'punchbox',
            'ishot': 1
        }, {
            'icon': 'task_icon_youmi',
            'name': '有米应用任务',
            'type': 'youmi',
            'ishot': 0
        }, {
            'icon': 'task_icon_miidi',
            'name': '米迪应用任务',
            'type': 'miidi',
            'ishot': 0
        }, {
            'icon': 'task_icon_domob',
            'name': '多盟应用任务',
            'type': 'domob',
            'ishot': 0
        }]
        '''
        resp.offerwall_list = [
            {
                'icon':'task_icon_punchbox',
                'name':'触控应用任务',
                'type':'punchbox',
                'ishot':1
            },
            {
                'icon':'task_icon_youmi',
                'name':'有米应用任务',
                'type':'youmi',
                'ishot':1
            },
            {
                'icon':'task_icon_domob',
                'name':'多盟应用任务',
                'type':'domob',
                'ishot':0
            },
            {
                'icon':'task_icon_dianru',
                'name':'点入应用任务',
                'type':'dianru',
                'ishot':0
            },
            {
                'icon':'task_icon_miidi',
                'name':'米迪应用任务',
                'type':'miidi',
                'ishot':0
            }
        ]
        '''

        #配置强制升级
        if cookies.get('app', '').lower() != 'wangcai' and cookies.get(
                'ver', '') in ['1.1', '1.1.1', '1.2', '1.3', '']:
            resp.force_update = 1
            return resp.dump_json()

        #屏蔽2g/3g用户
        if False:
            if cookies.get('app', '').lower() != 'wangcai' and cookies.get(
                    'net', '') == '3g':
                logger.info('2g/3g user, ban! idfa:%s, mac:%s' %
                            (req.idfa, req.mac))
                resp.res = 403
                resp.msg = '错误$由于一些不可告人的技术原因,赚钱小猪只能在Wifi下面跑,请原谅,萌萌哒。'
                return resp.dump_json()

        data = {
            'idfa': req.idfa,
            'mac': req.mac,
            'platform': cookies.get('p', ''),
            'version': cookies.get('app', '') + cookies.get('ver', ''),
            'network': cookies.get('net', ''),
            'ip': web.ctx.ip,
        }

        url = 'http://' + ACCOUNT_BACKEND + '/register'

        r = http_request(url, data)
        if r['rtn'] == 1:
            resp.res = 403
            resp.msg = '错误$当前IP访问的机器数过高,为了保证广告投放商大爷的推广效果,您的设备今日无法继续使用小猪,请明日再试。'
            return resp.dump_json()
        elif r['rtn'] == 2:
            resp.res = 403
            resp.msg = '错误$您当前的IP及绑定账号被广告投放商判断为异常,您的账号已被冻结,导致此问题的原因可能是通过重置系统重复完成任务。如需申诉,请邮件手机号及问题至[email protected]。'
            return resp.dump_json()
        elif r['rtn'] != 0:
            resp.res = 1
            resp.msg = 'error'
            return resp.dump_json()

        resp.userid = userid = r['userid']
        resp.device_id = device_id = r['device_id']
        resp.phone = r['phone_num']
        resp.inviter = r['inviter']
        resp.invite_code = r['invite_code']

        #创建session缓存
        resp.session_id = SessionManager.instance().create_session(
            device_id, userid)

        if r['new_device']:
            logger.info('new device, idfa:%s, mac:%s' % (req.idfa, req.mac))

        data = {'userid': userid, 'device_id': device_id}

        url = 'http://' + BILLING_BACKEND + '/query_balance?' + urllib.urlencode(
            data)

        logger.info('billing request, url = %s' % (url))

        r = http_request(url)
        if r['rtn'] == 0:
            resp.balance = r['balance']
            resp.income = r['income']
            resp.outgo = r['outgo']
            resp.shared_income = r['shared_income']
            resp.offerwall_income = r['offerwall_income']
            resp.task_list = self.query_task_list(userid, device_id)

        return resp.dump_json()
Пример #45
0
    for environ_key, kwarg in environ_kwargs_map.items():
        if not environ_key in os.environ:
            raise RuntimeError("Missing required environment variable %s" % environ_key)

# script imports
from session_manager import SessionManager

# called when spotify client is connected and ready
def session_callback(session):
    # get all the playlists for this user
    logger.info('session_callback');
    playlist_container = session.playlist_container()
    playlist_container.add_loaded_callback(playlist_container_loaded_callback)

# called when playlist container is finished loading
def playlist_container_loaded_callback(playlist_container, userdata=None):
    logger.info('playlist_container_loaded_callback');



 # connect to Spotify using the SessionManager, and invoke the main function
session_manager = SessionManager(os.environ['SPOTIFY_USER'], os.environ['SPOTIFY_PASS'])
session_manager.add_session_callback(session_callback)
session_manager.connect()

# connect() does not return until disconnected
logger.info('Disconnected.')



Пример #46
0
        session.manager.broadcast("Someone left.")


async def websocket(manager, request):
    session = manager.get(str(uuid.uuid4()), True)

    transport = WebSocketServerHLEB(manager, session, request)
    try:
        return await transport.process()
    except asyncio.CancelledError:
        raise
    except aiohttp.web.HTTPException as exc:
        return exc


async def send_currenttime(manager):
    while True:
        manager.broadcast("Payload: " + str(datetime.datetime.now()))
        await asyncio.sleep(1)


if __name__ == '__main__':
    app = aiohttp.web.Application()

    manager = SessionManager(app, chat_msg_handler, app.loop)

    app.router.add_get("/ws", lambda request: websocket(manager, request))

    asyncio.ensure_future(send_currenttime(manager), loop=app.loop)
    aiohttp.web.run_app(app)
Пример #47
0
    def POST(self):
        req  = protocol.RegisterReq(web.input(), web.cookies())
        resp = protocol.RegisterResp()

        if not self.re_idfa.match(req.idfa) or not self.re_mac.match(req.mac):
            resp.res = 1
            resp.msg = '参数错误'
            return resp.dump_json()
        
        cookies = web.cookies()
        logger.debug('cookies: platform=%s, version=%s%s, network=%s' \
                %(cookies.get('p', ''), 
                    cookies.get('app', ''),
                    cookies.get('ver', ''),
                    cookies.get('net', '')))
        logger.debug('client ip: %s' %web.ctx.ip)

        #服务器维护
        if SWITCH_SERVER_DOWN == 1:
            resp.res = 511
            resp.msg = SWITCH_SERVER_DOWN_MSG
            return resp.dump_json()

        #配置提现开关
        if SWITCH_NO_WITHDRAW == 1:
            resp.no_withdraw = 1

        #配置TIPS
        if SWITCH_SERVER_TIPS == 1:
            resp.tips = SWITCH_SERVER_TIPS_CONTENT

        #配置积分墙开关
        resp.offerwall = {'domob': 0, 'youmi': 1}

        #配置强制升级
        if cookies.get('app', '').lower() != 'wangcai' and cookies.get('ver', '') in ['1.1', '1.1.1', '1.2', '1.3', '']:
            resp.force_update = 1
            return resp.dump_json()

        #屏蔽2g/3g用户
        if cookies.get('app', '').lower() != 'wangcai' and cookies.get('net', '') == '3g':
            logger.info('2g/3g user, ban! idfa:%s, mac:%s' %(req.idfa, req.mac))
            resp.res = 403
            resp.msg = '错误$当前IP访问的机器数过高,为了保证广告商的推广效果,您的设备今日无法继续使用旺财,请明日再试。'
            return resp.dump_json()


        data = {
            'idfa': req.idfa,
            'mac': req.mac,
            'platform': cookies.get('p', ''),
            'version': cookies.get('app', '') + cookies.get('ver', ''),
            'network': cookies.get('net', ''),
            'ip': web.ctx.ip,
        }

        url = 'http://' + ACCOUNT_BACKEND + '/register'

        r = http_request(url, data)
        if r['rtn'] == 1:
            resp.res = 403
            resp.msg = '错误$当前IP访问的机器数过高,为了保证广告商的推广效果,您的设备今日无法继续使用旺财,请明日再试。'
            return resp.dump_json()
        elif r['rtn'] == 2:
            resp.res = 403
            resp.msg = '错误$您当前的IP及绑定账号被广告商判断为异常,您的账号已被冻结,导致此问题的原因可能是通过重置系统重复完成任务。如需申诉,请邮件手机号及问题至[email protected]。'
            return resp.dump_json()
        elif r['rtn'] != 0:
            resp.res = 1
            resp.msg = 'error'
            return resp.dump_json()

        resp.userid = userid = r['userid']
        resp.device_id = device_id = r['device_id']
        resp.phone = r['phone_num']
        resp.inviter = r['inviter']
        resp.invite_code = r['invite_code']

        #创建session缓存
        resp.session_id = SessionManager.instance().create_session(device_id, userid)

        if r['new_device']:
            logger.info('new device, idfa:%s, mac:%s' %(req.idfa, req.mac))

        data = {
            'userid': userid,
            'device_id': device_id
        }

        url = 'http://' + BILLING_BACKEND + '/query_balance?' + urllib.urlencode(data)

        r = http_request(url)
        if r['rtn'] == 0:
            resp.balance = r['balance']
            resp.income = r['income']
            resp.outgo = r['outgo']
            resp.shared_income = r['shared_income']
            resp.task_list = self.query_task_list(userid, device_id)

        return resp.dump_json()