コード例 #1
0
ファイル: zfjsyncer.py プロジェクト: jcsy521/ydws
    def post(self):
        res = list()
        try:
            corp_id = 13726103889   #开发区执法局
            begin_time = self.redis.getvalue('last_time')
            end_time = time.time()
            self.redis.setvalue('last_time', end_time)
            if (end_time - begin_time) < 14*60: # 14 分钟
                logging.info("[UWEB] ZFJ request too frequency,"
                             " skip it, begin time:%s, end time:%s", 
                             begin_time, end_time)
                self.write({'res':res})
                return

            logging.info("[UWEB] ZFJ request, begin time:%s, end time:%s", 
                         begin_time, end_time)
            if begin_time:
                terminals = QueryHelper.get_terminals_by_cid(corp_id,self.db)
                for terminal in terminals:
                    mobile = terminal['mobile']
                    tid = terminal['tid']
                    positions = self.db.query("SELECT id, latitude, longitude,"
                                              "  clatitude, clongitude, timestamp"
                                              "  FROM T_LOCATION"
                                              "  WHERE tid=%s" 
                                              "  AND timestamp BETWEEN %s AND %s"
                                              "  AND latitude != 0"
                                              "  AND longitude != 0"
                                              "  ORDER BY timestamp",
                                              tid, begin_time , end_time)

                    _start_time = time.time()
                    positions = get_locations_with_clatlon(positions, self.db) 
                    _now_time = time.time()
                    if _now_time - _start_time > 3: # 3 seconds
                        logging.info("[UWEB] Track offset used time: %s s, tid: %s, cid: %s",
                                     _now_time - _start_time, tid, corp_id)
                    res.append({'mobile':mobile, 'positions':positions})
            self.write({'res':res})

        except Exception as e:
            logging.exception("[UWEB] zfjsyncer: get location failed. Exception: %s", 
                              e.args) 
