示例#1
0
    def setUp(self):
        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()
        database.create_all()
        Role.insert_roles()
        self.bob = User(username='******',
                        password='******',
                        email='*****@*****.**',
                        confirmed=True)
        self.arthur = User(username='******',
                           password='******',
                           email='*****@*****.**',
                           confirmed=True)
        self.clair = User(username='******',
                          password='******',
                          email='*****@*****.**',
                          confirmed=True)
        self.morgana = User(username='******',
                            password='******',
                            email='*****@*****.**',
                            confirmed=True)
        self.ophelia = User(username='******',
                            password='******',
                            email='*****@*****.**',
                            confirmed=True)
        self.artorias = User(username='******',
                             password='******',
                             email='*****@*****.**',
                             confirmed=True)

        self.chat_bob_arthur = Chat()
        self.chat_bob_artorias = Chat()
        self.chat_bob_clair = Chat()
        self.chat_morgana_arthur = Chat()
        self.chat_morgana_bob = Chat(name='chat_morgana_bob_')
        self.chat_bob_arthur.add_users([self.bob, self.arthur])
        self.chat_bob_artorias.add_users([self.bob, self.artorias])
        self.chat_bob_clair.add_users([self.bob, self.clair])
        self.chat_morgana_arthur.add_users([self.arthur, self.morgana])
        self.chat_morgana_bob.add_users([self.bob, self.morgana])
        database.session.add_all([
            self.bob, self.arthur, self.ophelia, self.artorias, self.clair,
            self.morgana, self.chat_bob_arthur, self.chat_bob_artorias,
            self.chat_bob_clair, self.chat_morgana_arthur,
            self.chat_morgana_bob
        ])
        database.session.commit()
示例#2
0
def create_chat():
    raw_chat = request.get_json(True)
    chat = Chat(name=raw_chat['name'], created_by=current_user.id)
    db.session.add(chat)
    db.session.commit()

    first_chat_member = ChatMember(user_id=current_user.id,
                                   chat_id=chat.id,
                                   chat_role_id=2)

    chat_members = []
    for raw_member in raw_chat['members']:
        user = None
        print(raw_member)
        if 'id' in raw_member.keys():
            user = User.query.get(raw_member['id'])
        else:
            user = User.query.filter_by(
                username=raw_member['username']).first()

        if user:
            chat_members.append(
                ChatMember(chat_id=chat.id,
                           user_id=user.id,
                           chat_role_id=(raw_member['role'] if 'role'
                                         in raw_member.keys() else 1)))

    db.session.add_all([first_chat_member] + chat_members)
    db.session.commit()
    return ({
        'success': True,
        'id': chat.id,
        'firtsMemberId': first_chat_member.id
    })
def db_setting():
    db.session.add(User(name='김수완', gcn='1103', image_path='profile1'))
    db.session.add(User(name='조호원', gcn='1118', image_path='profile2'))
    db.session.add(
        Club(club_name='세미콜론',
             total_budget=3000,
             current_budget=2000,
             banner_image='banner image',
             hongbo_image='hongbo image',
             profile_image='profile_image'))
    db.session.add(ClubHead(user_id=1, club_id=1))
    db.session.add(Room(user_id=2, club_id=1))
    db.session.add(Chat(room_id=1, msg='첫번째 채팅', user_type='U'))
    db.session.add(Chat(room_id=1, msg='두번째 채팅', user_type='C'))

    db.session.commit()
示例#4
0
    def setUp(self):
        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()
        database.create_all()
        Role.insert_roles()
        self.client = self.app.test_client(use_cookies=True)

        self.bob = User(username='******',
                        password='******',
                        email='*****@*****.**',
                        confirmed=True)
        self.arthur = User(username='******',
                           password='******',
                           email='*****@*****.**',
                           confirmed=True)
        self.clair = User(username='******',
                          password='******',
                          email='*****@*****.**',
                          confirmed=True)
        self.chat_bob_arthur = Chat()
        self.chat_bob_arthur.add_users([self.bob, self.arthur])
        database.session.add_all(
            [self.bob, self.arthur, self.clair, self.chat_bob_arthur])
        database.session.commit()
