Beispiel #1
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.")
Beispiel #2
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)
Beispiel #3
0
    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)
Beispiel #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)
Beispiel #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)
Beispiel #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)
Beispiel #7
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)
Beispiel #8
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)
Beispiel #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)
Beispiel #10
0
    def sms_to_user(self, dev_id, sms, mobile):
        if not sms:
            return

        if not mobile:
            return

        if mobile:
            SMSHelper.send(mobile, sms)
Beispiel #11
0
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)
Beispiel #12
0
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)
Beispiel #13
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!")
Beispiel #14
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!")
Beispiel #15
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)
Beispiel #16
0
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)
Beispiel #17
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)
Beispiel #18
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)
Beispiel #19
0
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)
Beispiel #20
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.")
Beispiel #21
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()
Beispiel #22
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)
Beispiel #23
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)
Beispiel #24
0
    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)
Beispiel #25
0
    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
Beispiel #26
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
Beispiel #27
0
    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)
Beispiel #28
0
def send(content, mobile):
    logging.info("Send %s to %s", content, mobile)
    response = SMSHelper.send(mobile, content)
    logging.info("Response: %s", response)
Beispiel #29
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)
Beispiel #30
0
    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)