示例#1
0
def update_chat(chat_id):
    # TODO: Add authentication allowing any member of the chat to use
    data = request.get_json()
    chat_name = data.get("chat_name")
    background = data.get("background")

    chat = Chat.get(Chat.id == chat_id)
    if chat_name:
        query = Chat.update(name=chat_name).where(Chat.id == chat_id)
        query.execute()
    elif background:
        query = Chat.update(background=background).where(Chat.id == chat_id)
        query.execute()
    chat = Chat.get(Chat.id == chat_id)

    return jsonify(model_to_dict(chat)), 200
示例#2
0
def chat_info(chat_id):
    chat = Chat.get(Chat.id == chat_id)
    users = [
        model_to_dict(x.user)
        for x in Participation.select().where(Participation.chat == chat_id)
    ]
    return dict(chat=model_to_dict(chat), users=users)
示例#3
0
def list_user_chats(user_id):
    """List all chats for a given user"""
    chats = []
    raw_chats = Participation.select().where(Participation.user == user_id)
    for item in raw_chats:
        chat = Chat.get(Chat.id == item.chat)
        chats.append(model_to_dict(chat))
    return jsonify(chats), 200
示例#4
0
def delete_chat(chat_id):
    try:
        chat = Chat.get(Chat.id == chat_id)
        query = Participation.delete().where(Participation.chat == chat)
        query.execute()
        if chat.delete_instance():
            return "", 204
        else:
            return "", 400
    except Exception as e:
        return str(e), 400
示例#5
0
def user_view(uid, token=True):
    user = User.where('uid', uid).get().first()

    if user:
        if user.public or token == cache.get('user_token_{}'.format(uid)):
            # Get user statistics
            stats = UserStat.where('uid', uid).get().all()
            info = {'first_act': 0,
                    'last_act': 0,
                    'total_msg': 0,
                    'groups': []}
            if stats:
                for stat in stats:
                    info['total_msg'] += stat.msg_count

                    # Generating groups list
                    info['groups'].append({
                        'title': Chat.get(stat.cid).title,
                        'msg_count': stat.msg_count
                    })
                    # Get last activity timestamp
                    if info['last_act'] < stat.last_activity:
                        info['last_act'] = stat.last_activity

                # Generating date from timestamps
                info['first_act'] = datetime.fromtimestamp(stats[-1].last_activity).strftime('%d.%m.%y')
                info['last_act'] = datetime.fromtimestamp(info['last_act']).strftime('%d.%m.%y (%H:%M)')

            page_title = '{} - Confstat'.format(user.fullname)
        else:
            user = None
            info = None
            page_title = 'Confstat'

        return render_template('user.html',
                               page_title=page_title,
                               user=user,
                               info=info,
                               token=token)
    else:
        redirect('/')
示例#6
0
def send_message_to_chat(chat_id):
    """
    Adds a specified message to a chat identified by url "chat_id"

    Client must post json including:
        "type": either 'text' or 'image'
        "content": corresponds to above, message or url
        "size": text only. 0.5 is normal size, spans from 0 to 1
    """
    # TODO: Add authentication allowing any member of the chat to use
    data = request.get_json()

    kind = data.get("type")
    content = data.get("content")
    size = data.get("size")
    if kind != "text" and kind != "image":
        return str("Wrong type"), 400
    elif size < 0 or size > 1:
        return str("Bad size"), 400
    # TODO: if set to "image" test to make sure its a valid url

    message = {
        "event": "message",
        "payload": {
            "sender_id": 1,
            "type": kind,
            "content": content,
            "size": size,
            "seen_by": []
        }
    }
    # TODO: Stop hardcoding the sender_id, and get the id using auth
    events = Chat.get(Chat.id == chat_id).events
    events.append(message)
    query = Chat.update(events=events).where(Chat.id == chat_id)
    query.execute()
    # TODO: Update this using PostgreSQL json assessing features

    return jsonify(events), 200
示例#7
0
def unlike_message(chat_id):
    # TODO: Add authentication allowing any member of the chat to use
    data = request.get_json()

    message_index = data.get("message_index")

    # TODO: if set to "image" test to make sure its a valid url

    like = {
        "event": "dislike",
        "payload": {
            "sender_id": 1,
            "message_index": message_index,
        }
    }
    # TODO: Stop hardcoding the sender_id, and get the id using auth
    events = Chat.get(Chat.id == chat_id).events
    events.append(like)
    query = Chat.update(events=events).where(Chat.id == chat_id)
    query.execute()
    # TODO: Update this using PostgreSQL json assessing features

    return jsonify(events), 200
示例#8
0
def group(chat_hash):
    # Get chat statistics
    chat_stats = ChatStat.where('hash', chat_hash).limit(21).get()

    if chat_stats:
        # Chat
        cid = chat_stats[0].cid
        chat = Chat.get(cid)
        # Chat title
        chat_title = chat.title
        # Bot add date, dd.mm.yy
        add_date = datetime.fromtimestamp(chat_stats[0].last_time).strftime('%d.%m.%y')
        # Today messages
        msg_count = chat_stats[-1].msg_count
        # Today active users
        active_users = chat_stats[-1].users_count
        # Last update
        last_update = datetime.fromtimestamp(chat_stats[-1].last_time).strftime('%d.%m.%y (%H:%M)')
        # Link for public chats
        public_link = chat.public_link

        average_users = 0
        chart = {'labels': [], 'msg_values': [], 'users_values': []}

        # Charts generator
        i = 0
        for chat in chat_stats:
            average_users += chat.users_count

            # Dates, dd/mm
            d = datetime.fromtimestamp(chat.last_time).strftime('%d')

            chart['labels'].append(str(d))
            chart['msg_values'].append(chat.msg_count)
            chart['users_values'].append(chat.users_count)

            i += 1

        # Average number of users
        average_users = round(average_users / i)

        # Generating user list
        users = []
        user_stats = UserStat.where('cid', cid).order_by('msg_count', 'desc').limit(50).get().all()
        for ustat in user_stats:
            user = User.get(ustat.uid)
            users.append({'name': user.fullname,
                          'msg_count': ustat.msg_count,
                          'uid': ustat.uid,
                          'public': user.public})

        # Generating entities
        entities = {'total': 0,
                    'photo': 0,
                    'audio': 0,
                    'video': 0,
                    'document': 0,
                    'url': 0,
                    'hashtag': 0,
                    'bot_command': 0,
                    'mention': 0}
        urls = []
        i = 0
        _entities = Entity.where('cid', cid).order_by('count', 'desc').get().all()
        for entity in _entities:
            if entity.type == 'voice':
                entities['audio'] += entity.count
            else:
                entities[entity.type] += entity.count
            entities['total'] += entity.count

            # Generating urls list
            if entity.type == 'url' and i < 9:
                urls.append({'link': entity.title,
                             'count': entity.count})
                i += 1

        return render_template('group.html',
                               page_title='{} - Confstat'.format(chat_title),
                               chat_title=chat_title,
                               add_date=add_date,
                               msg_count=msg_count,
                               active_users=active_users,
                               average_users=average_users,
                               chart=chart,
                               users=users,
                               entities=entities,
                               urls=urls,
                               last_update=last_update,
                               public_link=public_link)

    else:
        return redirect('/')