コード例 #1
0
ファイル: group.py プロジェクト: jcsy521/ydws
    def post(self):
        """Transfer some terminals to a existing group.
        """
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            logging.info("[UWEB] Transfer group request: %s, cid: %s", data, self.current_user.cid)
        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:
            tids = [str(tid) for tid in data.tids]
            gid = data.gid

            sql_cmd = ("UPDATE T_TERMINAL_INFO" "  SET group_id = %s" "  WHERE tid IN %s") % (
                gid,
                tuple(tids + DUMMY_IDS_STR),
            )
            self.db.execute(sql_cmd)

            # NOTE: wspush to client
            tid = self.current_user.tid
            if status == ErrorCode.SUCCESS:
                WSPushHelper.pushS3(tid, self.db, self.redis)

            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] Transfer group failed. cid: %s, Exception: %s", self.current_user.cid, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
コード例 #2
0
ファイル: terminal.py プロジェクト: jcsy521/ydws
    def put(self):
        """Update the parameters of terminal.
        """
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            tid = data.get('tid', None)
            # check tid whether exist in request and update current_user
            self.check_tid(tid)
            logging.info("[UWEB] Terminal request: %s, uid: %s, tid: %s",
                         data, self.current_user.uid, self.current_user.tid)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            self.write_ret(status)
            return

        try:
            terminal = QueryHelper.get_available_terminal(
                self.current_user.tid, self.db)
            if not terminal:
                status = ErrorCode.LOGIN_AGAIN
                logging.error("[UWEB] The terminal with tid: %s does not exist,"
                              "  redirect to login.html",
                              self.current_user.tid)
                self.write_ret(status)
                return

            user = QueryHelper.get_user_by_uid(self.current_user.uid, self.db)
            if not user:
                status = ErrorCode.LOGIN_AGAIN
                logging.error("[UWEB] The user with uid: %s does not exist,"
                              "  redirect to login.html",
                              self.current_user.uid)
                self.write_ret(status)
                return

            # sql injection
            if data.has_key('corp_cnum') and not check_cnum(data.corp_cnum):
                status = ErrorCode.ILLEGAL_CNUM
                self.write_ret(status)
                return

            # NOTE: deprecated
            if data.has_key('white_list'):
                white_list = ":".join(data.white_list)
                if not check_sql_injection(white_list):
                    status = ErrorCode.ILLEGAL_WHITELIST
                    self.write_ret(status)
                    return

            self.update_terminal_db(data)
            # NOTE: wspush to client
            if status == ErrorCode.SUCCESS:
                WSPushHelper.pushS7(tid, self.db, self.redis)
            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] uid:%s, tid:%s update terminal info failed. Exception: %s",
                              self.current_user.uid, self.current_user.tid, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
コード例 #3
0
ファイル: group.py プロジェクト: jcsy521/ydws
    def put(self):
        """Modify a existing group.
        """
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            cid = self.current_user.cid
            tid = self.current_user.tid
            gid = data.gid
            name = data.name
            logging.info("[UWEB] Modify group request: %s, cid: %s", data, self.current_user.cid)
        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:
            group = self.get_group_by_cid(cid, name)
            if group:
                status = ErrorCode.GROUP_EXIST
                self.write_ret(status)
                return

            self.db.execute("UPDATE T_GROUP" "  SET name = %s" "  WHERE id = %s", name, gid)

            # NOTE: wspush to client
            if status == ErrorCode.SUCCESS:
                WSPushHelper.pushS3(tid, self.db, self.redis)

            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] Modify group failed. cid: %s, Exception: %s", self.current_user.cid, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
