Example #1
0
def notify_maintainer(db, redis, content, category):
    """Notify alarm info to maintainers.
    :arg category: int, e.g.
         1: gateway
         2: eventer
    """
    mobiles = []
    emails = []
    alarm_key = 'maintainer_alarm:%s' % category
    alarm_interval = 60 * 5  # 5 minutes

    alarm_flag = redis.getvalue(alarm_key)

    if not alarm_flag:
        maintainers = db.query(
            "SELECT mid, mobile, email FROM T_MAINTAINER WHERE valid = 1")

        for item in maintainers:
            mobiles.append(item['mobile'])
            emails.append(item['email'])

        for mobile in mobiles:
            SMSHelper.send(mobile, content)

        for email in emails:
            EmailHelper.send(email, content)

        redis.setvalue(alarm_key, True, alarm_interval)

        logging.info("[PUBLIC] Notify alarm to maintainers. content: %s, category: %s.",
                     content, category)
    else:
        logging.info("[PUBLIC] Notify alarm is ignored in 5 minutes. content: %s, category: %s.",
                     content, category)
Example #2
0
    def send_offline_remind_sms(self):
        logging.info("[CELERY] checkertask send offline remind sms started.")
        try:
            currenttime = int(time.time())

            terminals = self.db.query("SELECT tid, alias, mobile, owner_mobile, offline_time"
                                      "  FROM T_TERMINAL_INFO"
                                      "  WHERE login = 0"
                                      "  AND service_status = 1"
                                      "  AND offline_time < %s",
                                      (currenttime - 24*60*60))
            for terminal in terminals:
                sms_option = QueryHelper.get_sms_option_by_uid(terminal.owner_mobile, 'heartbeat_lost', self.db)
                if sms_option == UWEB.SMS_OPTION.SEND:
                    ctime = get_terminal_time(currenttime)
                    ctime = safe_unicode(ctime)

                    alias = terminal['alias'] if terminal['alias'] else terminal['mobile']
                    sms = SMSCode.SMS_HEARTBEAT_LOST % (alias, ctime)
                    SMSHelper.send(terminal.owner_mobile, sms)
                    logging.info("[CELERY] Send offline remind sms to user:%s, tid:%s", terminal.owner_mobile, terminal.tid)
           
            logging.info("[CELERY] checkertask send offline remind sms finished.")
        except Exception as e:
            logging.exception("[CELERY] Check terminal poweroff timeout exception.")
Example #3
0
    def post(self):
        """Insert new items."""
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            content = data.get('content', '')
            mobiles = data.get('mobiles', None)
            logging.info("[UWEB] Announcement request: %s", data)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            self.write_ret(status)
            return

        try:
            mobiles_ = u''
            if mobiles is not None:
                mobiles_ = ','.join(mobiles)
                for mobile in mobiles:
                    SMSHelper.send(mobile, content)

            announcement = dict(cid=self.current_user.cid,
                                content=content,
                                mobiles=mobiles_)
            record_announcement(self.db, announcement)

            self.write_ret(status)
        except Exception as e:
            status = ErrorCode.SERVER_BUSY
            logging.exception(
                "[UWEB] record share failed, Exception: %s", e.args)
            self.write_ret(status)
Example #4
0
    def sms_to_whitelist(self, sms, whitelist=None):
        if not sms:
            return

        if whitelist:
            for white in whitelist:
                SMSHelper.send(white['mobile'], sms)
Example #5
0
    def notify(self):
        content = SMSCode.SMS_GW_ERROR_REPORT % ConfHelper.UWEB_CONF.url_out
        for mobile in self.mobiles:
            SMSHelper.send(mobile, content)

        for email in self.emails:
            EmailHelper.send(email, content)
Example #6
0
 def check_service(self):
     try:
         base_id = self.get_lid_by_tid(self.tid)
         while True:
             time.sleep(600)  # 10 minutes
             new_lid = self.get_lid_by_tid(self.tid)
             logging.info("[CK] simulator terminal location base_id:%s, new_lid:%s", 
                          base_id, new_lid)
             if new_lid > base_id:
                 base_id = new_lid
             else:
                 for mobile in self.mobiles:
                     sms = SMSCode.SMS_SERVICE_EXCEPTION_REPORT % ConfHelper.UWEB_CONF.url_out
                     SMSHelper.send(mobile, sms)
                     logging.info("[CK] Notify Administrator:%s By SMS, service exception!", 
                                  mobile)
                 for email in self.emails:
                     content = SMSCode.SMS_SERVICE_EXCEPTION_REPORT % ConfHelper.UWEB_CONF.url_out
                     EmailHelper.send(email, content)
                     logging.info("[CK] Notify Administrator:%s By EMAIL, service exception!", 
                                  email)
     except KeyboardInterrupt:
         logging.error("Ctrl-C is pressed.")
     except Exception as e:
         logging.exception("[CK] Check service failed. Exception: %s", 
                           e.args)
Example #7
0
def move_data():
    db = DBConnection().db
       
    mobiles = ['18310505991', '13693675352', '13581731204']
    message = "数据库T_LOCATION已经完全转移到T_LOCATION_NEW,请及确认表信息的正确性和完整性。"
    #max_row = 1000000000
    max_row = 250000000
    begin_time = time.gmtime(time.time())
    for i in range(10000, max_row, 10000):
        sql = "INSERT INTO T_LOCATION_NEW" \
              " SELECT * FROM T_LOCATION WHERE id <=%d AND id > %d -10000" \
              " and (timestamp between 0 and 1448899200)" % (i, i)
        logging.info("exectue sql:%s", sql)
        
        n = db.execute(sql)
        #time.sleep(0.1)
        logging.info("last record  row id =%s", n)
        break
       # if i = 250000000:
        if i == 240000000:
            for mobile in mobiles:
                SMSHelper.send(mobile, message)    
                print "send", mobile
    end_time = time.gmtime(time.time())
    L_bak = "alter table T_LOCATION rename  to T_LOCATION_bak"
    NEW_L = "alter table T_LOCATION_NEW rename  to T_LOCATION"
    
    for i in range(1, 5): 
        time.sleep(1)
        logging.info("Will rename table neame after %d second", 5-i)
    
    db.execute(L_bak)
    db.execute(NEW_L)
    logging.info("exchange tables T_LOCATION and T_LOCATION_NEW is accomplished ")
    logging.info("Move table data begin_time:%s, end_time:%s", begin_time, end_time)
