def get(self): status = ErrorCode.SUCCESS try: tid = self.get_argument('tid',None) # check tid whether exist in request and update current_user self.check_tid(tid) terminal = self.db.get("SELECT id FROM T_TERMINAL_INFO" " WHERE tid = %s" " AND service_status = %s", self.current_user.tid, UWEB.SERVICE_STATUS.ON) if terminal: lq_sms_key = get_lq_sms_key(self.current_user.tid) sms = SMSCode.SMS_LQ % SMS.LQ.WEB biz_type = QueryHelper.get_biz_type_by_tmobile(self.current_user.sim, self.db) if biz_type != UWEB.BIZ_TYPE.YDWS: pass else: SMSHelper.send_to_terminal(self.current_user.sim, sms) self.redis.setvalue(lq_sms_key, True, SMS.LQ_INTERVAL) lq_interval_key = get_lq_interval_key(self.current_user.tid) self.redis.setvalue(lq_interval_key, int(time.time()), (SMS.LQ.WEB*60 - 160)) logging.info("[UWEB] wake up, send %s to Sim: %s", sms, self.current_user.sim) else: status = ErrorCode.LOGIN_AGAIN self.write_ret(status) except Exception as e: logging.exception("[UWEB] uid: %s wake up tid: %s failed. Exception: %s", self.current_user.uid, self.current_user.tid, e.args) status = ErrorCode.SERVER_BUSY self.write_ret(status)
def send_domain_sms(db, redis, tid, mobile, domain): """Send domain sms to terminal.. """ sms_domain = SMSCode.SMS_DOMAIN % domain SMSHelper.send_to_terminal(mobile, sms_domain) self.db.execute("UPDATE T_TERMINAL_INFO SET domain = %s" " WHERE tid = %s", domain_ip, tid) logging.info("[PUBLIC] Send domain sms: %s to mobile: %s", sms_domain, mobile)
def kqly(db, redis, tids): """Start bluetooth. """ for tid in tids: terminal = QueryHelper.get_terminal_by_tid(tid, db) kqly_key = get_kqly_key(tid) kqly_value = redis.getvalue(kqly_key) if not kqly_value: interval = 30 # in minute sms = SMSCode.SMS_KQLY % interval SMSHelper.send_to_terminal(terminal.mobile, sms) redis.setvalue(kqly_key, True, SMS.KQLY_SMS_INTERVAL)
def send(content, mobile): logging.info("Send %s to %s", content, mobile) #NOTE: send encrypt sms to mobile response = SMSHelper.send_to_terminal(mobile, content) #NOTE: send general sms to mobile #response = SMSHelper.send(mobile, content) logging.info("Response: %s", response)
def send_cq_sms(db, redis, tid, mobile): """Send cq sms to terminal.. """ sms_cq = SMSCode.SMS_CQ if len(mobile) != 11: logging.info("[PUBLIC] Mobile is valid, ignore it. mobile: %s", mobile) return biz_type = QueryHelper.get_biz_type_by_tmobile(mobile, db) if biz_type != UWEB.BIZ_TYPE.YDWS: logging.info( "[PUBLIC] Biz_type is no need cq, ignore it. mobile: %s, biz_type: %s", mobile, biz_type) return SMSHelper.send_to_terminal(mobile, sms_cq) logging.info("[PUBLIC] Send cq sms to terminal. mobile: %s", mobile)
def send_lq_sms(self, sim, tid, interval): """Send LQ Message to terminal. lq_sms_key: when send lq sms to terminal, keep it in redis for 3 minutes. in 3 minutes, do not send lq sms twice. lq_interval_key: when send lq sms to terminal, keep it in redis for interval. in the period of interval, terminal is been awaken. when the period of interval is past, lq_sms should be send again """ lq_sms_key = get_lq_sms_key(tid) lq_interval_key = get_lq_interval_key(tid) self.redis.setvalue(lq_interval_key, int(time.time()), (interval * 60 - 160)) if not self.redis.getvalue(lq_sms_key): sms = SMSCode.SMS_LQ % interval biz_type = QueryHelper.get_biz_type_by_tmobile(sim, self.db) if biz_type != UWEB.BIZ_TYPE.YDWS: pass else: SMSHelper.send_to_terminal(sim, sms) logging.info("[UWEB] send %s to Sim: %s", sms, sim) self.redis.setvalue(lq_sms_key, True, SMS.LQ_INTERVAL)
def post(self): """Reregist a pair of umobile and tmobile. Send sms to terminal. """ status = ErrorCode.SUCCESS try: data = DotDict(json_decode(self.request.body)) logging.info("[UWEB] Register request: %s", data) except Exception as e: status = ErrorCode.ILLEGAL_DATA_FORMAT self.write_ret(status) return try: tmobile = data.tmobile user = QueryHelper.get_user_by_tmobile(tmobile, self.db) if user: umobile = user.owner_mobile terminal = QueryHelper.get_terminal_by_tmobile( tmobile, self.db) if int(terminal.biz_type) == UWEB.BIZ_TYPE.YDWS: register_sms = SMSCode.SMS_REGISTER % (umobile, tmobile) ret = SMSHelper.send_to_terminal(tmobile, register_sms) else: activation_code = QueryHelper.get_activation_code(self.db) register_sms = SMSCode.SMS_REGISTER_YDWQ % ( ConfHelper.UWEB_CONF.url_out, activation_code) ret = SMSHelper.send(tmobile, register_sms) ret = DotDict(json_decode(ret)) if ret.status == ErrorCode.SUCCESS: logging.info("[UWEB] Reregist successfully. umobile: %s, tmobile: %s .", umobile, tmobile) else: status = ErrorCode.REGISTER_FAILED logging.error("[UWEB] Reregister failed. umobile: %s, tmobile: %s. Message: %s", umobile, tmobile, ErrorCode.ERROR_MESSAGE[status]) else: logging.exception("[UWEB] Terminal has no user, ignore it. tmobile: %s. ", tmobile) self.write_ret(status) except Exception as e: logging.exception("[UWEB] Reregister failed. tmobile: %s , Exception: %s", tmobile, e.args) status = ErrorCode.REGISTER_FAILED self.write_ret(status)
def send_jb_sms(self, tmobile, umobile, tid): """ #NOTE: deprecated. It should never be invoked. """ unbind_sms = SMSCode.SMS_UNBIND biz_type = QueryHelper.get_biz_type_by_tmobile(tmobile, self.db) if biz_type != UWEB.BIZ_TYPE.YDWS: ret = DotDict(status=ErrorCode.SUCCESS) else: ret = SMSHelper.send_to_terminal(tmobile, unbind_sms) ret = json_decode(ret) status = ret["status"] if status == ErrorCode.SUCCESS: self.db.execute( "UPDATE T_TERMINAL_INFO" " SET service_status = %s" " WHERE mobile = %s", UWEB.SERVICE_STATUS.TO_BE_UNBIND, tmobile, ) terminals = self.db.query( "SELECT id FROM T_TERMINAL_INFO" " WHERE owner_mobile = %s" " AND service_status = %s", umobile, UWEB.SERVICE_STATUS.ON, ) # clear user if len(terminals) == 0: self.db.execute("DELETE FROM T_USER" " WHERE mobile = %s", umobile) lastinfo_key = get_lastinfo_key(umobile) lastinfo_time_key = get_lastinfo_time_key(umobile) ios_id_key = get_ios_id_key(umobile) ios_badge_key = get_ios_badge_key(umobile) keys = [lastinfo_key, lastinfo_time_key, ios_id_key, ios_badge_key] self.redis.delete(*keys) logging.info("[UWEB] Delete User: %s", umobile) logging.info("[UWEB] umobile: %s, tid: %s, tmobile: %s SMS unbind successfully.", umobile, tid, tmobile) else: logging.error( "[UWEB] umobile: %s, tid: %s, tmobile: %s SMS unbind failed. Message: %s", umobile, tid, tmobile, ErrorCode.ERROR_MESSAGE[status], ) return status
def post(self): status = ErrorCode.SUCCESS try: # {"tmobile":18810496308,"pmobile":18810496308} data = DotDict(json_decode(self.request.body)) tmobile = data.tmobile pmobile = data.pmobile register_sms = SMSCode.SMS_REGISTER % (pmobile, tmobile) ret = SMSHelper.send_to_terminal(tmobile, register_sms) ret = DotDict(json_decode(ret)) if ret.status == ErrorCode.SUCCESS: self.db.execute("UPDATE T_TERMINAL_INFO" " SET msgid = %s" " WHERE mobile = %s", ret['msgid'], tmobile) self.write_ret(status) else: status = ErrorCode.FAILED self.write_ret(status) except Exception as e: logging.exception("SMS register failed. Exception: %s", e.args) status = ErrorCode.FAILED self.write_ret(status)
def post(self): """Turn on tracing.""" status = ErrorCode.SUCCESS try: data = DotDict(json_decode(self.request.body)) tid = data.get('tid', None) tids = data.get('tids', None) flag = int(data.get('flag', 1)) # check tid whether exist in request and update current_user self.check_tid(tid) logging.info("[UWEB] track LQ request: %s, " " uid: %s, tid: %s, tids: %s, flag: %s", data, self.current_user.uid, tid, tids, flag) except Exception as e: status = ErrorCode.ILLEGAL_DATA_FORMAT self.write_ret(status) return try: tids = str_to_list(tids) tids = tids if tids else [self.current_user.tid, ] tids = [str(tid) for tid in tids] if int(flag) == 1: for tid in tids: # NOTE: just send lqgz temporary terminal = QueryHelper.get_terminal_by_tid(tid, self.db) lqgz_key = get_lqgz_key(tid) lqgz_value = self.redis.getvalue(lqgz_key) lqgz_interval_key = get_lqgz_interval_key(tid) if not lqgz_value: interval = 30 # in minute biz_type = QueryHelper.get_biz_type_by_tmobile( terminal.mobile, self.db) if biz_type != UWEB.BIZ_TYPE.YDWS: self.write_ret(status) return sms = SMSCode.SMS_LQGZ % interval SMSHelper.send_to_terminal(terminal.mobile, sms) self.redis.setvalue( lqgz_key, True, SMS.LQGZ_SMS_INTERVAL) self.redis.setvalue( lqgz_interval_key, True, SMS.LQGZ_INTERVAL * 2) # END track_key = get_track_key(tid) track = self.redis.get(track_key) logging.info("[UWEB] Get track: %s from redis", track) if track and int(track) == 1: # turn on track already logging.info( "[UWEB] Terminal: %s turn on track already.", tid) else: self.db.execute("UPDATE T_TERMINAL_INFO SET track = %s" " WHERE tid = %s", flag, tid) self.redis.setvalue(track_key, 1, UWEB.TRACK_INTERVAL) sessionID_key = get_terminal_sessionID_key(tid) self.redis.delete(sessionID_key) self.write_ret(status) except Exception as e: logging.exception("[UWEB] uid: %s, tid: %s send lqgz failed. Exception: %s. ", self.current_user.uid, self.current_user.tid, e.args) status = ErrorCode.SERVER_BUSY self.write_ret(status)
def post(self): try: data = DotDict(json_decode(self.request.body)) gid = data.gid mobiles = list(data.mobiles) logging.info("[UWEB] batch jh: %s, corp_id: %s", data, self.current_user.cid) except Exception as e: status = ErrorCode.ILLEGAL_DATA_FORMAT logging.exception("[UWEB] Invalid data format. Exception: %s", e.args) self.write_ret(status) return try: status = ErrorCode.SUCCESS begintime = int(time.time()) now_ = datetime.datetime.now() endtime = now_ + relativedelta(years=1) endtime = int(time.mktime(endtime.timetuple())) res = [] for item in mobiles: tmobile = item['tmobile'] if item['umobile']: umobile = item['umobile'] else: corp = self.db.get( "SELECT cid, mobile FROM T_CORP WHERE cid = %s", self.current_user.cid) umobile = corp.mobile biz_type = item['biz_type'] r = DotDict(tmobile=tmobile, status=ErrorCode.SUCCESS) # 1. add terminal terminal = self.db.get("SELECT id, tid, service_status FROM T_TERMINAL_INFO WHERE mobile = %s", tmobile) if terminal: if terminal.service_status == UWEB.SERVICE_STATUS.TO_BE_UNBIND: delete_terminal(terminal.tid, self.db, self.redis) else: logging.error("[UWEB] mobile: %s already existed.", tmobile) r['status'] = ErrorCode.TERMINAL_ORDERED continue terminal_info = dict(tid=tmobile, group_id=gid, tmobile=tmobile, owner_mobile=umobile, mannual_status=UWEB.DEFEND_STATUS.YES, begintime=begintime, endtime=4733481600, offline_time=begintime, login_permit=0, biz_type=biz_type, service_status=UWEB.SERVICE_STATUS.ON) if int(biz_type) == UWEB.BIZ_TYPE.YDWS: register_sms = SMSCode.SMS_REGISTER % (umobile, tmobile) ret = SMSHelper.send_to_terminal(tmobile, register_sms) else: activation_code = QueryHelper.get_activation_code(self.db) tid = get_tid_from_mobile_ydwq(tmobile) terminal_info['tid'] = tid terminal_info['activation_code'] = activation_code terminal_info[ 'service_status'] = UWEB.SERVICE_STATUS.TO_BE_ACTIVATED register_sms = SMSCode.SMS_REGISTER_YDWQ % ( ConfHelper.UWEB_CONF.url_out, activation_code) ret = SMSHelper.send(tmobile, register_sms) add_terminal(terminal_info, self.db, self.redis) # record the add action, enterprise bind_info = dict(tid=terminal_info['tid'], tmobile=tmobile, umobile=umobile, group_id=gid, cid=self.current_user.cid, add_time=int(time.time())) record_add_action(bind_info, self.db) ret = DotDict(json_decode(ret)) if ret.status == ErrorCode.SUCCESS: self.db.execute("UPDATE T_TERMINAL_INFO" " SET msgid = %s" " WHERE tid = %s", ret['msgid'], terminal_info['tid']) else: r['status'] = ErrorCode.FAILED # 2. add user user_info = dict(umobile=umobile, password='******', uname=umobile) add_user(user_info, self.db, self.redis) res.append(r) self.write_ret(status, dict_=DotDict(res=res)) except Exception as e: logging.exception("[UWEB] cid: %s batch jh failed. Exception: %s", self.current_user.cid, e.args) status = ErrorCode.SERVER_BUSY self.write_ret(status)
def post(self): status = ErrorCode.SUCCESS try: data = DotDict(json_decode(self.request.body)) logging.info("[UWEB] batch delete request: %s, corp_id: %s", data, self.current_user.cid) except Exception as e: status = ErrorCode.ILLEGAL_DATA_FORMAT logging.exception("[UWEB] Invalid data format. Exception: %s", e.args) self.write_ret(status) return try: status = ErrorCode.SUCCESS tids = list(data.tids) flag = data.flag res = [] for tid in tids: r = DotDict(tid=tid, status=ErrorCode.SUCCESS) terminal = QueryHelper.get_available_terminal(tid, self.db) if not terminal: r.status = ErrorCode.SUCCESS res.append(r) logging.error( "[UWEB] The terminal with tid: %s does not exist!", tid) continue key = get_del_data_key(tid) self.redis.set(key, flag) biz_type = QueryHelper.get_biz_type_by_tmobile( terminal.mobile, self.db) if int(biz_type) == UWEB.BIZ_TYPE.YDWQ: delete_terminal(tid, self.db, self.redis) res.append(r) continue elif int(biz_type) == UWEB.BIZ_TYPE.YDWS: if terminal.login != GATEWAY.TERMINAL_LOGIN.ONLINE: if terminal.mobile == tid: delete_terminal(tid, self.db, self.redis) else: r.status = self.send_jb_sms( terminal.mobile, terminal.owner_mobile, tid) res.append(r) continue # NOT: unbind. TODO: It should be re-factor some day. seq = str(int(time.time() * 1000))[-4:] args = DotDict(seq=seq, tid=tid) response = GFSenderHelper.forward( GFSenderHelper.URLS.UNBIND, args) response = json_decode(response) if response['success'] == ErrorCode.SUCCESS: logging.info("[UWEB] uid:%s, tid: %s, tmobile:%s GPRS unbind successfully", self.current_user.uid, tid, terminal.mobile) res.append(r) else: # unbind failed. clear sessionID for relogin, then unbind # it again sessionID_key = get_terminal_sessionID_key(tid) self.redis.delete(sessionID_key) logging.error('[UWEB] uid:%s, tid: %s, tmobile:%s GPRS unbind failed, message: %s, send JB sms...', self.current_user.uid, tid, terminal.mobile, ErrorCode.ERROR_MESSAGE[response['success']]) unbind_sms = SMSCode.SMS_UNBIND biz_type = QueryHelper.get_biz_type_by_tmobile( terminal.mobile, self.db) if biz_type != UWEB.BIZ_TYPE.YDWS: ret = DotDict(status=ErrorCode.SUCCESS) else: ret = SMSHelper.send_to_terminal( terminal.mobile, unbind_sms) ret = DotDict(json_decode(ret)) if ret.status == ErrorCode.SUCCESS: res.append(r) self.db.execute("UPDATE T_TERMINAL_INFO" " SET service_status = %s" " WHERE id = %s", UWEB.SERVICE_STATUS.TO_BE_UNBIND, terminal.id) logging.info("[UWEB] uid: %s, tid: %s, tmobile: %s SMS unbind successfully.", self.current_user.uid, tid, terminal.mobile) else: r.status = ErrorCode.FAILED res.append(r) logging.error("[UWEB] uid: %s, tid: %s, tmobile: %s SMS unbind failed. Message: %s", self.current_user.uid, tid, terminal.mobile, ErrorCode.ERROR_MESSAGE[status]) self.write_ret(status, dict_=DotDict(res=res)) except Exception as e: logging.exception("[UWEB] cid: %s batch delete failed. Exception: %s", self.current_user.cid, e.args) status = ErrorCode.ILLEGAL_FILE self.write_ret(status)
def post(self, tmobile, pmobile, is_clear): """Delete a terminal. @param: tmobile // terminal's mobile @param: pmobile // owner_mobile @param: is_clear: 清除// 1: 清除历史数据; 0: 不清楚历史数据 """ status = ErrorCode.SUCCESS try: terminal = self.db.get("SELECT id, login, mobile, tid" " FROM T_TERMINAL_INFO" " WHERE mobile = %s", tmobile) tid = terminal.tid #NOTE: record whether clear history in redis key = get_del_data_key(tid) self.redis.set(key, is_clear) biz_type = QueryHelper.get_biz_type_by_tmobile(tmobile, self.db) if int(biz_type) == UWEB.BIZ_TYPE.YDWS: if terminal.login != GATEWAY.TERMINAL_LOGIN.ONLINE: # offline if terminal.mobile == tid: delete_terminal_new(tid, self.db, self.redis) logging.info('[ADMIN] Delete terminal. umobile:%s, tid: %s, tmobile:%s.', pmobile, tid, tmobile) else: delete_terminal_new(tid, self.db, self.redis) unbind_sms = SMSCode.SMS_UNBIND ret = SMSHelper.send_to_terminal(tmobile, unbind_sms) ret = DotDict(json_decode(ret)) logging.info('[ADMIN] Send JB sms. umobile:%s, tid: %s, tmobile:%s.', pmobile, tid, tmobile) self.write_ret(status) return else: delete_terminal_new(tid, self.db, self.redis) self.write_ret(status) return # unbind terminal seq = str(int(time.time()*1000))[-4:] args = DotDict(seq=seq, tid=terminal.tid) response = GFSenderHelper.forward(GFSenderHelper.URLS.UNBIND, args) response = json_decode(response) if response['success'] == ErrorCode.SUCCESS: logging.info("[ADMIN] Umobile: %s, tid: %s, tmobile:%s" " GPRS unbind successfully", pmobile, terminal.tid, tmobile) else: status = response['success'] # unbind failed. clear sessionID for relogin, then unbind it again sessionID_key = get_terminal_sessionID_key(terminal.tid) self.redis.delete(sessionID_key) logging.error("[ADMIN] Umobile:%s, tid: %s, tmobile:%s" " GPRS unbind failed, message: %s, send JB sms...", pmobile, terminal.tid, tmobile, ErrorCode.ERROR_MESSAGE[status]) unbind_sms = SMSCode.SMS_UNBIND biz_type = QueryHelper.get_biz_type_by_tmobile(tmobile, self.db) if biz_type != UWEB.BIZ_TYPE.YDWS: ret = DotDict(status=ErrorCode.SUCCESS) else: ret = SMSHelper.send_to_terminal(tmobile, unbind_sms) ret = DotDict(json_decode(ret)) status = ret.status if ret.status == ErrorCode.SUCCESS: self.db.execute("UPDATE T_TERMINAL_INFO" " SET service_status = %s" " WHERE id = %s", UWEB.SERVICE_STATUS.TO_BE_UNBIND, terminal.id) logging.info("[ADMIN] umobile: %s, tid: %s, tmobile: %s" " SMS unbind successfully.", pmobile, terminal.tid, tmobile) else: logging.error("[ADMIN] umobile: %s, tid: %s, tmobile: %s" " SMS unbind failed. Message: %s", pmobile, terminal.tid, tmobile, ErrorCode.ERROR_MESSAGE[status]) except Exception as e: status = ErrorCode.FAILED logging.exception("[ADMIN] Delete service failed." " tmobile: %s, owner mobile: %s, Exception: %s", tmobile, pmobile, e.args) self.write_ret(status)
def post(self): """Create business for a couple of users. """ fields = DotDict(group_id="", cnum="", ctype="", ccolor="", cbrand="", tmobile="", begintime="", endtime="", uname="", umobile="", password="", address="", email="", ecmobile="") for key in fields.iterkeys(): fields[key] = self.get_argument(key,'') #if not check_sql_injection(fields[key]): # logging.error("Create business condition contain SQL inject. %s : %s", key, fields[key]) # self.render('errors/error.html', # message=ErrorCode.ERROR_MESSAGE[ErrorCode.CREATE_CONDITION_ILLEGAL]) # return white_list = check_zs_phone(fields.tmobile, self.db) if not white_list: logging.error("Create business error, %s is not whitelist", fields.tmobile) self.render('errors/error.html', message=ErrorCode.ERROR_MESSAGE[ErrorCode.MOBILE_NOT_ORDERED]) return try: # 1: add user user_info = dict(umobile=fields.umobile, password=fields.password, uname=fields.uname, address=fields.address, email=fields.email) add_user(user_info, self.db, self.redis) # record the add action bind_info = dict(tid=fields.tmobile, tmobile=fields.tmobile, umobile=fields.umobile, group_id=-1, cid=fields.ecmobile, add_time=int(time.time())) record_add_action(bind_info, self.db) # 2: add terminal if not fields.umobile: user_mobile = fields.ecmobile else: user_mobile = fields.umobile terminal_info = dict(tmobile=fields.tmobile, owner_mobile=user_mobile, begintime=fields.begintime, offline_time=fields.begintime, endtime=4733481600, # 2120.1.1 cnum=fields.cnum, ctype=fields.ctype, ccolor=fields.ccolor, cbrand=fields.cbrand) add_terminal(terminal_info, self.db, self.redis) # 4: send message to terminal register_sms = SMSCode.SMS_REGISTER % (fields.umobile, fields.tmobile) ret = SMSHelper.send_to_terminal(fields.tmobile, register_sms) ret = DotDict(json_decode(ret)) sms_status = 0 if ret.status == ErrorCode.SUCCESS: self.db.execute("UPDATE T_TERMINAL_INFO" " SET msgid = %s" " WHERE mobile = %s", ret['msgid'], fields.tmobile) #convert front desk need format sms_status = 1 else: sms_status = 0 logging.error("Create business sms send failure. terminal mobile: %s, owner mobile: %s", fields.tmobile, fields.mobile) fields.sms_status = sms_status fields.service_status = 1 self.render('business/list.html', business=fields, status=ErrorCode.SUCCESS, message='') except Exception as e: logging.exception("Create business failed. Exception: %s.", e.args) self.render('errors/error.html', message=ErrorCode.ERROR_MESSAGE[ErrorCode.CREATE_USER_FAILURE])
def post(self): """Regist a pair of umobile and tmobile. """ status = ErrorCode.SUCCESS try: data = DotDict(json_decode(self.request.body)) logging.info("[UWEB] Register request: %s", data) umobile = data.umobile tmobile = data.tmobile captcha = data.captcha except Exception as e: status = ErrorCode.ILLEGAL_DATA_FORMAT logging.exception("[UWEB] Invalid data format. Exception: %s", e.args) self.write_ret(status) return try: # check tmobile is whitelist or not white_list = check_zs_phone(tmobile, self.db) if not white_list: logging.info("[UWEB] Mobile is not whitelist. tmobile: %s.", tmobile) status = ErrorCode.MOBILE_NOT_ORDERED message = ErrorCode.ERROR_MESSAGE[status] % tmobile self.write_ret(status, message=message) return captcha_key = get_captcha_key(umobile) captcha_old = self.redis.get(captcha_key) if captcha_old: if captcha == str(captcha_old): terminal = QueryHelper.get_terminal_by_tmobile( tmobile, self.db) if terminal: if terminal.service_status == UWEB.SERVICE_STATUS.TO_BE_UNBIND: # delete to_be_unbind terminal! delete_terminal(terminal.tid, self.db, self.redis) else: status = ErrorCode.TERMINAL_ORDERED logging.info("[UWEB] Regist failed. umobile: %s, tmobile: %s Message: %s", umobile, tmobile, ErrorCode.ERROR_MESSAGE[status]) self.write_ret(status) return register_sms = SMSCode.SMS_REGISTER % (umobile, tmobile) ret = SMSHelper.send_to_terminal(tmobile, register_sms) ret = DotDict(json_decode(ret)) if ret.status == ErrorCode.SUCCESS: logging.info("[UWEB] Regist successfully. umobile: %s, tmobile: %s ", umobile, tmobile) self.redis.delete(captcha_key) else: status = ErrorCode.REGISTER_FAILED logging.error("[UWEB] Regist failed. umobile: %s, tmobile: %s. Message: %s", umobile, tmobile, ErrorCode.ERROR_MESSAGE[status]) else: status = ErrorCode.WRONG_CAPTCHA logging.error("[UWEB] Regist failed. umobile: %s, captcha: %s, captcha_old: %s, Message: %s", umobile, captcha, captcha_old, ErrorCode.ERROR_MESSAGE[status]) else: status = ErrorCode.NO_CAPTCHA logging.error("[UWEB] Register failed. umobile: %s, captcha: %s, Message: %s", umobile, captcha, ErrorCode.ERROR_MESSAGE[status]) self.write_ret(status) except Exception as e: logging.exception("[UWEB] Register failed. umobile: %s tmobile: %s , Exception: %s", umobile, tmobile, e.args) status = ErrorCode.REGISTER_FAILED self.write_ret(status)
def post(self): """Create business for a couple of users. """ fields = DotDict(ecid="", cnum="", ctype="", ccolor="", cbrand="", tmobile="", begintime="", endtime="", uname="", umobile="", password="", address="", email="", ecmobile="", biz_type="") for key in fields.iterkeys(): fields[key] = self.get_argument(key, '') # if not check_sql_injection(fields[key]): # logging.error("Create business condition contain SQL inject. %s : %s", key, fields[key]) # self.render('errors/error.html', # message=ErrorCode.ERROR_MESSAGE[ErrorCode.CREATE_CONDITION_ILLEGAL]) # return white_list = check_zs_phone(fields.tmobile, self.db) if not white_list: logging.error( "Create business error, %s is not whitelist", fields.tmobile) self.render('errors/error.html', message=ErrorCode.ERROR_MESSAGE[ErrorCode.MOBILE_NOT_ORDERED]) return try: # 1: add user user = self.db.get( "SELECT id FROM T_USER WHERE mobile = %s", fields.umobile) if not user: self.db.execute("INSERT INTO T_USER(id, uid, password, name, mobile, address, email, remark)" " VALUES(NULL, %s, password(%s), %s, %s, %s, %s, NULL)", fields.umobile, '111111', fields.uname, fields.umobile, fields.address, fields.email) self.db.execute("INSERT INTO T_SMS_OPTION(uid)" " VALUES(%s)", fields.umobile) # 2: add terminal group = self.db.get("SELECT id FROM T_GROUP" " WHERE corp_id = %s AND type = 0 LIMIT 1", fields.ecid) if not group: gid = self.db.execute("INSERT INTO T_GROUP(corp_id, name, type)" " VALUES(%s, default, default)", fields.ecid) else: gid = group.id # record the add action, enterprise bind_info = dict(tid=fields.tmobile, tmobile=fields.tmobile, umobile=fields.umobile, group_id=gid, cid=fields.ecmobile, add_time=int(time.time())) record_add_action(bind_info, self.db) if not fields.umobile: user_mobile = fields.ecmobile else: user_mobile = fields.umobile # 3: send message to terminal biz_type = int(fields.biz_type) if biz_type == UWEB.BIZ_TYPE.YDWS: self.db.execute("INSERT INTO T_TERMINAL_INFO(tid, group_id, mobile, owner_mobile," " begintime, endtime, offline_time, login_permit)" " VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", fields.tmobile, gid, fields.tmobile, user_mobile, fields.begintime, 4733481600, fields.begintime, 0) register_sms = SMSCode.SMS_REGISTER % ( fields.umobile, fields.tmobile) ret = SMSHelper.send_to_terminal(fields.tmobile, register_sms) self.db.execute("INSERT INTO T_CAR(tid, cnum, type, color, brand)" " VALUES(%s, %s, %s, %s, %s)", fields.tmobile, fields.cnum, fields.ctype, fields.ccolor, fields.cbrand) else: tid = get_tid_from_mobile_ydwq(fields.tmobile) activation_code = QueryHelper.get_activation_code(self.db) self.db.execute("INSERT INTO T_TERMINAL_INFO(tid, group_id, mobile, owner_mobile," " begintime, endtime, offline_time, login_permit," " biz_type, activation_code, service_status)" " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", tid, gid, fields.tmobile, user_mobile, fields.begintime, 4733481600, fields.begintime, 0, biz_type, activation_code, UWEB.SERVICE_STATUS.TO_BE_ACTIVATED) register_sms = SMSCode.SMS_REGISTER_YDWQ % ( ConfHelper.UWEB_CONF.url_out, activation_code) ret = SMSHelper.send(fields.tmobile, register_sms) self.db.execute("INSERT INTO T_CAR(tid, cnum, type, color, brand)" " VALUES(%s, %s, %s, %s, %s)", tid, fields.cnum, fields.ctype, fields.ccolor, fields.cbrand) ret = DotDict(json_decode(ret)) sms_status = 0 if ret.status == ErrorCode.SUCCESS: self.db.execute("UPDATE T_TERMINAL_INFO" " SET msgid = %s" " WHERE mobile = %s", ret['msgid'], fields.tmobile) # convert front desk need format sms_status = 1 else: sms_status = 0 logging.error("[ADMIN] Create business sms send failure." " terminal mobile: %s, owner mobile: %s", fields.tmobile, fields.umobile) fields.sms_status = sms_status fields.service_status = 1 self.render('business/list.html', business=fields, status=ErrorCode.SUCCESS, message='') except Exception as e: logging.exception("Add terminal failed. Exception: %s.", e.args) self.render('errors/error.html', message=ErrorCode.ERROR_MESSAGE[ErrorCode.CREATE_USER_FAILURE])
def post(self, ecmobile): """Delete the corp. """ status = ErrorCode.SUCCESS try: ec = self.get_ecbusiness_info(ecmobile) groups = self.db.query( "SELECT id FROM T_GROUP WHERE corp_id = %s", ec.cid) groups = [group.id for group in groups] terminals = self.db.query("SELECT id, tid, mobile, owner_mobile" " FROM T_TERMINAL_INFO WHERE group_id IN %s", tuple(groups + DUMMY_IDS)) for terminal in terminals: # unbind terminal seq = str(int(time.time() * 1000))[-4:] args = DotDict(seq=seq, tid=terminal.tid) response = GFSenderHelper.forward( GFSenderHelper.URLS.UNBIND, args) response = json_decode(response) if response['success'] == ErrorCode.SUCCESS: logging.info("[ADMIN] umobile: %s, tid: %s, tmobile:%s" " GPRS unbind successfully", terminal.owner_mobile, terminal.tid, terminal.mobile) else: status = response['success'] # unbind failed. clear sessionID for relogin, then unbind # it again sessionID_key = get_terminal_sessionID_key(terminal.tid) self.redis.delete(sessionID_key) logging.error("[ADMIN] umobile:%s, tid: %s, tmobile:%s" " GPRS unbind failed, message: %s, send JB sms...", terminal.owner_mobile, terminal.tid, terminal.mobile, ErrorCode.ERROR_MESSAGE[status]) unbind_sms = SMSCode.SMS_UNBIND biz_type = QueryHelper.get_biz_type_by_tmobile( terminal.mobile, self.db) if biz_type != UWEB.BIZ_TYPE.YDWS: ret = DotDict(status=ErrorCode.SUCCESS) else: ret = SMSHelper.send_to_terminal( terminal.mobile, unbind_sms) ret = DotDict(json_decode(ret)) status = ret.status if ret.status == ErrorCode.SUCCESS: self.db.execute("UPDATE T_TERMINAL_INFO" " SET service_status = %s" " WHERE id = %s", UWEB.SERVICE_STATUS.TO_BE_UNBIND, terminal.id) logging.info("[ADMIN] umobile: %s, tid: %s, tmobile: %s" " SMS unbind successfully.", terminal.owner_mobile, terminal.tid, terminal.mobile) else: logging.error("[ADMIN] umobile: %s, tid: %s, tmobile: %s" " SMS unbind failed. Message: %s", terminal.owner_mobile, terminal.tid, terminal.mobile, ErrorCode.ERROR_MESSAGE[status]) self.db.execute("DELETE FROM T_CORP WHERE cid = %s", ec.cid) except Exception as e: status = ErrorCode.FAILED logging.exception("Delete service failed. ecmobile: %s, Exception: %s.", ecmobile, e.args) self.write_ret(status)
def post(self): status = ErrorCode.SUCCESS try: data = json_decode(self.request.body) logging.info("[LOG] message request: %s", data) sms_type = data.get('sms_type') tmobile = data.get('tmobile') content = '' if check_phone(tmobile) is None: status = ErrorCode.ILLEGAL_MOBILE self.write_ret(status) else: if sms_type == 'JH': umobile = data.get('umobile') if check_phone(umobile): content = ':SIM' + ' ' + umobile + ':' + tmobile SMSHelper.send_to_terminal(tmobile, content) self.write_ret(status) else: status = ErrorCode.ILLEGAL_MOBILE self.write_ret(status) elif sms_type == 'JB': content = ':' + sms_type is_clear = data.get('is_clear') ret = SMSHelper.send_to_terminal(tmobile, content) ret = json_decode(ret) terminal = self.acbdb.get("SELECT id, tid, owner_mobile, login" " FROM T_TERMINAL_INFO" " WHERE mobile = %s" " AND service_status = 1", tmobile) if not terminal: status = ErrorCode.TERMINAL_NOT_EXISTED logging.error("The terminal with tmobile: %s does not exist!", tmobile) self.write_ret(status) return umobile = terminal.owner_mobile if ret['status'] == 0: self.acbdb.execute("UPDATE T_TERMINAL_INFO" " SET service_status = 2" " WHERE mobile = %s", tmobile) # terminals = self.acbdb.query("SELECT id FROM T_TERMINAL_INFO" # " WHERE owner_mobile = %s" # " AND service_status = 1", # umobile) # clear user # if len(terminals) == 0: # self.acbdb.execute("DELETE FROM T_USER" # " WHERE mobile = %s", # umobile) if is_clear == 1: clear_data(terminal['tid'], self.acbdb, self.redis) self.write_ret(status) elif sms_type == 'CQ': content = ':' + sms_type SMSHelper.send_to_terminal(tmobile, content) self.write_ret(status) elif sms_type == 'REBOOT': content = ':' + sms_type # SMSHelper.send_to_terminal(tmobile,content) SMSHelper.send_update_to_terminal(tmobile, content) self.write_ret(status) elif sms_type == 'TEST': content = u'尊敬的顾客,您好:这是一条测试短信,收到本条短信,说明短信提示服务正常,本短信不需要回复,如有问题,请和客服人员联系。感谢使用我们的产品,您的移动卫士。' SMSHelper.send(tmobile, content) self.write_ret(status) elif sms_type == 'KQLY': content = ':%s 30' % sms_type SMSHelper.send_to_terminal(tmobile, content) self.write_ret(status) elif sms_type == 'LQGZ': content = ':%s 30' % sms_type SMSHelper.send_to_terminal(tmobile, content) self.write_ret(status) elif sms_type == 'DW': content = ':' + sms_type SMSHelper.send_to_terminal(tmobile, content) self.write_ret(status) elif sms_type == 'UPDATE': content = ':' + sms_type SMSHelper.send_update_to_terminal(tmobile, content) self.write_ret(status) elif sms_type == 'DEL': terminal = self.acbdb.get( 'SELECT tid FROM T_TERMINAL_INFO WHERE mobile=%s', tmobile) if terminal: delete_terminal( terminal.tid, self.acbdb, self.redis, del_user=False) self.write_ret(status) elif sms_type == 'DOMAIN': ip = data.get('domain') content = ':DOMAIN ' + ip info = self.acbdb.get( 'SELECT * FROM T_TERMINAL_INFO WHERE mobile=%s', tmobile) if info: self.acbdb.execute("UPDATE T_TERMINAL_INFO" " SET domain=%s WHERE mobile=%s", ip, tmobile) SMSHelper.send_to_terminal(tmobile, content) self.write_ret(status) else: status = ErrorCode.TERMINAL_NOT_EXISTED self.write_ret(status) except Exception, e: logging.exception("acb-->sms post exception : %s", e) self.render('errors/error.html', message=ErrorCode.ERROR_MESSAGE[ErrorCode.FAILED])
def update_terminal_db(self, data): """Update database. """ # NOTE: these fields should to be modified in db terminal_keys = ['cellid_status', 'white_pop', 'trace', 'freq', 'vibchk', 'vibl', 'push_status', 'login_permit', 'alert_freq', 'stop_interval', 'biz_type', 'speed_limit'] terminal_fields = [] if data.has_key('tid'): del data['tid'] for key, value in data.iteritems(): # NOTE: These fields should be modified in database. if key in terminal_keys: if data.get(key, None) is not None: terminal_fields.append(key + ' = ' + str(value)) # NOT: These fields should be handled specially. if key == 'white_list': white_list = data[key] if len(data['white_list']) < 1: pass else: self.db.execute("DELETE FROM T_WHITELIST WHERE tid = %s", self.current_user.tid) for white in white_list[1:]: self.db.execute("INSERT INTO T_WHITELIST" " VALUES(NULL, %s, %s)" " ON DUPLICATE KEY" " UPDATE tid = VALUES(tid)," " mobile = VALUES(mobile)", self.current_user.tid, white) elif key == 'alias': self.db.execute("UPDATE T_TERMINAL_INFO" " SET alias = %s" " WHERE tid = %s", value, self.current_user.tid) terminal_info_key = get_terminal_info_key( self.current_user.tid) terminal_info = self.redis.getvalue(terminal_info_key) if terminal_info: terminal_info[key] = value self.redis.setvalue(terminal_info_key, terminal_info) elif key == 'icon_type': self.db.execute("UPDATE T_TERMINAL_INFO" " SET icon_type = %s" " WHERE tid = %s", value, self.current_user.tid) terminal_info_key = get_terminal_info_key( self.current_user.tid) terminal_info = self.redis.getvalue(terminal_info_key) if terminal_info: terminal_info[key] = value self.redis.setvalue(terminal_info_key, terminal_info) elif key == 'corp_cnum': self.db.execute("UPDATE T_CAR" " SET cnum = %s" " WHERE tid = %s", safe_utf8(value), self.current_user.tid) self.db.execute("UPDATE T_TERMINAL_INFO" " SET alias = %s" " WHERE tid = %s", safe_utf8(value), self.current_user.tid) terminal_info_key = get_terminal_info_key( self.current_user.tid) terminal_info = self.redis.getvalue(terminal_info_key) if terminal_info: terminal_info[ 'alias'] = value if value else self.current_user.sim self.redis.setvalue(terminal_info_key, terminal_info) elif key == 'owner_mobile' and value is not None: umobile = value user = dict(umobile=umobile, password=u'111111') add_user(user, self.db, self.redis) t = QueryHelper.get_terminal_by_tid(self.current_user.tid, self.db) old_uids = [t.owner_mobile] # send sms self.db.execute("UPDATE T_TERMINAL_INFO" " SET owner_mobile = %s" " WHERE tid = %s", umobile, self.current_user.tid) register_sms = SMSCode.SMS_REGISTER % ( umobile, self.current_user.sim) SMSHelper.send_to_terminal(self.current_user.sim, register_sms) # update redis terminal_info_key = get_terminal_info_key( self.current_user.tid) terminal_info = self.redis.getvalue(terminal_info_key) if terminal_info: terminal_info[key] = umobile self.redis.setvalue(terminal_info_key, terminal_info) # wspush to client WSPushHelper.pushS3(self.current_user.tid, self.db, self.redis) WSPushHelper.pushS3_dummy(old_uids, self.db, self.redis) elif key == "alert_freq": alert_freq_key = get_alert_freq_key(self.current_user.tid) if self.redis.exists(alert_freq_key): logging.info( "[UWEB] Termianl %s delete alert freq in redis.", self.current_user.tid) self.redis.delete(alert_freq_key) # if vibl has been changed,then update use_scene as well elif key == "vibl": use_scene = get_use_scene_by_vibl(value) self.db.execute("UPDATE T_TERMINAL_INFO SET use_scene=%s WHERE tid=%s", use_scene, self.current_user.tid) logging.info("[UWEB] Terminal %s update use_scene %s and vibl %s", self.current_user.tid, use_scene, value) logging.info( "[UWEB] Termianl %s delete session in redis.", self.current_user.tid) # NOTE: deprecated. elif key == "parking_defend" and value is not None: if value == 1: mannual_status = UWEB.DEFEND_STATUS.SMART else: mannual_status = UWEB.DEFEND_STATUS.YES update_mannual_status( self.db, self.redis, self.current_user.tid, mannual_status) elif key == 'login_permit': # wspush to client WSPushHelper.pushS3(self.current_user.tid, self.db, self.redis) else: pass # NOTE:update database. terminal_clause = ','.join(terminal_fields) if terminal_clause: self.db.execute("UPDATE T_TERMINAL_INFO" " SET " + terminal_clause + " WHERE tid = %s ", self.current_user.tid) # NOTE: clear sessionID if freq, stop_interval, vibl can be found. if data.has_key('freq') or data.has_key('stop_interval') or data.has_key('vibl'): clear_sessionID(self.redis, self.current_user.tid)
def handle_new_login(t_info, address, connection, channel, exchange, gw_binding, db, redis): """Handle the login packet with version bigger than 2.2.0 S1 t_info:{'dev_id' // tid 't_msisdn' // tmobile 'u_msisdn' // umobile 'imei' // sim's id 'imsi' // track's id 'dev_type' 'softversion' // version of terminal, like 2.3.0 'timestamp' 'psd' 'keys_num' 'sessionID' 'command' 'factory_name' } flag(t_info['psd']): 0 - boot_normally 1 - active_terminal 2 - assert_reboot 3 - network_uncovered 4 - server_no_response 5 - config_changed 6 - session_expired 7 - terminal_unactived 8 - package_send_fail 9 - simcard_error 10 - gprs_error 11 - mcu_timeout 12 - reboot_by_sms 100 - script_reload workflow: if normal login: if sn and imsi exist, but msisdn and msisdn are empty: send register sms again normal login, check [SN,PHONE,IMSI,USER] is matching or not. else: #JH delete old bind relation of tid, and send message to old user. update new bind relation of tmobile, and send message to new user. login response packet: 0 - success, then get a sessionID for terminal and record terminal's address 1 - unregister, terminal login first. 3 - illegal sim, a mismatch between [SN,PHONE,IMSI,USER] 6 - not whitelist """ args = DotDict(success=GATEWAY.LOGIN_STATUS.SUCCESS, sessionID='') tid = t_info.dev_id resend_key, resend_flag = get_resend_flag(redis, tid, t_info.timestamp, t_info.command) sms = '' t_status = None #NOTE: new softversion, new meaning, 1: active; othter: normal login flag = t_info['psd'] terminal = db.get("SELECT tid, group_id, mobile, imsi, owner_mobile, service_status," " defend_status, mannual_status, icon_type, login_permit, " " alias, vibl, use_scene, push_status, speed_limit, stop_interval," " distance_current" " FROM T_TERMINAL_INFO" " WHERE mobile = %s LIMIT 1", t_info['t_msisdn']) cnum = QueryHelper.get_cnum_by_terminal(tid, t_info['t_msisdn'], redis, db) #NOTE: normal login if flag != "1": # normal login #NOTE: no tmobile and ower_mobile if (not t_info['t_msisdn']) and (not t_info['u_msisdn']): t = db.get("SELECT tid, group_id, mobile, imsi, owner_mobile, service_status" " FROM T_TERMINAL_INFO" " WHERE service_status=1" " AND tid = %s " " AND imsi = %s LIMIT 1", t_info['dev_id'], t_info['imsi']) if t: args.success = GATEWAY.LOGIN_STATUS.ILLEGAL_SIM t_info['t_msisdn'] = t.mobile t_info['u_msisdn'] = t.owner_mobile register_sms = SMSCode.SMS_REGISTER % (t.owner_mobile, t.mobile) SMSHelper.send_to_terminal(t.mobile, register_sms) logging.info("[GW] A crash terminal tid:%s, imei:%s has no tmobile: %s, umobile:%s in login packet, so send %s again.", t_info['dev_id'], t_info['imei'], t_info['t_msisdn'], t_info['u_msisdn'], register_sms) else: args.success = GATEWAY.LOGIN_STATUS.ILLEGAL_SIM logging.info("[GW] A crash terminal:%s login without umobile and tmobile, and there is no record in db.", t_info['dev_id']) else: #NOTE: no tmobile if not t_info['t_msisdn']: # login first. tid_terminal = db.get("SELECT tid, mobile, owner_mobile, service_status" " FROM T_TERMINAL_INFO" " WHERE tid = %s LIMIT 1", t_info['dev_id']) args.success = GATEWAY.LOGIN_STATUS.ILLEGAL_SIM if tid_terminal: #NOTE: mobile is not not JH, send caution to owner sms_ = SMSCode.SMS_NOT_JH % tid_terminal.mobile SMSHelper.send(tid_terminal.owner_mobile, sms_) logging.warn("[GW] terminal: %s login at first time.", t_info['dev_id']) #NOTE: tmobile is exist elif terminal: alias = QueryHelper.get_alias_by_tid(terminal['tid'], redis, db) if terminal['tid'] != t_info['dev_id']: args.success = GATEWAY.LOGIN_STATUS.ILLEGAL_SIM sms = SMSCode.SMS_TERMINAL_HK % alias logging.warn("[GW] Terminal changed dev, mobile: %s, old_tid: %s, new_tid: %s", t_info['t_msisdn'], terminal['tid'], t_info['dev_id']) elif terminal['imsi'] != t_info['imsi']: args.success = GATEWAY.LOGIN_STATUS.ILLEGAL_SIM sms = SMSCode.SMS_TERMINAL_HK % alias logging.warn("[GW] Terminal imsi is wrong, tid: %s, mobile: %s, old_imsi: %s, new_imsi: %s", t_info['dev_id'], t_info['t_msisdn'], terminal['imsi'], t_info['imsi']) elif terminal['owner_mobile'] != t_info['u_msisdn']: register_sms = SMSCode.SMS_REGISTER % (terminal['owner_mobile'], terminal['mobile']) SMSHelper.send_to_terminal(terminal['mobile'], register_sms) logging.warn("[GW] Terminal owner_mobile is wrong, tid: %s, old_owner_mobile: %s, new_owner_mobile: %s, send the regist sms: %s again", t_info['dev_id'], terminal['owner_mobile'], t_info['u_msisdn'], register_sms) elif terminal['service_status'] == UWEB.SERVICE_STATUS.TO_BE_UNBIND: t_status = UWEB.SERVICE_STATUS.TO_BE_UNBIND logging.warn("[GW] Terminal is unbinded. tid: %s, mobile: %s", t_info["dev_id"], t_info['t_msisdn']) else: logging.info("[GW] Terminal normal login successfully. tid: %s, mobile: %s", t_info['dev_id'], t_info['t_msisdn']) else: args.success = GATEWAY.LOGIN_STATUS.UNREGISTER logging.error("[GW] Terminal login failed, unregister. tid: %s, mobile: %s", t_info['dev_id'], t_info['t_msisdn']) #NOTE: JH else: # JH logging.info("[GW] Terminal JH started. tid: %s, mobile: %s", t_info['dev_id'], t_info['t_msisdn']) # 0. Initialize the valus keeps same as the default value in database. group_id = -1 login_permit = 1 mannual_status = UWEB.DEFEND_STATUS.YES defend_status = UWEB.DEFEND_STATUS.YES icon_type = 0 alias = '' push_status = 1 vibl = 1 use_scene = 3 speed_limit = 120 stop_interval = 0 distance_current = 0 # send JH sms to terminal. default active time is one year. begintime = datetime.datetime.now() endtime = begintime + relativedelta(years=1) # 1. check data validation logging.info("[GW] Checking terminal mobile: %s and owner mobile: %s, Terminal: %s", t_info['t_msisdn'], t_info['u_msisdn'], t_info['dev_id']) if not (check_phone(t_info['u_msisdn']) and check_phone(t_info['t_msisdn'])): args.success = GATEWAY.LOGIN_STATUS.ILLEGAL_SIM lc = LoginRespComposer(args) request = DotDict(packet=lc.buf, address=address, dev_id=t_info['dev_id']) if t_info['u_msisdn']: # send JH failed caution to owner sms = SMSCode.SMS_JH_FAILED SMSHelper.send(t_info['u_msisdn'], sms) logging.error("[GW] Login failed! Invalid terminal mobile: %s or owner_mobile: %s, tid: %s", t_info['t_msisdn'], t_info['u_msisdn'], t_info['dev_id']) append_gw_request(request, connection, channel, exchange, gw_binding) # 2. delete to_be_unbind terminal if terminal and terminal.service_status == UWEB.SERVICE_STATUS.TO_BE_UNBIND: logging.info("[GW] Delete terminal which is to_be_unbind. tid: %s, mobile: %s", terminal['tid'], terminal['mobile']) delete_terminal_new(terminal['tid'], db, redis) terminal = None # 3. add user info exist = db.get("SELECT id FROM T_USER" " WHERE mobile = %s", t_info['u_msisdn']) #NOTE: Check ydcw or ajt ajt = QueryHelper.get_ajt_whitelist_by_mobile(t_info['t_msisdn'], db) if ajt: url_out = ConfHelper.UWEB_CONF.ajt_url_out else: url_out = ConfHelper.UWEB_CONF.url_out logging.info("[GW] Login url is: %s, tid: %s, mobile: %s ", url_out, t_info['dev_id'], t_info['t_msisdn']) if exist: logging.info("[GW] Owner already existed. tid: %s, mobile: %s", t_info['dev_id'], t_info['t_msisdn']) sms = SMSCode.SMS_USER_ADD_TERMINAL % (t_info['t_msisdn'], url_out) else: # get a new psd for new user logging.info("[GW] Create new owner started. tid: %s, mobile: %s", t_info['dev_id'], t_info['t_msisdn']) psd = get_psd() user_info = dict(umobile=t_info['u_msisdn'], password=psd, uname=t_info['u_msisdn']) add_user(user_info, db, redis) sms = SMSCode.SMS_JH_SUCCESS % (t_info['t_msisdn'], url_out, t_info['u_msisdn'], psd) # 4. JH existed tmobile is_refurbishment = False if terminal: if (terminal['tid'] == t_info['dev_id']) and \ (terminal['imsi'] == t_info['imsi']) and \ (terminal['owner_mobile'] == t_info['u_msisdn']): # 4.1 SCN: Refurbishment, the terminal-info has existed in platform. JH it again. is_refurbishment = True # check the login packet whether is send again if resend_flag: sms = '' logging.info("[GW] Recv resend packet, do not send sms. tid: %s, mobile: %s", t_info['dev_id'], t_info['t_msisdn']) else: sms = SMSCode.SMS_USER_ADD_TERMINAL % (t_info['t_msisdn'], url_out) logging.info("[GW] Terminal is refurbishment. tid: %s, mobile: %s", t_info['dev_id'], t_info['t_msisdn']) else: # 4.2 existed tmobile changed dev or corp terminal login first, get the old info(group_id, login_permit and so on) before change group_id = terminal.group_id login_permit = terminal.login_permit mannual_status = terminal.mannual_status defend_status = terminal.defend_status icon_type = terminal.icon_type alias = terminal.alias vibl = terminal.vibl use_scene = terminal.use_scene push_status = terminal.push_status speed_limit = terminal.speed_limit stop_interval = terminal.stop_interval distance_current = terminal.distance_current if terminal.tid == terminal.mobile: # corp terminal login first, keep corp info db.execute("UPDATE T_REGION_TERMINAL" " SET tid = %s" " WHERE tid = %s", t_info['dev_id'], t_info['t_msisdn']) logging.info("[GW] Corp terminal login first, tid: %s, mobile: %s.", t_info['dev_id'], t_info['t_msisdn']) elif terminal.tid != t_info['dev_id']: logging.info("[GW] Terminal changed dev, mobile: %s, new_tid: %s, delete old_tid: %s.", t_info['t_msisdn'], t_info['dev_id'], terminal.tid) else: # Refurbishment, change user logging.info("[GW] Terminal change user, tid: %s, mobile: %s, new_owner_mobile: %s, old_owner_mobile: %s", t_info['dev_id'], t_info['t_msisdn'], t_info['u_msisdn'], terminal.owner_mobile) #NOTE: If terminal has exist, firt remove the terminal logging.info("[GW] Terminal is deleted, tid: %s, mobile: %s.", terminal['tid'], terminal['mobile']) del_user = True if terminal.owner_mobile != t_info['u_msisdn']: # send message to old user of dev_id sms_ = SMSCode.SMS_DELETE_TERMINAL % terminal.mobile SMSHelper.send(terminal.owner_mobile, sms_) if terminal.tid == t_info['dev_id']: # clear data belongs to the terminal clear_data(terminal.tid, db, redis) logging.info("[GW] Send delete terminal message: %s to user: %s", sms_, terminal.owner_mobile) else: del_user = False delete_terminal_new(terminal.tid, db, redis, del_user=del_user) #NOTE: Normal JH. if not is_refurbishment: # 5. delete existed tid tid_terminal = db.get("SELECT tid, mobile, owner_mobile, service_status" " FROM T_TERMINAL_INFO" " WHERE tid = %s LIMIT 1", t_info['dev_id']) if tid_terminal: logging.info("[GW] Terminal is deleted, tid: %s, mobile: %s.", tid_terminal['tid'], tid_terminal['mobile']) del_user = True if tid_terminal['owner_mobile'] != t_info['u_msisdn']: if tid_terminal['service_status'] == UWEB.SERVICE_STATUS.TO_BE_UNBIND: logging.info("[GW] Terminal is to_be_unbind, tid: %s, mobile: %s, delete it.", tid_terminal['tid'], tid_terminal['mobile']) else: # send message to old user of dev_id sms_ = SMSCode.SMS_DELETE_TERMINAL % tid_terminal['mobile'] SMSHelper.send(tid_terminal['owner_mobile'], sms_) logging.info("[GW] Send delete terminal message: %s to user: %s", sms_, tid_terminal['owner_mobile']) # user changed, must clear history data of dev_id clear_data(tid_terminal['tid'], db, redis) else: del_user = False delete_terminal_new(tid_terminal['tid'], db, redis, del_user=del_user) # 6 add terminal info # check use sence ttype = get_terminal_type_by_tid(t_info['dev_id']) logging.info("[GW] Terminal's type is %s. tid: %s, mobile: %s", ttype, t_info['dev_id'], t_info['t_msisdn']) terminal_info = dict(tid=t_info['dev_id'], group_id=group_id, dev_type=t_info['dev_type'], tmobile=t_info['t_msisdn'], owner_mobile=t_info['u_msisdn'], imsi=t_info['imsi'], imei=t_info['imei'], factory_name=t_info['factory_name'], softversion=t_info['softversion'], keys_num=t_info['keys_num'], login=GATEWAY.TERMINAL_LOGIN.ONLINE, service_status=UWEB.SERVICE_STATUS.ON, mannual_status=mannual_status, push_status=push_status, icon_type=icon_type, begintime=int(time.mktime(begintime.timetuple())), endtime=4733481600, offline_time=int(time.mktime(begintime.timetuple())), cnum=cnum, login_permit=login_permit, bt_mac=t_info['bt_mac'], bt_name=t_info['bt_name'], vibl=vibl, use_scene=use_scene, biz_type=UWEB.BIZ_TYPE.YDWS, alias=alias, speed_limit=speed_limit, stop_interval=stop_interval, distance_current=distance_current) add_terminal(terminal_info, db, redis) # record the add action, enterprise or individual corp = QueryHelper.get_corp_by_gid(group_id, db) bind_info = dict(tid=t_info['dev_id'], tmobile=t_info['t_msisdn'], umobile=t_info['u_msisdn'], group_id=group_id, cid=corp.get('cid', '') if corp else '', add_time=int(time.time())) record_add_action(bind_info, db) logging.info("[GW] Terminal JH success! tid: %s, mobile: %s.", t_info['dev_id'], t_info['t_msisdn']) # subscription LE for new sim thread.start_new_thread(subscription_lbmp, (t_info,)) if args.success == GATEWAY.LOGIN_STATUS.SUCCESS: # get SessionID if resend_flag: logging.warn("[GW] Recv resend login packet and use old sessionID! packet: %s, tid: %s, mobile: %s.", t_info, t_info['dev_id'], t_info['t_msisdn']) args.sessionID = QueryHelper.get_terminal_sessionID(t_info['dev_id'], redis) if not args.sessionID: args.sessionID = get_sessionID() else: #NOTE: generate a sessionid and keep it in redis. args.sessionID = get_sessionID() terminal_sessionID_key = get_terminal_sessionID_key(t_info['dev_id']) redis.setvalue(terminal_sessionID_key, args.sessionID) redis.setvalue(resend_key, True, GATEWAY.RESEND_EXPIRY) # record terminal address update_terminal_status(redis, t_info["dev_id"], address) #NOTE: When termianl is normal login, update some properties to platform. info = DotDict(login=GATEWAY.TERMINAL_LOGIN.ONLINE, mobile=t_info['t_msisdn'], keys_num=t_info['keys_num'], softversion=t_info['softversion'], login_time=int(time.time()), dev_id=t_info["dev_id"], bt_mac=t_info['bt_mac'], bt_name=t_info['bt_name'], dev_type=t_info['dev_type']) update_terminal_info(db, redis, info) logging.info("[GW] Terminal login success! tid: %s, mobile: %s", t_info['dev_id'], t_info['t_msisdn']) #NOTE: wspush to cient if flag != "1": # normal login WSPushHelper.pushS4(t_info["dev_id"], db, redis) else: # JH pass lc = LoginRespComposer(args) request = DotDict(packet=lc.buf, address=address, dev_id=t_info["dev_id"]) append_gw_request(request, connection, channel, exchange, gw_binding) if sms and t_info['u_msisdn']: logging.info("[GW] Send sms to owner. mobile: %s, content: %s", t_info['u_msisdn'], sms) SMSHelper.send(t_info['u_msisdn'], sms) if t_status == UWEB.SERVICE_STATUS.TO_BE_UNBIND: seq = str(int(time.time()*1000))[-4:] args_ = DotDict(seq=seq, tid=t_info["dev_id"]) ubc = UNBindComposer(args_) request = DotDict(packet=ubc.buf, address=address, dev_id=t_info["dev_id"]) append_gw_request(request, connection, channel, exchange, gw_binding) logging.warn("[GW] Terminal is unbinded, tid: %s, send unbind packet.", t_info["dev_id"])
def post(self): """Add a terminal. """ status = ErrorCode.SUCCESS try: data = DotDict(json_decode(self.request.body)) logging.info("[UWEB] Corp add terminal request: %s, cid: %s", data, self.current_user.cid) except Exception as e: status = ErrorCode.ILLEGAL_DATA_FORMAT self.write_ret(status) return try: if data.has_key('cnum') and not check_cnum(data.cnum): status = ErrorCode.ILLEGAL_CNUM self.write_ret(status) return # 1 year begintime = int(time.time()) now_ = datetime.datetime.now() endtime = now_ + relativedelta(years=1) endtime = int(time.mktime(endtime.timetuple())) # 1: add terminal #umobile = data.umobile if data.umobile else self.current_user.cid if data.umobile: umobile = data.umobile else: corp = QueryHelper.get_corp_by_cid(self.current_user.cid, self.db) umobile = corp.get('c_mobile', '') terminal = QueryHelper.get_terminal_by_tmobile(data.tmobile, self.db) if terminal: if terminal.service_status == UWEB.SERVICE_STATUS.TO_BE_UNBIND: delete_terminal(terminal.tid, self.db, self.redis) else: logging.error( "[UWEB] mobile: %s already existed.", data.tmobile) status = ErrorCode.TERMINAL_ORDERED self.write_ret(status) return vibl = data.get("vibl") use_scene = get_use_scene_by_vibl(vibl) biz_type = data.get('biz_type', UWEB.BIZ_TYPE.YDWS) tid = data.tmobile terminal_info = dict(tid=tid, group_id=data.group_id, tmobile=data.tmobile, owner_mobile=umobile, mannual_status=UWEB.DEFEND_STATUS.YES, begintime=begintime, endtime=4733481600, offline_time=begintime, cnum=data.cnum, icon_type=data.icon_type, login_permit=data.login_permit, push_status=data.push_status, vibl=data.vibl, use_scene=use_scene, biz_type=biz_type, speed_limit=data.speed_limit, stop_interval=data.stop_interval, service_status=UWEB.SERVICE_STATUS.ON) if int(biz_type) == UWEB.BIZ_TYPE.YDWS: # 0. check tmobile is whitelist or not white_list = check_zs_phone(data.tmobile, self.db) if not white_list: logging.error("[UWEB] mobile: %s is not whitelist.", data.tmobile) status = ErrorCode.MOBILE_NOT_ORDERED message = ErrorCode.ERROR_MESSAGE[status] % data.tmobile self.write_ret(status, message=message) return # 4: send message to terminal register_sms = SMSCode.SMS_REGISTER % (umobile, data.tmobile) ret = SMSHelper.send_to_terminal(data.tmobile, register_sms) else: tid = get_tid_from_mobile_ydwq(data.tmobile) activation_code = QueryHelper.get_activation_code(self.db) terminal_info['tid'] = tid terminal_info['activation_code'] = activation_code terminal_info['service_status'] = UWEB.SERVICE_STATUS.TO_BE_ACTIVATED register_sms = SMSCode.SMS_REGISTER_YDWQ % (ConfHelper.UWEB_CONF.url_out, activation_code) ret = SMSHelper.send(data.tmobile, register_sms) add_terminal(terminal_info, self.db, self.redis) # record the add action bind_info = dict(tid=data.tmobile, tmobile=data.tmobile, umobile=umobile, group_id=data.group_id, cid=self.current_user.cid, add_time=int(time.time())) record_add_action(bind_info, self.db) if ret: ret = DotDict(json_decode(ret)) if ret.status == ErrorCode.SUCCESS: self.db.execute("UPDATE T_TERMINAL_INFO" " SET msgid = %s" " WHERE mobile = %s", ret['msgid'], data.tmobile) else: logging.error("[UWEB] Send %s to terminal %s failed.", register_sms, data.tmobile) else: logging.error("[UWEB] Send %s to terminal %s failed.", register_sms, data.tmobile) # NOTE: add user user_info = dict(umobile=umobile, password='******', uname=umobile) add_user(user_info, self.db, self.redis) self.write_ret(status) except Exception as e: logging.exception("[UWEB] Update terminal info failed. cid:%s, Exception: %s", self.current_user.cid, e.args) status = ErrorCode.SERVER_BUSY self.write_ret(status)