def create_group(): uid = loggedUserUid() if uid == 0: return -2 try: data = json.loads(request.stream.read()) except: return -3 gdata = {} fulldata = True for k in group_model: if data.get(k, None) is None: fulldata = False break else: gdata[k] = data[k] if not fulldata: return "Few data" gid = rs.incr('group_counter') gdata['id'] = gid gdata['create_date'] = int(calendar.timegm(datetime.utcnow().timetuple())) rs.hmset("group:%s" % gid, {'data': json.dumps(gdata), 'id': gid, 'uid': uid}) group_add_user(gid, uid) rs.sadd("whoosh:groups:added", gid) return gid
def delete_battle(battle_id, admin=0): if rs.exists("battle:%s" % battle_id) == 1 and (admin == 1 or str( loggedUserUid()) == rs.hget("battle:%s" % battle_id, 'uid')): uid = rs.hget("battle:%s" % battle_id, 'uid') rs.zrem("user_battles:" + uid, battle_id) rs.zrem("battles_ids", battle_id) battle = json.loads(rs.hget("battle:%s" % battle_id, 'data')) rs.zrem("battles:%s" % battle['type'], battle_id) rs.zrem("privacy:%s" % battle['privacy'], battle_id) tanks = rs.smembers("battle:%s:tanks" % battle_id) for tank_id in tanks: rs.srem("tank:%s:battles" % tank_id, battle_id) users = rs.zrange('battle:%s:users' % battle_id, 0, -1) from warg.views.battle_followers import unFollowBattleByUser from warg.views.notifications import create_battle_notification, NTFY_BATTLE_KICK for user_id in users: unFollowBattleByUser(battle_id, int(user_id)) if user_id != uid: create_battle_notification(uid, user_id, battle_id, NTFY_BATTLE_KICK) rs.delete("battle:%s:tanks" % battle_id) from warg.views.jobs.battle_reminder import remove_battle_reminders remove_battle_reminders(battle_id) rs.delete("battle:%s:reminders" % battle_id) rs.delete("battle:%s" % battle_id) rs.sadd("whoosh:battles:deleted", battle_id) return 1 return 0
def battleAddUser(battle_id, user_id): if rs.exists("battle:" + str(battle_id)) != 1: return -1 if rs.hget("battle:%s" % battle_id, "uid") != str(loggedUserUid()): return -2 rs.sadd('battle:%s:invited' % battle_id, user_id) create_battle_notification(loggedUserUid(), user_id, battle_id, NTFY_BATTLE_INVITE) return followBattleByUser(battle_id, user_id)
def battleAcceptUser(battle_id, user_id, admin=False): if rs.exists("battle:" + str(battle_id)) != 1: return -1 uid = loggedUserUid() if rs.hget("battle:%s" % battle_id, "uid") != str(uid) and not admin: return -2 rs.zadd('battle:%s:users' % battle_id, user_id, 1) rs.sadd('battle:%s:accepted' % battle_id, user_id) rs.zadd('user:%s:battles' % user_id, battle_id, rs.zscore("battles_ids", battle_id)) if uid != user_id: create_battle_notification(loggedUserUid(), user_id, battle_id, NTFY_BATTLE_ACCEPT) return rs.scard('battle:%s:accepted' % battle_id)
def update_battle(battle_id): uid = loggedUserUid() if uid == 0: return -2 if str(uid) != rs.hget("battle:%s" % battle_id, 'uid'): return -1 try: data = json.loads(request.stream.read()) except: return -3 battle = json.loads(rs.hget("battle:%s" % battle_id, 'data')) battle_old = battle.copy() fulldata = True for k in battle_model: if data.get(k, None) is None: fulldata = False break else: battle[k] = data[k] if not fulldata: return "Few data" if data['type'] not in battle_types: return "Wrong battle type" if battle_old['type'] != data['type']: rs.zrem("battles:%s" % battle_old['type'], battle_id) if battle_old['privacy'] != data['privacy']: rs.zrem("privacy:%s" % battle_old['privacy'], battle_id) tanks = rs.smembers("battle:%s:tanks" % battle_id) for tank_id in tanks: rs.srem("tank:%s:battles" % tank_id, battle_id) rs.delete("battle:%s:tanks" % battle_id) from warg.views.jobs.battle_reminder import remove_battle_reminders remove_battle_reminders(battle_id) rs.delete("battle:%s:reminders" % battle_id) process_battle_db(battle_id, uid, battle, data.get("reminders", default_reminders)) users = rs.zrange('battle:%s:users' % battle_id, 0, -1) for user_id in users: rs.zadd('user:%s:battles' % user_id, battle_id, battle['battle_date']) #from uhelp.views.full_text import storeLookInIndex #storeLookInIndex(look, None, True) rs.sadd("whoosh:battles:updated", battle_id) return battle_id
def update_group(group_id): uid = loggedUserUid() if uid == 0: return -2 if str(uid) != rs.hget("group:%s" % group_id, 'uid'): return -1 try: data = json.loads(request.stream.read()) except: return -3 group = json.loads(rs.hget("group:%s" % group_id, 'data')) for k in group_model: group[k] = data[k] rs.hset("group:%s" % group_id, "data", json.dumps(group)) rs.sadd("whoosh:groups:updated", group_id) return group_id
def battleFollowUser(battle_id): if rs.exists("battle:" + str(battle_id)) != 1: return -1 uid = loggedUserUid() if uid == 0: return -2 if rs.sismember('battle:%s:invited' % battle_id, uid): create_battle_notification(uid, 0, battle_id, NTFY_INVITE_ACCEPT) rs.srem('battle:%s:invited' % battle_id, uid) rs.zadd('battle:%s:users' % battle_id, uid, 1) rs.sadd('battle:%s:accepted' % battle_id, uid) rs.zadd('user:%s:battles' % uid, battle_id, rs.zscore("battles_ids", battle_id)) return 1 else: create_battle_notification(uid, 0, battle_id, NTFY_BATTLE_FOLLOW) return followBattleByUser(battle_id, uid)
def process_battle_db(bid, uid, bdata, reminders): timedelta = int(rs.get('user:%s:timedelta' % uid) or 0) bdata['battle_date'] = int(bdata['battle_date']) + timedelta rs.hmset( "battle:%s" % bid, { 'data': json.dumps(bdata), 'id': bid, 'uid': uid, 'battle_date': bdata['battle_date'], 'type': bdata['type'], 'privacy': bdata['privacy'] }) rs.zadd("battles:%s" % bdata['type'], bid, bdata['battle_date']) rs.zadd("user_battles:" + str(uid), bid, bdata['battle_date']) rs.zadd("battles_ids", bid, bdata['battle_date']) rs.zadd("privacy:%s" % bdata['privacy'], bid, bdata['battle_date']) for remmin in reminders: rs.sadd("battle:%s:reminders" % bid, remmin) from warg.views.jobs.battle_reminder import init_battle_reminders init_battle_reminders(bid, bdata['battle_date'])
def battleAddExternalUser(battle_id, account_id): if rs.exists("battle:" + str(battle_id)) != 1: return -1 if rs.hget("battle:%s" % battle_id, "uid") != str(loggedUserUid()): return -2 access_token = request.args.get("access_token", None) if access_token is None: return json.dumps("No access token") wotuid = 'wot_user:%s' % account_id if rs.exists(wotuid) != 1: from warg.views.users import insert_wot_user, account_info data = account_info(access_token, account_id) if data['status'] == 'ok': uid = insert_wot_user(data['data'][str(account_id)], 1) else: return json.dumps("Error: " + data['error']['message']) else: uid = rs.hget(wotuid, 'uid') create_battle_notification(loggedUserUid(), int(uid), battle_id, NTFY_BATTLE_INVITE) rs.sadd('battle:%s:invited' % battle_id, uid) return followBattleByUser(battle_id, uid)
def on_chat_message(uid, msg): rid = int(msg.get('rid', 0)) if rid == 0 or len(msg.get('text', "")) == 0: return chid = "chat:message:%s:%s:" % (uid, rid) mid = rs.incr(chid + "counter") chid = chid + str(mid) score = calendar.timegm(datetime.utcnow().timetuple()) chatm = { "id": mid, "text": msg.get('text'), 'is_read': 'false', 'sid': uid, 'rid': rid, "type": "chat" } rs.hmset(chid, chatm) rs.zadd("chat:user:%s:unread" % rid, chid, score) rs.sadd("chat:user:%s:ntfy" % rid, chid) dialog = "chat:dialog:%s:%s" % (min(int(uid), rid), max(int(uid), rid)) rs.zadd(dialog, chid, score) rs.zadd("chat:user:%s:dialogs" % uid, dialog, score) rs.zadd("chat:user:%s:dialogs" % rid, dialog, score) chatm["create_date"] = score message = json.dumps({"type": "chat", "content": chatm}) send_message_to_user(uid, message) send_message_to_user(rid, message) ntfs = rs.scard("chat:user:%s:ntfy" % rid) unread = get_unread._original() unread_message = "" if ntfs > 0 and len(unread) > 0: unread_message = json.dumps({ "type": "unread", "content": { "count": len(unread), "message": unread[0] } }) send_message_to_user(rid, unread_message)
def do_create_battle(uid, data): bdata = {} fulldata = True for k in battle_model: if data.get(k, None) is None: fulldata = False break else: bdata[k] = data[k] if not fulldata: return -4 # "Few data" if data['type'] not in battle_types: return -5 # "Wrong battle type" bid = rs.incr('battle_counter') bdata['id'] = bid bdata['create_date'] = int(calendar.timegm(datetime.utcnow().timetuple())) process_battle_db(bid, uid, bdata, data.get("reminders", default_reminders)) from warg.views.battle_followers import battleAcceptUser battleAcceptUser(bid, uid, True) #from warg.views.full_text import storeBattleInIndex #storeBattleInIndex(bdata, None) rs.sadd("whoosh:battles:added", bid) return bid
def insert_wot_user(profile, virtual=0): uid = rs.incr('users_counter') wotuid = 'wot_user:'******'account_id']) user_data = {'id': uid, 'avatar': None, 'create_date': int(mktime(datetime.now().timetuple()))} for k in profile: if k != 'private': user_data[k] = profile[k] from warg.views.followers import followUserByUser if profile['private'] is not None: for fid in profile['private']['friends']: wotfid = 'wot_user:%s' % fid if rs.exists(wotfid) == 1: followUserByUser(rs.hget(wotfid, 'uid'), str(uid)) rs.set("users:" + str(uid), json.dumps(user_data)) rs.sadd("user_soc_links:" + str(uid), wotuid) rs.hmset(wotuid, {'uid': str(uid), 'profile': json.dumps(profile), "virtual": virtual}) if virtual == 1: rs.sadd("users:virtual", uid) from warg.views.full_text import storeUserInIndex storeUserInIndex(user_data) rs.sadd("user_ids", uid) return uid
def create_battle_notification(from_user, to_user, battle_id, template): battle = get_battle._original(battle_id) to_user = battle['user']["id"] if int(to_user) == 0 else to_user #timedelta = int(rs.get('user:%s:timedelta' % to_user) or 0) #zonedelta = int(rs.get('user:%s:zonedelta' % to_user) or 0) battle_date = datetime.fromtimestamp( int(battle["battle_date"]), tz=pytz.utc).strftime('UTC %H:%M %d/%m') message = None if template == NTFY_BATTLE_INVITE: message = NTFY_BATTLE_INVITE % (battle['user']['nickname'], battle_date, battle["descr"]) if template == NTFY_BATTLE_FOLLOW: usr = user_datail._original(from_user) to_user = battle['user']["id"] message = NTFY_BATTLE_FOLLOW % (usr["nickname"], battle_date, battle["descr"]) if template == NTFY_BATTLE_UFLLOW: usr = user_datail._original(from_user) to_user = battle['user']["id"] message = NTFY_BATTLE_UFLLOW % (usr["nickname"], battle_date, battle["descr"]) if template == NTFY_BATTLE_KICK: message = NTFY_BATTLE_KICK % (battle['user']['nickname'], battle_date, battle["descr"]) if template == NTFY_BATTLE_ACCEPT: message = NTFY_BATTLE_ACCEPT % (battle_date, battle["descr"]) if template == NTFY_BATTLE_REJECT: message = NTFY_BATTLE_REJECT % (battle_date, battle["descr"]) if template == NTFY_INVITE_ACCEPT: usr = user_datail._original(from_user) to_user = battle['user']["id"] message = NTFY_INVITE_ACCEPT % (usr["nickname"], battle_date, battle["descr"]) if template == NTFY_INVITE_REJECT: usr = user_datail._original(from_user) to_user = battle['user']["id"] message = NTFY_INVITE_REJECT % (usr["nickname"], battle_date, battle["descr"]) if message is None: message = template if rs.sismember("users:virtual", to_user): return chid = "chat:message:%s:%s:" % (from_user, to_user) mid = rs.incr(chid + "counter") chid = chid + str(mid) score = calendar.timegm(datetime.utcnow().timetuple()) chatm = { "id": mid, "text": message, 'is_read': 'false', 'sid': from_user, 'rid': to_user, "type": "battle", "battle_id": battle_id } rs.hmset(chid, chatm) rs.zadd("chat:user:%s:unread" % to_user, chid, score) rs.sadd("chat:user:%s:ntfy" % to_user, chid) rs.zadd("battle:%s:unread" % battle_id, chid, score) ucount = rs.zcard("chat:user:%s:unread" % to_user) unread = get_user_unread(to_user) if len(unread) > 0: unread_message = json.dumps({ "type": "unread", "content": { "count": ucount, "message": unread[0] } }) send_message_to_user(to_user, unread_message)
def websocket_api(): uid = loggedUserUid() if uid == 0: return "Not authorized" if request.environ.get('wsgi.websocket'): ws = request.environ['wsgi.websocket'] print "New user ", uid, "joined" if participants.get(str(uid)) is None: participants[str(uid)] = set() participants[str(uid)].add(ws) participants[str(uid)].add(ws) rs.sadd("users_online", uid) online_cnt = rs.scard("users_online") if online_cnt > int(rs.get("stat:max_online")): rs.set("stat:max_online", online_cnt) notify_online_status(uid, True) ntfs = rs.scard("chat:user:%s:ntfy" % uid) unread = get_unread._original() if ntfs > 0 and len(unread) > 0: ws.send( json.dumps({ "type": "unread", "content": { "count": len(unread), "message": unread[0] } })) rs.delete("chat:user:%s:ntfy" % uid) while True: try: message = ws.receive() if message is None: break try: evt = json.loads(message) # .encode('utf-8') #print "type =", evt.get("type") if evt.get("type") == "chat": on_chat_message(uid, evt.get("content")) if evt.get("type") == "battle_chat": on_battle_message(uid, evt.get("content")) if evt.get("type") == "group_chat": on_group_message(uid, evt.get("content")) if evt.get("type") == "clan_chat": on_clan_message(uid, evt.get("content")) if evt.get("type") == "read_chat": rm = evt.get("content") read_message._original(rm.get('sid'), rm.get('mid')) except: traceback.print_exc() print "Bad json", message, uid except: traceback.print_exc() break ws.close() print "User ", uid, "exit" rs.srem("users_online", uid) notify_online_status(uid, False) if participants.get(str(uid)) is not None: participants[str(uid)].remove(ws) if len(participants[str(uid)]) == 0: del participants[str(uid)] else: print "NO wsgi.websocket:(" return "OK"
def group_add_user(group_id, user_id): rs.sadd("group:%s:users" % group_id, user_id) rs.zadd("user:%s:groups" % user_id, group_id, rs.zcard("user:%s:groups" % user_id) + 1) user_cnt = rs.scard('group:%s:users' % group_id) rs.zadd("group_ids", group_id, user_cnt) return user_cnt
def followUserByUser(user_id, by_user_id): rs.sadd('user:%s:following' % by_user_id, user_id) rs.sadd('user:%s:followers' % user_id, by_user_id) rs.sunionstore('user:%s:follownig_looks' % by_user_id, 'user:%s:follownig_looks' % by_user_id, 'user_looks:' + str(user_id)) return rs.scard('user:%s:followers' % user_id)
def clan_add_user(clan_id, user_id): rs.sadd("clan:%s:users" % clan_id, user_id) rs.set("user:%s:clan" % user_id, clan_id) user_cnt = rs.scard('clan:%s:users' % clan_id) rs.zadd("clan_ids", clan_id, user_cnt) return user_cnt