Example #8
0
    def sms_to_user(self, dev_id, sms, mobile):
        if not sms:
            return

        if not mobile:
            return

        if mobile:
            SMSHelper.send(mobile, sms)
Example #9
0
    def login_sms_remind(self, uid, owner_mobile, terminals, login="******"):

        sms_option = QueryHelper.get_sms_option_by_uid(uid, "login", self.db)
        if sms_option == UWEB.SMS_OPTION.SEND:
            login_time = time.strftime("%Y-%m-%d %H:%M:%S")
            login_method = UWEB.LOGIN_WAY[login]
            terminal_mobile = u"”,“".join(terminal.alias for terminal in terminals)
            remind_sms = SMSCode.SMS_LOGIN_REMIND % (login_time, login_method, owner_mobile, terminal_mobile)
            SMSHelper.send(owner_mobile, remind_sms)
Example #10
0
 def check_push(self):
     """
     """
     res = self.db_push.get(
         "SELECT count(id) as count FROM T_PUSH where status = 1")
     if res and res['count'] >= self.alarm_size:
         content = SMSCode.SMS_PUSH_REPORT % ConfHelper.UWEB_CONF.url_out
         for mobile in self.mobiles:
             SMSHelper.send(mobile, content)
         for email in self.emails:
             EmailHelper.send(email, content)
         logging.info("[CK] Notify push queue exception to administrator!")
Example #11
0
 def check_sms(self):
     """Notify administrators when sms to be send is more than alarm_size;
     """
     res = self.db.get(
         "SELECT count(id) as count FROM T_SMS where send_status = -1")
     if res and res['count'] >= self.alarm_size:
         content = SMSCode.SMS_SMS_REPORT % ConfHelper.UWEB_CONF.url_out
         for mobile in self.mobiles:
             SMSHelper.send(mobile, content)
         for email in self.emails:
             EmailHelper.send(email, content)
         logging.info("[CK] Notify sms queue exception to administrator!")
Example #12
0
 def alarm(self):
     """
     #NOTE: Send alarm message if need.
     """
     send_flag = self.redis.getvalue(self.alarm_key) 
     if (not send_flag): 
         content = SMSCode.SMS_GW_DELAY_REPORT % ConfHelper.UWEB_CONF.url_out 
         for mobile in self.mobiles: 
             SMSHelper.send(mobile, content) 
         for email in self.emails:
             EmailHelper.send(email, content) 
     logging.info("[CK] Notify S packet delay to administrator!") 
     self.redis.setvalue(self.alarm_key, True, self.alarm_interval)
Example #13
0
def send(content, mobile):
    logging.info("Send %s to %s", content, mobile)
    #NOTE: send encrypt sms to mobile
    response = SMSHelper.send(mobile, content)
    #NOTE: send general sms to mobile
    #response = SMSHelper.send(mobile, content)
    logging.info("Response: %s", response)
Example #14
0
    def post(self):
        """Send captcha to user's phone through sms.
        """
        status = ErrorCode.SUCCESS
        try: 
            mobile = self.get_argument('mobile','')
            captcha = ''.join(random.choice(string.digits) for x in range(6))
            ios_captcha_sms = SMSCode.SMS_IOS_CAPTCHA % (captcha) 
            ret = SMSHelper.send(mobile, ios_captcha_sms)
            ret = DotDict(json_decode(ret))
            if ret.status == ErrorCode.SUCCESS:
                logging.info("[CLIENT] passenger get sms captcha: %s successfully, mobile: %s",
                             captcha, mobile)
                captcha_key = get_captcha_key(mobile)
                self.redis.setvalue(captcha_key, captcha, UWEB.SMS_CAPTCHA_INTERVAL)
            else:
                status = ErrorCode.SERVER_BUSY
                logging.error("[CLIENT] passenger get sms captcha failed, mobile: %s", mobile)

            self.write_ret(status)
        except Exception as e:
            logging.exception("[CLIENT] passenger get sms captcha failed, mobile: %s. Exception: %s", 
                              mobile, e.args) 
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
Example #15
0
 def send(self, content, mobile):
     return
     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)
Example #16
0
 def check_poweroff_timeout(self):
     logging.info("[CELERY] checkertask check poweroff timeout started.")
     try:
         terminals = self.db.query("SELECT tpt.tid, tpt.sms_flag, tpt.timestamp"
                                   "  FROM T_POWEROFF_TIMEOUT as tpt, T_TERMINAL_INFO as tti"
                                   "  WHERE tti.tid = tpt.tid"
                                   "  AND tti.service_status = 1"
                                   "  AND tti.login = %s"
                                   "  AND tpt.sms_flag = %s"
                                   "  AND tpt.timestamp < %s",
                                   GATEWAY.TERMINAL_LOGIN.OFFLINE, GATEWAY.POWEROFF_TIMEOUT_SMS.UNSEND, (time.time() - 2*60*60))
         for terminal in terminals:
             terminal_info = QueryHelper.get_terminal_info(terminal.tid, self.db, self.redis)
             if int(terminal_info['pbat']) < 5:
                 user = QueryHelper.get_user_by_tid(terminal.tid, self.db)
                 sms = SMSCode.SMS_POWEROFF_TIMEOUT % terminal_info['alias'] 
                 SMSHelper.send(user.owner_mobile, sms)
                 self.update_sms_flag(terminal.tid)
                 logging.info("[CELERY] Send poweroff timeout sms to user:%s, tid:%s", user.owner_mobile, terminal.tid)
     except Exception as e:
         logging.exception("[CELERY] Check terminal poweroff timeout exception.")
