Пример #1
0
def detail(user_id):
    #return request.headers.get('Cookie')
    u = None
    if (user_id is not None) and rs.exists('users:' + str(user_id)) == 1:
        u = json.loads(rs.get("users:" + str(user_id)))
        u['soc_links'] = list(rs.smembers('user_soc_links:' + str(user_id)))
        u['is_online'] = int(rs.sismember('users_online', user_id))
        u['is_follow'] = int(rs.sismember('user:%s:followers' % user_id, loggedUserUid()))
        u['virtual'] = int(rs.sismember('users:virtual', user_id))
        u['memo'] = rs.get('user:%s:memo:%s' % (user_id, loggedUserUid()))
        clan_id = int(rs.get("user:%s:clan" % user_id) or 0)
        if clan_id > 0:
            u['clan'] = json.loads(rs.hget("clan:%s" % clan_id, 'data'))
        #u = json.dumps(u)
    return u or {}
Пример #2
0
def create_clan():
    uid = loggedUserUid()
    if uid == 0:
        return -2
    try:
        data = json.loads(request.stream.read())
    except:
        return -3
    gdata = {}
    fulldata = True
    for k in clan_model:
        if data.get(k, None) is None:
            fulldata = False
            break
        else:
            gdata[k] = data[k]
    if not fulldata:
        return "Few data"
    user_clan_id = rs.get("user:%s:clan" % uid)
    if user_clan_id == str(data["clan_id"]):
        return data["clan_id"]
    if int(user_clan_id or 0) > 0:
        clan_del_user(user_clan_id, uid)
    rs.hmset("clan:%s" % data["clan_id"], {
        'data': json.dumps(data),
        'id': data["clan_id"]
    })
    clan_add_user(data["clan_id"], uid)
    return data["clan_id"]
Пример #3
0
def systemInfo():
    info = rs.info()
    lua = """local r1 = redis.call('keys', 'users:*');
return table.getn(r1);"""
    stat = {"users": rs.eval(lua, 0) - rs.scard("users:virtual")}
    #users = rs.keys("users:*")
    stat["battles"] = rs.zcard("battles_ids")
    stat["groups"] = rs.zcard("group_ids")
    stat["clans"] = rs.zcard("clan_ids")
    stat["online"] = rs.scard("users_online")
    stat["max_online"] = rs.get("stat:max_online")
    stat["disk_usage"] = getFolderSize(app.config['UPLOAD_FOLDER'])
    stat["redis_usage"] = info['used_memory_human']
    #print "SYSTEM: ", os.popen("du -hs " + app.config['UPLOAD_FOLDER']).read().split()[0]
    return stat
Пример #4
0
def add_user_avatar():
    uid = loggedUserUid()
    if uid == 0:
        return -2
    outfile = user_directory(uid)
    for f in request.files:
        _file = request.files.get(f)
        ensure_dir(app.config['UPLOAD_FOLDER'] + outfile)
        print "File: " + f, _file.filename
        if allowed_file(_file.filename):
            ext = _file.filename.rsplit('.', 1)[1]
            outfile = "%s%s_%s" % (outfile, uid, rs.incr('user:%s:avatar' % uid))
            _file.save(app.config['UPLOAD_FOLDER'] + outfile + "_orig." + ext)
            process_user_image(outfile, ext, uid)
            u = json.loads(rs.get("users:%s" % uid))
            u["avatar"] = outfile
            rs.set("users:%s" % uid, json.dumps(u))
        break
    return uid
Пример #5
0
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'])
Пример #6
0
def on_clan_message(uid, msg):
    clan_id = int(msg.get('clan_id', 0))
    if clan_id == 0 or len(msg.get('text', "")) == 0 or rs.sismember(
            "clan:%s:users" % clan_id, uid) == 0:
        return
    chid = "clan:%s:message:%s:" % (clan_id, uid)
    mid = rs.incr(chid + "counter")
    chid = chid + str(mid)
    score = calendar.timegm(datetime.utcnow().timetuple())
    chatm = {
        "id": mid,
        "text": msg.get('text'),
        'sid': uid,
        'clan_id': clan_id,
        "type": "clan_chat"
    }
    chatm['user'] = json.loads(rs.get("users:%s" % uid))
    rs.hmset(chid, chatm)
    rs.zadd("clan:%s:messages" % clan_id, chid, score)
    chatm["create_date"] = score
    message = json.dumps({"type": "clan_chat", "content": chatm})
    members = rs.smembers("clan:%s:users" % clan_id)
    for user_id in members:
        send_message_to_user(user_id, message)
Пример #7
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"