示例#5
0
def add_chat():
    if request.method == 'POST':
        data = request.form.to_dict()
        chat_context = data['comment_context']
        new_chat = Chat(chat_context, current_user.id)
        db.session.add(new_chat)
        db.session.commit()
    all_chats = Chat.query.all()
    result_list = []
    # TODO limit 두기
    for chat in all_chats:
        author = db.session.query(User).filter(User.id == chat.user_id).first()
        result_list.append({
            "id":
            chat.id,
            "comment_context":
            chat.chat_context,
            "comment_creDate":
            chat.chat_creDate,
            "author":
            author.username,
            "author_id":
            author.id,
            "author_thumbnail":
            "http://127.0.0.1:5000/static/image/user/" + author.thumbnail
        })
    return jsonify(result_list)
def post_chats():
    """
    Create chat
    """
    form = ChatForm()

    if request.content_type != 'application/x-www-form-urlencoded':
        error_msg = 'Invalid content type'
        response = make_response({"error": error_msg}, 400)
        return response

    if not form.validate_on_submit():
        error_msg = 'Invalid form data'
        response = make_response({"error": error_msg}, 400)
        return response

    data = form.title.data

    chat_ = Chat(title=data)

    db.session.add(chat_)
    db.session.commit()

    user_id = request.cookies.get('user_id')
    user = User.query.get(user_id)
    user.chats.append(chat_)
    db.session.commit()

    response = make_response({"status": "ok"}, 201)
    response.headers[
        "Location"] = f"http://{request.host}/api/chats/{chat_.id}"

    return response
def event_send_chat(json):
    logger.info('JSON: ' + str(json))
    emit('recv_chat', {'msg': json.get('msg')}, room=json.get('room_id'))
    db.session.add(
        Chat(room_id=json.get('room_id'),
             msg=json.get('msg'),
             user_type=json.get('user_type')))
    db.session.commit()
示例#8
0
 def get_or_create_chat(self, chat_id: str):
     chat = self.session.query(Chat).get(str(chat_id))
     if chat:
         return chat
     chat = Chat(id=str(chat_id))
     self.session.add(chat)
     self.session.commit()
     return chat
    def wrapper(update: Update, context: CallbackContext, *args, **kwargs):
        if not update.effective_user:
            # bots, may be exclude in filter messages
            return

        if update.effective_chat:
            # we need settings for a group chats, not for a specific user
            # private chat id == user id
            chat_id = update.effective_chat.id
        else:
            # inline commands, get settings for his private chat
            chat_id = update.effective_user.id

        if update.effective_user.language_code:
            # chats don't have language_code, that why we take from user, not so correct yes
            # they will able change language later
            # https://en.wikipedia.org/wiki/IETF_language_tag
            language_code = update.effective_user.language_code.lower()
        else:
            # some users don't have locale, set default
            language_code = settings.LANGUAGE_CODE

        db_session = Session()

        chat = db_session.query(Chat).filter_by(id=chat_id).first()

        if not chat:
            chat = Chat(
                id=chat_id,
                locale=language_code,
                is_show_keyboard=True if chat_id > 0 else
                False,  # never show keyboard for a group chats
            )
            db_session.add(chat)
            try:
                transaction.commit()
                chat_created = True
            except IntegrityError:
                chat_created = False
                logging.exception("Error create chat, chat exists")
                transaction.abort()
            finally:
                chat = db_session.query(Chat).filter_by(id=chat_id).one()
        else:
            chat_created = False

        kwargs["chat_info"] = {
            "chat_id": chat.id,
            "created": chat_created,
            "locale": chat.locale,
            "is_subscribed": chat.is_subscribed,
            "is_show_keyboard": chat.is_show_keyboard,
            "keyboard_size": chat.keyboard_size,
            "default_currency": chat.default_currency,
            "default_currency_position": chat.default_currency_position,
        }

        return func(update, context, *args, **kwargs)
示例#10
0
 def wrapper(bot, update, *args, **kwargs):
     s = Session()
     if not Chat.q.get(update.message.chat.id):
         chat = Chat(id=update.message.chat.id,
                     is_private=update.message.chat.type == 'private')
         s.add(chat)
         s.commit()
     chat = Chat.q.get(update.message.chat.id)  # type: Chat
     return fn(bot, update, *args, chat, **kwargs)
