def get_body_str(ret): body_str = u'' for key in keys: tmp = '#%s' % ret.get(key,'') body_str = safe_utf8(body_str) + safe_utf8(tmp) body_str = body_str[1:] return body_str
def __init__(self, data): ConfHelper.load(options.conf) data = safe_utf8(data) length = str(len(data)) bytes = struct.pack(length + 's', data) des_key = ConfHelper.SMS_CONF.des_key k = des(des_key, CBC, des_key, pad=None, padmode=PAD_PKCS5) self.result = k.encrypt(bytes)
def post(self): """Add an activity. """ try: author = self.get_argument('author', '') title = self.get_argument('title', '') begintime = self.get_argument('begintime', 0) endtime = self.get_argument('endtime', 0) html_name = self.get_argument('html_name', '') filename = '' if self.request.files: upload_file = self.request.files['fileupload'][0] filename = safe_utf8(upload_file['filename']) except Exception as e: logging.exception("[ADMIN] Script upload failed, exception:%s", e.args) status = ErrorCode.FAILED self.write_ret(status) return try: status = ErrorCode.SUCCESS # check filename whether contains illegal character if filename: if not check_filename(filename): status = ErrorCode.ACTIVITY_NAME_ILLEGAL self.write_ret(status) logging.info("[ADMIN] filename: %s, Message: %s", filename, ErrorCode.ERROR_MESSAGE[status]) return # check filename whether exists files = os.listdir(ACTIVITY_DIR_) for file in files: if file == filename: status = ErrorCode.ACTIVITY_EXISTED logging.info("[ADMIN] filename: %s, Message: %s", filename, ErrorCode.ERROR_MESSAGE[status]) self.write_ret(status) return file_path = os.path.join(ACTIVITY_DIR_, filename) logging.info("[ADMIN] Upload path: %s", file_path) output_file = open(file_path, 'w') output_file.write(upload_file['body']) output_file.close() self.db.execute("INSERT INTO T_ACTIVITY(title, filename," " begintime, endtime, author, html_name)" "VALUES(%s, %s, %s, %s, %s, %s)", title, filename, begintime, endtime, author, html_name) logging.info("[ADMIN] %s upload %s file success.", author, filename) self.write_ret(status) except Exception as e: status = ErrorCode.SERVER_BUSY logging.exception("[ADMIN] %s upload %s file failed. Exception:%s", author, filename, e.args) self.write_ret(status)
def send(to_email, content, cc_email=[], files=[], subject=''): """ @param to_email: list, emails to be sent to @param cc_email: list, emails to be copy to @param content: str, what to send @param files: list, the attachements to be sent @return response: str, { 'status':int 0:success,-1:failed. 'msgid': } """ logging.info("to_email=%s, cc_email=%s, content=%s", to_email, cc_email, content) #text = "From:%s\r\nTo:%s\r\nSubject:%s\r\n\r\n%s" #text = text % (ConfHelper.EMAIL_CONF.efrom, # email, # ConfHelper.EMAIL_CONF.subject, # content) #text = safe_utf8(text) if type(to_email) != list: to_email = [to_email,] msg = MIMEMultipart() msg['From'] = ConfHelper.EMAIL_CONF.efrom if subject: msg['Subject'] = subject else: msg['Subject'] = ConfHelper.EMAIL_CONF.subject msg['To'] = COMMASPACE.join(to_email) if cc_email: msg['Cc'] = COMMASPACE.join(cc_email) msg['Date'] = formatdate(localtime=True) msg.attach(MIMEText(safe_utf8(content), 'plain', 'utf-8')) for file in files: part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data part.set_payload(open(file, 'rb').read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) senderrs = None try: smtp = smtplib.SMTP() smtp.connect(ConfHelper.EMAIL_CONF.server) #smtp.ehlo() #smtp.starttls() smtp.login(ConfHelper.EMAIL_CONF.user, ConfHelper.EMAIL_CONF.password) senderrs = smtp.sendmail(ConfHelper.EMAIL_CONF.user, to_email+cc_email, msg.as_string()) smtp.quit() except Exception as e: senderrs = e.args[0] logging.error("Unknow error: %s", e.args) return senderrs
def push(pids, message): if pids is None: return ErrorCode.SUCCESS alert = u'资讯推送' try: h = httplib2.Http() headers = {"Content-type": "application/x-www-form-urlencoded; charset=utf-8"} url = ConfHelper.OPENFIRE_CONF.ios_push_url num = 0 for pid in pids: data = DotDict(uid=pid, alert=safe_utf8(alert),#下拉列表推送消息title badge=1,#图标右上角消息条数提示 body=safe_utf8(message)) response, content = h.request(url, 'POST', body=urlencode(data), headers=headers) if response['status'] == '200': ret = json_decode(content) if ret['status'] == 0: num += 1 logging.info("Push to push server success! pid: %s", pid) else: logging.error("Push to push server failed! pid: %s, Message: %s", pid, ret['message']) else: logging.error("Send message to push server failed! response: %s", response) if num != len(pids): status = ErrorCode.FAILED return status else: status = ErrorCode.SUCCESS return status except Exception as e: logging.exception("[UWEB] Send message to push server failed. Exception: %s", e.args) status = ErrorCode.SERVER_BUSY return status
def send(mobile, content, nosign=0): """ @param mobile: send to whom @param content: what to send @param is_cmpp: whether use sms_cmpp @return response: str, { 'status':int 0:success,-1:failed. 'msgid': } status = ErrorCode.SUCCESS response = dict(status=status, message=ErrorCode.ERROR_MESSAGE[status], msgid=1111) response = json_encode(response) return response """ response = None f = None logging.info("[SMS] mobile=%s, content=%s, nosign:%s", mobile, content, nosign) try: content = safe_utf8(content) req = urllib2.Request(url=ConfHelper.SMS_CONF.sms_url, data=urlencode(dict(mobile=mobile, content=content, nosign=nosign))) f = urllib2.urlopen(req) response = f.read() except urllib2.URLError as e: logging.error("URLError: %s", e.args) except Exception as e: logging.error("Unknow error: %s", e.args) finally: if f: f.close() return response
def generate_file_name(self, file_name): if "MSIE" in self.request.headers['User-Agent']: file_name = quote(safe_utf8(file_name)) return '-'.join((file_name, strftime("%Y%m%d")))
def generate_file_name(self, file_name): # NOTE: special handlings for IE. if "MSIE" in self.request.headers['User-Agent']: file_name = urllib.quote(safe_utf8(file_name)) return '-'.join((file_name, strftime("%Y%m%d")))
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)
def post(self): """Check the parameters of login and check whether or not prevent it. """ login = self.get_argument('username', '') password = self.get_argument('password', '') captcha = self.get_argument('captcha', '') # NOTE: Get captchahash from cookie captchahash = self.get_secure_cookie("captchahash") # must check username and password avoid sql injection. if not login.isalnum(): self.render("login.html", username="", password="", message_captcha=None, message=ErrorCode.LOGIN_FAILED) return if not (check_sql_injection(login) and check_sql_injection(password)): self.render("login.html", username="", password="", message_captcha=None, message=ErrorCode.LOGIN_FAILED) return # check the captcha(hash) m = hashlib.md5() m.update(captcha.lower()) hash_ = m.hexdigest() if hash_.lower() != captchahash.lower(): self.render("login.html", username=login, password='', message=None, message_captcha=ErrorCode.WRONG_CAPTCHA) return # check username and password r = self.db.get("SELECT id, name, type FROM T_ADMINISTRATOR" " WHERE login = %s" " AND password = password(%s)" " AND valid = %s", login, password, XXT.VALID.VALID) if r: self.__log(r.id) self.bookkeep(dict(id=r.id, session_id=uuid.uuid4().hex), quote(safe_utf8(r.name))) # update the privilege_area for current user.(through BaseMixin) key = self.get_area_memcache_key(r.id) areas = self.get_privilege_area(r.id) self.redis.setvalue(key, areas) self.clear_cookie('captchahash') self.redirect(self.get_argument("next", "/")) else: self.render("login.html", username=login, password='', message_captcha=None, message=ErrorCode.LOGIN_FAILED)
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)
def post(self): try: upload_file = self.request.files['fileupload'][0] except Exception as e: logging.info("[LOG] Script upload failed, exception:%s", e.args) global MESSAGE MESSAGE = '获取不到文件' self.redirect("/uploadluascript") return try: author = self.get_current_user() # check version records = self.acbdb.query("SELECT * " " FROM T_SCRIPT" " ORDER BY id DESC") version_list = [record.version for record in records] versionname = self.get_argument('versionname', '') if versionname in version_list: global MESSAGE MESSAGE = '该版本号已存在' logging.info("[LOG] Message: %s", MESSAGE) self.redirect("/uploadluascript") return # check filename whether contains illegal character filename = safe_utf8(upload_file['filename']) if not check_filename(filename): global MESSAGE MESSAGE = '文件名只能包含字母、数字、下划线、点' logging.info("[LOG] Message: %s", MESSAGE) self.redirect("/uploadluascript") return # check filename whether exists timestamp = int(time.time()) localtime = time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime(timestamp)) files = os.listdir(DOWNLOAD_DIR_) for file in files: if file == filename: global MESSAGE MESSAGE = '文件已经存在,请先删除' self.redirect("/uploadluascript") return self.acbdb.execute("INSERT INTO T_SCRIPT(version, filename, timestamp, author)" "VALUES(%s, %s, %s, %s)", versionname, filename, timestamp, author) file_path = os.path.join(DOWNLOAD_DIR_, filename) logging.info("[LOG] Upload path: %s", file_path) output_file = open(file_path, 'w') output_file.write(upload_file['body']) output_file.close() except Exception as e: logging.info("[LOG] %s upload %s file fail at the time of %s Exception:%s", author, filename, localtime, e.args) else: logging.info("[LOG] %s upload %s file success at the time of %s", author, filename, localtime) self.redirect("/uploadluascript")
def push_to_ios(category, tid, t_alias, location, ios_id, ios_badge, region_id=None): """Push info fo IOS by the means of ANPS @param: category, tid, t_alias, location, ios_id, ios_bagde """ try: h = httplib2.Http(timeout=20) # 1: format alert CATEGORY = {2:u'电量告警', 3:u'震动告警', 4:u'移动告警', 5:u'SOS', 6:u'通讯异常', 7:u'进入围栏', 8:u'离开围栏', 9:u'断电告警' } if not CATEGORY.get(category, None): logging.info("Invalid category, drop it. category: %s", category) return alert = u"您的定位器 “%s” 产生了%s" % (t_alias, CATEGORY[category]) # 2: format body ret = DotDict(tid=tid, category=category, longitude=location.lon, latitude=location.lat, clongitude=location.cLon, clatitude=location.cLat, name=location.name if location.name else '', timestamp=location.timestamp, speed=float(location.speed), degree=float(location.degree), type=location.type, alias=t_alias, pbat=location.pbat, comment=location.comment, region_id=region_id if region_id else -1) keys = ['tid', 'category', 'latitude', 'longitude', 'clatitude', 'clongitude', 'name', 'timestamp', 'speed', 'degree', 'type', 'alias', 'pbat', 'comment', 'region_id'] def get_body_str(ret): body_str = u'' for key in keys: tmp = '#%s' % ret.get(key,'') body_str = safe_utf8(body_str) + safe_utf8(tmp) body_str = body_str[1:] return body_str body_str = get_body_str(ret) #NOTE: here, the maxsize is 180, it bigger than it, set ret.name '' if len(body_str) > UWEB.IOS_MAX_SIZE: logging.info("Push body is bigger than: %s, set name ''", UWEB.IOS_MAX_SIZE) ret.name='' body_str = get_body_str(ret) headers = {"Content-type": "application/x-www-form-urlencoded; charset=utf-8"} url = ConfHelper.OPENFIRE_CONF.ios_push_url data = DotDict(uid=ios_id, alert=safe_utf8(alert), badge=ios_badge, body=safe_utf8(body_str)) response, content = h.request(url, 'POST', body=urlencode(data), headers=headers) if response['status'] == '200': ret = json_decode(content) if ret['status'] == 0: logging.info("Push to IOS success! Message: %s", ret['message']) else: logging.error("Push to IOS failed! Message: %s", ret['message']) else: logging.error("Push to IOS failed! response: %s", response) except Exception as e: logging.exception("Push to IOS failed. Exception: %s", e.args)
def post(self): try: author = self.get_argument("author", "") versioncode = self.get_argument("versioncode", "") versionname = self.get_argument("versionname", "") versioninfo = self.get_argument("versioninfo", "") updatetime = self.get_argument("updatetime", "") category = int(self.get_argument("category", "")) filesize = self.get_argument("filesize", "") upload_file = self.request.files["fileupload"][0] filename = safe_utf8(upload_file["filename"]) except Exception as e: logging.exception("[ADMIN] Apk upload failed, exception:%s", e.args) status = ErrorCode.FAILED self.write_ret(status) return try: status = ErrorCode.SUCCESS if not check_filename(filename): status = ErrorCode.ACTIVITY_NAME_ILLEGAL self.write_ret(status) logging.info("[ADMIN] filename: %s, Message: %s", filename, ErrorCode.ERROR_MESSAGE[status]) return if category == UWEB.APK_TYPE.YDWS: # 1 filename_ = "ACB_%s.apk" elif category == UWEB.APK_TYPE.YDWQ_MONITOR: # 2 filename_ = "YDWQ_monitor_%s.apk" elif category == UWEB.APK_TYPE.YDWQ_MONITORED: # 3 filename_ = "YDWQ_monitored_%s.apk" elif category == UWEB.APK_TYPE.YDWS_ANJIETONG: # 4 filename_ = "YDWS_anjietong_%s.apk" filename = filename_ % versionname self.db.execute( "INSERT INTO T_APK(versioncode, versionname, versioninfo," " updatetime, filesize, author, category, filename) " " VALUES(%s, %s, %s, %s, %s, %s, %s, %s)", versioncode, versionname, versioninfo, updatetime, filesize, author, category, filename, ) file_path = os.path.join(APK_DIR_, filename) logging.info("[ADMIN] Upload path: %s", file_path) output_file = open(file_path, "w") output_file.write(upload_file["body"]) output_file.close() logging.info("[ADMIN] %s upload %s file success.", author, filename) self.write_ret(status) except Exception as e: status = ErrorCode.SERVER_BUSY logging.exception("[ADMIN] %s upload %s file failed. Exception:%s", author, filename, e.args) self.write_ret(status)
def __init__(self, str): hash_object = hashlib.md5() hash_object.update(safe_utf8(str)) self.result = hash_object.hexdigest()