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 login_user(request): context = RequestContext(request) logout(request) # Logout if request.POST: username = request.POST.get('username', '') if not username: raise Http404('Please enter a Username.') user = authenticate(username=username, password='') if user is not None: login(request, user) # Create Chat Rooms ChatRoom.create_rooms(user) next = request.POST.get('next', '') print 'next....... : ', next if next: return HttpResponseRedirect(next) return HttpResponseRedirect('/available_chats/') else: raise Http404('Username does not exist. {0}'.format(username)) context = { 'next': request.GET.get('next', '') } return render_to_response('login.html', context, RequestContext(request))
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)
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 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 chat_room(request, username): """ :param username: The username the logged in user wants to chat with """ if not username: raise Http404('Please provide Username inorder to chat.') if request.user.username.lower() == username.lower(): return HttpResponseRedirect('/available_chats/') user = get_object_or_404(User, username=username) chat_room = ChatRoom.get_room(request.user, user) # Get a chat room for the chat, create's it if one does not exist. # Obtain all the messages in the Chat, order in ascending order of date created messages = reversed(chat_room.messages.order_by('created_dt')) context = { 'username': username, 'chat_room': chat_room, 'messages': messages, } return render(request, "chat/chat_room.html", context=context)
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 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 post(self): chat_room = ChatRoom.get_by_ip(self.request.remote_addr) message = self.get_message() person = self.person() # if message == 'connected': # person.send_sign_on_to_chat_room(chat_room) # else: person.send_message_to_chat_room(message, chat_room)
def GET(self): get_data = web.input(last_id=0) last_id = int(get_data.last_id) room_id = web.ctx.game.player_color messages = [] delete_id = None if last_id == 0: messages = ChatMessage.load(room_id, last_id) else: action, kwargs = wait_for_message(room_id) #sleep up to 300 ms to prevent the thundering herd time.sleep(random.random() * .3) if action == 'send': messages = ChatMessage.load(room_id, last_id) elif action == 'delete': delete_id = kwargs['id'] deletable = is_admin() ChatRoom.set_online(room_id) online_users = [{ 'name': u[1], 'rating': Pretty.rating(u[2]), } for u in ChatRoom.get_online(room_id)] return json.dumps({ 'messages': list( reversed([{ 'id': x.id, 'name': x.name, 'rating': Pretty.rating(x.rating), 'message': x.message, 'deletable': deletable, } for x in messages])), 'online_users': online_users, 'refresh': False, 'delete_id': delete_id, })
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 GET(self): get_data = web.input(last_id=0) last_id = int(get_data.last_id) room_id = web.ctx.game.player_color messages = [] delete_id = None if last_id == 0: messages = ChatMessage.load(room_id, last_id) else: action, kwargs = wait_for_message(room_id) #sleep up to 300 ms to prevent the thundering herd time.sleep(random.random() * .3) if action == 'send': messages = ChatMessage.load(room_id, last_id) elif action == 'delete': delete_id = kwargs['id'] deletable = is_admin() ChatRoom.set_online(room_id) online_users = [{ 'name': u[1], 'rating': Pretty.rating(u[2]), } for u in ChatRoom.get_online(room_id)] return json.dumps({ 'messages': list(reversed([ { 'id': x.id, 'name': x.name, 'rating': Pretty.rating(x.rating), 'message': x.message, 'deletable': deletable, } for x in messages ])), 'online_users': online_users, 'refresh': False, 'delete_id': delete_id, })
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 get(self): ip = self.request.remote_addr chat_room = ChatRoom.get_by_ip(ip) person = self.person() if not person.in_chat_room(chat_room): person.remove_from_old_chat_room() chat_room.add(person) self.template_out('templates/home.html', template_values={ 'token': person.channel_token(), 'num_people': chat_room.num_people() })
def update(self, msg): try: # insert new room-user record cr = ChatRoom_DB() cr.roomname = msg['roomname'] cr.username = msg['postedby'] cr.datelastposted = msg['dateposted'] cr.save() except Exception, e: #print "Error creating new chatroom-user record", e # if record exists, update time instead try: cr = ChatRoom_DB.objects.get(roomname=msg['roomname'], username=msg['postedby']) cr.datelastposted = msg['dateposted'] cr.save() except Exception, e: print "Error updating chat room", e raise
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('/')
import asyncio import peewee_async from models import User, Message, ChatRoom from db import database from settings import DATABASE database.init(**DATABASE) manager = peewee_async.Manager(database) with manager.allow_sync(): User.create_table(True) Message.create_table(True) ChatRoom.create_table(True) for username in ['User1', 'User2', 'User3']: try: User.create(username=username, password='******') except: pass default_user = User.get(User.id == 1) for room in ['flood', 'nsfw', 'music']: ChatRoom.create(name=room, owner=default_user)
async def get(self): # ohuet' mojno rooms = await self.request.app.objects.execute(ChatRoom.select(ChatRoom, User).join(User)) resp = list(map(ChatRoom.as_dict, rooms)) return web.json_response(resp)