def try_to_connect_to_room(self, pickle_data: dict) -> dict: try: user = User.get_by_auth_key(auth_key=pickle_data['auth_key']) except UserDoesNotExistsError as error: return {'action': 'ERROR', 'data': str(error)} try: room = Room.get_by_name(pickle_data['data']) except RoomDoesNotExistsError as error: return {'action': 'ERROR', 'data': str(error)} else: users_id = room['users'] for u_id in users_id: room_user = User.get_by_id(u_id) payload = { 'action': 'RECEIVE_MESSAGE', 'data': ('ChatInfo', f"User {user['nickname']} has been connected to a room") } self.connected_clients[room_user['auth_key']].send( pickle.dumps(payload)) Room.add_user_to_room(room_name=room['name'], user_id=user['id']) return { 'action': 'CONNECTED_TO_ROOM_SUCCESSFULLY', 'data': (room['name'], room['messages']) }
def broadcast(self, pickle_data): while True: print(f"BroadCAst: \n{pickle_data}\n") if pickle_data['action'] == 'EXIT_ROOM': print("EXIT_ROOM") users_id = Room.get_by_name(pickle_data['data'][0])['users'] for user_id in users_id: user = User.get_by_id(user_id) if user['auth_key'] != pickle_data['auth_key']: payload = { 'action': 'RECEIVE_MESSAGE', 'data': (User.get_by_auth_key( pickle_data['auth_key'])['nickname'], pickle_data['data'][1]) } self.connected_clients[user['auth_key']].send( pickle.dumps(payload)) # message = b'' # while True: # print('packet') packet = self.connected_clients[pickle_data['auth_key']].recv( 64000) # if not packet: break # message += packet pickle_data = pickle.loads(packet)
def register_user(self, pickle_data: dict) -> dict: try: User.create(pickle_data['data'][0], pickle_data['data'][1]) return { 'action': 'REGISTER_SUCCESS', 'data': 'User has been created successfully', } except UserAlreadyExistsError as error: return {'action': 'ERROR', 'data': str(error)}
def send_text_message_to_chat(self, pickle_data: dict) -> dict: users_id = Room.get_by_name(pickle_data['data'][0])['users'] for user_id in users_id: user = User.get_by_id(user_id) if user['auth_key'] != pickle_data['auth_key']: payload = { 'action': 'RECEIVE_MESSAGE', 'data': (User.get_by_auth_key(pickle_data['auth_key'])['nickname'], pickle_data['data'][1]) } self.connected_clients[user['auth_key']].send( pickle.dumps(payload))
def createRecords(categories, items): from db.database import session, Item, Category, User, getTable img = 'default.jpg' #create users for i in range(1, 6): user = User(email='*****@*****.**' % i, name='User %s' % i) session.add(user) users = getTable(User) #create categories for i in range(1, categories + 1): category = Category(name="Category %s" % i) session.add(category) #create items for j in range(1, items + 1): item = Item(name="Item %s-%s" % (i, j), image=img, category=category, description="Description for item %s %s" % (j, LOREM), user=users[randint(0, 4)]) session.add(item) session.commit()
def login_user(self, pickle_data: dict) -> dict: try: auth_key = User.authenticate(pickle_data['data'][0], pickle_data['data'][1]) return {'action': 'AUTH_SUCCESS', 'data': auth_key} except AuthenticatedError as error: return {'action': 'ERROR', 'data': str(error)}
def exit_rooms(self, pickle_data: dict) -> dict: user_id = User.get_by_auth_key(pickle_data['auth_key']) Room.remove_user_from_room(pickle_data['data'], user_id) text_rooms = self.get_all_text_rooms() voice_rooms = self.get_all_voice_rooms() return { 'action': 'ALL_ROOMS', 'data': { 'text_rooms': text_rooms, 'voice_rooms': voice_rooms } }
def create_room(self, pickle_data: dict) -> dict: try: user = User.get_by_auth_key(pickle_data['auth_key']) room_id = Room.create(pickle_data['data'][0], pickle_data['data'][1], user['_id']) return { 'action': 'CREATED_SUCCESS', 'data': Room.get_by_id(room_id).get('name', None) } except RoomAlreadyExistsError as error: return {'action': 'ERROR', 'data': str(error)} except UserDoesNotExistsError as error: return {'action': 'ERROR', 'data': str(error)} except RoomDoesNotExistsError as error: return {'action': 'ERROR', 'data': str(error)}
def start(update, context): session = Session() try: u = User(chat_id=update.message.chat.id) session.add(u) session.commit() except IntegrityError: print("User already exists") buttons = [[ InlineKeyboardButton(text='To main menu', callback_data=str(MAIN)), ]] keyboard = InlineKeyboardMarkup(buttons) update.message.reply_text("Choose the menu", reply_markup=keyboard) return SELECTING_ACTION
def add_users(self, username, password, email): user = User.query.filter_by(username=username).first() if user: return {'errcode': 1, 'errmsg': '数据存在'} else: try: print(password) t = User( # username=request.json['username'], # password=request.json['password'], # email=request.json['email'], username=username, password=password, email=email, ) # print(email) except Exception as e: print(e) db.session.add(t) db.session.commit() return {"msk": 'ok'}
def message_handler(self, client_socket: socket.socket): while True: try: message = client_socket.recv(1024) pickle_data = pickle.loads(message) print(pickle_data) except: client_socket.close() break # Exit from application and close connection if pickle_data['action'] == "EXIT": if pickle_data.get("auth_key"): auth_key = pickle_data['auth_key'] Room.remove_user_from_rooms( User.get_by_auth_key(auth_key)['_id']) User.logout(auth_key) del self.connected_clients[auth_key] client_socket.close() break # Broadcast message to all chat users # Continue because user, who send a message, does not receive anything elif pickle_data['action'] == "SEND_MESSAGE" and pickle_data.get( 'auth_key', None): self.send_text_message_to_chat(pickle_data) continue # Login user elif pickle_data['action'] == "LOGIN": payload = self.login_user(pickle_data) # add to dict pair: user_auth_key -> socket object self.connected_clients[payload['data']] = client_socket # Register elif pickle_data['action'] == "REGISTER": payload = self.register_user(pickle_data) # Create new room elif pickle_data['action'] == "CREATE_ROOM" and pickle_data.get( 'auth_key', None): payload = self.create_room(pickle_data) # Get all available rooms elif pickle_data['action'] == "GET_ROOMS" and pickle_data.get( 'auth_key', None): payload = self.gel_all_available_rooms(pickle_data) elif pickle_data['action'] == "EXIT_ROOM" and pickle_data.get( 'auth_key', None): payload = self.exit_rooms(pickle_data) elif pickle_data[ 'action'] == "TRY_TO_CONNECT_TO_ROOM" and pickle_data.get( 'auth_key', None): payload = self.try_to_connect_to_room(pickle_data) else: payload = { 'action': 'ERROR', 'data': 'Oopps, something went wrong and we lost yout auth key:( ' 'Please, reconnect to fix this problem.' } print(f"Send:{payload}") client_socket.send(pickle.dumps(payload)) time.sleep(1)