Example #17
0
def handle_unusual(info, address, connection, channel, exchange, gw_binding, db, redis):
    """Unusual activate report packet: owner_mobile changed.
    S27 

    0: success, then record new terminal's address
    1: invalid SessionID 
    """
    try:
        head = info.head
        body = info.body
        dev_id = head.dev_id

        resend_key, resend_flag = get_resend_flag(redis, dev_id, head.timestamp, head.command) 

        args = DotDict(success=GATEWAY.RESPONSE_STATUS.SUCCESS,
                       command=head.command)
        if resend_flag:
            logging.warn("[GW] Recv resend packet, head: %s, body: %s and drop it!",
                         info.head, info.body)
        else: 
            redis.setvalue(resend_key, True, GATEWAY.RESEND_EXPIRY)
            uap = UnusualActivateParser(body, head)
            t_info = uap.ret
            terminal = db.get("SELECT mobile FROM T_TERMINAL_INFO"
                              "  WHERE tid = %s LIMIT 1",
                              t_info['dev_id'])
            if terminal:
                sms = SMSCode.SMS_UNUSUAL_ACTIVATE % terminal['mobile'] 
                SMSHelper.send(t_info['u_msisdn'], sms)
            else:
                logging.error("[GW] Terminal: %s is not existent, what's up?", t_info['dev_id'])

        uac = UnusualActivateComposer(args)
        request = DotDict(packet=uac.buf,
                          address=address,
                          dev_id=dev_id)
        append_gw_request(request, connection, channel, exchange, gw_binding)
    except:
        logging.exception("[GW] Hand unusual activate report exception.")
        GWException().notify()
Example #18
0
    def post(self):
        """Send sms to user's mobile."""
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))          
            mobile = data.mobile
            captcha_sms = data.captcha_sms
            captchahash_sms = self.get_secure_cookie("captchahash_sms")
            category = data.category
            logging.info("[UWEB] downloadsms request: %s", data)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.exception("[UWEB] Invalid data format. body:%s, Exception: %s",
                              self.request.body, e.args)
            self.write_ret(status)
            return

        try:
            m = hashlib.md5()
            m.update(captcha_sms.lower())
            m.update(UWEB.HASH_SALT)
            hash_ = m.hexdigest()
            if hash_.lower() != captchahash_sms.lower():
                status = ErrorCode.WRONG_CAPTCHA
                logging.info("[UWEB] downloadsms failed. Message: %s", 
                             ErrorCode.ERROR_MESSAGE[status])
            else:                
                # downloadurl = DOWNLOAD.URL.ANDROID % ConfHelper.UWEB_CONF.url_out
                download_remind = SMSCode.SMS_DOWNLOAD_REMIND % (
                    ConfHelper.UWEB_CONF.url_out)
                SMSHelper.send(mobile, download_remind)

            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] Smsdownload failed. Exception: %s. ",
                              e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
Example #19
0
    def check_charge_remind(self):
        logging.exception("[CELERY] checkertask charge remind started")
        try:
            terminals = self.db.query("SELECT tid, mobile, owner_mobile, begintime"
                                      "  FROM T_TERMINAL_INFO "
                                      "  WHERE service_status = 1")
            for terminal in terminals:
                begintime = int(terminal.begintime)
                begintime = time.strftime("%Y,%m,%d", time.localtime(begintime)).split(",")
                b_year = int(begintime[0])
                b_month = int(begintime[1])
                b_day = int(begintime[2])

                currenttime = int(time.time())
                currenttime = time.strftime("%Y,%m,%d", time.localtime(currenttime)).split(",")
                c_year = int(currenttime[0])
                c_month = int(currenttime[1])
                c_day = int(currenttime[2])
                # get days of current month
                days = calendar.monthrange(c_year, c_month)[1]

                if b_year > c_year:
                    continue 
                elif b_year == c_year and b_month == c_month:
                    # do not remind user on register month
                    continue 
                elif b_day < c_day:
                    continue 
                elif (b_day == c_day) or (b_day > days and c_day == days):
                    # 1. equal day
                    # 2. has no equal day on this month, send sms on the last day of this month
                    # send charge remind sms
                    if terminal.owner_mobile:
                        content = SMSCode.SMS_CHARGE_REMIND % terminal.mobile
                        SMSHelper.send(terminal.owner_mobile, content)
                        logging.info("[CELERY] Send charge remind sms to user: %s", terminal.owner_mobile)
        except Exception as e:
            logging.exception("[CELERY] Check charge remind exception: %s", e.args)
Example #20
0
    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)
Example #21
0
def send_sms(mobiles, message):
    if mobiles is None:
        return ErrorCode.SUCCESS
    num = 0
    try:
        for mobile in mobiles:
            ret = SMSHelper.send(mobile, message)
            ret = json_decode(ret)
            status = ret['status']
            if status == ErrorCode.SUCCESS:
                num += 1
                
        if num != len(mobiles):
            status = ErrorCode.FAILED
            return status
        else:
            status = ErrorCode.SUCCESS
            return status
    except Exception as e:
            logging.exception("[UWEB] Send sms to sms server failed. Exception: %s", 
                              e.args) 
            status = ErrorCode.SERVER_BUSY
            return status
