Esempio n. 1
0
    def post(self):
        """Turn on buletooth."""
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            tid = data.get('tid', None)
            tids = data.get('tids', None)
            self.check_tid(tid)
            logging.info("[BLUETOOTH] kqly request: %s, uid: %s, tids: %s",
                         data, self.current_user.uid, 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:
            tids = str_to_list(tids)
            tids = tids if tids else [self.current_user.tid, ]
            tids = [str(t) for t in tids]          
            kqly(self.db, self.redis, tids)
            self.write_ret(status)
        except Exception as e:
            logging.exception("[BLUETOOTH] Kqly failed. uid: %s, tid: %s, Exception: %s. ",
                              self.current_user.uid, self.current_user.tid, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
Esempio n. 2
0
        def wrapper(self, *args, **kwargs):
            province_ids = map(int, str_to_list(self.get_argument('province_id', '')))
            city_ids = map(int, str_to_list(self.get_argument('city_id', '')))
            group_ids = map(int, str_to_list(self.get_argument('group', '')))

            is_permitted = _internal_check(self.current_user.id,
                                           province_ids,
                                           city_ids,
                                           group_ids,
                                           self.db)
            if is_permitted:
                return method(self, *args, **kwargs)
            else:
                self.render(error_page,
                            error=True,
                            message=ErrorCode.PERMISSION_DENIED)
Esempio n. 3
0
File: line.py Progetto: jcsy521/ydws
    def delete(self):
        """Delete a line.
        """
        try:
            delete_ids = map(int, str_to_list(self.get_argument('ids', None)))
            logging.info("[UWEB] delete line: %s, cid: %s", 
                         delete_ids, self.current_user.cid)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            self.write_ret(status)
            return

        try:
            status = ErrorCode.SUCCESS
            self.db.execute("DELETE FROM T_LINE_PASSENGER WHERE line_id IN %s",
                            tuple(delete_ids + DUMMY_IDS)) 
            self.db.execute("DELETE FROM T_LINE WHERE id IN %s",
                            tuple(delete_ids + DUMMY_IDS)) 

            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] cid: %s delete line failed. Exception: %s", 
                              self.current_user.cid, e.args) 
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
Esempio n. 4
0
    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)
Esempio n. 5
0
    def delete(self):
        """Delete region.
        """
        try:
            delete_ids = map(int, str_to_list(self.get_argument('ids', None)))
            logging.info("[UWEB] delete region: %s, cid: %s", 
                         delete_ids, self.current_user.cid)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            self.write_ret(status)

        try:
            status = ErrorCode.SUCCESS
            delete_region(delete_ids, self.db, self.redis)           
            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] cid: %s delete region failed. Exception: %s", 
                              self.current_user.cid, e.args) 
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
Esempio n. 6
0
File: apk.py Progetto: jcsy521/ydws
    def delete(self):
        """Delete activity.  
        """
        try:
            delete_ids = map(int, str_to_list(self.get_argument("ids", None)))
            logging.info("[ADMIN] delete apk: %s", delete_ids)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.exception("[ADMIN] data format illegal. Exception: %s", e.args)
            self.write_ret(status)
            return

        try:
            status = ErrorCode.SUCCESS
            self.db.execute("DELETE FROM T_APK WHERE id IN %s", tuple(delete_ids + DUMMY_IDS))
            self.write_ret(status)
        except Exception as e:
            status = ErrorCode.SERVER_BUSY
            logging.exception("[ADMIN] delete apk failed. Exception: %s", e.args)
            self.write_ret(status)
Esempio n. 7
0
    def delete(self):
        """Delete single.
        """
        status = ErrorCode.SUCCESS
        try:
            delete_ids = map(int, str_to_list(self.get_argument("single_ids", None)))
            logging.info("[UWEB] Delete single: %s, cid: %s", delete_ids, self.current_user.cid)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.exception("[UWEB] Invalid data format. Exception: %s", e.args)
            self.write_ret(status)
            return

        try:
            delete_single(delete_ids, self.db, self.redis)
            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] Delete single failed. cid: %s, Exception: %s", self.current_user.cid, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
