async def delete(self): try: assert self.pk is not None token_is = Token() token_is.db = self.db search_q = { 'client': ObjectId(self.pk), 'token': "{}".format(await self.token) } search_key = await token_is.get(**search_q) token_is.pk = search_key.get('_id') await token_is.delete() q = {'_id': ObjectId(self.pk)} remove_result = await self.objects.remove(q) self.result = {'status': True, 'result': remove_result} except (Exception, ) as error: self.result = {'status': False, 'error': "{}".format(error)} finally: return self.result
async def add_person_to_chat(self): q = { 'chat': ObjectId(self.chat), 'client': ObjectId(self.client), } result = await self.get(**q) if result.get('status') is False: await self.save()
async def add_person_to_chat(self): q = { 'chat': ObjectId(self.chat), 'client': ObjectId(self.client), } print("Add person to chat :: ", q) try: await self.get(**q) except(Exception,): pass finally: await self.save()
async def prepare_msg(self): async for msg in self.socket: content = json.loads(msg.data) receiver = content.get('receiver', None) if receiver: await self.check_receiver(receiver) receiver = ObjectId(receiver) msg_obj = MessagesFromClientInChat(chat=self.chat_pk, client=self.client_pk, msg=content.get('msg'), receiver_message=receiver) if self.db: msg_obj.db = self.db await msg_obj.save() for item in self.agents: await self.notify( sender=item.get('client_uid'), message=msg_obj.message_content, socket=item.get('socket'), receiver=receiver, )
async def list_clients(self): result = [] try: assert self.pk is not None cursor = self.objects.find( {'chat': ObjectId(self.pk)} ) while await cursor.fetch_next: doc = cursor.next_object() result.append( { 'chat-id': "{}".format(doc.get('_id')), 'author': "{}".format(doc.get('author')) } ) return result except(Exception,) as error: log.error("%s" % error) finally: return result
async def check_receiver(self, receiver: ObjectId): """ Метод проверяет, что получатель существует и находится в чате с отправителем. :param receiver: индификатор получателя """ client = Client(pk=ObjectId(receiver)) if self.db: client.db = self.db await client.get() q = {'chat': self.chat_pk, 'client': ObjectId(receiver)} if not await self.client_in_chat.get(**q): self.client_in_chat.save(**q)
async def get(self): try: self.ws = web.WebSocketResponse() await self.ws.prepare(self.request) self.chat_pk = ObjectId(self.chat_pk) chat = Chat(pk=self.chat_pk) if self.db: chat.db = self.db self.chat = await chat.get() await self.check_client() self.client_in_chat = ClientsInChatRoom( chat=self.chat_pk, client=self.client_pk, ) if self.db: self.client_in_chat.db = self.db await self.client_in_chat.add_person_to_chat() self.request.app['websockets'].append({ "socket": self.ws, "client_uid": self.client_pk, 'chat_uid': self.chat_pk }) for _ws in self.agents: _ws.get('socket').send_str('%s joined' % self.client_pk) await self.prepare_msg() except (Exception, ) as error: self.response = {'status': False, 'error': "{}".format(error)} log.error(self.response) await self.ws.close() finally: return self.ws
async def check_client(self): token_in_header = self.request.__dict__.get('headers').get( 'AUTHORIZATION', None) if not token_in_header: raise TokeInHeadersNotFound else: token = Token() token.token = token_in_header if self.db: token.db = self.db self.client = await token.find_client_by_key() if not self.client: raise TokenIsNotFound self.client_pk = ObjectId(self.client.get('client'))
async def key(self): assert self.client_uid is not None q = {'client': self.client_uid} search_key = await self.objects.find_one(q) if search_key: token = "{}".format(search_key.get('token')) else: token = str(uuid.uuid4()) await self.save( **{ 'client': ObjectId(self.client_uid), 'token': "{}".format(token), 'create_at': self.create_at.now() }) return token
def __init__(self, client_uid=None): self.client_uid = ObjectId(client_uid) super(Token, self).__init__()
async def messages(self): return await self.objects.find({ 'chat': ObjectId(self.chat) }).order(['join', 1])