Example #22
0
def handle_old_login(t_info, address, connection, channel, exchange, gw_binding, db, redis):
    """
    S1
    Login response packet:

    0 - success, then get a sessionID for terminal and record terminal's address
    1 - illegal format of sim
    2 - expired, service stop or endtime < now
    3 - illegal sim, a mismatch between imsi and sim
    4 - psd wrong. HK
    5 - dev_id is empty
    6 - not whitelist
    """
    sms = None
    args = DotDict(success=GATEWAY.LOGIN_STATUS.SUCCESS,
                   sessionID='')
    dev_id = t_info['dev_id']

    resend_key, resend_flag = get_resend_flag(redis, dev_id, t_info.timestamp, t_info.command) 

    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"])
        append_gw_request(request, connection, channel, exchange, gw_binding)
        logging.error("[GW] Login failed! Invalid terminal mobile: %s or owner_mobile: %s, dev_id: %s",
                      t_info['t_msisdn'], t_info['u_msisdn'], t_info['dev_id'])
        return

    t_status = db.get("SELECT service_status"
                      "  FROM T_TERMINAL_INFO"
                      "  WHERE mobile = %s",
                      t_info['t_msisdn'])
    if t_status and t_status.service_status == GATEWAY.SERVICE_STATUS.OFF:
        args.success = GATEWAY.LOGIN_STATUS.EXPIRED
        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)
        logging.error("[GW] Login failed! terminal service expired! mobile: %s, dev_id: %s",
                      t_info['t_msisdn'], t_info['dev_id'])
        return


    logging.info("[GW] Checking imsi: %s and mobile: %s, Terminal: %s",
                 t_info['imsi'], t_info['t_msisdn'], t_info['dev_id'])
    tmobile = db.get("SELECT imsi FROM T_TERMINAL_INFO"
                     "  WHERE mobile = %s", t_info['t_msisdn'])
    if tmobile and tmobile.imsi and tmobile.imsi != t_info['imsi']:
        # check terminal and give a appropriate HK notification
        terminal = db.get("SELECT id FROM T_TERMINAL_INFO WHERE tid=%s", t_info['dev_id'])
        if terminal:
            alias = QueryHelper.get_alias_by_tid(t_info['dev_id'], redis, db)
        else: 
            alias = t_info['t_msisdn']
        args.success = GATEWAY.LOGIN_STATUS.ILLEGAL_SIM
        sms = SMSCode.SMS_TERMINAL_HK % alias 
        SMSHelper.send(t_info['u_msisdn'], sms)
        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)
        logging.error("[GW] Login failed! Illegal SIM: %s for Terminal: %s",
                      t_info['t_msisdn'], t_info['dev_id'])
        return

    terminal = db.get("SELECT id, mobile, owner_mobile, service_status"
                      "  FROM T_TERMINAL_INFO"
                      "  WHERE tid = %s", t_info['dev_id'])
    if terminal:
        if terminal.mobile != t_info['t_msisdn']:
            logging.info("[GW] Terminal: %s changed mobile, old mobile: %s, new mobile: %s",
                         t_info['dev_id'], terminal.mobile,
                         t_info['t_msisdn'])
            if (terminal.owner_mobile == t_info['u_msisdn'] or
                terminal.service_status == UWEB.SERVICE_STATUS.TO_BE_UNBIND):
                # delete old terminal!
                logging.info("[GW] Delete old tid bind relation. tid: %s, owner_mobile: %s, service_status: %s",
                             t_info['dev_id'], t_info['u_msisdn'],
                             terminal.service_status)
                delete_terminal_new(t_info['dev_id'], db, redis, del_user=False)
                exist = db.get("SELECT tid, owner_mobile, service_status FROM T_TERMINAL_INFO"
                               "  WHERE mobile = %s LIMIT 1",
                               t_info['t_msisdn'])
                if exist:
                    # cannot send unbind packet to dev_id
                    t_status = None
                    logging.info("[GW] Delete old tmobile bind relation. tid: %s, mobile: %s",
                                 exist.tid, t_info['t_msisdn'])
                    delete_terminal_new(exist.tid, db, redis, del_user=False)
                    if exist.service_status == UWEB.SERVICE_STATUS.TO_BE_UNBIND:
                        logging.info("[GW] Terminal: %s of %s is to_be_unbind, delete it.",
                                     exist.tid, t_info['t_msisdn'])
                    elif exist.owner_mobile != t_info['u_msisdn']:
                        sms = SMSCode.SMS_DELETE_TERMINAL % t_info['t_msisdn']
                        SMSHelper.send(exist.owner_mobile, sms)
                terminal = None
            else:
                args.success = GATEWAY.LOGIN_STATUS.ILLEGAL_SIM
                sms = SMSCode.SMS_TID_EXIST % t_info['dev_id']
                SMSHelper.send(t_info['u_msisdn'], sms)
                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)
                logging.error("[GW] Login failed! Terminal: %s already bound by %s, new mobile: %s",
                              t_info['dev_id'], terminal.mobile, t_info['t_msisdn'])
                return

    #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] Terminal: %s, login url is: %s", t_info['t_msisdn'], url_out)

    if t_info['psd']:
        flag = 0
        # check terminal exist or not when HK
        if not terminal:
            args.success = GATEWAY.LOGIN_STATUS.UNREGISTER
            sms = SMSCode.SMS_TID_NOT_EXIST
            SMSHelper.send(t_info['u_msisdn'], sms)
            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)
            logging.error("[GW] Login failed! Terminal %s execute HK, but tid is not exist",
                          t_info['dev_id'])
            return
        # HK, change terminal mobile or owner mobile
        logging.info("[GW] Checking password. Terminal: %s",
                     t_info['dev_id'])
        owner = db.get("SELECT id FROM T_USER"
                       "  WHERE mobile = %s"
                       "    AND password = password(%s)",
                       terminal.owner_mobile, t_info['psd'])
        if not owner:
            # psd wrong
            sms = SMSCode.SMS_PSD_WRONG
            args.success = GATEWAY.LOGIN_STATUS.PSD_WRONG
            logging.error("[GW] Login failed! Password invalid. Terminal: %s",
                          t_info['dev_id'])
        else:
            if terminal:
                if terminal.mobile != t_info['t_msisdn']:
                    # terminal HK
                    logging.info("[GW] Terminal: %s HK started.", t_info['dev_id'])
                    # unbind old tmobile
                    old_bind = db.get("SELECT id, tid FROM T_TERMINAL_INFO"
                                      "  WHERE mobile = %s"
                                      "    AND id != %s",
                                      t_info['t_msisdn'], terminal.id)
                    if old_bind:
                        # clear db
                        db.execute("DELETE FROM T_TERMINAL_INFO"
                                   "  WHERE id = %s", 
                                   old_bind.id) 
                        # clear redis
                        sessionID_key = get_terminal_sessionID_key(old_bind.tid)
                        address_key = get_terminal_address_key(old_bind.tid)
                        info_key = get_terminal_info_key(old_bind.tid)
                        lq_sms_key = get_lq_sms_key(old_bind.tid)
                        lq_interval_key = get_lq_interval_key(old_bind.tid)
                        keys = [sessionID_key, address_key, info_key, lq_sms_key, lq_interval_key]
                        redis.delete(*keys)
                        logging.info("[GW] Delete old bind Terminal: %s, SIM: %s",
                                     t_info['dev_id'], t_info['t_msisdn'])

                    # update new tmobile
                    db.execute("UPDATE T_TERMINAL_INFO"
                               "  SET mobile = %s,"
                               "      imsi = %s"
                               "  WHERE id = %s",
                               t_info['t_msisdn'],
                               t_info['imsi'], terminal.id)
                    # clear redis
                    sessionID_key = get_terminal_sessionID_key(t_info['dev_id'])
                    address_key = get_terminal_address_key(t_info['dev_id'])
                    info_key = get_terminal_info_key(t_info['dev_id'])
                    lq_sms_key = get_lq_sms_key(t_info['dev_id'])
                    lq_interval_key = get_lq_interval_key(t_info['dev_id'])
                    keys = [sessionID_key, address_key, info_key, lq_sms_key, lq_interval_key]
                    redis.delete(*keys)
                    # HK sms
                    sms = SMSCode.SMS_TERMINAL_HK_SUCCESS % (terminal.mobile, t_info['t_msisdn'])
                    # subscription LE for new sim
                    thread.start_new_thread(subscription_lbmp, (t_info,)) 
                    logging.info("[GW] Terminal: %s HK success!", t_info['dev_id'])

                if terminal.owner_mobile != t_info['u_msisdn']:
                    logging.info("[GW] Owner HK started. Terminal: %s", t_info['dev_id'])
                    # owner HK
                    user = db.get("SELECT id FROM T_USER"
                                  "  WHERE mobile = %s",
                                  t_info['u_msisdn'])
                    if user:
                        logging.info("[GW] Owner already existed. Terminal: %s", t_info['dev_id'])
                        sms = SMSCode.SMS_USER_ADD_TERMINAL % (t_info['t_msisdn'],
                                                               url_out) 
                    else:
                        logging.info("[GW] Create new owner started. Terminal: %s", t_info['dev_id'])
                        psd = get_psd()
                        user_info = dict(umobile=t_info['u_msisdn'],
                                         password=psd)
                        add_user(user_info, db, redis)
                        sms = SMSCode.SMS_USER_HK_SUCCESS % (t_info['u_msisdn'],
                                                             url_out,
                                                             t_info['u_msisdn'],
                                                             psd)
                    db.execute("UPDATE T_TERMINAL_INFO"
                               "  SET owner_mobile = %s"
                               "  WHERE id = %s",
                               t_info['u_msisdn'], terminal.id)
                    logging.info("[GW] Owner of %s HK success!", t_info['dev_id'])
            else:
                logging.error("[GW] What happened? Cannot find old terminal by dev_id: %s",
                              t_info['dev_id']) 
    else:
        flag = 1 
        # login or JH
        if terminal:
            # login
            logging.info("[GW] Terminal: %s Normal login started!",
                         t_info['dev_id']) 
        else:
            # SMS JH or admin JH or change new dev JH
            logging.info("[GW] Terminal: %s, mobile: %s JH started.",
                         t_info['dev_id'], t_info['t_msisdn'])
            exist = db.get("SELECT id FROM T_USER"
                           "  WHERE mobile = %s",
                           t_info['u_msisdn'])
            if exist:
                logging.info("[GW] Owner already existed. Terminal: %s", t_info['dev_id'])
                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. Terminal: %s", t_info['dev_id'])
                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)

            admin_terminal = db.get("SELECT id, tid FROM T_TERMINAL_INFO"
                                    "  WHERE tid = %s",
                                    t_info['t_msisdn'])
            if admin_terminal:
                # admin JH
                db.execute("UPDATE T_TERMINAL_INFO"
                           "  SET tid = %s,"
                           "      dev_type = %s,"
                           "      owner_mobile = %s,"
                           "      imsi = %s,"
                           "      imei = %s,"
                           "      factory_name = %s,"
                           "      keys_num = %s,"
                           "      softversion = %s"
                           "  WHERE id = %s",
                           t_info['dev_id'],
                           t_info['dev_type'],
                           t_info['u_msisdn'],
                           t_info['imsi'],
                           t_info['imei'],
                           t_info['factory_name'],
                           t_info['keys_num'],
                           t_info['softversion'],
                           admin_terminal.id)
                db.execute("UPDATE T_CAR SET tid = %s"
                           "  WHERE tid = %s",
                           t_info['dev_id'], t_info['t_msisdn'])
                logging.info("[GW] Terminal %s by ADMIN JH success!", t_info['dev_id'])
            else:
                exist_terminal = db.get("SELECT id, tid FROM T_TERMINAL_INFO"
                                        "  WHERE mobile = %s",
                                        t_info['t_msisdn'])
                if exist_terminal:
                    # unbind old tmobile
                    db.execute("DELETE FROM T_TERMINAL_INFO"
                               "  WHERE id = %s",
                               exist_terminal.id)
                    # clear redis
                    sessionID_key = get_terminal_sessionID_key(exist_terminal.tid)
                    address_key = get_terminal_address_key(exist_terminal.tid)
                    info_key = get_terminal_info_key(exist_terminal.tid)
                    lq_sms_key = get_lq_sms_key(exist_terminal.tid)
                    lq_interval_key = get_lq_interval_key(exist_terminal.tid)
                    keys = [sessionID_key, address_key, info_key, lq_sms_key, lq_interval_key]
                    redis.delete(*keys)
                    logging.info("[GW] Terminal %s change dev, old dev: %s!",
                                 t_info['dev_id'], exist_terminal.tid)

                # send JH sms to terminal. default active time
                # is one year.
                begintime = datetime.datetime.now() 
                endtime = begintime + relativedelta(years=1)

                terminal_info = dict(tid=t_info['dev_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,
                                     group_id=-1,
                                     mannual_status=UWEB.DEFEND_STATUS.YES,
                                     begintime=int(time.mktime(begintime.timetuple())),
                                     endtime=4733481600,
                                     offline_time=int(time.mktime(begintime.timetuple())),
                                     biz_type=UWEB.BIZ_TYPE.YDWS)
                add_terminal(terminal_info, db, redis)

                # record the add action, enterprise or individual
                bind_info = dict(tid=t_info['dev_id'],
                                 tmobile=t_info['t_msisdn'],
                                 umobile=t_info['u_msisdn'],
                                 group_id=-1,
                                 cid='',
                                 add_time=int(time.time()))
                record_add_action(bind_info, db)

                logging.info("[GW] Terminal %s by SMS JH success!", t_info['dev_id'])

            # 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:
            args.sessionID = QueryHelper.get_terminal_sessionID(t_info['dev_id'], redis)
            logging.warn("[GW] Recv resend login packet: %s and use old sessionID: %s!", t_info, args.sessionID) 
            if not args.sessionID:
                args.sessionID = get_sessionID()
        else:
            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)
        # set login
        info = DotDict(login=GATEWAY.TERMINAL_LOGIN.ONLINE,
                       mobile=t_info['t_msisdn'],
                       keys_num=t_info['keys_num'],
                       login_time=int(time.time()),
                       dev_id=t_info["dev_id"])
        update_terminal_info(db, redis, info)
        logging.info("[GW] Terminal %s login success! SIM: %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']:
        SMSHelper.send(t_info['u_msisdn'], sms)

    # unbind terminal of to_be_unbind
    if t_status and t_status.service_status == UWEB.SERVICE_STATUS.TO_BE_UNBIND:
        logging.info("[GW] Terminal: %s is unbinded, send unbind packet.", t_info["dev_id"])            
        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)
