예제 #1
0
def read_message(sid, mid):
    uid = loggedUserUid()
    if uid == 0:
        return -2
    chid = "chat:message:%s:%s:%s" % (sid, uid, mid)
    if rs.exists(chid) != 1:
        return -1
    if rs.hget(chid, "is_read") == "true":
        return 0
    rs.hset(chid, "is_read", 'true')
    rs.zrem("chat:user:%s:unread" % uid, chid)
    battle_id = rs.hget(chid, "battle_id")
    if battle_id is not None:
        rs.zrem("battle:%s:unread" % battle_id, chid)
        rs.delete(chid)
    unread = get_unread._original()
    ntfs = rs.scard("chat:user:%s:ntfy" % uid)
    message = {"type": "unread", "content": {"count": len(unread)}}
    if ntfs > 0 and len(unread) > 0:
        message["content"]["message"] = unread[0]
        send_message_to_user(uid, json.dumps(message))
    send_message_to_user(
        sid,
        json.dumps({
            "type": "read_chat",
            "content": {
                "mid": mid,
                "rid": int(uid)
            }
        }))
    return 1
예제 #2
0
def searchuser():
    q = request.args.get("q", "")  # repr
    offset = int(request.args.get("offset", 0))
    count = int(request.args.get("count", 20))
    with uix.searcher() as searcher:
        query = QueryParser("nickname", uix.schema).parse(
            "nickname:*%s*" %
            q)  # QueryParser("name", ix.schema).parse("tash*")
        #print query
        user_id = sorting.FieldFacet("user_id", reverse=True)
        results = searcher.search_page(query,
                                       max(offset / count, 0) + 1,
                                       pagelen=count,
                                       sortedby=user_id)
        print results.offset, count, offset, max(offset / count, 0) + 1
        if results.offset < offset:
            return "[]"
        tmp = hashlib.md5(str(mktime(datetime.datetime.now().timetuple()))
                          ).hexdigest() + "user_search_tmp"
        lua = """local searched = loadstring('return ' .. KEYS[1])()
for i = 1, table.getn(searched) do
    redis.call('sadd', KEYS[2], tostring(searched[i]))
end
local arr = redis.call('sort', KEYS[2], 'GET', 'users:*')
return arr"""
        res = rs.eval(
            lua, 2,
            '{' + ','.join(str(hit['user_id']) for hit in results) + '}', tmp)
        rs.delete(tmp)
        r = ",".join(res)
    return "[" + r + "]"
예제 #3
0
def logout():
    ussid = request.cookies.get('uSSID')
    if ussid is None:
        return app.make_response(json.dumps(0))
    response = app.make_response(json.dumps(1))
    rs.delete('ussid:' + ussid)
    response.set_cookie('uSSID', value="")
    return response
예제 #4
0
def send_message_to_user(uid, message):
    wss = participants.get(str(uid))
    if wss is not None:
        for ws in wss:
            try:
                ws.send(message)
                rs.delete("chat:user:%s:ntfy" % uid)
            except:
                pass
예제 #5
0
def delete_group(group_id, admin=0):
    if rs.exists("group:%s" % group_id) == 1 and (admin == 1 or str(loggedUserUid()) == rs.hget("group:%s" % group_id, 'uid')):
        users = rs.smembers("group:%s:users" % group_id)
        for user_id in users:
            rs.srem("user:%s:groups" % user_id, group_id)
        rs.delete("group:%s:users" % group_id)
        rs.delete("group:%s" % group_id)
        return 1
    else:
        return 0
예제 #6
0
def get_group(group_id):
    tmp = hashlib.md5(str(mktime(datetime.now().timetuple()))).hexdigest() + "group_" + str(group_id)
    zscore = rs.zscore("group_ids", group_id)
    if zscore is not None:
        rs.zadd(tmp, group_id, zscore)
        res = get_groups_arr_by_set(tmp, 0, 1)
        rs.delete(tmp)
        return {} if len(res) == 0 else res[0]
    else:
        rs.delete(tmp)
        return {}
예제 #7
0
def get_battle(battle_id):
    tmp = hashlib.md5(str(mktime(
        datetime.now().timetuple()))).hexdigest() + "battle_" + str(battle_id)
    zscore = rs.zscore("battles_ids", battle_id)
    if zscore is not None:
        rs.zadd(tmp, battle_id, 10 * zscore)
        res = get_battles_arr_by_set(tmp, None, 0, 1)
        rs.delete(tmp)
        return {} if len(res) == 0 else res[0]
    else:
        rs.delete(tmp)
        return {}
예제 #8
0
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
예제 #9
0
def get_allowed_battles():
    uid = loggedUserUid()
    if uid == 0:
        return []
    lua = """local r1 = redis.call('sort', 'user:'******':followers', 'GET', 'user:*->battles');
for i = 1, table.getn(r1) do
  redis.call('zadd', KEYS[1], redis.call('hget', 'battle:'..tostring(r1[i]), 'battle_date'), r1[i]);
end
redis.call('zinterstore', KEYS[1], 2, KEYS[1], 'privacy:PRIVATE', 'AGGREGATE', 'MIN');
redis.call('zunionstore', KEYS[1], 4, KEYS[1], 'user:'******':battles','privacy:ALL', 'user_battles:'..tostring(KEYS[2]), 'AGGREGATE', 'MIN');
return 1;"""
    tmp = hashlib.md5(str(mktime(datetime.now().timetuple()))).hexdigest(
    ) + "allowed_battle_" + str(uid)
    #rs.sort('user:%s:followers' % uid, get=["user:*->battles"], store=tmp)
    #rs.zinterstore(tmp, tmp, "privacy:PRIVATE", aggregate="MIN")
    #rs.zinterstore(tmp, tmp, 'user:%s:battles' % uid, "privacy:ALL", "user_battles:%s" % uid, aggregate="MIN")
    rs.eval(lua, 2, tmp, uid)
    res = get_battles_by_set(tmp)
    rs.delete(tmp)
    return res
예제 #10
0
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
예제 #11
0
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"
예제 #12
0
def clan_del_user(clan_id, user_id):
    rs.srem("clan:%s:users" % clan_id, user_id)
    rs.delete("user:%s:clan" % user_id)
    user_cnt = rs.scard('clan:%s:users' % clan_id)
    rs.zadd("clan_ids", clan_id, user_cnt)
    return user_cnt
예제 #13
0
def emptySessions():
    ussids = rs.keys("ussid:*")
    for ussid in ussids:
        rs.delete(ussid)
    return 1