Esempio n. 8
0
    def delete(self):
        status = ErrorCode.SUCCESS
        try:
            delete_ids = map(int, str_to_list(self.get_argument('ids', None)))
        except Exception as e:
            logging.info("[LOG] Feedback illegal data format. Exception: %s", 
                         e.args)
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            self.write_ret(status)

        try: 
            self.acbdb.execute("DELETE FROM T_FEEDBACK"
                               "  WHERE id IN %s",
                               tuple(delete_ids + DUMMY_IDS))
            self.write_ret(status)
        except Exception as e: 
            logging.exception("[LOG] Feedback query failed. Exception: %s", 
                              e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
Esempio n. 9
0
    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)
Esempio n. 10
0
    def delete(self):
        """Delete announcement. 
        """
        status = ErrorCode.SUCCESS
        try:
            delete_ids = map(int, str_to_list(self.get_argument('ids', None)))
            logging.info("[UWEB] Delete announcement: %s",
                         delete_ids)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.exception(
                "[UWEB] data format illegal. Exception: %s", e.args)
            self.write_ret(status)
            return

        try:
            self.db.execute("DELETE FROM T_ANNOUNCEMENT_LOG WHERE id IN %s",
                            tuple(delete_ids + DUMMY_IDS))
            self.write_ret(status)
        except Exception as e:
            status = ErrorCode.SERVER_BUSY
            logging.exception("[UWEB] Delete announcement failed. Exception: %s",
                              e.args)
            self.write_ret(status)
Esempio n. 11
0
    def post(self):
        """Provide some statistics about terminals.
        """
        status = ErrorCode.SUCCESS
        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
            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
            # no checks for enterprise
            if self.current_user.cid != UWEB.DUMMY_CID:
                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'
                if self.current_user.oid == UWEB.DUMMY_OID:  # enterprise
                    terminals = QueryHelper.get_all_terminals_by_cid(
                        self.current_user.cid, self.db)
                else:  # operator
                    terminals = QueryHelper.get_all_terminals_by_oid(
                        self.current_user.oid, 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 = []
                dis_count = Decimal()
                for item, tid in enumerate(tids):
                    seq = item + 1
                    # NOTE: It's amazing: In database, distance's type is long. sum(distance)'s type is Decimal
                    mileage_log = self.db.get("SELECT SUM(distance) AS distance"
                                              " FROM T_MILEAGE_LOG"
                                              "  WHERE tid = %s"
                                              "  AND (timestamp BETWEEN %s AND %s)",
                                              tid, start_time,
                                              end_time + 60 * 60 * 24)
                    if mileage_log and mileage_log['distance']:
                        dis_sum = '%0.1f' % (mileage_log['distance'] / 1000,)
                    else:
                        dis_sum = 0

                    alias = QueryHelper.get_alias_by_tid(
                        tid, self.redis, self.db)
                    dct = dict(seq=seq,
                               alias=alias,
                               distance=float(dis_sum))
                    reports.append(dct)
                    dis_count += Decimal(dis_sum)
                counts = [float(dis_count), ]

                # 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, counts), 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]
                # end_time must be bigger than start_time
                delta = end_time - 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

                res = []
                graphics = []
                counts = []
                dis_sum = Decimal()
                current_time = int(time.time())

                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)

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

                    mileage_log = self.db.get("SELECT distance FROM T_MILEAGE_LOG"
                                              "  WHERE tid = %s"
                                              "  AND timestamp = %s",
                                              tid, end_time_)
                    distance = mileage_log['distance'] if mileage_log else 0

                    # meter --> km
                    distance = '%0.1f' % (Decimal(distance) / 1000,)
                    if float(distance) == 0:
                        distance = 0

                    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))