Example #23
0
def send(content, mobile):
    logging.info("Send %s to %s", content, mobile)
    response = SMSHelper.send(mobile, content)
    logging.info("Response: %s", response)
Example #24
0
    def post(self):
        """Generate a captcha for retrieving the password."""
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            umobile = data.mobile
            captcha_psd = data.captcha_psd
            logging.info("[UWEB] Get captcha request: %s", data)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.exception("[UWEB] Invalid data format. body: %s, Exception: %s",
                              self.request.body, e.args)
            self.write_ret(status)
            return 

        try:

            status = self.check_privilege(umobile) 
            if status != ErrorCode.SUCCESS: 
                logging.error("[UWEB] User: %s is just for test, has no right to access the function.", 
                              umobile) 
                self.write_ret(status) 
                return
           
            captchahash = self.get_secure_cookie("captchahash_password")

            m = hashlib.md5()
            m.update(captcha_psd.lower())
            m.update(UWEB.HASH_SALT)
            hash_ = m.hexdigest()
            if hash_.lower() != captchahash.lower():
                status = ErrorCode.WRONG_CAPTCHA_IMAGE
                logging.info("[UWEB] Come from browser, captcha-check failed.")
                self.write_ret(status)
                return
            
            user = self.db.get("SELECT mobile"
                               "  FROM T_USER"
                               "  WHERE mobile = %s"
                               "  LIMIT 1",
                               umobile)
            if user:
                remote_ip = self.request.remote_ip
                remote_ip_key = "register_remote_ip:%s" % remote_ip 
                umobile_key = "register_umobile:%s" % umobile
                remote_ip_times = self.redis.getvalue(remote_ip_key)  
                umobile_times = self.redis.getvalue(umobile_key)  
    
                if remote_ip_times is None:
                    remote_ip_times = 0 
    
                if umobile_times is None:
                    umobile_times = 0 
    
                logging.info("[UWEB] Register. umobile: %s, umobile_times: %s, remote_ip: %s, remote_ip_times: %s",
                             umobile, umobile_times, remote_ip, remote_ip_times)
    
                #NOTE: In current day, the same remote_ip allows 10 times, the umobile, 3 times
                current_time = int(time.time())
                date = get_date_from_utc(current_time)
                year, month, day = date.year, date.month, date.day
                start_time_, end_time_ = start_end_of_day(year=year, month=month, day=day)
        
                if umobile_times >= 3: # <= 3 is ok
                    status = ErrorCode.REGISTER_EXCESS
                if remote_ip_times >= 10: # <= 10 is ok
                    status = ErrorCode.REGISTER_EXCESS

                if status == ErrorCode.REGISTER_EXCESS:
                    body = u'管理员您好:检测到频繁注册,请查看. umobile: %s, umobile_times: %s, remote_ip: %s, remote_ip_times: %s' % (
                            umobile, umobile_times, remote_ip, remote_ip_times) 
                    notify_maintainer(self.db, self.redis, body, 'password')
                    self.write_ret(status)
                    return

                captcha = ''.join(random.choice(string.digits) for x in range(4))
                getcaptcha_sms = SMSCode.SMS_CAPTCHA % (captcha) 
                ret = SMSHelper.send(umobile, getcaptcha_sms)
                ret = DotDict(json_decode(ret))
                if ret.status == ErrorCode.SUCCESS:
                    logging.info("[UWEB] user uid: %s get captcha success, the captcha: %s", 
                                 umobile, captcha)
                    captcha_key = get_captcha_key(umobile)
                    self.redis.setvalue(captcha_key, captcha, UWEB.SMS_CAPTCHA_INTERVAL)

                    self.redis.set(umobile_key, umobile_times+1)  
                    self.redis.expireat(umobile_key, end_time_)  
                    self.redis.set(remote_ip_key, remote_ip_times+1)  
                    self.redis.expireat(remote_ip_key, end_time_)  

                else:
                    status = ErrorCode.SERVER_BUSY
                    logging.error("[UWEB] user uid: %s get captcha failed.", umobile)
            else:
                status = ErrorCode.USER_NOT_ORDERED
                logging.error("[UWEB] user uid: %s does not exist, get captcha failed.", 
                              umobile)
            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] user uid: %s retrieve password failed. Exception: %s", 
                              umobile, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
