def CREATE_ROOM(secure_channel, request): roomname = request['roomname'].strip() members = request['members'] session = Session() result = {'success': False, 'message': ''} room = session.query(ChatRoom).\ filter(ChatRoom.room_name == roomname).\ first() if room: result['message'] = '聊天室已存在!' secure_channel.send(Command.CREATE_ROOM_RESULTT, result) return room = ChatRoom(room_name=roomname) session.add(room) session.commit() for member_name in members: member = session.query(User).\ filter(User.username == member_name).count() if member: roomuser = RoomUser(roomname=roomname, username=member_name) session.add(roomuser) session.commit() if member_name in username_to_secure_channel: username_to_secure_channel[member_name].\ send(Command.ON_NEW_ROOM, roomname)
async def get(self): ws = web.WebSocketResponse() await ws.prepare(self.request) room = [ x for x in self.request.app.rooms if x.id == self.request.match_info['room'] ] if len(room) != 1: room = [ChatRoom(self.request.match_info['room'], self.request.db)] room = room[0] room.subscribe(ws) async for msg in ws: print("Message: ", msg.data) if msg.type == WSMsgType.TEXT: if msg.data == 'close': await ws.close() else: await room.broadcast({ 'msg': msg.data, }) elif msg.type == WSMsgType.ERROR: print('Ws closed with E: %' % ws.exception()) room.remove(ws) print('WS Closed') return ws
def user_page(username): if g.user: #Make sure this is the correct user if username == g.user.username: error = None #Signifies the user has left a chatroom: set their current_chat to null g.user.current_chat = None db.session.commit() if request.method == "POST": #Add a new chatroom chat = ChatRoom.query.filter_by( title=request.form['title']).first() if not request.form['title']: #Check that a title has been added error = "Please enter a title" elif chat is not None: error = "That title already exists" else: #Note: chatrooms can have the same titles, does not affect overall implementation newChat = ChatRoom(request.form['title'], g.user.user_id) db.session.add(newChat) g.user.chatrooms.append(newChat) db.session.commit() return render_template( 'user_page.html', user_chatrooms=g.user.chatrooms, chatrooms=ChatRoom.query.filter( ChatRoom.creator_id != g.user.user_id).all(), error=error) else: abort(401) #If no one is in session, redirect to the root page else: return redirect(url_for('root_page'))
def getMessages(request, message_id=None): try: roomname = request.REQUEST['roomname'] except: return HttpResponseForbidden("Unauthorized access!") try: start_id = request.REQUEST['start_id'] except: start_id = None info = {} cm = ChatMessages() cr = ChatRoom() try: info['messages'] = cm.getMessages(roomname=roomname, start_id=start_id) info['users'] = cr.getUsers(roomname) except: return HttpResponseServerError("Server Error!") json_data = simplejson.dumps(info) response = HttpResponse(json_data) response['Cache-Control'] = 'no-store, no-cache, private, must-revalidate' return response
def testdb_command(): db.drop_all() db.create_all() user1 = User(username='******', password='******') db.session.add(user1) print('User1: %s' % user1.username) user2 = User(username='******', password='******') db.session.add(user2) print('User2: %s' % user2.username) chatroom1 = ChatRoom(name='Super Awesome Chat Room') print('Chatroom1: %s' % chatroom1.name) print(chatroom1.name) db.session.add(chatroom1) user1.created_rooms.append(chatroom1) chatroom1.users.append(user1) print(len(user2.curr_room)) posttime1 = datetime.datetime.now() message1 = Message(creator=user1.username, text="Hello, there!", chatroom=chatroom1.name, posttime=posttime1) db.session.add(message1) db.session.commit() print('Message1: %s' % message1.text)
def chat_create(): room = ChatRoom(name='#' + request.form['name'], desc=request.form['desc'], user_id=current_user.id) db.session.add(room) try: db.session.commit() return redirect(url_for('chat') + '/' + str(room.id)) except: flash('Something is wrong. Try again', 'danger') return redirect(url_for('index'))
def handle_client_msg(json, methods=['GET', 'POST']): print (str(json)) #Get the user who sent the msg user = User.query.filter(User.username == current_user.username).first() #Check to see if user is a client if current_user.username == user.username and user.role == "Client": booster = match_user_with_booster(user) #Create a room name roomname = str(current_user.username) + str(booster) cr = ChatRoom(roomname=roomname) try: db.session.add(cr) db.session.commit() finally: join_room(roomname) socketio.emit('display_to_chat', json, room=roomname, callback=message_received) elif user.role == "None": # Else was the user who sent the message a booster? user = match_booster_with_user(user) print ("User to booster"+ user) roomname = str(user) + str(current_user.username) roomtojoin = ChatRoom.query.filter(ChatRoom.roomname==roomname).first() print (roomtojoin) cr = ChatRoom(roomname=roomtojoin.roomname) print (roomtojoin.roomname) join_room(roomtojoin.roomname) socketio.emit('display_to_chat', json, room=roomname, callback=message_received) else: print (current_user.username) join_room(request.sid) try: msg = ChatLog(json['message'], current_user.username, datetime.datetime.now(), room=roomname) finally: db.session.add(msg) db.session.commit()
def post(self): chatroom_args = chatroom_parser.parse_args() chatroom = ChatRoom(name=chatroom_args['name']) creator = User.query.filter_by( username=chatroom_args['creator']).first() creator.created_rooms.append(chatroom) db.session.add(chatroom) db.session.commit() return chatroom, 201
def sendMessage(request): sent_message = {} # Get request parameters try: sent_message['roomname'] = request.REQUEST['roomname'] sent_message['postedby'] = request.REQUEST['postedby'] sent_message['message'] = request.REQUEST['message'] sent_message['dateposted'] = datetime.utcnow() except: return HttpResponseForbidden("Unauthorized access!") try: start_id = request.REQUEST['start_id'] except: start_id = None cm = ChatMessages() cr = ChatRoom() users = [] messages = [] try: cm.saveMessage(sent_message) cr.update(sent_message) users = cr.getUsers(sent_message['roomname']) messages = cm.getMessages(roomname=sent_message['roomname'], start_id=start_id) except: return HttpResponseServerError("Server Error!") # convert date to string isoformat for return sent_message['dateposted'] = sent_message['dateposted'].isoformat(' ') info = {} info['msg_sent'] = sent_message info['users'] = users info['messages'] = messages json_data = simplejson.dumps(info) response = HttpResponse(json_data) response['Cache-Control'] = 'no-store, no-cache, private, must-revalidate' return response
def testdb_command(): db.drop_all() db.create_all() user1 = User(username='******', password='******') db.session.add(user1) chatroom1 = ChatRoom(name='Super Awesome Chat Room') db.session.add(chatroom1) user1.created_rooms.append(chatroom1) message1 = Message(creator=user1.username, text="Hello, there!", chatroom=chatroom1.name) db.session.add(message1) db.session.commit() print('Initialized the database.')
async def create_room(req): room = await Rooms(req.db).insert({}) req.app.rooms.append(ChatRoom(room.inserted_id, req.db)) return web.HTTPFound('/')