Esempio n. 12
0
    def post(self):
        """Turn on tracing."""
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            tid = data.get('tid', None)
            tids = data.get('tids', None)
            flag = int(data.get('flag', 1))
            # check tid whether exist in request and update current_user
            self.check_tid(tid)
            logging.info("[UWEB] track LQ request: %s, "
                         "  uid: %s, tid: %s, tids: %s, flag: %s",
                         data, self.current_user.uid, tid, tids, flag)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            self.write_ret(status)
            return

        try:
            tids = str_to_list(tids)
            tids = tids if tids else [self.current_user.tid, ]
            tids = [str(tid) for tid in tids]

            if int(flag) == 1:
                for tid in tids:
                    # NOTE: just send lqgz temporary
                    terminal = QueryHelper.get_terminal_by_tid(tid, self.db)
                    lqgz_key = get_lqgz_key(tid)
                    lqgz_value = self.redis.getvalue(lqgz_key)
                    lqgz_interval_key = get_lqgz_interval_key(tid)
                    if not lqgz_value:
                        interval = 30  # in minute
                        biz_type = QueryHelper.get_biz_type_by_tmobile(
                            terminal.mobile, self.db)
                        if biz_type != UWEB.BIZ_TYPE.YDWS:
                            self.write_ret(status)
                            return
                        sms = SMSCode.SMS_LQGZ % interval
                        SMSHelper.send_to_terminal(terminal.mobile, sms)
                        self.redis.setvalue(
                            lqgz_key, True, SMS.LQGZ_SMS_INTERVAL)
                        self.redis.setvalue(
                            lqgz_interval_key, True, SMS.LQGZ_INTERVAL * 2)
                    # END

                    track_key = get_track_key(tid)
                    track = self.redis.get(track_key)
                    logging.info("[UWEB] Get track: %s from redis", track)
                    if track and int(track) == 1:
                        # turn on track already
                        logging.info(
                            "[UWEB] Terminal: %s turn on track already.", tid)
                    else:
                        self.db.execute("UPDATE T_TERMINAL_INFO SET track = %s"
                                        "  WHERE tid = %s",
                                        flag, tid)
                        self.redis.setvalue(track_key, 1, UWEB.TRACK_INTERVAL)
                        sessionID_key = get_terminal_sessionID_key(tid)
                        self.redis.delete(sessionID_key)
            self.write_ret(status)
        except Exception as e:
            logging.exception("[UWEB] uid: %s, tid: %s send lqgz failed. Exception: %s. ",
                              self.current_user.uid, self.current_user.tid, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
Esempio n. 13
0
    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))
Esempio n. 14
0
    def post(self):
        """Retrive various attendance.
        """
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))

            mobile = data.get('mobile', None)
            mobiles = str_to_list(mobile)

            if not mobiles:
                terminals = self.db.query("SELECT tmobile FROM V_TERMINAL"
                                          "  where cid = %s", 
                                          self.current_user.cid)
                mobiles = [str(terminal['tmobile']) for terminal in terminals]
            logging.info("[UWEB] attendance request: %s, cid: %s", 
                         data, self.current_user.cid)
        except Exception as e:
            status = ErrorCode.ILLEGAL_DATA_FORMAT
            logging.exception("[UWEB] Invalid data format. Exception: %s",
                              e.args)
            self.write_ret(status)
            return

        try:
            page_size = int(data.get('pagesize', UWEB.LIMIT.PAGE_SIZE))
            page_number = int(data.pagenum)
            page_count = int(data.pagecnt)
            start_time = data.start_time
            end_time = data.end_time

            # we need return the event count to GUI at first time query
            if page_count == -1:
                sql = ("SELECT COUNT(*) as count FROM V_ATTENDANCE" 
                       "  WHERE mobile IN %s " 
                       "    AND (timestamp BETWEEN %s AND %s)") 

                sql = sql % (tuple(mobiles + DUMMY_IDS_STR), start_time, end_time)
                res = self.db.get(sql)
                event_count = res.count
                d, m = divmod(event_count, page_size)
                page_count = (d + 1) if m else d

            sql = ("SELECT mobile as tid, mobile, clatitude, clongitude," 
                   "  timestamp, name, type, speed, degree,"
                   "  locate_error"  
                   "  FROM V_ATTENDANCE"
                   "  WHERE mobile IN %s"
                   "    AND (timestamp BETWEEN %s AND %s)"
                   "  ORDER BY timestamp DESC"
                   "  LIMIT %s, %s") 
            sql = sql % (tuple(mobiles + DUMMY_IDS_STR), start_time, end_time, page_number * page_size, page_size)

            res = self.db.query(sql)
                
            # change the type form decimal to float.
            for r in res:
                r['alias'] = QueryHelper.get_alias_by_tid(r['tid'], self.redis, self.db)
                r['name'] = r['name'] if r['name'] is not None else u''
                r['degree'] = float(r['degree'])
                r['speed'] = float(r['speed'])
                r['comment'] = ''
                
            self.write_ret(status,
                           dict_=DotDict(res=res,
                                         pagecnt=page_count))
        except Exception as e:
            status = ErrorCode.SERVER_BUSY
            logging.exception("[UWEB] cid:%s get attendance info failed. Exception: %s",
                              self.current_user.cid, e.args)
            self.write_ret(status)