Example #25
0
    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)
Example #26
0
    def get(self):
        """Send captcha to user's phone through sms.
        """
        status = ErrorCode.SUCCESS
        try:
            umobile = self.get_argument('umobile', '')
            tmobile = self.get_argument('tmobile', '')
            remote_ip = self.request.remote_ip

            captcha_image = self.get_argument('captcha_img', '')
            captchahash = self.get_secure_cookie("captchahash_image")

            logging.info("[UWEB] Get captcha-sms request. umobile:%s, tmobile: %s, captcha_img: %s",
                         umobile, tmobile, captcha_image)

            m = hashlib.md5()
            m.update(captcha_image.lower())
            m.update(UWEB.HASH_SALT)
            hash_ = m.hexdigest()
            if hash_.lower() != captchahash.lower():
                status = ErrorCode.WRONG_CAPTCHA_IMAGE
                logging.info(
                    "[UWEB] Come from browser, captcha-check failed.")
                self.write_ret(status)
                return

            # check tmobile is whitelist or not
            white_list = check_zs_phone(tmobile, self.db)
            if not white_list:
                logging.info("[UWEB] %s is not whitelist", tmobile)
                status = ErrorCode.MOBILE_NOT_ORDERED
                message = ErrorCode.ERROR_MESSAGE[status] % tmobile
                self.write_ret(status, message=message)
                return

            # NOTE: check times
            remote_ip_key = "register_remote_ip:%s" % remote_ip
            umobile_key = "register_umobile:%s" % umobile
            remote_ip_times = self.redis.getvalue(remote_ip_key)
            umobile_times = self.redis.getvalue(umobile_key)

            if remote_ip_times is None:
                remote_ip_times = 0

            if umobile_times is None:
                umobile_times = 0

            logging.info("[UWEB] Register. umobile: %s, umobile_times: %s, remote_ip: %s, remote_ip_times: %s",
                         umobile, umobile_times, remote_ip, remote_ip_times)

            # NOTE: In current day, the same remote_ip allows 10 times, the
            # umobile, 3 times
            current_time = int(time.time())
            date = get_date_from_utc(current_time)
            year, month, day = date.year, date.month, date.day
            start_time_, end_time_ = start_end_of_day(
                year=year, month=month, day=day)

            if umobile_times >= 3:  # <= 3 is ok
                status = ErrorCode.REGISTER_EXCESS
            if remote_ip_times >= 10:  # <= 10 is ok
                status = ErrorCode.REGISTER_EXCESS

            if status == ErrorCode.REGISTER_EXCESS:
                body = u'管理员您好:检测到频繁注册,请查看. umobile: %s, umobile_times: %s, remote_ip: %s, remote_ip_times: %s' % (
                    umobile, umobile_times, remote_ip, remote_ip_times)
                notify_maintainer(self.db, self.redis, body, 'register')
                self.write_ret(status)
                return

            psd = ''.join(random.choice(string.digits) for x in range(4))
            captcha_sms = SMSCode.SMS_REG % (psd)
            ret = SMSHelper.send(umobile, captcha_sms)
            ret = DotDict(json_decode(ret))
            if ret.status == ErrorCode.SUCCESS:
                logging.info("[UWEB] Get sms captcha successfully. umobile: %s, captcha: %s.",
                             umobile, psd)
                captcha_key = get_captcha_key(umobile)
                self.redis.setvalue(
                    captcha_key, psd, UWEB.SMS_CAPTCHA_INTERVAL)

                self.redis.set(umobile_key, umobile_times + 1)
                self.redis.expireat(umobile_key, end_time_)
                self.redis.set(remote_ip_key, remote_ip_times + 1)
                self.redis.expireat(remote_ip_key, end_time_)
            else:
                status = ErrorCode.SERVER_BUSY
                logging.error(
                    "[UWEB] Get sms captcha failed. umobile: %s.", umobile)

            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] Get sms captcha failed. umobile:%s. Exception: %s",
                              umobile, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