示例#11
0
def createchat(user, bot):
    newchat = Chat(user_id = user, bot_id = bot, botdetail_id = 1)
    db.session.add(newchat)
    db.session.commit()
    response = {}
    instruction = getbotmessage(bot, 1, user)
    response['instruction'] = instruction
    response['id'] = newchat.id
    return response
示例#12
0
 def test_remove_users(self):
     chat = Chat()
     chat.add_users([self.bob, self.clair, self.morgana])
     self.assertEqual(chat.users.count(), 3)
     self.assertIn(self.bob, chat.users.all())
     chat.remove_users([self.bob])
     self.assertEqual(chat.users.count(), 2)
     self.assertNotIn(self.bob, chat.users.all())
     chat.remove_users([self.morgana, self.clair])
     self.assertEqual(chat.users.count(), 0)
示例#13
0
def text(message):
    """Sent by a client when the user entered a new message.
    The message is sent to all people in the room."""
    room = session.get('room')
    print(room)
    username = session.get('name')
    user = db.session.query(User).filter_by(username=username)
    chat = Chat(author=current_user, recipient=user, body=message['msg'])
    db.session.add(chat)
    emit('message', {'msg': session.get('name') + ':' + message['msg']},
         room=room)
示例#14
0
def left(message):
    """Sent by clients when they leave a room.
    A status message is broadcast to all people in the room."""
    room = session.get('room')
    leave_room(room)
    specialty = Specialty.query.get(room)
    if current_user.is_authenticated:
        emit('status', {'msg': current_user.username + ' has left the room.'},
             room=room)
        chat = Chat(author=current_user,
                    text=current_user.username + ' has left the room.',
                    specialty=specialty)
    else:
        emit('status', {'msg': 'anonymous has left the room.'}, room=room)
        chat = Chat(text='anonymous has left the room.', specialty=specialty)
    db.session.add(chat)
    if Chat.query.count() > 25:
        oldest_chat = Chat.query.order_by(Chat.timestamp.asc())[0]
        db.session.delete(oldest_chat)
    db.session.commit()
示例#15
0
    def wrapper_register(*args, **kwargs):
        message = args[0]
        if message is not None:
            chat = message.chat
            if Chat.query.filter(Chat.id == chat.id).first() is None:
                name = chat.first_name if chat.type == 'private' else chat.title
                new_chat = Chat(id=chat.id, name=name)
                db_session.add(new_chat)
                db_session.commit()

        func(*args, **kwargs)
示例#16
0
def create_chat():
    form = ChatForm()

    if form.validate_on_submit():
        new_chat = Chat(name=form.name.data, about=form.about.data, creator=current_user)
        current_user.follow(new_chat)
        db.session.add(new_chat)
        db.session.commit()
        flash('Your new chat is now live!')
        return redirect(url_for('main.show_chat', name=new_chat.name))

    return render_template('create_chat.html', title="New Chat", form=form)
示例#17
0
def text(message):
    """Sent by a client when the user entered a new message.
    The message is sent to all people in the room."""
    room = session.get('room')
    specialty = Specialty.query.get(room)
    if current_user.is_authenticated:
        emit('message', {'msg': current_user.username + ': ' + message['msg']},
             room=room)
        chat = Chat(author=current_user,
                    text=current_user.username + ': ' + message['msg'],
                    specialty=specialty)
    else:
        emit('message', {'msg': 'anonymous' + ': ' + message['msg']},
             room=room)
        chat = Chat(text='anonymous' + ': ' + message['msg'],
                    specialty=specialty)
    db.session.add(chat)
    if Chat.query.count() > 25:
        oldest_chat = Chat.query.order_by(Chat.timestamp.asc())[0]
        db.session.delete(oldest_chat)
    db.session.commit()
示例#18
0
 def friend_send(user_id):
     """好友发送内容"""
     content = request.form.get('content')
     chat = Chat(
         type='chat_room',
         content=content,
         sender_id=current_user.id,
         receiver_id=user_id,
     )
     db.session.add(chat)
     db.session.commit()
     return json.dumps('true')
示例#19
0
def create():
    if request.method == 'POST':
        data = json.loads(request.get_data())
        chat = Chat()
        chat.title = data['title']
        chat.type_id = data['type_id']
        chat.content = data['content']
        chat.is_show = data['is_show']

        db.session.add(chat)
        db.session.commit()
        info = {'chat': chat.to_json()}
        return jsonify(info)