コード例 #2
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)
コード例 #3
0
ファイル: mileage.py プロジェクト: jcsy521/ydws
    def post(self):
        """ Provide some statistics about terminals.
        """
      
        status = ErrorCode.SUCCESS
        #NOTE: check data format
        try:
            data = DotDict(json_decode(self.request.body))
            page_size = UWEB.LIMIT.PAGE_SIZE
            page_number = int(data.pagenum) 
            start_time= data.start_time
            end_time = data.end_time
            query_type = data.query_type
            if query_type == UWEB.QUERY_TYPE.JUNIOR: # 0
                start_period_ = 0
                end_period_ = 0 
            else:
                start_period= data.start_period
                end_period = data.end_period
                start_period_ = int(start_period[:2])*60*60 + int(start_period[2:])*60
                end_period_ = int(end_period[:2])*60*60 + int(end_period[2:])*60
            tids = str_to_list(data.tids)
            logging.info("[UWEB] mileage request: %s, cid: %s, oid: %s", 
                         data, self.current_user.cid, self.current_user.oid)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.exception("[UWEB] Invalid data format. Exception: %s",
                              e.args)
            self.write_ret(status)
            self.finish()
            return

        #NOTE: prepare  
        try:
            # the interval between start_time and end_time is one week
            if self.current_user.cid != UWEB.DUMMY_CID: # no checks for enterprise
                pass
            elif (int(end_time) - int(start_time)) > UWEB.QUERY_INTERVAL:
                self.write_ret(ErrorCode.QUERY_INTERVAL_EXCESS)
                self.finish()
                return

            statistic_mode = 'single' 
            if not tids: # all terminals
                statistic_mode = 'all' 
                terminals = QueryHelper.get_terminals_by_cid(self.current_user.cid, self.db)
                tids = [terminal.tid for terminal in terminals]
        except Exception as e:
            logging.exception("[UWEB] cid:%s, oid:%s get mileage report failed. Exception: %s",
                              self.current_user.cid, self.current_user.oid, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
            self.finish()
            return

        def _on_finish(db):
            self.db = db
            page_count = int(data.pagecnt)
            if statistic_mode == 'all': # all
                if page_count == -1:
                    count = len(tids)
                    d, m = divmod(count, page_size)
                    page_count = (d + 1) if m else d

                reports = []                
                for item, tid in enumerate(tids):
                    seq=item+1
                    dis_sum = Decimal()  

                    start_date = get_date_from_utc(start_time)
                    end_date = get_date_from_utc(end_time)
                    start_day = datetime.datetime.fromtimestamp(start_time)
                    end_day = datetime.datetime.fromtimestamp(end_time)
                    # get how many days the end_time and start_time cover
                    days = abs(end_day-start_day).days+1
                    for item in range(days):
                        distance = Decimal()
                        timestamp = start_time+1*60*60*24*(item)
                        date = get_date_from_utc(timestamp)
                        year, month, day = date.year, date.month, date.day
                        start_time_, end_time_ = start_end_of_day(year=year, month=month, day=day)
                 
                        points = self.db.query("SELECT longitude, latitude FROM T_LOCATION"
                                               "  WHERE tid = %s"
                                               "    AND (timestamp BETWEEN %s AND %s)"
                                               "    AND type = 0"
                                               "  ORDER BY timestamp asc",
                                               tid, start_time_+start_period_, start_time_+end_period_)
                        for i in range(len(points)-1):
                            if points[i].longitude and points[i].latitude and \
                               points[i+1].longitude and points[i+1].latitude:
                               dis = get_distance(points[i].longitude, points[i].latitude,
                                                         points[i+1].longitude, points[i+1].latitude) 
                               distance += Decimal(str(dis))
                        # meter --> km
                        distance = '%0.1f' % (distance/1000,)
                        dis_sum += Decimal(distance)

                    alias = QueryHelper.get_alias_by_tid(tid, self.redis, self.db)
                    dct = dict(seq=seq,
                               alias=alias,
                               distance=float(dis_sum))
                    reports.append(dct)

                # orgnize and store the data to be downloaded 
                m = hashlib.md5()
                m.update(self.request.body)
                hash_ = m.hexdigest()
                mem_key = self.KEY_TEMPLATE % (self.current_user.uid, hash_)
                
                self.redis.setvalue(mem_key, (statistic_mode, reports, 0), time=UWEB.STATISTIC_INTERVAL)

                reports= reports[(page_number * page_size):((page_number+1) * page_size)]
                self.write_ret(status,
                               dict_=DotDict(res=reports,
                                             pagecnt=page_count,
                                             hash_=hash_))
            else: # single
                tid = tids[0]
                delta = end_time - start_time # end_time must bigger than start_time
                d, m = divmod(delta, 60*60*24) 
                start_date = get_date_from_utc(start_time)
                end_date = get_date_from_utc(end_time)
                start_day = datetime.datetime.fromtimestamp(start_time)
                end_day = datetime.datetime.fromtimestamp(end_time)
                # get how many days the end_time and start_time cover
                days = abs(end_day-start_day).days+1
                #if days == 0: 
                #    if start_date.day  == end_date.day:   
                #        days = 1
                #    else: 
                #        days = 2
                #else: 
                #    days = days+1 if m else days
                #    if end_day.hour*60*60 + end_day.minute*60 + end_day.second <  start_day.hour*60*60 + start_day.minute*60 + start_day.second:                   
                #        days = days+1 
  
                res = []
                graphics = [] 
                counts = []
                dis_sum = Decimal() 
                current_time = int(time.time()) 

                sql_cmd = ("SELECT longitude, latitude FROM T_LOCATION"
                           "  WHERE tid = %s"
                           "    AND (timestamp BETWEEN %s AND %s)"
                           "    AND type = 0"
                           "  ORDER BY timestamp asc")

                #last_cmd = ("SELECT timestamp FROM T_LOCATION"
                #            "  WHERE tid = %s"
                #            "    AND (timestamp BETWEEN %s AND %s)"
                #            "    AND type = 0"
                #            "  ORDER BY timestamp desc limit 1")

                #next_cmd = ("SELECT timestamp FROM T_LOCATION"
                #            "  WHERE tid = %s"
                #            "    AND (timestamp BETWEEN %s AND %s)"
                #            "    AND type = 0"
                #            "  ORDER BY timestamp asc limit 1")
                 
                if days == 1: # start_time, end_time in the same day
                    timestamp = start_time
                    date = get_date_from_utc(timestamp)

                    re = {} 
                    re['alias'] = '-'.join([str(date.year),str(date.month),str(date.day)]) 
                    distance = Decimal() 

                    points = self.db.query(sql_cmd, tid, start_time+start_period_, start_time+end_period_)
                    for i in range(len(points)-1):
                        if points[i].longitude and points[i].latitude and \
                           points[i+1].longitude and points[i+1].latitude:
                            dis = get_distance(points[i].longitude, points[i].latitude,
                                               points[i+1].longitude, points[i+1].latitude) 
                            distance += Decimal(str(dis)) 
                    # meter --> km
                    distance = '%0.1f' % (distance/1000,)      
                        
                    graphics.append(float(distance))
                    dis_sum += Decimal(distance)

                    re['distance'] = distance 
                    re['seq'] = 1 
                    res.append(re)
                else: # start_time, end_time in different days
                    for item in range(days):
                        timestamp = start_time+1*60*60*24*(item)
                        date = get_date_from_utc(timestamp)
                        year, month, day = date.year, date.month, date.day
                        start_time_, end_time_ = start_end_of_day(year=year, month=month, day=day)
                        ## handle the first day and last day
                        #if item == 0: 
                        #    start_time_ = start_time
                        #if item == days: 
                        #    end_time_ = end_time
                        #last_point = self.db.get(last_cmd, tid, start_time_-60*60*24, start_time_,)
                        #next_point = self.db.get(next_cmd, tid, end_time_, end_time_+60*60*24)
                        #start_time_ = last_point['timestamp'] if last_point else start_time_
                        #end_time_ = next_point['timestamp'] if next_point else end_time_

                        re = {} 
                        re['alias'] = '-'.join([str(year),str(month),str(day)]) 
                        distance = Decimal() 
                        points = self.db.query(sql_cmd, tid, start_time_+start_period_, start_time_+end_period_)
                        for i in range(len(points)-1):
                            if points[i].longitude and points[i].latitude and \
                               points[i+1].longitude and points[i+1].latitude:
                                dis = get_distance(points[i].longitude, points[i].latitude,
                                                   points[i+1].longitude, points[i+1].latitude) 
                                distance += Decimal(str(dis)) 
                        # meter --> km
                        distance = '%0.1f' % (distance/1000,)      
                            
                        graphics.append(float(distance))
                        dis_sum += Decimal(distance)

                        re['distance'] = distance 
                        re['seq'] = item+1 
                        res.append(re)

                counts = [float(dis_sum),]

                if page_count == -1:
                    items_count = len(res) 
                    d, m = divmod(items_count, page_size) 
                    page_count = (d + 1) if m else d
    
                # store resutl in redis
                m = hashlib.md5()
                m.update(self.request.body)
                hash_ = m.hexdigest()
                mem_key = self.KEY_TEMPLATE % (self.current_user.uid, hash_)
                
                self.redis.setvalue(mem_key, (statistic_mode, res, counts,), time=UWEB.STATISTIC_INTERVAL)
    
                res= res[page_number*page_size:(page_number+1)*page_size]
                self.write_ret(status, 
                               dict_=dict(res=res, 
                                          counts=counts,
                                          graphics=graphics,
                                          pagecnt=page_count,
                                          hash_=hash_)) 
            self.finish()
        self.queue.put((10, _on_finish))