Example #27
0
    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])
Example #28
0
def handle_locationdesc(info, address, connection, channel, exchange, gw_binding, db, redis):
    """
    S10
    locationdesc packet

    0: success, then return locationdesc to terminal and record new terminal's address
    1: invalid SessionID 
    """
    try:
        head = info.head
        body = info.body
        dev_id = head.dev_id
        if len(body) == 6:
            body.append(20) 
            logging.info("[GW] old version is compatible, append locate_error")

        resend_key, resend_flag = get_resend_flag(redis, dev_id, head.timestamp, head.command) 

        go_ahead = False 
        args = DotDict(success=GATEWAY.RESPONSE_STATUS.SUCCESS,
                       locationdesc="",
                       ew="E",
                       lon=0.0,
                       ns="N",
                       lat=0.0)
        sessionID = QueryHelper.get_terminal_sessionID(dev_id, redis)
        if sessionID != head.sessionID:
            args.success = GATEWAY.RESPONSE_STATUS.INVALID_SESSIONID
            logging.error("[GW] Invalid sessionID, terminal: %s", head.dev_id)
        else:
            if resend_flag:
                logging.warn("[GW] Recv resend packet, head: %s, body: %s and drop it!",
                             info.head, info.body)
            else:
                go_ahead = True


        #NOTE: Check ydcw or ajt 
        ajt = QueryHelper.get_ajt_whitelist_by_mobile(head.dev_id, db) 
        if ajt: 
            url_out = ConfHelper.UWEB_CONF.ajt_url_out 
        else: 
            url_out = ConfHelper.UWEB_CONF.url_out

        if go_ahead:
            redis.setvalue(resend_key, True, GATEWAY.RESEND_EXPIRY)
            ldp = LocationDescParser(body, head)
            location = ldp.ret
            logging.info("[GW] T10 packet parsered:%s", location)
            if not  location.has_key('gps_time'):
                location['gps_time'] = int(time.time())
                logging.info("[GW] what's up? location:%s hasn't gps_time.", location)
            location['t'] = EVENTER.INFO_TYPE.POSITION
            if location['valid'] != GATEWAY.LOCATION_STATUS.SUCCESS:
                cellid = True
            else:
                cellid = False
            location = lbmphelper.handle_location(location, redis, cellid=cellid, db=db)
            location.name = location.get('name') if location.get('name') else ""
            location.name = safe_unicode(location.name)
            user = QueryHelper.get_user_by_tid(head.dev_id, db)
            tname = QueryHelper.get_alias_by_tid(head.dev_id, redis, db)
            dw_method = u'GPS' if not cellid else u'基站'
            if location.cLat and location.cLon:
                if user:
                    current_time = get_terminal_time(int(time.time()))
                    sms = SMSCode.SMS_DW_SUCCESS % (tname, dw_method,
                                                    location.name, 
                                                    safe_unicode(current_time)) 
                    url = url_out + '/wapimg?clon=' +\
                          str(location.cLon/3600000.0) + '&clat=' + str(location.cLat/3600000.0)
                    tiny_id = URLHelper.get_tinyid(url)
                    if tiny_id:
                        base_url = url_out + UWebHelper.URLS.TINYURL
                        tiny_url = base_url + '/' + tiny_id
                        logging.info("[GW] get tiny url successfully. tiny_url:%s", tiny_url)
                        redis.setvalue(tiny_id, url, time=EVENTER.TINYURL_EXPIRY)
                        sms += u"点击 " + tiny_url + u" 查看定位器位置。" 
                    else:
                        logging.info("[GW] get tiny url failed.")
                    SMSHelper.send(user.owner_mobile, sms)
            else:
                if user:
                    sms = SMSCode.SMS_DW_FAILED % (tname, dw_method)
                    SMSHelper.send(user.owner_mobile, sms)
            if not (location.lat and location.lon):
                args.success = GATEWAY.RESPONSE_STATUS.CELLID_FAILED
            else:
                insert_location(location, db, redis)

        lc = LocationDescRespComposer(args)
        request = DotDict(packet=lc.buf,
                          address=address,
                          dev_id=dev_id)
        update_terminal_status(redis, head.dev_id, address)
        append_gw_request(request, connection, channel, exchange, gw_binding)
    except:
        logging.exception("[GW] Handle locationdesc exception.")
        GWException().notify()