示例#20
0
def chat_create_new(telegram_chat_id: int, session=None) -> Chat:
    """
    Создает новый чат

    :param telegram_chat_id: Идентификатор чата в телеграме
    :param session: Сессия БД
    :return: Созданный чат
    """
    chat = Chat()
    chat.telegram_chat_id = telegram_chat_id
    session.add(chat)
    session.flush()
    return chat
示例#21
0
def add_chat():
    if request.method == 'POST':
        form = request.form
        name = form.get('name')
        chat_url = form.get('chat_url')
        chat_id = form.get('chat_id')
        if chat_id:
            chat = Chat.query.get(chat_id)
            if chat:
                db.session.delete(chat)
                db.session.commit()

        if name:
            if chat_id:
                chat = Chat(chat_id=chat_id, name=name, chat_url=chat_url)
            else:
                chat = Chat(name=name, chat_url=chat_url)
            db.session.add(chat)
            db.session.commit()
            return redirect('/chat')

    return "of the jedi"
示例#22
0
def add_chat():
    data = request.json['nameValuePairs']
    chat = Chat(data['user1'], data['user2'], data['lastMessage'])
    try:
        db.session.add(chat)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        print(getattr(e, 'message', repr(e)))
        return json.jsonify({
            'error': 'Что-то пошло не так! Попробуйте ещё раз.',
            'data': None
        })
示例#23
0
 def chat_room_send(chat_room_id):
     """聊天室发送内容"""
     content = request.form.get('content')
     # import cgi
     # content = cgi.escape(content)
     chat = Chat(
         type='chat_room',
         content=content,
         sender_id=current_user.id,
         chat_room_id=chat_room_id,
     )
     db.session.add(chat)
     db.session.commit()
     send_room_message(chat)
     return json.dumps('true')
示例#24
0
def create_chat(admin, members, chat_id, title):
    members = [get_user(username=mem) for mem in members]

    if not all(admin.have_friend(mem) for mem in members):
        return "one of members is not admin's friend"

    if Chat.query.filter_by(id=chat_id).count() > 0:
        return "i already have chat with this id"

    chat = Chat(chat_id, title)
    db.session.add(chat)
    db.session.commit()

    members.append(admin)
    db.session.add_all([UsersInChat(chat_id, m.id) for m in members])
    db.session.commit()
示例#25
0
def create_and_update_chats(message, methods=['GET', 'POST']):
    room = message['room']
    print(message)
    chatroom = Chatroom.query.get_or_404(message['room'])
    chat = Chat(Content=message['data'],
                OwnerUser=current_user,
                ChatroomId=room)
    # db.session.add(chat)
    # db.session.commit()
    socketio.emit("chat_b", {
        "message": message['data'],
        "email": current_user.Email,
        "ProfilePicture": current_user.ProfilePicture,
        "FirstName": current_user.FirstName
    },
                  room=room)
示例#26
0
def create_all():
    db.create_all()
    user = User(1761161690, '*****@*****.**', 'CITADEL', 1, None, None,
                None, None)
    db.session.add(user)
    user = User(-1235243292, '*****@*****.**', 'Company you need', 0, None,
                None, None, None)
    db.session.add(user)
    auth = Auth(1761161690, -1861353340)
    db.session.add(auth)
    auth = Auth(-1235243292, -1861353340)
    db.session.add(auth)

    tagAndroid = Tag('Android')
    tagWeb = Tag('Web')
    tagAI = Tag('AI')
    tagB = Tag('B2B')
    tagC = Tag('B2C')
    tagG = Tag('B2G')
    tagEd = Tag('Education')
    db.session.add_all([tagAndroid, tagAI, tagB, tagEd, tagWeb, tagC, tagG])
    db.session.commit()

    project = Project(name='RISE',
                      contact=1761161690,
                      contact_name='CITADEL',
                      description_long='The best startup platform ever',
                      cost='100 000',
                      deadlines='1 месяц',
                      website='http://bestApp.ever/RISE')
    project.tags.extend([tagAndroid, tagB, tagC, tagG])
    db.session.add(project)
    project1 = Project('CITADEL Education', 1761161690, 'CITADEL',
                       'The best education platform ever', '110 000 000',
                       '2 месяца', 'http://bestApp.ever/Education')
    project1.tags.extend([tagAI, tagEd, tagWeb])
    db.session.add(project1)

    chat = Chat(1761161690, -1235243292, "Hi there!")
    db.session.add(chat)

    message = Message(1, 1761161690, -1235243292, "Hi there!", "0.0.00 00:00")
    db.session.add(message)

    db.session.commit()
    return str(200)