Esempio n. 15
0
    def post(self):
        """Create a administrator.
        """
        # create
        fields = DotDict(corporation="",
                         name="",
                         login="",
                         password="",
                         mobile="",
                         phone="",
                         email="",
                         valid="",
                         source_id="")

        list_inject = ['name', 'password', 'mobile', 'phone']
        for key in list_inject:
            v = self.get_argument(key, '')
            # if not check_sql_injection(v):
            #    self.get()
            #    return
        for key in fields.iterkeys():
            fields[key] = self.get_argument(key, '')

        fields.source_id = fields.source_id if fields.source_id else 5
        administrator_id = self.db.execute("INSERT INTO T_ADMINISTRATOR (login, password, "
                                           " name, mobile, phone, email, "
                                           " corporation, source_id, valid, type)"
                                           "  VALUES (%s, password(%s), %s, %s, "
                                           "          %s, %s, %s, %s, %s, %s)",
                                           fields.login, fields.password,
                                           fields.name, fields.mobile,
                                           fields.phone, fields.email,
                                           fields.corporation,
                                           fields.source_id, fields.valid, 2)
        # insert privilege
        privileges = map(int, self.get_arguments('privileges'))
        if privileges:
            self.db.executemany("INSERT INTO T_PRIVILEGE"
                                "  VALUES (%s, %s)",
                                [(administrator_id, id)
                                 for id in privileges])

        cities = map(int, str_to_list(self.get_argument('cities', '')))
        key = self.get_area_memcache_key(administrator_id)
        if len(cities) == 1 and cities[0] == 0:
            self.db.execute("INSERT INTO T_AREA_PRIVILEGE"
                            "  VALUES(NULL, %s, %s, %s)",
                            administrator_id, AREA.CATEGORY.PROVINCE,
                            AREA.PROVINCE.LIAONING)
            cities = self.db.query("SELECT city_id, city_name FROM T_HLR_CITY"
                                   "  WHERE province_id = %s",
                                   AREA.PROVINCE.LIAONING)
            self.redis.setvalue(key, cities)
        else:
            # put privilege_areas into memcached
            areas = self.get_area(cities)
            self.redis.setvalue(key, areas)

            cities = self.db.query("SELECT region_code FROM T_HLR_CITY"
                                   "  WHERE city_id IN %s",
                                   tuple(cities + DUMMY_IDS))
            cids = [c.region_code for c in cities]

            for cid in cids:
                self.db.execute("INSERT INTO T_AREA_PRIVILEGE"
                                "  VALUES (NULL, %s, %s, %s)",
                                administrator_id, AREA.CATEGORY.CITY, cid)

        self.redirect("/administrator/list/%s" % administrator_id)