Example #29
0
def handle_defend(info, address, connection, channel, exchange, gw_binding, db, redis):
    """
    S18
    defend status report packet
    0: success, then record new terminal's address
    1: invalid SessionID 
    """
    try:
        head = info.head
        body = info.body
        dev_id = head.dev_id

        resend_key, resend_flag = get_resend_flag(redis, dev_id, head.timestamp, head.command) 

        # old version is compatible
        if len(body) == 1:
            body.append('0')
            logging.info("[GW] old version is compatible, append mannual status 0")
        args = DotDict(success=GATEWAY.RESPONSE_STATUS.SUCCESS,
                       command=head.command)
        sessionID = QueryHelper.get_terminal_sessionID(dev_id, redis)
        if sessionID != head.sessionID:
            args.success = GATEWAY.RESPONSE_STATUS.INVALID_SESSIONID 
        else:
            if resend_flag:
                logging.warn("[GW] Recv resend packet, head: %s, body: %s and drop it!",
                             info.head, info.body)
            else: 
                redis.setvalue(resend_key, True, GATEWAY.RESEND_EXPIRY)
                hp = AsyncParser(body, head)
                defend_info = hp.ret 
                defend_info['mannual_status'] = defend_info['defend_status']
                if defend_info['defend_source'] != 0:
                    # come from sms or web 
                    if defend_info['defend_source'] == "1":
                        _status = u"设防" if defend_info['defend_status'] == "1" else u"撤防"
                        tname = QueryHelper.get_alias_by_tid(head.dev_id, redis, db)
                        sms = SMSCode.SMS_DEFEND_SUCCESS % (tname, _status) 
                        user = QueryHelper.get_user_by_tid(head.dev_id, db)
                        if user:
                            SMSHelper.send(user.owner_mobile, sms)
                    del defend_info['defend_status']
                del defend_info['defend_source']
                update_mannual_status(db, redis, head.dev_id, defend_info['mannual_status'])
            update_terminal_status(redis, head.dev_id, address)

        if args['success'] == GATEWAY.RESPONSE_STATUS.SUCCESS: 
            acc_status_info_key = get_acc_status_info_key(dev_id) 
            acc_status_info = redis.getvalue(acc_status_info_key) 
            if acc_status_info and (not acc_status_info['t2_status']): # T2(query) is need
                args['success'] = 3 # acc_status is changed 
                logging.info("[GW] ACC_status is changed, dev_id: %s, acc_status_info: %s", 
                             dev_id, acc_status_info)
        hc = AsyncRespComposer(args)
        request = DotDict(packet=hc.buf,
                          address=address,
                          dev_id=dev_id)
        append_gw_request(request, connection, channel, exchange, gw_binding)
    except:
        logging.exception("[GW] Handle defend status report exception.")
        GWException().notify()
Example #30
0
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"])