示例#27
0
def create_chat():
    #print('create chat called')
    form = ChatCreateForm()
    if form.validate_on_submit():
        #print('validated')
        chat = Chat(user_id=current_user.id,
                    title=form.title.data,
                    description=form.description.data)
        #print(chat)
        #print('chat created')
        #chat.set
        db.session.add(chat)
        db.session.commit()
        flash('new chat created')
        #return 'chat finished'
        return redirect(url_for('chat', id=chat.id))
    return render_template('chatCreate.html', title='create chat', form=form)
示例#28
0
def find_create_chat():
    user_id = session["id"]
    try:
        recipient_id = request.json.get("recipient_id")
    except:
        return {"error": "Bad request"}, 404
    recipient = User.query.filter_by(id=recipient_id).first()
    if recipient is None:
        return {"error": "User not found"}, 404
    chat = Chat.query \
        .filter(Chat.user1_id.in_([user_id, recipient_id])) \
        .filter(Chat.user2_id.in_([user_id, recipient_id])) \
        .first()
    if chat is None:
        chat = Chat(user1_id=user_id, user2_id=recipient_id)
        db.session.add(chat)
        db.session.commit()
    return {"chat_id": chat.id, "user_id": user_id}, 200
示例#29
0
def create_process():
    if session.get('id', '') == '':
        return redirect('/business/')
    elif not Business.check_confirmed(session.get('id', '')):
        return redirect('/business/unconfirmed')
    b_id = session['id']
    form = CreateProcessForm()
    s_form = SelectFieldTypeForm()
    h = HelpForm()
    s_form.select_type.choices = [(p.id, p.type) for p in PossibleProcess.query.filter_by(business_id=b_id).all()]
    d_form = DateForm()

    if form.validate_on_submit() and d_form.validate_on_submit():

        if Client.email_is_free(form.client_email.data):
            client = Client(form.client_email.data)
            cl_id = client.save()
        else:
            cl_id = Client.get_id(form.client_email.data)
        client_password = Client.random_password(10)
        number = Process.random_number()
        process = Process(s_form.select_type.data, form.description.data, b_id, cl_id, number, form.price.data,
                          client_password,
                          d_form.dt.data, 0)
        pr_id = process.save()
        id_stage = Stage.get_not_started(s_form.select_type.data)
        process = Process.query.filter_by(id=pr_id).first()
        process.current_stage = id_stage
        chat = Chat(pr_id, b_id)
        chat.save()
        process.save()

        Process.send_number(form.client_email.data, Business.get_name(b_id), number, client_password)

        # string = "Услуга была создана под номером: " + number
        return redirect(url_for('business.created_process', process_id=pr_id))
    elif form.validate_on_submit() and not d_form.validate_on_submit():
        d_form.dt.errors = ("Выберите дату", "")

    h.desc.choices = [(p.desc, p.desc) for p in PossibleProcess.query.filter_by(business_id=b_id).all()]
    h.price.choices = [(p.price, p.price) for p in PossibleProcess.query.filter_by(business_id=b_id).all()]
    h.pic.choices = [(p.picture, p.picture) for p in PossibleProcess.query.filter_by(business_id=b_id).all()]
    return render_template('create_process.html', form=form, h=h, s_form=s_form, d_form=d_form, title='Создание заказа')
示例#30
0
def chat_group():
    token = request.headers['token']
    uid = request.get_json().get('user_id')
    username = request.get_json().get('username')
    chatimage = request.get_json().get('chatimage')

    customer = Customer.query.filter_by(id=uid).first()
    if customer.confirm(token):
        try:
            chat = Chat(username=username,
                        customer_id=uid,
                        consumption=0.0,
                        chatimage=chatimage)
            db.session.add(chat)
            db.session.commit()
            return jsonify({}), 200
        except:
            return jsonify({}), 500
    return jsonify({}), 401