async def process(self): """ Processing websocket messages """ logger.debug('[%s] [transport] wait', self.name) try: await self._connection() self.listener_task = asyncio.ensure_future(self._ws.receive()) self.sender_task = asyncio.ensure_future(self._outgoing.get()) done, pending = await asyncio.wait( [self.listener_task, self.sender_task], return_when=asyncio.FIRST_COMPLETED) if self.listener_task in done: logger.debug('[%s] [transport] receiving', self.name) await self._incomming.put(self.listener_task.result()) else: self.listener_task.cancel() if self.sender_task in done: message = self.sender_task.result() if str(message) == 'close': return self._ws.send_str(message) logger.debug('[%s] [transport] sending: %r', self.name, message) else: self.sender_task.cancel() except Exception as e: logger.error('[%s] [transport] error: %s %s', self.name, type(e), e)
async def process(self): """ Processing incomming messages """ try: logger.debug('[%s] [processor] processor wait', self.name) message = await self._incomming.get() if str(message) == 'close': return if message.tp == aiohttp.MsgType.text: logger.debug('[%s] [processor] incomming message: %r', self.name, message.data) incomming = BaseMessage( json.loads(message.data.replace('$type', 'type'))) if incomming.type == 'Response': asyncio.ensure_future(self._conversations[int( incomming.id[:-5])].response_handler(incomming)) if incomming.type == 'FatSeqUpdate': peer = incomming.body.peer if peer: if peer.id not in self._conversations: self._conversations[peer.id] = self._conversation( self, peer, self._outgoing, **self._params) asyncio.ensure_future( self._conversations[peer.id].message_handler( incomming.body.message)) if 'HookData' in incomming.body.type: self.webhooks_handler(incomming.body.data) if message.tp in (aiohttp.MsgType.close, aiohttp.MsgType.error): logger.error( '[%s] [processor] websocket error: data: %r, extra: %r', self.name, message.data, message.extra) except Exception as e: logger.error('[%s] [processor] error: %s %s', self.name, type(e), e)
async def _connection(self): """ Make wesocket connection """ if self._ws is None: self._session = aiohttp.ClientSession(loop=self._loop) try: self._ws = await self._session.ws_connect(self._url) logger.debug('[%s] [transport] connect: %s', self.name, self._url) except Exception as e: logger.error('[%s] [transport] connect error: %s %s %s', self.name, self._url, type(e), e) if self._ws.closed: try: self._ws = await self._session.ws_connect(self._url) logger.debug('[%s] [transport] reconnect: %s', self.name, self._url) except Exception as e: logger.error('[%s] [transport] reconnect error: %s %s', self.name, self._url, type(e), e)
async def loadStickerPack(self, **kwargs): """ """ stage, substage = self.stage self.error = False # Download zip-file with stickers if substage == 0: url = kwargs.get('url') try: self.packdata = await download(url) text = 'Download: %d bytes' % (len(self.packdata)) except Exception as e: logger.error('Error download: %s %s', type(e), e) text = 'Failed download %s' % url self.error = True await self.sendText(text) # unpack stickers elif substage == 1: try: with ZipFile(io.BytesIO(self.packdata), 'r') as zf: self.names = [] for name in zf.namelist(): name = name.split('_')[0] if name not in self.names: self.names.append(name) if len(self.names) > 0: text = 'Found %d names in zip-file.' % (len( self.names)) else: text = 'Stickers not found.' % (len(self.names)) self.error = True await self.sendText(text) except Exception as e: logger.error('Error unzip pack: %s %s', type(e), e) text = 'Unpack error. Try once more.' self.error = True await self.sendText(text) # create pack elif substage == 2: out_msg = stickers.CreateStickerPack(self._get_id(), creatorUserId=self._peer.id) await self.send(out_msg) # set packId elif substage == 3: self.packId = kwargs.get('packId') text = ' '.join([ 'Create pack: %s.' % self.packId, ' Uploading stickers on server. Please wait...' ]) await self.sendText(text) # upload stickers to server elif substage == 4: try: with ZipFile(io.BytesIO(self.packdata), 'r') as zf: if len(self.names) > 0: name = self.names.pop(0) image128 = zf.read(name + '_128.webp') image256 = zf.read(name + '_256.webp') image512 = zf.read(name + '_512.webp') out_msg = stickers.AddSticker( self._get_id(), ownerUserId=self._peer.id, packId=self.packId, emoji=[''], small=list(image128), smallW=128, smallH=128, medium=list(image256), mediumW=256, mediumH=256, large=list(image512), largeW=512, largeH=512) await self.send(out_msg) else: await self.sendText('All stickers uploaded.') except Exception as e: logger.error('Error unzip sticker: %s %s', type(e), e) text = 'Upload sticker error. Try once more.' self.error = True await self.sendText(text) # set pack as default elif substage == 5: out_msg = stickers.MakeStickerPackDefault(self._get_id(), userId=self._peer.id, packId=self.packId) await self.send(out_msg) # end of operation elif substage == 6: code = kwargs.get('code') if code: text = 'Error make pack as defaut: %s. Operation end.' % code else: text = 'Pack %s made default. Operation end.' % self.packId await self.sendText(text)