def updateUserMobile(self, uid, pnum): m = mmysql() try: sql = 'SELECT pnum FROM z_user WHERE uid = %s;' % uid m.Q(sql) rs = m.fetchone() if not rs: return 'uid 对应的用户不存在' # 只有免注册的手机号才允许修改,开头是'200', '20', '300', '30' mobile = str(rs['pnum']) if mobile[:3] != self._PREFIX_ANDROID_OLD and mobile[:2] != self._PREFIX_ANDROID_NEW and mobile[:3] != self._PREFIX_IOS_OLD and mobile[:2] != self._PREFIX_IOS_NEW: return '不允许修改手机号' # 检查手机号是否已经存在 sql = 'SELECT * FROM z_user WHERE pnum = %s;' % pnum m.Q(sql) if m.fetchone(): return '新手机号已经被其他账号绑定' # 可以更改了 sql = 'UPDATE z_user SET pnum = %s, pnum_md5 = "%s", update_time = NOW() WHERE uid = %s;' % (pnum, self._get_pnum(pnum), uid) m.Q(sql) self.cacheUpdateUserInfo(uid) return '' except: traceback().print_exc() finally: m.close() return '服务器错误'
def getUidByDeviceId(self, device_id, app_id = 0): r = m_redis.get_instance() if app_id == None: raise InvalidOperation(1, "app_id is None.") device_id_key = m_redis._ZHUAN_USER_ID_BY_DEVICE_ID_ + str(app_id) + "_" + str(device_id) uid = r.get(device_id_key) if not uid: m = mmysql() sql = "SELECT uid FROM device_id_uid_appid_%s WHERE device_id = '%s';" % (int(app_id), m.F(device_id)) m.Q(sql) rs = m.fetchone() if not rs: sql = 'SELECT uid FROM z_user WHERE device_id = "%s"' % m.F(device_id) m.Q(sql) rs = m.fetchone() if rs: uid = rs["uid"] r.setex(device_id_key, uid, 800) else: m.close() return 0 m.close() return int(uid)
def getUserPointById(self, uid): default_return_rs = {'point': 0, 'subpoint': 0, 'penaltypoint': 0, 'sumpoint': 0, 'vip': 1} cache_key = m_redis._ZHUAN_USER_POINT_ + str(uid) r = m_redis.get_instance('ad') cache = r.get(cache_key) if not cache: m = mmysql() sql = 'SELECT point, subpoint, penaltypoint, sumpoint FROM user_contribution_%s WHERE uid = %s;' % (str(int(uid))[-1], int(uid)) m.Q(sql) rs = m.fetchone() m.close() if rs: vip = 0 if rs['sumpoint'] >= 10 and rs['sumpoint'] < 150: vip = 1 elif rs['sumpoint'] >= 150 and rs['sumpoint'] < 600: vip = 2 elif rs['sumpoint'] >= 600 and rs['sumpoint'] < 5000: vip = 3 elif rs['sumpoint'] >= 5000: vip = 4 rs['vip'] = vip r.set(cache_key, json.dumps(rs if rs else default_return_rs, cls = CJsonEncoder), 3600 * 4) cache = r.get(cache_key) if not cache: return default_return_rs return json.loads(cache)
def updateUserMobileForAdmin(self, uid, old_mobile, new_mobile): m = mmysql() try: sql = 'SELECT pnum FROM z_user WHERE uid = %s AND pnum = %s;' % (uid, old_mobile) m.Q(sql) rs = m.fetchone() if not rs: return 'uid 和 old_mobile 对应的用户不存在' # 检查新手机号是否已经存在 sql = 'SELECT * FROM z_user WHERE pnum = %s;' % new_mobile m.Q(sql) if m.fetchone(): return '新手机号已经被其他账号绑定' # 走到这里说明是 web 版的手机号,可以更改了 sql = 'UPDATE z_user SET pnum = %s, pnum_md5 = "%s", update_time = NOW() WHERE uid = %s;' % (new_mobile, self._get_pnum(new_mobile), uid) m.Q(sql) self.cacheUpdateUserInfo(uid) return '' except: traceback().print_exc() finally: m.close() return '服务器错误'
def getUserExInfo(self, uid): uid = int(uid) r = m_redis.get_instance("ad") key = m_redis._ZHUAN_USER_EX_INFO_ + str(uid) uinfo_str = r.get(key) if uinfo_str: uinfo_obj = json.loads(uinfo_str) else: m = mmysql() sql = "select uid,sex,workspace,birth_day,ctime from z_user_info_ex where uid = '%s'" % ( uid) m.Q(sql) uinfo_obj = m.fetchone() if uinfo_obj: uinfo_str = json.dumps(uinfo_obj, cls=CJsonEncoder) r.set(key, uinfo_str, 86400) uinfo_obj = json.loads(uinfo_str) else: uinfo_obj = {} r.set(key, "{}", 300) m.close() if not uinfo_obj: return UserExInfo() else: uei = UserExInfo() uei.uid = uinfo_obj["uid"] uei.sex = uinfo_obj["sex"] uei.workspace = uinfo_obj["workspace"] uei.birthday = uinfo_obj["birth_day"] uei.ctime = uinfo_obj["ctime"] return uei
def addAppRegister(self, uid, app_id, device_id, imsi, os_type, channel, client_ip): if not self._validate_param('device_id', device_id): return False m = mmysql() try: # 新规则 如果device_id 已经被人用了 且uid和你不一样 就不让激活 # 增加这个规则意义在于 如果z_user表内已经有人用过这个device_id 也是不允许其他人激活的 sql = "SELECT uid FROM device_id_uid_appid_%s WHERE device_id = '%s';" % (int(app_id), m.F(device_id)) m.Q(sql) rs = m.fetchone() if rs and rs["uid"] and rs["uid"] != uid: return False sql = "INSERT INTO device_id_uid_appid_%s(device_id, uid, update_time) VALUES('%s', '%s', now())" % (int(app_id), m.F(device_id), int(uid)) m.Q(sql) sql = "INSERT INTO app_register_%s(uid, appid, rtime, device_id, imsi, os_type, channel, register_ip) \ VALUES('%s', '%s', now(), '%s', '%s', '%s', '%s', '%s')" % (str(int(uid))[-1], int(uid), int(app_id), m.F(device_id), m.F(imsi) ,m.F(os_type), m.F(channel), m.F(client_ip)) m.Q(sql) self.cacheUpdateUserInfo(int(uid), m.F(device_id), app_id) except: traceback.print_exc() return False finally: m.close() r = m_redis.get_instance() r.delete(self._appIdCacheKey(uid, app_id)) return True
def createUserExInfo(self, userexinfo): if not re.findall("^\d{8,10}$", str(userexinfo.uid)): raise InvalidOperation(1, "uid is not validate.") if userexinfo.sex not in [1, 2]: raise InvalidOperation(2, "sex is not validate.") if not workSpace._VALUES_TO_NAMES.has_key(userexinfo.workspace): raise InvalidOperation(3, "workSpace is not validate.") if not re.findall("^\d{4}-\d{2}-\d{2}$", userexinfo.birthday): raise InvalidOperation(4, "birth day is not validate.") try: m = mmysql() sql = "insert into z_user_info_ex(uid,sex,workspace,birth_day,ctime) values('%s','%s','%s','%s',now())" % ( userexinfo.uid, userexinfo.sex, userexinfo.workspace, userexinfo.birthday) m.Q(sql) m.close() key = m_redis._ZHUAN_USER_EX_INFO_ + str(userexinfo.uid) r = m_redis.get_instance("ad") r.delete(key) except: raise InvalidOperation(5, traceback.format_exc()) return True
def checkUserAdOrInviteInSevenDays(self, uid, sdate): m = mmysql(self.witchDb(uid)) sql = 'SELECT count(*) AS total FROM %s WHERE (action_type = %s OR action_type = %s) AND uid = %s AND ctime >= date_add("%s", interval -6 day) AND ctime <= date_add("%s", interval 1 day)' % \ (self.witchScoreLogTable(uid), Scoretype._ACTION_TYPE_AD, Scoretype._ACTION_TYPE_REGISTER, uid, sdate, sdate) m.Q(sql) result = m.fetchone() return True if result['total'] > 0 else False
def resumeUserScoreForExchange(self, uid, score): if not self._validate_param('uid', uid): return False m = mmysql(self.witchDb(uid)) try: sql = "SELECT uid, score FROM %s WHERE uid = '%s';" % ( self.witchScoreTable(uid), int(uid)) m.Q(sql) rs = m.fetchone() if not rs: m.close() return False # log表规则是取uid倒数第2位分库 最后1位分表 共100个表(包括0) sql = "UPDATE %s SET score = score + %s, update_time = now() WHERE uid = '%s';" % ( self.witchScoreTable(uid), score, int(uid)) m.Q(sql) except: traceback.print_exc() m.close() return False # 如果今天有缓存,更新积分退款和减余额全部更新缓存 r = m_redis.get_instance() r.delete(self._scoreListKey(uid)) m.close() return True
def getUserCautionByIp(self, ip): m = mmysql("old_hongbao") r = m_redis.get_instance() try: iplist = [] ip_cache_list = r.get(m_redis._ZHUAN_USER_BLACK_IP_) or "" if ip_cache_list: iplist = json.loads(ip_cache_list) else: sql = 'SELECT black_ip FROM z_ip_black WHERE status = 0;' m.Q(sql) rs = m.fetchall() for row in rs: iplist.append(row["black_ip"]) r.setex(m_redis._ZHUAN_USER_BLACK_IP_, json.dumps(iplist), 600) if iplist: for ip_str in iplist: if re.findall(r"%s" % ip_str, ip): return True except: traceback.print_exc() print "ip black is wrong" finally: m.close() return False
def create_user_score_line(self, uid): m = mmysql(self.witchDb(uid)) sql = "INSERT INTO z_user_score_%s(uid, score, update_time) VALUES('%s', 0, now())" % ( str(uid)[-1], uid) m.Q(sql) m.close() return True
def updateUserPassword(self, password, uid, pnum): password = self._get_password(password) m = mmysql() sql = "UPDATE z_user SET password = '******', update_time = NOW() WHERE uid = %s AND pnum = '%s';" % (password, uid, pnum) m.Q(sql) m.close() self.cacheUpdateUserInfo(uid) return True
def _insertAppLog(self, uid, device_id, dict_action_log): m = mmysql(self.witchDb(uid)) try: for pack_name, action in dict_action_log.items(): sql = 'INSERT INTO %s (uid, device_id, pack_name, action, ctime) VALUES(%s, "%s", "%s", %s, NOW());' % (self._witchAppTable(uid), uid, device_id, pack_name, action) m.Q(sql) except Exception, e: m.close() return False
def updateUserStatus(self, uid, status): if status not in [0, 1, 2]: return False m = mmysql() sql = "UPDATE z_user SET status = %s, update_time = NOW() WHERE uid = %s" % (status, uid) m.Q(sql) m.close() self.cacheUpdateUserInfo(uid) return True
def isTestUser(self, pnum): m = mmysql() try: sql = 'SELECT who FROM test_user_list WHERE pnum = %s;' % pnum m.Q(sql) rs = m.fetchone() if rs: return True except: traceback().print_exc() finally: m.close() return False
def updateUserDeviceId(self, uid, old_device_id, new_device_id, app_id = 0): uid = int(uid) old_device_id = mmysql.F(old_device_id) new_device_id = mmysql.F(new_device_id) m = mmysql() sql = "UPDATE z_user SET device_id = '%s', update_time = NOW() WHERE status = 1 AND device_id = '%s' AND uid = %s AND from_app = %s;" % (new_device_id, old_device_id, uid, int(app_id)) m.Q(sql) sql = "UPDATE app_register_%s SET device_id = '%s' WHERE uid = %s AND device_id = '%s' AND appid = %s;" % (str(uid)[-1], new_device_id, uid, old_device_id, int(app_id)) m.Q(sql) sql = "UPDATE device_id_uid_appid_%s SET device_id = '%s' WHERE uid = %s AND device_id = '%s';" % (int(app_id), new_device_id, uid, old_device_id) m.Q(sql) m.close() self.cacheUpdateUserInfo(uid, old_device_id,app_id) return True
def _getUserInfoByAppId(self, uid, app_id = 0): rkey = self._appIdCacheKey(uid, app_id) r = m_redis.get_instance() cache = r.get(rkey) if not cache: m = mmysql() sql = "SELECT uid, appid, rtime, device_id, imsi, os_type, channel, register_ip FROM app_register_%s WHERE uid = %s AND appid = %s;" % (str(int(uid))[-1], int(uid), int(app_id)) m.Q(sql) rs = m.fetchone() r.set(rkey, json.dumps(rs if rs else {},cls=CJsonEncoder), 86400) cache = r.get(rkey) m.close() if not cache: return {} return json.loads(cache)
def addSmallExchange(self, uid, type_score): if not self._addSmallExchangeDirtyWork(uid, type_score): return False # 到这里说明可以进行小额兑换,那么充值一下数据 r = m_redis.get_instance() m = mmysql() ad_time = self.SMALL_EXCHANGE_SCORE_AD_TIME_LIST.get(type_score) redis_key = m_redis._ZHUAN_USER_SMALL_EXCHANGE_ALL_AD_TIME_ + str(uid) r.delete(redis_key) sql = 'UPDATE user_small_exchange_%s SET score_ad_time = score_ad_time - %s, score_ad_holding_time = %s WHERE uid = %s;' % ( self._whichTable(uid), ad_time, ad_time, uid) result = m.Q(sql) m.close() return result
def existUser(self, uid): r = m_redis.get_instance() u_r_key = m_redis._ZHUAN_USER_LOGIN_NEW_ + str(uid) user_re = r.get(u_r_key) if user_re: return True m = mmysql() sql = "SELECT 'x' FROM z_user WHERE uid = '%s';" % int(uid) m.Q(sql) rs = m.fetchone() if rs and rs["x"]: m.close() return True m.close() return False
def getInviteMember(self, uid): r = m_redis.get_instance("ad") invite_key = m_redis._ZHUAN_INVITE_MEMBER_ + str(uid) num = r.get(invite_key) if not num: m = mmysql() sql = "SELECT COUNT(uid) AS num FROM z_user WHERE invite_code = '%s';" % (int(uid)) m.Q(sql) rs = m.fetchone() if rs: num = rs["num"] r.setex(invite_key,rs["num"],800) else: m.close() return 0 m.close() return int(num)
def consumeAdDownloadTimes(self, uid, times): if not self._validate_param('uid', uid): return False all_ad_time_data = json.loads(self.getUserSmallExchangeAllAdTime(uid)) score_ad_time = all_ad_time_data.get('score_ad_time', 0) if score_ad_time < times: return False m = mmysql() sql = 'UPDATE user_small_exchange_%s SET score_ad_time = score_ad_time - %s, score_ad_finish_time = score_ad_finish_time + %s WHERE uid = %s;' % ( self._whichTable(uid), times, times, uid) result = m.Q(sql) m.close() if result: r = m_redis.get_instance() redis_key = m_redis._ZHUAN_USER_SMALL_EXCHANGE_ALL_AD_TIME_ + str( uid) r.delete(redis_key) return result
def addUser(self, useraddobj): # 生成 uid if useraddobj.app_id == 2: uid = self._get_user_code(2) elif useraddobj.app_id == 1: uid = self._get_user_code(6) else: uid = self._get_user_code() if useraddobj.os_type != "ios" else self._get_user_code(9) # 处理一下邀请码 ic = useraddobj.ic if not ic: ic = 0 # 免手机号注册,需要分配一个假手机号。安卓为 uid 前 加上 300 或 30,iOS 为 uid 前加上 200 或 20 pnum = useraddobj.pnum if pnum == 0 and useraddobj.os_type == 'android': pnum = int(self._PREFIX_ANDROID_OLD + str(uid)) if len(str(uid)) == 8 else int(self._PREFIX_ANDROID_NEW + str(uid)) elif pnum == 0: pnum = int(self._PREFIX_IOS_OLD + str(uid)) if len(str(uid)) == 8 else int(self._PREFIX_IOS_NEW + str(uid)) # 如果 device_id 已经注册过,就不让注册 m = mmysql() if self.getUidByDeviceId(m.F(useraddobj.device_id), int(useraddobj.app_id)): raise InvalidOperation(1, "device_id在这个app_id %s 已经存在" % useraddobj.app_id) # 开始真正的注册 try: if uid > 0: sql = "INSERT INTO z_user(uid, pnum, pnum_md5, password, device_id, imsi, os_type, status, register_ip, ctime, invite_code, channel, from_app, update_time) \ VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), '%s', '%s', '%s', now())" % (uid, int(pnum), self._get_pnum(pnum), self._get_password(useraddobj.pw), m.F(useraddobj.device_id), m.F(useraddobj.imsi), m.F(useraddobj.os_type), 1, m.F(useraddobj.client_ip), int(ic), m.F(useraddobj.channel), int(useraddobj.app_id)) user_ok = m.Q(sql) if user_ok: self.create_user_score_line(uid) self.addAppRegister(uid, useraddobj.app_id, useraddobj.device_id, useraddobj.imsi, useraddobj.os_type, useraddobj.channel, useraddobj.client_ip) m.close() return uid except: traceback.print_exc() m.close() return 0
def getUidByPnum(self, pnum): r = m_redis.get_instance() pnum = str(pnum) uid = r.get(m_redis._ZHUAN_USER_ID_BY_PNUM_ + str(pnum)) if not uid: uid = 0 m = mmysql() sql = 'SELECT uid FROM z_user WHERE pnum = "%s";' % m.F(pnum) m.Q(sql) rs = m.fetchone() if rs: uid = rs["uid"] r.setex(m_redis._ZHUAN_USER_ID_BY_PNUM_ + str(pnum), uid, 86400) else: m.close() return 0 m.close() return int(uid)
def _getUserSmallExchangeTime(self, uid, redis_key_prefix, db_column, cache_time): self._validate_param('uid', uid) r = m_redis.get_instance() m = mmysql() redis_key = redis_key_prefix + str(uid) s_time = r.get(redis_key) if not s_time: sql = 'SELECT %s FROM user_small_exchange_%s WHERE uid = %s;' % ( db_column, self._whichTable(uid), uid) m.Q(sql) rs = m.fetchone() if rs and rs[db_column]: s_time = rs[db_column] else: s_time = 0 self._cacheSmallExchangeData(r, redis_key, s_time, cache_time) s_time = r.get(redis_key) m.close() return int(s_time)
def getUserThisMonthScoreTime(self, uid, action_type=0): r = m_redis.get_instance() scoreTimeMonthly = r.get(m_redis._ZHUAN_USER_SCORE_TIME_THIS_MONTH_ + str(uid)) if scoreTimeMonthly == None: today = datetime.date.today() firstDay = datetime.date(day=1, month=today.month, year=today.year) firstDay = firstDay.strftime('%Y-%m-%d %H:%M:%S') m = mmysql(self.witchDb(uid)) sql = 'SELECT count(*) as time FROM %s WHERE uid = %s AND action_type = %s AND ctime >= "%s";' % ( self.witchScoreLogTable(uid), int(uid), int(action_type), firstDay) m.Q(sql) result = m.fetchone() scoreTimeMonthly = result['time'] r.setex(m_redis._ZHUAN_USER_SCORE_TIME_THIS_MONTH_ + str(uid), scoreTimeMonthly, 60 * 60) return int(scoreTimeMonthly)
def finishSmallExchange(self, uid, type_score, succ): r = m_redis.get_instance() if not self._finishSmallExchangeDirtyWork(r, uid, type_score): return False # 到这里说明可以进行小额兑换完毕的操作,处理一下数据 r = m_redis.get_instance() m = mmysql() ad_time = self.SMALL_EXCHANGE_SCORE_AD_TIME_LIST.get(type_score) redis_key = m_redis._ZHUAN_USER_SMALL_EXCHANGE_ALL_AD_TIME_ + str(uid) r.delete(redis_key) if succ: sql = 'UPDATE user_small_exchange_%s SET score_ad_holding_time = 0, score_ad_finish_time = score_ad_finish_time + %s WHERE uid = %s;' % ( self._whichTable(uid), ad_time, uid) else: sql = 'UPDATE user_small_exchange_%s SET score_ad_holding_time = 0, score_ad_time = score_ad_time + %s WHERE uid = %s;' % ( self._whichTable(uid), ad_time, uid) result = m.Q(sql) m.close() return result
def _get_user_code(self, uid_case = 3): m = mmysql() uid_code = 0 ucase = 8 for i in range(0, 100): if isinstance(uid_case, list): ucase = uid_case[random.randint(0, len(uid_case) - 1)] else: ucase = uid_case st = 10000000 * ucase ed = st + 9999999 randcode = random.randint(st, ed) m.Q('SELECT uid FROM z_user WHERE uid = "%s";' % (randcode)) rs = m.fetchone() if not rs: uid_code = randcode break if i == 100: break m.close() return uid_code
def _addScoreSmallExchangeWork(self, uid, ScoreAddObj, currency): # 如果加分类型不是广告,直接返回 if ScoreAddObj.action_type != Scoretype._ACTION_TYPE_AD: return # 如果广告不是自家的,直接返回 if ScoreAddObj.trade_type != 1: return ''' # 如果不是 ios 系统,直接返回 if ScoreAddObj.os_type_id != OS_TYPE._OS_TYPE_IOS: return ''' # 如果金额为0(特惠),直接返回 if currency == 0: return m = mmysql() r = m_redis.get_instance() self._firstAdWork(m, r, uid, currency) # 先看看是不是第一次下载广告 self._addSmallExchangeAdTime(m, r, uid) # 增加用户可用于小额兑换的广告次数 m.close()
def updateUserPoint(self, uid, point, subpoint): # 该函数只做加分操作,减分操作是由每天凌晨的脚本跑出来的 uinfo = self.getUserInfoByUid(uid) if not uinfo or uinfo.uid == None: return False stat_date = datetime.datetime.now().strftime("%Y-%m-%d") m = mmysql() m.Q("INSERT INTO user_contribution_%s VALUES('%s', '%s', %s, 0, 0, `point` + `subpoint` + `penaltypoint`, -100, NOW()) ON DUPLICATE KEY UPDATE \ stat_date ='%s', `point` = `point` + %d, `sumpoint` = `sumpoint` + %d, utime = now();" % (str(uid)[-1], str(uid), stat_date, int(point), stat_date, int(point), int(point))) if int(uinfo.invite_code) and uinfo.invite_code > 0: subinfo = self.getUserInfoByUid(uinfo.invite_code) if subinfo and subinfo.uid != None: m.Q("INSERT INTO user_contribution_%s VALUES('%s', '%s', 50, %s, 0, `point` + `subpoint` + `penaltypoint`, -100, NOW()) ON DUPLICATE KEY UPDATE \ stat_date = '%s', subpoint = subpoint + %d, `sumpoint` = `sumpoint` + %d, utime = now();" % (str(uinfo.invite_code)[-1], str(uinfo.invite_code), stat_date, int(subpoint), stat_date, int(subpoint), int(subpoint))) m.close() # 清除缓存 cache_key = m_redis._ZHUAN_USER_POINT_ + str(uid) r = m_redis.get_instance("ad") r.delete(cache_key) return True
def _getUserScoreList(self, uid): r = m_redis.get_instance() list = r.hgetall(self._scoreListKey(uid)) if not list: m = mmysql(self.witchDb(uid)) sql = 'SELECT uid, score, update_time, score_ad, score_right_catch, score_register, score_other, score_task, score_active, \ score_field_1 AS wifi_share, score_field_2 AS bind_bank_card, score_field_3 AS ad_wall_20, score_field_4 AS score_offspring, \ score_ad + score_right_catch + score_register + score_other + score_task + score_active + score_field_1 + score_field_2 + score_field_3 + score_field_4 as num \ FROM %s WHERE uid = "%s";' % (self.witchScoreTable(uid), int(uid)) m.Q(sql) rs = m.fetchone() if not rs: return {} rs['update_time'] = int(time.mktime(rs['update_time'].timetuple())) m.close() r.hmset(self._scoreListKey(uid), rs) r.expire(self._scoreListKey(uid), 86400) list = r.hgetall(self._scoreListKey(uid)) for key in list.keys(): list[key] = int(list[key]) return list