Esempio n. 16
0
    def post(self, administrator_id):
        """Edit the administrator.
        """
        is_self = (administrator_id == self.current_user.id)

        # update basic info
        fields = DotDict(corporation="corporation = %s",
                         name="name = %s",
                         mobile="mobile = %s",
                         phone="phone = %s",
                         email="email = %s",
                         valid="valid = %s",
                         source_id="source_id = %s"
                         )
        list_inject = ['corporation', 'name', 'mobile', 'phone']
        for key in list_inject:
            v = self.get_argument(key, '')
            # if not check_sql_injection(v):
            #   self.get(administrator_id)
            #   return
        if is_self:
            del fields['valid']
            del fields['source_id']

            self.bookkeep(dict(id=self.current_user.id,
                               session_id=self.current_user.session_id),
                          quote(safe_utf8(self.get_argument('name', u""))))

        data = [self.get_argument(key, '')
                for key in fields.iterkeys()] + [administrator_id]

        set_clause = ','.join([v for v in fields.itervalues()])

        self.db.execute("UPDATE T_ADMINISTRATOR"
                        " SET " + set_clause +
                        "  WHERE id = %s",
                        *data)

        if not is_self:
            # update privilege
            privileges = map(int, self.get_arguments('privileges'))
            if privileges:
                rs = self.db.query("SELECT privilege_group_id FROM T_PRIVILEGE"
                                   "  WHERE administrator_id = %s",
                                   administrator_id)
                ids = [r.privilege_group_id for r in rs]
                new_ids = list(set(privileges) - set(ids))
                old_ids = list(set(ids) - set(privileges))
                # clean up old ids
                self.db.execute("DELETE FROM T_PRIVILEGE"
                                "  WHERE administrator_id = %s"
                                "    AND privilege_group_id in %s",
                                administrator_id, tuple(old_ids + DUMMY_IDS))
                # insert new ids
                self.db.executemany("INSERT INTO T_PRIVILEGE"
                                    "  VALUES (%s, %s)",
                                    [(administrator_id, priv)
                                     for priv in new_ids])

            key = self.get_area_memcache_key(administrator_id)
            cities = [int(i)
                      for i in str_to_list(self.get_argument('cities', ''))]
            if len(cities) == 1 and int(cities[0]) == 0:
                self.db.execute("DELETE FROM T_AREA_PRIVILEGE"
                                "  WHERE administrator_id = %s",
                                administrator_id)
                self.db.execute("INSERT INTO T_AREA_PRIVILEGE"
                                "  VALUES(NULL, %s, %s, %s)",
                                administrator_id, AREA.CATEGORY.PROVINCE,
                                AREA.PROVINCE.LIAONING)
                cities = self.db.query("SELECT city_id, city_name FROM T_HLR_CITY"
                                       "  WHERE province_id = %s",
                                       AREA.PROVINCE.LIAONING)
                self.redis.setvalue(key, cities)
            else:
                if cities:
                    areas = self.get_area(cities)
                    self.redis.setvalue(key, areas)

                    cities = self.db.query("SELECT region_code FROM T_HLR_CITY"
                                           "  WHERE city_id IN %s",
                                           tuple(cities + DUMMY_IDS))
                    cids = [c.region_code for c in cities]
                    rs = self.db.query("SELECT area_id FROM T_AREA_PRIVILEGE"
                                       "  WHERE category = %s"
                                       "    AND administrator_id = %s",
                                       AREA.CATEGORY.CITY, administrator_id)
                    ids = [r.area_id for r in rs]
                    new_ids = list(set(cids) - set(ids))
                    old_ids = list(set(ids) - set(cids))
                    # clean up old ids
                    self.db.execute("DELETE FROM T_AREA_PRIVILEGE"
                                    "  WHERE administrator_id = %s"
                                    "    AND category = %s"
                                    "    AND area_id in %s",
                                    administrator_id, AREA.CATEGORY.CITY,
                                    tuple(old_ids + DUMMY_IDS))
                    self.db.execute("DELETE FROM T_AREA_PRIVILEGE"
                                    "  WHERE administrator_id = %s"
                                    "    AND category = %s",
                                    administrator_id, AREA.CATEGORY.PROVINCE)
                    # insert new ids
                    self.db.executemany("INSERT INTO T_AREA_PRIVILEGE"
                                        "  VALUES (NULL, %s, %s, %s)",
                                        [(administrator_id, AREA.CATEGORY.CITY, id)
                                         for id in new_ids])
                else:
                    self.db.execute("DELETE FROM T_AREA_PRIVILEGE"
                                    "  WHERE administrator_id = %s",
                                    administrator_id)
                    self.redis.delete(key)

        self.redirect("/administrator/list/%s" % administrator_id)