コード例 #4
0
ファイル: group.py プロジェクト: jcsy521/ydws
    def post(self):
        """Create a new group.
        """
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            logging.info("[UWEB] add group request: %s, cid: %s", data, self.current_user.cid)
        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:
            cid = data.cid
            name = data.name
            group = self.get_group_by_cid(cid, name)
            if group:
                status = ErrorCode.GROUP_EXIST
                self.write_ret(status)
                return

            group_info = dict(cid=cid, name=name, type=UWEB.GROUP_TYPE.NEW)
            gid = add_group(group_info, self.db, self.redis)
            # NOTE: wspush to client
            tid = self.current_user.tid
            if status == ErrorCode.SUCCESS:
                WSPushHelper.pushS3(tid, self.db, self.redis)

            self.write_ret(status, dict_=dict(gid=gid, cid=cid, name=name))

        except Exception as e:
            logging.exception("[UWEB] Create group failed. uid: %s, Exception: %s", self.current_user.uid, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
コード例 #5
0
ファイル: defend.py プロジェクト: jcsy521/ydws
    def post(self):
        status = ErrorCode.SUCCESS
        try: 
            data = DotDict(json_decode(self.request.body))
            tid = data.get('tid', None)
            tids = data.get('tids', None)
            # check tid whether exist in request and update current_user
            self.check_tid(tid)
            logging.info("[UWEB] Defend request: %s, uid: %s, tid: %s, tids: %s",
                         data, self.current_user.uid, self.current_user.tid, tids)
        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:
            res = []
            tids = str_to_list(tids)
            tids = tids if tids else [self.current_user.tid, ]
            tids = [str(tid) for tid in tids]
            for tid in tids:
                r = DotDict(tid=tid,
                            status=ErrorCode.SUCCESS)
                try:
                    terminal = QueryHelper.get_available_terminal(tid, self.db)
                    if not terminal:
                        r.status = ErrorCode.LOGIN_AGAIN
                        res.append(r)
                        logging.error("[UWEB] The terminal with tid: %s does not exist, redirect to login.html",
                                       tid)
                        continue

                    update_mannual_status(self.db, self.redis, tid, data.mannual_status)

                    logging.info("[UWEB] uid:%s, tid:%s set mannual status to %s successfully",
                                 self.current_user.uid, tid, data.mannual_status)
                except Exception as e:
                    r.status = ErrorCode.FAILED
                    logging.exception("[UWEB] uid:%s, tid:%s set mannual status to %s failed. Exception: %s",
                                      self.current_user.uid, tid,
                                      data.mannual_status, e.args)
                finally:
                    res.append(r)

            # NOTE: wspush
            if status == ErrorCode.SUCCESS:
                for tid in tids:
                    WSPushHelper.pushS7(tid, self.db, self.redis)
            self.write_ret(status, dict_=DotDict(res=res))
        except Exception as e:
            logging.exception("[UWEB] uid:%s, tid:%s set mannual status to %s failed. Exception: %s",
                              self.current_user.uid, self.current_user.tid, data.mannual_status, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
コード例 #6
0
ファイル: public.py プロジェクト: jcsy521/ydws
def update_terminal_info(db, redis, t_info):
    """Update terminal's info in db and redis.

    :arg db: database instance 
    :arg redis: redis instance
    :arg terminal: dict, e.g.

        {
          'mobile':'',
          ...
        }

    NOTE: 
    Only those properties which are different from platform is needed to change.
    """
    tid = t_info['dev_id']
    terminal_info_key = get_terminal_info_key(tid)
    terminal_info = QueryHelper.get_terminal_info(tid,
                                                  db, redis)

    # 1: db
    set_clause_dct = []
    # gps, gsm, pbat, changed by position report
    keys = ['mobile', 'defend_status', 'login', 'keys_num', 'fob_status', 'mannual_status',
            'softversion', 'bt_mac', 'bt_name', 'dev_type']

    for key in keys:
        value = t_info.get(key, None)
        t_value = terminal_info.get(key, '')
        if value is not None and value != t_value:
            set_clause_dct.append(key + " = " + "'" + str(t_info[key]) + "'")

    if 'login_time' in t_info:
        set_clause_dct.append('login_time' + " = " + str(t_info['login_time']))
        login_time_key = get_login_time_key(tid)
        redis.setvalue(login_time_key, t_info['login_time'])

    set_clause = ','.join(set_clause_dct)
    if set_clause:
        sql_cmd = ("UPDATE T_TERMINAL_INFO "
                   "  SET " + set_clause +
                   "  WHERE tid = %s")
        db.execute(sql_cmd, tid)

    # 2: redis
    for key in terminal_info:
        value = t_info.get(key, None)
        if value is not None:
            terminal_info[key] = value
    redis.setvalue(terminal_info_key, terminal_info)

    # NOTE:wspush to client. terminal basic info
    WSPushHelper.pushS6(tid, db, redis)
    return terminal_info
コード例 #7
0
ファイル: wspush.py プロジェクト: jcsy521/ydws
    def get(self):
        """Acquire push account through uid

        @uid: user uid
        """

        status = ErrorCode.SUCCESS
        try:
            #NOTE:  get_uid
            uid = self.current_user.uid
            logging.info("Get push account request from uid:%s", uid)
            wspush = dict(id='',
                          key='')

            json_data = WSPushHelper.register_wspush(uid, self.redis)
            if json_data:
                data = json_data.get("data")
                id = data.get('push_id', '')
                key = data.get('psd', '')
                wspush['id']=id
                wspush['key']=key
                logging.info("[UWEB] WSPushHandler get push account successfully."
                             "  id:%s, key:%s",
                             id, key)
                self.write_ret(status=status,
                               dict_=dict(wspush=wspush))
            else:
                status = ErrorCode.SERVER_BUSY
                self.write_ret(status=status)
        except Exception as e:
            logging.exception("[UWEB] WSPushHandler get push account failed, Exception:%s",
                              e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
コード例 #8
0
ファイル: wspush_checker.py プロジェクト: jcsy521/ydws
 def register(self):
     start_time = time.time()
     t = int(time.time()) * 1000
     push_key = get_push_key(self.uid, t)
     res = WSPushHelper.register(self.uid, t, push_key, self.redis)
     end_time = time.time()
     print "register time used: %s" % (end_time - start_time)
     print res
     return res
コード例 #9
0
ファイル: acc.py プロジェクト: jcsy521/ydws
def handle_acc_status(info, address, connection, channel, exchange, gw_binding, db, redis):
    """
    S30
    ACC_status: 

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

        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
            logging.error("[GW] Invalid sessionID, terminal: %s", head.dev_id)
        else:
            uap = ACCStatusParser(body, head)
            t_info = uap.ret
            acc_status_info_key = get_acc_status_info_key(dev_id)
            acc_status_info = redis.getvalue(acc_status_info_key)
            if acc_status_info:  
                acc_status_info['op_status'] = 1 # success
                redis.setvalue(acc_status_info_key, acc_status_info, UWEB.ACC_STATUS_EXPIRY)
                WSPushHelper.pushS8(dev_id, 1, db, redis)
            else: # It should never occur. 
                logging.error("[GW] ACC_status can not be found. dev_id: %s",
                              dev_id)
                pass

        asc = ACCStatusComposer(args)
        request = DotDict(packet=asc.buf,
                          address=address,
                          dev_id=dev_id)
        append_gw_request(request, connection, channel, exchange, gw_binding)
    except:
        logging.exception("[GW] Handle acc status exception.")
        GWException().notify()
コード例 #10
0
ファイル: public.py プロジェクト: jcsy521/ydws
def delete_terminal_new(tid, db, redis, del_user=True):
    """Delete terminal from platform and clear the associated info.
    """
    terminal = db.get("SELECT mobile, owner_mobile, group_id FROM T_TERMINAL_INFO"
                      "  WHERE tid = %s", tid)
    if not terminal:
        logging.info("Terminal: %s already does not exist, do nothing.", tid)
        return
    else:
        t_info = QueryHelper.get_terminal_basic_info(tid, db)
        # NOTE: record the del action.
        corp = QueryHelper.get_corp_by_gid(terminal.group_id, db)
        bind_info = dict(tid=tid,
                         tmobile=terminal.mobile,
                         umobile=terminal.owner_mobile,
                         group_id=terminal.group_id,
                         cid=corp.get('cid', '') if corp else '',
                         del_time=int(time.time()))
        record_del_action(bind_info, db)
        WSPushHelper.pushS3(tid, db, redis, t_info)
        clear_data(tid, db, redis)
        logging.info("[PUBLIC] Delete Terminal: %s, tmobile: %s, umobile: %s",
                     tid, terminal.mobile, terminal.owner_mobile)
コード例 #11
0
ファイル: group.py プロジェクト: jcsy521/ydws
    def delete(self):
        """Delete a group.
        """
        try:
            status = ErrorCode.SUCCESS
            delete_ids = map(int, str_to_list(self.get_argument("ids", None)))
            for delete_id in delete_ids:
                terminals = self.db.query(
                    "SELECT * FROM T_TERMINAL_INFO"
                    "  WHERE group_id = %s"
                    "  AND (service_status = %s "
                    "  OR service_status = %s)",
                    delete_id,
                    UWEB.SERVICE_STATUS.ON,
                    UWEB.SERVICE_STATUS.TO_BE_ACTIVATED,
                )
                if not terminals:
                    logging.info(
                        "[UWEB] group delete request: %s, uid: %s, tid: %s",
                        delete_ids,
                        self.current_user.uid,
                        self.current_user.tid,
                    )
                    self.db.execute("DELETE FROM T_GROUP WHERE id = %s", delete_id)
                else:
                    status = ErrorCode.GROUP_HAS_TERMINAL

            # NOTE: wspush to client
            tid = self.current_user.tid
            if status == ErrorCode.SUCCESS:
                WSPushHelper.pushS3(tid, self.db, self.redis)
            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] Delete group failed. cid: %s, Exception: %s", self.current_user.cid, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
コード例 #12
0
ファイル: packettask.py プロジェクト: jcsy521/ydws
    def push_to_client(self, location):
        """Push information to weixin and wspush.
        """
        #NOTE: use timestamp first. If it does not work, use gps_time.
        if location.get('timestamp',''):
            timestamp = location['timestamp']
        else:
            timestamp = location['gps_time']
        flag = self.check_timestamp(int(timestamp))
        if not flag: 
            return

        tid = location['dev_id']
        terminal = QueryHelper.get_terminal_info(tid, self.db, self.redis)
        body = dict(tid=tid,
                    category=location['category'], 
                    type=location['type'], 
                    timestamp=timestamp,
                    gps_time=location['gps_time'],
                    latitude=location.get('lat',0),
                    longitude=location.get('lon',0),
                    clatitude=location.get('cLat',0),
                    clongitude=location.get('cLon',0),
                    name=location['name'] if location.get('name',None) is not None else '',
                    degree=location.get('degree',0),
                    speed=location.get('speed',0),
                    locate_error=location.get('locate_error',0),
                    region_id=location.get('region_id',-1),
                    # for terminal
                    alias=terminal.get('alias'),
                    gps=terminal.get('gps'),
                    gsm=terminal.get('gsm'),
                    pbat=terminal.get('pbat'))

        WSPushHelper.pushS5(tid, body, self.db, self.redis)
        WeixinPushHelper.push(tid, body, self.db, self.redis)
コード例 #13
0
ファイル: wspush.py プロジェクト: jcsy521/ydws
 def push(self, packet):
     start_time = time.time()
     t = int(time.time()) * 1000
     t_info = QueryHelper.get_terminal_basic_info(self.tid, self.db)
     uid = t_info.get('umobile','')
     cid = t_info.get('cid','') 
     lst = [] 
     if uid: 
         lst.append(uid) 
     if cid: 
         lst.append(cid) 
     for item in set(lst):
         push_key = get_push_key(item, t)
         res = WSPushHelper.push(item, t, push_key, packet, self.redis) 
         end_time = time.time()
         print "push time: %s" % (end_time - start_time)
         print res
コード例 #14
0
ファイル: main.py プロジェクト: jcsy521/ydws
    def get(self):
        status=ErrorCode.SUCCESS
        # from_ = self.get_argument('from', '').lower()
        index_html = "index.html"
        bizcode = None
        name = ''
        if self.current_user.oid != UWEB.DUMMY_OID: # operator
            index_html = "index_corp.html"
            umobile=self.current_user.oid
            user_info = QueryHelper.get_operator_by_oid(self.current_user.oid, self.db)
            corp_info = QueryHelper.get_corp_by_oid(self.current_user.oid, self.db)
            if user_info:
                name = user_info.name if user_info.name else user_info.mobile 
            user_type = UWEB.USER_TYPE.OPERATOR
            bizcode = corp_info.bizcode
        elif self.current_user.cid != UWEB.DUMMY_CID: # corp
            index_html = "index_corp.html"
            umobile=self.current_user.cid
            user_info = QueryHelper.get_corp_by_cid(self.current_user.cid, self.db)
            if user_info:
                name = user_info.c_linkman if user_info.c_linkman else user_info.c_mobile 
            user_type = UWEB.USER_TYPE.CORP
            bizcode = user_info.bizcode
        else: # user
            umobile=self.current_user.uid
            user_info = QueryHelper.get_user_by_uid(self.current_user.uid, self.db)
            if user_info:
                name = user_info.name if user_info.name else user_info.mobile 
            user_type = UWEB.USER_TYPE.PERSON

        if not user_info:
            status = ErrorCode.LOGIN_AGAIN
            logging.error("The user with uid: %s does not exist, redirect to login.html", self.current_user.uid)
            self.render("login.html",
                        username='',
                        password='',
                        user_type=UWEB.USER_TYPE.PERSON,
                        message=None,
                        message_captcha=None)
            return

        static_hash = self.redis.get('static_hash')
        static_hash = static_hash if static_hash else u'dummy_hash'

        wspush = dict(id='', 
                      key='') 
        json_data = WSPushHelper.register_wspush(umobile, self.redis) 
        if json_data: 
            data = json_data['data'] 
            id = data.get('push_id', '') 
            key = data.get('psd', '') 
            wspush['id'] = id
            wspush['key'] = key

        self.render(index_html,
                    map_type=ConfHelper.LBMP_CONF.map_type,
                    user_type=user_type,
                    bizcode=bizcode,
                    status=status,
                    name=name,
                    umobile=umobile,
                    static_hash=static_hash,
                    wspush=wspush,)
コード例 #15
0
ファイル: login.py プロジェクト: jcsy521/ydws
    def post(self):
        logging.info("[UWEB] Android login test")
        status = ErrorCode.SUCCESS
        cid = UWEB.DUMMY_CID
        oid = UWEB.DUMMY_OID
        uid = ConfHelper.UWEB_CONF.test_uid
        tid = ConfHelper.UWEB_CONF.test_tid
        sim = ConfHelper.UWEB_CONF.test_sim
        version_type = int(self.get_argument("version_type", 0))
        biz_type = UWEB.BIZ_TYPE.YDWS

        self.bookkeep(dict(cid=cid,
                           oid=oid,
                           uid=uid,
                           tid=tid,
                           sim=sim))

        user_info = QueryHelper.get_user_by_uid(uid, self.db)

        # NOTE: add cars_info, it's same as lastinfo
        cars_info = {}

        terminals = QueryHelper.get_terminals_by_uid(uid, biz_type, self.db)
        for terminal in terminals:
            # 1: get terminal
            tid = terminal.tid

            group_info = get_group_info_by_tid(self.db, tid)

            terminal_info_key = get_terminal_info_key(tid)
            terminal_cache = self.redis.getvalue(terminal_info_key)
            if terminal_cache:
                terminal['gps'] = terminal_cache['gps']
                terminal['gsm'] = terminal_cache['gsm']
                terminal['pbat'] = terminal_cache['pbat']

            mobile = terminal['mobile']
            terminal['keys_num'] = 0
            if terminal['login'] == GATEWAY.TERMINAL_LOGIN.SLEEP:
                terminal['login'] = GATEWAY.TERMINAL_LOGIN.ONLINE
            # NOTE: if alias is null, provide cnum or sim instead
            terminal['alias'] = QueryHelper.get_alias_by_tid(
                tid, self.redis, self.db)
            fobs = self.db.query("SELECT fobid FROM T_FOB"
                                 "  WHERE tid = %s", tid)
            terminal['fob_list'] = [fob.fobid for fob in fobs]
            terminal['sim'] = terminal['mobile']

            # 2: get location
            location = QueryHelper.get_location_info(tid, self.db, self.redis)
            if location and not (location.clatitude or location.clongitude):
                location_key = get_location_key(str(tid))
                locations = [location, ]
                locations = get_locations_with_clatlon(locations, self.db)
                location = locations[0]
                self.redis.setvalue(
                    location_key, location, EVENTER.LOCATION_EXPIRY)

            if location and location['name'] is None:
                location['name'] = ''

            avatar_name, avatar_path, avatar_full_path, avatar_time = self.get_avatar_info(
                mobile)
            service_status = QueryHelper.get_service_status_by_tmobile(
                self.db, mobile)
            car_dct = {}
            if location and location['type'] == 1:  # cellid
                location['locate_error'] = 500  # mile

            car_info = dict(defend_status=terminal['defend_status'] if terminal['defend_status'] is not None else 1,
                            service_status=service_status,
                            mannual_status=terminal['mannual_status'] if terminal['mannual_status'] is not None else 1,
                            fob_status=terminal['fob_status'] if terminal['fob_status'] is not None else 0,
                            timestamp=location['timestamp'] if location else 0,
                            speed=location.speed if location else 0,
                            # NOTE: degree's type is Decimal, float() it before json_encode
                            degree=float(location.degree) if location else 0.00,
                            locate_error=location.get('locate_error', 20) if location else 20,
                            bt_name=terminal['bt_name'] if terminal.get('bt_name', None) is not None else '',
                            bt_mac=terminal['bt_mac'] if terminal.get('bt_mac', None) is not None else '',
                            dev_type=terminal['dev_type'] if terminal.get('dev_type', None) is not None else 'A',
                            name=location.name if location else '',
                            type=location.type if location else 1,
                            latitude=location['latitude'] if location else 0,
                            longitude=location['longitude'] if location else 0,
                            clatitude=location['clatitude'] if location else 0,
                            clongitude=location['clongitude'] if location else 0,
                            login=terminal['login'] if terminal['login'] is not None else 0,
                            gps=terminal['gps'] if terminal['gps'] is not None else 0,
                            gsm=terminal['gsm'] if terminal['gsm'] is not None else 0,
                            pbat=terminal['pbat'] if terminal['pbat'] is not None else 0,
                            mobile=terminal['mobile'],
                            owner_mobile=terminal['owner_mobile'],
                            alias=terminal['alias'],
                            #keys_num=terminal['keys_num'] if terminal['keys_num'] is not None else 0,
                            keys_num=0,
                            group_id=group_info['group_id'],
                            group_name=group_info['group_name'],
                            icon_type=terminal['icon_type'],
                            avatar_path=avatar_path,
                            avatar_time=avatar_time,
                            fob_list=terminal['fob_list'] if terminal['fob_list'] else [])

            
            car_dct[tid] = car_info
            cars_info.update(car_dct)

        #push_info = NotifyHelper.get_push_info()

        push_id = uid
        push_key = NotifyHelper.get_push_key(push_id, self.redis)

        lastinfo_time_key = get_lastinfo_time_key(uid)
        lastinfo_time = self.redis.getvalue(lastinfo_time_key)

        push = dict(id='',
                    key='')
        t = int(time.time()) * 1000
        push_key = get_push_key(uid, t)
        json_data = WSPushHelper.register_wspush(uid, self.redis)
        data = json_data['data']
        if data:
            id = data.get('push_id', '')
            key = data.get('psd', '')
            push['id'] = id
            push['key'] = key

        if version_type >= 1:
            terminals = []
            for k, v in cars_info.iteritems():
                v.update({'tid': k})
                terminals.append(v)

            self.write_ret(status,
                           dict_=DotDict(wspush=push,
                                         push_id=push_id,
                                         push_key=push_key,
                                         name=user_info.name if user_info else uid,
                                         user_type=UWEB.USER_TYPE.PERSON,
                                         lastinfo_time=lastinfo_time,
                                         terminals=terminals))

        else:
            self.write_ret(status,
                           dict_=DotDict(wspush=push,
                                         push_id=push_id,
                                         # app_key=push_info.app_key,
                                         push_key=push_key,
                                         name=user_info.name if user_info else uid,
                                         user_type=UWEB.USER_TYPE.PERSON,
                                         cars_info=cars_info,
                                         lastinfo_time=lastinfo_time,
                                         cars=terminals,))
コード例 #16
0
ファイル: login.py プロジェクト: jcsy521/ydws
    def post(self):
        username = self.get_argument("username")
        password = self.get_argument("password")
        user_type = self.get_argument("user_type", UWEB.USER_TYPE.PERSON)
        biz_type = self.get_argument("biz_type", UWEB.BIZ_TYPE.YDWS)
        devid = self.get_argument("devid", "")
        versionname = self.get_argument("versionname", "")
        version_type = int(self.get_argument("version_type", 0))
        logging.info("[UWEB] Android login request, username: %s, password: %s, user_type: %s, devid: %s",
                     username, password, user_type, devid)
        # must check username and password avoid sql injection.
        if not (username.isalnum() and password.isalnum()):
            status = ErrorCode.ILLEGAL_LABEL
            self.write_ret(status)
            return

        # check the user, return uid, tid, sim and status
        cid, oid, uid, terminals, user_type, status = self.login_passwd_auth(username, password, user_type)
        logging.info(
            "[UWEB] Login auth, cid:%s, oid:%s, uid:%s, user_type:%s", cid, oid, uid, user_type)
        if status == ErrorCode.SUCCESS:
            # role: 0: person; 1: operator; 2: enterprise
            # method 0: web; 1: android; 2: ios
            # NOTE: keep the login log
            login_info = dict(uid=uid,
                              role=0,
                              method=1,
                              versionname=versionname)
            record_login_user(login_info, self.db)

            self.bookkeep(dict(cid=cid,
                               oid=oid,
                               uid=uid,
                               tid=terminals[0].tid,
                               sim=terminals[0].sim))

            user_info = QueryHelper.get_user_by_uid(uid, self.db)

            # NOTE: add cars_info, it's same as lastinfo
            cars_info = {}

            if user_type == UWEB.USER_TYPE.PERSON:
                terminals = QueryHelper.get_terminals_by_uid(uid, biz_type, self.db)
            elif user_type == UWEB.USER_TYPE.OPERATOR:
                terminals = QueryHelper.get_terminals_by_oid(oid, biz_type, self.db)
            elif user_type == UWEB.USER_TYPE.CORP:
                terminals = QueryHelper.get_terminals_by_cid(cid, biz_type, self.db)
            else:
                logging.error("[UWEB] Invalid user_type: %s", user_type)

            for terminal in terminals:
                # 1: get terminal
                tid = terminal.tid

                group_info = get_group_info_by_tid(self.db, tid)

                terminal_info_key = get_terminal_info_key(tid)
                terminal_cache = self.redis.getvalue(terminal_info_key)
                if terminal_cache:
                    terminal['gps'] = terminal_cache['gps']
                    terminal['gsm'] = terminal_cache['gsm']
                    terminal['pbat'] = terminal_cache['pbat']

                mobile = terminal['mobile']
                terminal['keys_num'] = 0
                if terminal['login'] == GATEWAY.TERMINAL_LOGIN.SLEEP:
                    terminal['login'] = GATEWAY.TERMINAL_LOGIN.ONLINE
                # NOTE: if alias is null, provide cnum or sim instead
                terminal['alias'] = QueryHelper.get_alias_by_tid(
                    tid, self.redis, self.db)
                fobs = self.db.query("SELECT fobid FROM T_FOB"
                                     "  WHERE tid = %s", tid)
                terminal['fob_list'] = [fob.fobid for fob in fobs]
                terminal['sim'] = terminal['mobile']

                # 2: get location
                location = QueryHelper.get_location_info(tid, self.db, self.redis)
                if location and not (location.clatitude or location.clongitude):
                    location_key = get_location_key(str(tid))
                    locations = [location, ]
                    locations = get_locations_with_clatlon(locations, self.db)
                    location = locations[0]
                    self.redis.setvalue(location_key, location, EVENTER.LOCATION_EXPIRY)

                if location and location['name'] is None:
                    location['name'] = ''

                avatar_name, avatar_path, avatar_full_path, avatar_time = self.get_avatar_info(mobile)

                service_status = QueryHelper.get_service_status_by_tmobile(
                    self.db, mobile)
                car_dct = {}

                if location and location['type'] == 1:  # cellid
                    location['locate_error'] = 500  # mile

                car_info = dict(defend_status=terminal['defend_status'] if terminal['defend_status'] is not None else 1,
                            service_status=service_status,
                            mannual_status=terminal['mannual_status'] if terminal['mannual_status'] is not None else 1,
                            fob_status=terminal['fob_status'] if terminal['fob_status'] is not None else 0,
                            timestamp=location['timestamp'] if location else 0,
                            speed=location.speed if location else 0,
                            # NOTE: degree's type is Decimal, float() it before json_encode
                            degree=float(location.degree) if location else 0.00,
                            locate_error=location.get('locate_error', 20) if location else 20,
                            bt_name=terminal['bt_name'] if terminal.get('bt_name', None) is not None else '',
                            bt_mac=terminal['bt_mac'] if terminal.get('bt_mac', None) is not None else '',
                            dev_type=terminal['dev_type'] if terminal.get('dev_type', None) is not None else 'A',
                            name=location.name if location else '',
                            type=location.type if location else 1,
                            latitude=location['latitude'] if location else 0,
                            longitude=location['longitude'] if location else 0,
                            clatitude=location['clatitude'] if location else 0,
                            clongitude=location['clongitude'] if location else 0,
                            login=terminal['login'] if terminal['login'] is not None else 0,
                            gps=terminal['gps'] if terminal['gps'] is not None else 0,
                            gsm=terminal['gsm'] if terminal['gsm'] is not None else 0,
                            pbat=terminal['pbat'] if terminal['pbat'] is not None else 0,
                            mobile=terminal['mobile'],
                            owner_mobile=terminal['owner_mobile'],
                            alias=terminal['alias'],
                            #keys_num=terminal['keys_num'] if terminal['keys_num'] is not None else 0,
                            keys_num=0,
                            group_id=group_info['group_id'],
                            group_name=group_info['group_name'],
                            icon_type=terminal['icon_type'],
                            avatar_path=avatar_path,
                            avatar_time=avatar_time,
                            fob_list=terminal['fob_list'] if terminal['fob_list'] else [])
             
                car_dct[tid] = car_info
                cars_info.update(car_dct)

            #push_info = NotifyHelper.get_push_info()

            push_id = devid if devid else uid
            push_key = NotifyHelper.get_push_key(push_id, self.redis)

            lastinfo_time_key = get_lastinfo_time_key(uid)
            lastinfo_time = self.redis.getvalue(lastinfo_time_key)

            # uid --> android_push_list
            # check push_id whether exists in a old android_push_list
            old_android_push_list_key = self.redis.get(push_id)
            if old_android_push_list_key:
                old_android_push_list = self.redis.getvalue(
                    old_android_push_list_key)
                if not isinstance(old_android_push_list, list):
                    self.redis.delete(old_android_push_list_key)
                    old_android_push_list = []
                if old_android_push_list and (push_id in old_android_push_list):
                    logging.info("[UWEB] push_id:%s has existed in a old_android_push_list: %s, so remove push_id from the list.",
                                 push_id, old_android_push_list)
                    old_android_push_list.remove(push_id)
                    self.redis.set(old_android_push_list_key, old_android_push_list)

            android_push_list_key = get_android_push_list_key(uid)
            android_push_list = self.redis.getvalue(android_push_list_key)
            android_push_list = android_push_list if android_push_list else []
            if push_id not in android_push_list:
                android_push_list.append(push_id)
            self.redis.set(android_push_list_key, android_push_list)
            self.redis.set(push_id, android_push_list_key)
            logging.info("[UWEB] uid: %s, android_push_lst: %s", username, android_push_list)

            if user_info:
                self.login_sms_remind(uid, user_info.mobile, terminals, login="******")
            else:
                pass  # corp maybe no user_info

            push = dict(id='',
                        key='')
            json_data = WSPushHelper.register_wspush(uid, self.redis)
            data = json_data['data']
            if data:
                id = data.get('push_id', '')
                key = data.get('psd', '')
                push['id'] = id
                push['key'] = key

            if version_type >= 1:
                terminals = []
                for k, v in cars_info.iteritems():
                    v.update({'tid': k})
                    terminals.append(v)

                self.write_ret(status,
                               dict_=DotDict(wspush=push,
                                             push_id=push_id,
                                             push_key=push_key,
                                             name=user_info.name if user_info else username,
                                             user_type=user_type,
                                             terminals=terminals,
                                             lastinfo_time=lastinfo_time,))
            else:
                self.write_ret(status,
                               dict_=DotDict(wspush=push,
                                             push_id=push_id,
                                             # app_key=push_info.app_key,
                                             push_key=push_key,
                                             name=user_info.name if user_info else username,
                                             user_type=user_type,
                                             cars_info=cars_info,
                                             lastinfo_time=lastinfo_time,
                                             cars=terminals))
        else:
            logging.info("[UWEB] username: %s login failed, message: %s",
                         username, ErrorCode.ERROR_MESSAGE[status])
            self.write_ret(status)
コード例 #17
0
ファイル: terminal.py プロジェクト: jcsy521/ydws
    def update_terminal_db(self, data):
        """Update database.
        """
        # NOTE: these fields should to be modified in db
        terminal_keys = ['cellid_status', 'white_pop', 'trace', 'freq',
                         'vibchk', 'vibl', 'push_status', 'login_permit',
                         'alert_freq', 'stop_interval', 'biz_type', 'speed_limit']
        terminal_fields = []

        if data.has_key('tid'):
            del data['tid']

        for key, value in data.iteritems():

            # NOTE: These fields should be modified in database.
            if key in terminal_keys:
                if data.get(key, None) is not None:
                    terminal_fields.append(key + ' = ' + str(value))
                    
            # NOT: These fields should be handled specially.
            if key == 'white_list':
                white_list = data[key]
                if len(data['white_list']) < 1:
                    pass
                else:
                    self.db.execute("DELETE FROM T_WHITELIST WHERE tid = %s",
                                    self.current_user.tid)
                    for white in white_list[1:]:
                        self.db.execute("INSERT INTO T_WHITELIST"
                                        "  VALUES(NULL, %s, %s)"
                                        "  ON DUPLICATE KEY"
                                        "  UPDATE tid = VALUES(tid),"
                                        "    mobile = VALUES(mobile)",
                                        self.current_user.tid, white)

            elif key == 'alias':
                self.db.execute("UPDATE T_TERMINAL_INFO"
                                "  SET alias = %s"
                                "  WHERE tid = %s",
                                value, self.current_user.tid)

                terminal_info_key = get_terminal_info_key(
                    self.current_user.tid)
                terminal_info = self.redis.getvalue(terminal_info_key)
                if terminal_info:
                    terminal_info[key] = value
                    self.redis.setvalue(terminal_info_key, terminal_info)
            elif key == 'icon_type':
                self.db.execute("UPDATE T_TERMINAL_INFO"
                                "  SET icon_type = %s"
                                "  WHERE tid = %s",
                                value, self.current_user.tid)

                terminal_info_key = get_terminal_info_key(
                    self.current_user.tid)
                terminal_info = self.redis.getvalue(terminal_info_key)
                if terminal_info:
                    terminal_info[key] = value
                    self.redis.setvalue(terminal_info_key, terminal_info)
            elif key == 'corp_cnum':
                self.db.execute("UPDATE T_CAR"
                                "  SET cnum = %s"
                                "  WHERE tid = %s",
                                safe_utf8(value), self.current_user.tid)
                self.db.execute("UPDATE T_TERMINAL_INFO"
                                "  SET alias = %s"
                                "  WHERE tid = %s",
                                safe_utf8(value), self.current_user.tid)
                terminal_info_key = get_terminal_info_key(
                    self.current_user.tid)
                terminal_info = self.redis.getvalue(terminal_info_key)
                if terminal_info:
                    terminal_info[
                        'alias'] = value if value else self.current_user.sim
                    self.redis.setvalue(terminal_info_key, terminal_info)
            elif key == 'owner_mobile' and value is not None:
                umobile = value
                user = dict(umobile=umobile,
                            password=u'111111')
                add_user(user, self.db, self.redis)   
                t = QueryHelper.get_terminal_by_tid(self.current_user.tid, self.db)                
                old_uids = [t.owner_mobile]
                # send sms                
                self.db.execute("UPDATE T_TERMINAL_INFO"
                                "  SET owner_mobile = %s"
                                "  WHERE tid = %s",
                                umobile, self.current_user.tid)
                register_sms = SMSCode.SMS_REGISTER % (
                    umobile, self.current_user.sim)
                SMSHelper.send_to_terminal(self.current_user.sim, register_sms)

                # update redis
                terminal_info_key = get_terminal_info_key(
                    self.current_user.tid)
                terminal_info = self.redis.getvalue(terminal_info_key)
                if terminal_info:
                    terminal_info[key] = umobile
                    self.redis.setvalue(terminal_info_key, terminal_info)

                # wspush to client
                WSPushHelper.pushS3(self.current_user.tid, self.db, self.redis)
                WSPushHelper.pushS3_dummy(old_uids, self.db, self.redis)
            elif key == "alert_freq":
                alert_freq_key = get_alert_freq_key(self.current_user.tid)
                if self.redis.exists(alert_freq_key):
                    logging.info(
                        "[UWEB] Termianl %s delete alert freq in redis.", self.current_user.tid)
                    self.redis.delete(alert_freq_key)

            # if vibl has been changed,then update use_scene as well
            elif key == "vibl":
                use_scene = get_use_scene_by_vibl(value)
                self.db.execute("UPDATE T_TERMINAL_INFO SET use_scene=%s WHERE tid=%s",
                                use_scene, self.current_user.tid)
                logging.info("[UWEB] Terminal %s update use_scene %s and vibl %s",
                             self.current_user.tid, use_scene, value)
                logging.info(
                    "[UWEB] Termianl %s delete session in redis.", self.current_user.tid)
            # NOTE: deprecated.
            elif key == "parking_defend" and value is not None:
                if value == 1:
                    mannual_status = UWEB.DEFEND_STATUS.SMART
                else:
                    mannual_status = UWEB.DEFEND_STATUS.YES
                update_mannual_status(
                    self.db, self.redis, self.current_user.tid, mannual_status)
            elif key == 'login_permit':
                # wspush to client
                WSPushHelper.pushS3(self.current_user.tid, self.db, self.redis)                
            else:
                pass               

        # NOTE:update database.
        terminal_clause = ','.join(terminal_fields)
        if terminal_clause:
            self.db.execute("UPDATE T_TERMINAL_INFO"
                            "  SET " + terminal_clause +
                            "  WHERE tid = %s ",
                            self.current_user.tid)
        # NOTE: clear sessionID if freq, stop_interval, vibl can be found.
        if data.has_key('freq') or data.has_key('stop_interval') or data.has_key('vibl'):
            clear_sessionID(self.redis, self.current_user.tid)
コード例 #18
0
ファイル: login.py プロジェクト: jcsy521/ydws
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)
コード例 #19
0
ファイル: login.py プロジェクト: jcsy521/ydws
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"])            
コード例 #20
0
ファイル: test_wspush.py プロジェクト: jcsy521/ydws
    def post(self):
        """Acquire push account through uid

        @uid: user uid
        """
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            tid = data.tid
            s_type = data.s_type
            if data.get("category", None):
                category = int(data.get("category"))
            else:
                category = 1

            logging.info("[UWEB] Test wspush 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:
            # user = self.db.get("select owner_mobile")
            user = QueryHelper.get_user_by_tid(tid, self.db)
            uid = user.owner_mobile
            if s_type == "S3":
                WSPushHelper.pushS3(tid, self.db, self.redis)
            elif s_type == "S4":
                WSPushHelper.pushS4(tid, self.db, self.redis)
            elif s_type == "S5":
                body = dict(
                    tid=tid,
                    category=category,
                    pbat=100,
                    type=1,
                    timestamp=int(time.time()),
                    longitude=419004000,
                    latitude=143676000,
                    clongitude=419004000,
                    clatitude=143676000,
                    name="test name",
                    speed=111,
                    degree=203,
                    gsm=0,
                    locate_error=100,
                    gps=25,
                    alias="111",
                    region_id=11,
                )
                WSPushHelper.pushS5(tid, body, self.db, self.redis)
            elif s_type == "S6":
                WSPushHelper.pushS6(tid, self.db, self.redis)
            elif s_type == "S7":
                WSPushHelper.pushS7(tid, self.db, self.redis)
            elif s_type == "S8":
                acc_message = 1
                WSPushHelper.pushS8(tid, acc_message, self.db, self.redis)

            self.write_ret(status=status)
        except Exception as e:
            logging.exception("[UWEB] WSPushHandler get push account failed, Exception:%s", e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
コード例 #21
0
ファイル: terminal.py プロジェクト: jcsy521/ydws
    def delete(self):
        """Delete a terminal.
        """
        try:
            status = ErrorCode.SUCCESS
            tid = self.get_argument('tid', None)
            flag = self.get_argument('flag', 0)
            logging.info("[UWEB] Corp delete terminal request. tid: %s, flag: %s, cid: %s",
                         tid, flag, self.current_user.cid)

            terminal = QueryHelper.get_available_terminal(tid, self.db)
            if not terminal:
                logging.error("[UWEB] The terminal with tid: %s does not exist!", 
                              tid)
                status = ErrorCode.TERMINAL_NOT_EXISTED
                self.write_ret(status)
                return

            t_info = QueryHelper.get_terminal_basic_info(tid, self.db)
            key = get_del_data_key(tid)
            self.redis.set(key, flag)
            biz_type = QueryHelper.get_biz_type_by_tmobile(
                terminal.mobile, self.db)
            if int(biz_type) == UWEB.BIZ_TYPE.YDWS:
                if terminal.login != GATEWAY.TERMINAL_LOGIN.ONLINE:
                    if terminal.mobile == tid:
                        delete_terminal(tid, self.db, self.redis)
                    else:
                        status = self.send_jb_sms(
                            terminal.mobile, terminal.owner_mobile, tid)

                    if status == ErrorCode.SUCCESS:
                        WSPushHelper.pushS3(tid, self.db, self.redis, t_info)
                    self.write_ret(status)
                    return
            else:
                delete_terminal(tid, self.db, self.redis)
                if status == ErrorCode.SUCCESS:
                    WSPushHelper.pushS3(tid, self.db, self.redis, t_info)
                self.write_ret(status)
                return

            # unbind terminal
            seq = str(int(time.time() * 1000))[-4:]
            args = DotDict(seq=seq,
                           tid=tid)
            response = GFSenderHelper.forward(GFSenderHelper.URLS.UNBIND, args)
            response = json_decode(response)
            logging.info(
                "[UWEB] UNBind terminal: %s, response: %s", tid, response)
            if response['success'] == ErrorCode.SUCCESS:
                logging.info("[UWEB] uid:%s, tid: %s, tmobile:%s GPRS unbind successfully",
                             self.current_user.uid, tid, terminal.mobile)
            else:
                status = response['success']
                # unbind failed. clear sessionID for relogin, then unbind it
                # again
                clear_sessionID(self.redis, tid)
                logging.error('[UWEB] uid:%s, tid: %s, tmobile:%s GPRS unbind failed, message: %s, send JB sms...',
                              self.current_user.uid, tid, terminal.mobile,
                              ErrorCode.ERROR_MESSAGE[status])
                status = self.send_jb_sms(
                    terminal.mobile, terminal.owner_mobile, tid)

            if status == ErrorCode.SUCCESS:
                WSPushHelper.pushS3(tid, self.db, self.redis, t_info)
            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] Delete terminal failed. cid: %s, Exception: %s",
                              self.current_user.cid, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
コード例 #22
0
ファイル: public.py プロジェクト: jcsy521/ydws
def add_terminal(terminal, db, redis):
    """"Add a terminal.

    @param: terminal, {'tid':'',
                       'tmobile':'', 
                       'owner_mobile':'',
                       'group_id':'',
                       'dev_type':'',
                       'imsi':'',
                       'imei':'',
                       'factory_name':'',
                       'softversion':'',
                       'keys_num':'',
                       'bt_name':'',
                       'bt_mac':'',
                       'login':'',
                       'mannual_status':'',
                       'alias':'',
                       'icon_type':'',
                       'login_permit':'',
                       'push_status':'',
                       'vibl':'',
                       'use_scene':'',
                       'biz_type':'',
                       'activation_code':'',
                       'service_status':'',
                       'begintime':'',
                       'endtime':'',
                       'offline_time':''
                       'speed_limit':''
                       'stop_interval':''
                       'distance_current':''
                       # car
                       'cnum':'',
                       }
    @param: db
    @param: redis
    """
    if terminal.get('tid', ''):
        tid = terminal['tid']
    else:
        tid = terminal['tmobile']

    #NOTE: If tid has exist, delete it. This should never happen.
    t = db.get("SELECT id, service_status, mobile, tid, owner_mobile, group_id"
               "  FROM T_TERMINAL_INFO WHERE tid = %s", 
               tid)
    if t:
        db.execute("DELETE FROM T_TERMINAL_INFO WHERE tid = %s", 
                   tid)
        logging.info("[PUBLIC] Delete the existed but unvalid terminal. terminal: %s.",
                     t)

    #NOTE: If mobile has exist, delete it. This should not appears often.
    t = db.get("SELECT id, service_status, mobile, tid, owner_mobile, group_id"
               "  FROM T_TERMINAL_INFO WHERE mobile = %s", 
               terminal.get('tmobile'))
    if t and int(t['service_status']) == 2:
        db.execute("DELETE FROM T_TERMINAL_INFO WHERE mobile = %s", 
                   terminal.get('tmobile'))
        logging.info("[PUBLIC] Delete the existed but unvalid terminal. terminal: %s.",
                     t)

    # add terminal 28 items.
    db.execute("INSERT INTO T_TERMINAL_INFO(tid, mobile, owner_mobile,"
               "  group_id, dev_type, imsi, imei, factory_name, softversion,"
               "  keys_num, bt_name, bt_mac, login, mannual_status, alias,"
               "  icon_type, login_permit, push_status, vibl, use_scene,"
               "  biz_type, activation_code, service_status, begintime,"
               "  endtime, offline_time, speed_limit, stop_interval,"
               "  distance_current)"
               "  VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,"
               "          %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,"
               "          %s, %s, %s, %s, %s)",
               tid, terminal.get('tmobile'), terminal.get('owner_mobile'),
               terminal.get('group_id', -1), terminal.get('dev_type', 'A'),
               terminal.get('imsi', ''), terminal.get('imei', ''),
               terminal.get('factory_name', ''), terminal.get('softversion', ''),
               terminal.get('keys_num', 0), terminal.get('bt_name', ''),
               terminal.get('bt_mac', ''), terminal.get('login', 0),
               terminal.get('mannual_status', 1), terminal.get('alias', ''),
               terminal.get('icon_type', 0), terminal.get('login_permit', 1),
               terminal.get('push_status', 1), terminal.get('vibl', 1),
               terminal.get('use_scene', 3), terminal.get('biz_type', 0),
               terminal.get('activation_code', ''), terminal.get('service_status', 1),
               terminal.get('begintime'), terminal.get('endtime'),
               terminal.get('offline_time'), terminal.get('speed_limit', 120),
               terminal.get('stop_interval', 0), terminal.get('distance_current', 0))

    # add car tnum --> cnum
    car = db.get("SELECT id FROM T_CAR WHERE tid= %s", tid)
    if car:
        db.execute("DELETE FROM T_CAR WHERE tid = %s", tid)

    db.execute("INSERT INTO T_CAR(tid, cnum, type, color, brand)"
               "  VALUES(%s, %s, %s, %s, %s)",
               tid, terminal.get('cnum', ''),
               terminal.get('ctype', 1), terminal.get('ccolor', 0),
               terminal.get('cbrand', ''))
    # NOTE: wspush to client
    WSPushHelper.pushS3(tid, db, redis)
    logging.info("[PUBLIC] Add terminal, tid: %s, terminal: %s.",
                 tid, terminal)