Esempio n. 17
0
    def post(self):
        """Retrive various event.
        """
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))

            tid = data.get('tid', None)

            tids = data.get('tids', None)
            tids = str_to_list(tids)

            if not tids:
                tids = [tid, ] if tid else []
            tids = [str(t) for t in tids]

            if not tid:
                tid = tids[0] if len(tids) > 0 else ''

            # check tid whether exist in request and update current_user
            self.check_tid(tid)
            logging.info("[UWEB] Event 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:
            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

            page_size = int(data.get('pagesize', UWEB.LIMIT.PAGE_SIZE))
            category = data.get('category', None)
            categories = data.get('categories', None)
            page_number = int(data.pagenum)
            page_count = int(data.pagecnt)
            start_time = data.start_time
            end_time = data.end_time

            # NOTE: all catgories
            all_categories = [2,  # powerlow
                              3,  # illegalshake
                              4,  # illegalmove
                              5,  # sos
                              6,  # hearbeat lost
                              7,  # region enter
                              8,  # retion out
                              9,  # power off
                              10,  # stop
                              11,  # speed_limit
                              ]

            if category is not None:
                if int(category) == -1:
                    categories = all_categories
                else:
                    categories = [int(category), ]
            elif categories:
                if int(categories[0]) == -1:
                    categories = all_categories
                else:
                    categories = [int(c) for c in categories]

            # NOTE: for individual: the interval between start_time and end_time is one week;
            # for enterprise: no need to check time interval
            if self.current_user.cid != UWEB.DUMMY_CID:
                hide_lst = [5]  # enterprise: no sos
            else:  # individual: no stop
                hide_lst = [5, 10, 11]
                if (int(end_time) - int(start_time)) > UWEB.QUERY_INTERVAL:
                    self.write_ret(ErrorCode.QUERY_INTERVAL_EXCESS)
                    return

            # we need return the event count to GUI at first time query
            if page_count == -1:
                sql = ("SELECT COUNT(*) as count FROM V_EVENT"
                       "  WHERE tid IN %s " +
                       "  AND category  IN %s" +
                       "    AND (timestamp BETWEEN %s AND %s)")\
                    % (tuple(tids + DUMMY_IDS_STR), tuple(list(set(categories) - set(hide_lst)) + DUMMY_IDS), start_time, end_time)
                res = self.db.get(sql)
                event_count = res.count
                d, m = divmod(event_count, page_size)
                page_count = (d + 1) if m else d

            sql = ("SELECT tid, latitude, longitude, clatitude, clongitude,"
                   "  timestamp, name, type, speed, degree,"
                   "  category, pbat, terminal_type, fobid, rid, locate_error"
                   "  FROM V_EVENT"
                   "  WHERE tid IN %s"
                   "    AND (timestamp BETWEEN %s AND %s)"
                   "    AND category IN %s"
                   "  ORDER BY timestamp DESC"
                   "  LIMIT %s, %s") %\
                  (tuple(tids + DUMMY_IDS_STR), start_time, end_time,
                   tuple(list(set(categories) - set(hide_lst)) + DUMMY_IDS),  page_number * page_size, page_size)
            events = self.db.query(sql)

            alias_dict = {}
            for tid in tids:
                terminal_info_key = get_terminal_info_key(tid)
                terminal_info = self.redis.getvalue(terminal_info_key)
                alias_dict[tid] = terminal_info['alias'] if terminal_info[
                    'alias'] else terminal_info['mobile']

            # Adjust the fields in events.
            for event in events:
                event['alias'] = alias_dict[event['tid']]
                event['pbat'] = event['pbat'] if event[
                    'pbat'] is not None else 0
                event['fobid'] = event['fobid'] if event[
                    'fobid'] is not None else u''
                event['name'] = event['name'] if event[
                    'name'] is not None else u''
                event['degree'] = float(event['degree'])
                event['speed'] = float(event['speed'])
                event['comment'] = ''
                if event['category'] == EVENTER.CATEGORY.POWERLOW:
                    if event['terminal_type'] == '1':
                        if int(event['pbat']) == 100:
                            event['comment'] = ErrorCode.ERROR_MESSAGE[
                                ErrorCode.TRACKER_POWER_FULL]
                        elif int(event['pbat']) <= 5:
                            event['comment'] = ErrorCode.ERROR_MESSAGE[
                                ErrorCode.TRACKER_POWER_OFF]
                        else:
                            event['comment'] = (
                                ErrorCode.ERROR_MESSAGE[ErrorCode.TRACKER_POWER_LOW]) % event['pbat']
                    else:
                        event['comment'] = ErrorCode.ERROR_MESSAGE[
                            ErrorCode.FOB_POWER_LOW] % event['fobid']

                if event['category'] in [EVENTER.CATEGORY.REGION_ENTER, EVENTER.CATEGORY.REGION_OUT]:
                    region = self.db.get("SELECT name AS region_name"
                                         "  FROM T_REGION"
                                         "  WHERE id = %s",
                                         event.rid)

                    region_name = safe_unicode(
                        region.region_name) if region else u''
                    event['comment'] = u'围栏名:' + region_name

            self.write_ret(status,
                           dict_=DotDict(events=events,
                                         pagecnt=page_count))
        except Exception as e:
            logging.exception("[UWEB] uid:%s, tid:%s get alarm info failed. Exception: %s",
                              self.current_user.uid, self.current_user.tid, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)
Esempio n. 18
0
File: sms.py Progetto: jcsy521/ydws
    def prepare_data(self, hash_):

        mem_key = self.get_memcache_key(hash_)

        data = self.redis.getvalue(mem_key)
        if data:
            return data

        provinces = self.get_argument('province_id', None)
        cities = self.get_argument('city_id', None)
        start_time = int(self.get_argument('start_time', None))
        end_time = int(self.get_argument('end_time', None))
        group = self.get_argument('group', None)
        user_name = self.get_argument('user_name', None)
        mobile = self.get_argument('mobile', None)

        #if user_name and  (not check_sql_injection(user_name)):
        #    return [], [start_time, end_time]
        #if mobile  and  (not check_sql_injection(mobile)):
        #    return [], [start_time, end_time]
            
        # the result of today is inavaliable
        d = datetime.datetime.fromtimestamp(time.time())
        t = datetime.datetime.combine(datetime.date(d.year,d.month, d.day), datetime.time(0, 0, 0))
        today_ = int(time.mktime(t.timetuple())) * 1000
        if start_time >= today_:
            return [], [start_time, end_time]

        results = []
        if not (cities or provinces):
            return results, [start_time, end_time]
        elif not cities:
            provinces = str_to_list(provinces)
            cities = city_list(provinces, self.db)
        else:
            cities = str_to_list(cities)

        cities = [int(c) for c in cities]
        cs = self.db.query("SELECT DISTINCT region_code FROM T_HLR_CITY"
                           "  WHERE city_id IN %s",
                           tuple(cities + DUMMY_IDS))
        citylist = [c.region_code for c in cs]

        query_term = {'city_id':{'$in':citylist},
                      'fetchtime':{'$gte':start_time, '$lte':end_time},
                      'group_id': None,
                      'user_name': None,
                      'mobile': None}
        for term in ['user_name', 'mobile']:
            v = self.get_argument(term, None)
            if v:
                query_term[term] = {'$regex': '\S*'+v+'\S*'}
            else:
                query_term.pop(term)
        if group: 
            query_term['group_id'] = str(self.get_argument('group'))
        else:
            query_term.pop('group_id')

        display_term = {'province':1, 'city':1, 'group_name':1,
                        'user_name':1, 'mobile':1, '_id':0}

        res = []
        try:
            mobiles = self.collection.find(query_term, {'mobile':1}).distinct('mobile')
            if mobiles:
                for m in mobiles:
                    count = self.collection.find({'mobile':m,
                        'fetchtime':{'$gte':start_time, '$lte':end_time}}).count()
                    r = self.collection.find_one({'mobile':m,
                        'fetchtime':{'$gte':start_time, '$lte':end_time}}, display_term)
                    r['count'] = count
                    res.append(r)
            if not res:
                ins = MSms()
                res = ins.retrieve(citylist, start_time, end_time)
                
        except:
            ins = MSmsMixin()
            res = ins.retrieve_mixin(citylist, start_time, end_time)
            res = ins.distinct(res)

        if user_name:
            p_name = re.compile(user_name)
        if mobile:
            p_mobile = re.compile(mobile)
        results = []
        for r in res:
            flag = True
            if group and r['group_id'] != group:
                flag &= False
            if user_name and not p_name.findall(r['user_name']):
                flag &= False
            if mobile and not p_mobile.findall(r['mobile']):
                flag &= False
            if flag:
                results.append(r)
      
        self.redis.setvalue(mem_key,(results, [start_time, end_time]), 
                           time=self.MEMCACHE_EXPIRY)
        return results, [start_time, end_time]
Esempio n. 19
0
    def prepare_data(self, hash_):
        """Associated with the post method.

        workflow:

        if get value according the hash:
            return value
        else:
            retrieve the db and return the result.
        """
        mem_key = self.get_memcache_key(hash_)
        
        data = self.redis.getvalue(mem_key)
        if data:
            return data

        # TODO: retrieve all the cities
        # HOW TO BEST PASS province and city?
        provinces = self.get_argument('province_id', None)
        cities = self.get_argument('city_id', None)
        start_time = int(self.get_argument('timestamp', None))
        end_time = end_of_month(start_time)
        d = date.fromtimestamp(start_time/1000)
        year = d.year
        month = d.month

        # only last six days of this month can retrieve results
        s_time = start_of_month(int(time.time())*1000)
        e_time = end_of_month(int(time.time())*1000)
        
        if start_time == s_time:
            # this month
            cal = date.today().timetuple()
            year = cal.tm_year
            month = cal.tm_mon
            day = cal.tm_mday
            maxdays = monthrange(year, month)[1]
            if maxdays - day > ADMIN.MONTH_RETRIEVE_DAYS:
                return [], start_time
        elif start_time > e_time:
            return [], start_time

        if cities is None:
            provinces = str_to_list(provinces)
            cities = city_list(provinces, self.db)
        else:
            cities = str_to_list(cities)

        cities = [int(c) for c in cities]
        cs = self.db.query("SELECT DISTINCT region_code FROM T_HLR_CITY"
                           "  WHERE city_id IN %s",
                           tuple(cities + DUMMY_IDS))
        citylist = [int(c.region_code) for c in cs]

        query_term = {'city_id': {'$in': citylist}, 'year': year, 'month': month}
        try:
            results = list(self.collection.find(query_term, {'_id':0}))
            if not results:
                ins = MLocation()
                results = ins.retrieve(citylist, start_time, end_time)
        except:
            ins = MLocationMixin()
            results = ins.retrieve_mixin(citylist, start_time, end_time)

        self.redis.setvalue(mem_key, (results, start_time), 
                            time=self.MEMCACHE_EXPIRY)
        return results, start_time
Esempio n. 20
0
    def post(self):
        """Provide some statistics about terminals.
        """
        status = ErrorCode.SUCCESS
        try:
            data = DotDict(json_decode(self.request.body))
            logging.info("[UWEB] event statistic 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:
            res = []
            page_size = UWEB.LIMIT.PAGE_SIZE
            page_number = int(data.pagenum)
            page_count = int(data.pagecnt)
            start_time = data.start_time
            end_time = data.end_time
            tids = str_to_list(data.tids)
            # 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)
                return

            CATEGORY_DCT = DotDict(illegalmove=EVENTER.CATEGORY.ILLEGALMOVE,
                                   illegashake=EVENTER.CATEGORY.ILLEGALSHAKE,
                                   #sos=EVENTER.CATEGORY.EMERGENCY,
                                   heartbeat_lost=EVENTER.CATEGORY.HEARTBEAT_LOST, 
                                   powerlow=EVENTER.CATEGORY.POWERLOW)
            if page_count == -1:
                count = len(tids)
                d, m = divmod(count, page_size)
                page_count = (d + 1) if m else d


            for tid in tids: 
                res_item = {} 
                res_item['alias'] = QueryHelper.get_alias_by_tid(tid, self.redis, self.db)
                for key, category in CATEGORY_DCT.iteritems():
                     item = self.db.get("SELECT COUNT(*) as count FROM V_EVENT"
                                        "  WHERE tid = %s"
                                        "    AND (timestamp BETWEEN %s AND %s)"
                                        "    AND category = %s",
                                        tid, start_time, end_time, category)
                     res_item[key] = item.count
                res.append(res_item)

            # 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, res, time=UWEB.STATISTIC_INTERVAL)

            res = res[(page_number * page_size):((page_number+1) * page_size)]

            self.write_ret(status, 
                           dict_=DotDict(res=res,
                                         pagecnt=page_count,
                                         hash_=hash_))
        except Exception as e:
            logging.exception("[UWEB] event statistic, uid:%s, tid:%s  failed. Exception: %s",
                              self.current_user.uid, self.current_user.tid, e.args)
            status = ErrorCode.SERVER_BUSY
            self.write_ret(status)