def websocket_connect(self, event): try: queryParams = parse_qs(self.scope["query_string"].decode("utf8")) other_username = queryParams["receiver_username"][0] receiver_id = queryParams["receiver_id"][0] except KeyError: raise StopConsumer("Invalid Payload") user = self.scope['user'] thread_obj, _ = Thread.objects.get_or_new(user, other_username) if not thread_obj: raise StopConsumer("Invalid Payload") self.thread_obj = thread_obj self.room_group_name = room_formatter([int(user.id), int(receiver_id)]) async_to_sync(self.channel_layer.group_add)(self.room_group_name, self.channel_name) user = self.scope['user'] user.online = True user.save() self.send({ "type": "websocket.accept", })
async def connect(self): # Accept first or no close code await self.accept() user_object = self.scope['user'] if not user_object.is_authenticated: await self.close(self.close_codes.NOT_LOGIN) raise StopConsumer() try: self.room_id = self.scope['url_route']['kwargs']['room_id'] self.user = { 'id': user_object.id, 'username': user_object.username, 'avatar': user_object.avatar, } user_already_in_room = await room_manager.join_room( self.room_id, self.channel_name, self.user) await self.send_user_room_info() if user_already_in_room: return await room_manager.room_send( self.room_id, { 'type': 'join_room_msg', 'user': self.user, 'onlineNumber': room_manager.get_online_number( self.room_id), }) except ObjectDoesNotExist: await self.close(self.close_codes.ROOM_NOT_EXIST) raise StopConsumer() except RoomFull: await self.close(self.close_codes.ROOM_FULL) raise StopConsumer()
async def handle(self, body): self.order_id = self.scope["url_route"]["kwargs"][ "order_id" ] is_authorized = await database_sync_to_async( self.verify_user )(self.scope["user"], self.order_id) if is_authorized: logger.info( "Order tracking request for user %s and order %s", self.scope.get("user"), self.order_id, ) payload = await self.query_remote_server( self.order_id ) logger.info( "Order tracking response %s for user %s and order %s", payload, self.scope.get("user"), self.order_id ) await self.send_response(200, payload) else: raise StopConsumer("unauthorized")
def websocket_connect(self, message): task_id = self.scope['url_route']['kwargs'].get('task_id') task_object = models.DeployTask.objects.filter(id=task_id).first() self.accept() # 1. 去数据库中获取现在任务的所有记录以生成图标 diagram_object_list = models.Diagram.objects.filter(task=task_object) diagram_data_list = [] for item in diagram_object_list: temp = { "key": str(item.id), "text": item.text, "color": item.status, } if item.parent: temp['parent'] = str(item.parent_id) diagram_data_list.append(temp) self.send(text_data=json.dumps({'code': 'log', 'data': item.log})) # 2. 将数据返还给用户 self.send(text_data=json.dumps({'code': 'init', 'data': diagram_data_list})) # 3. 判断发布任务的状态,如果发布成功,则断开websocket链接。 if task_object.status == 3: self.close() # 告诉客户端,我要和你断开连接。 raise StopConsumer() # 我先自杀 # 把自己加到 task_id 群里,以接受以后发来的消息。 async_to_sync(self.channel_layer.group_add)(task_id, self.channel_name)
async def websocket_disconnect(self, event): video_thread_id = self.scope['session'].get('video_thread_id', None) videothread = await self.change_videothread_status( video_thread_id, VC_ENDED) if videothread is not None: await self.change_videothread_datetime(video_thread_id, False) await self.channel_layer.group_send( f"videochat_{videothread.caller.id}", { 'type': 'chat_message', 'message': json.dumps({ 'type': "offerResult", 'status': VC_ENDED, 'video_thread_id': videothread.id }), }) await self.channel_layer.group_send( f"videochat_{videothread.callee.id}", { 'type': 'chat_message', 'message': json.dumps({ 'type': "offerResult", 'status': VC_ENDED, 'video_thread_id': videothread.id }), }) await self.channel_layer.group_discard(self.user_room_id, self.channel_name) raise StopConsumer()
async def handle(self, body): self.order_id = self.scope['url_route']['kwargs'][ 'order_id' ] is_authorized = await self.verify_user(self.scope['user'], self.order_id) if is_authorized: logger.info( f'Order tracking request for user ' f'{self.scope.get("user")} and' f' order {self.order_id}', ) payload = await self.query_remote_server(self.order_id) logger.info( f'Order tracking response {payload}' f' for user {self.scope.get("user")} and' f' order {self.order_id}', ) await self.send_response(200, payload) else: logger.error( f'Unauthorized user tracking attempt. OrderID: {self.order_id}. User: {self.scope["cookies"]["username"]}' ) raise StopConsumer()
def websocket_disconnect(self, message): for group in self.groups.keys(): group_discard = async_to_sync(self.channel_layer.group_discard) group_discard('django.%s' % group, self.channel_name) self.send({"type": "websocket.close", "code": 1000}) raise StopConsumer()
async def handle(self, body): """ Трансляция осуществляется только для авторизованных пользователей. Для неавторизованных пользователей метод handle() вызовет исключение StopConsumer, которое остановит потребителя и закроет текущее соединение с клиентом. """ is_employee = await database_sync_to_async(self.is_employee_func )(self.scope['user']) if is_employee: logger.info( "Opening notify stream for user %s and params %s", self.scope.get('user'), self.scope.get('query_string'), ) # Мы будем вызывать метод send_headers() для запуска HTTP-ответа. await self.send_headers(headers=[ ('Cache-Control', 'no-cache'), ('Content-Type', 'text/event-stream'), ('Transfer-Encoding', 'chunked'), ]) self.is_streaming = True self.no_poll = (self.scope.get('query_string') == 'nopoll') asyncio.get_event_loop().create_task(self.stream()) else: logger.info('Unauthorized notify stream for user %s and params %s', self.scope.get('user'), self.scope.get('query_string')) raise StopConsumer('Unauthorized')
async def handle(self, body): is_employee = await database_sync_to_async(self.is_employee_func )(self.scope["user"]) if is_employee: logger.info( "Opening notify stream for user %s and params %s", self.scope.get("user"), self.scope.get("query_string"), ) await self.send_headers(headers=[ ("Cache-Control", "no-cache"), ("Content-Type", "text/event-stream"), ("Transfer-Encoding", "chunked"), ]) self.is_streaming = True self.no_poll = (self.scope.get("query_string") == "nopoll") asyncio.get_event_loop().create_task(self.stream()) else: logger.info( "Unauthorized notify stream for user %s and params %s", self.scope.get("user"), self.scope.get("query_string"), ) raise StopConsumer("Unauthorized")
def websocket_disconnect(self, message): """ Websocket disconnect function. """ self.close() raise StopConsumer()
async def handle(self, body): print('we handling the requests') close_old_connections() is_employee = await database_sync_to_async(self.is_employee_func )(self.scope["user"]) if is_employee: print('is_employee:', is_employee) logger.info( 'Opening notify stream for user %s and params %s', self.scope.get('user'), self.scope.get('query_string'), ) print('available user:'******'user')) print('available chats:', self.scope.get('query_string')) await self.send_headers(headers=[ ("Cache-Control", "no-cache"), ('Content-Type', 'text/event-stream'), ('Transfer-Encoding', 'chunked'), ]) # print('headers:', self.send_headers()) self.is_streaming = True # print('headers:', self.is_streaming) self.no_poll = (self.scope.get('query_string') == "nopoll") asyncio.get_event_loop().create_task(self.stream()) else: logger.info( "Unauthorized notify stream for user %s and params %s", self.scope.get("user"), self.scope.get("query_string"), ) raise StopConsumer('Unauthorized')
def websocket_disconnect(self, message): """ 客户端主动断开了连接 :param message: :return: """ print('客户端断开了') raise StopConsumer()
async def websocket_disconnect(self, close_code): BitmexConsumer.connections.remove(self.channel_name) if len(self.connections) == 0: BitmexConsumer.instrument_task.cancel() BitmexConsumer.instrument_task = None await self.channel_layer.group_discard(self.bitmex_instrument_group, self.channel_name) raise StopConsumer()
async def websocket_disconnect(self, close_code): await self.channel_layer.group_add(self.name, self.channel_name) await self.send({"type": "websocket.close", "code": close_code}) print(f'[{self.name}] Disconnected with code {close_code}') raise StopConsumer()
def websocket_disconnect(self, message): # logger.info(f'{self.account_key}: websocket_disconnect called\nmessage: {message}') # if hasattr(self, 'presence_groups'): # for group in self.presence_groups: # PresenceGroup.objects.remove(group, self.channel_name) raise StopConsumer()
def websocket_disconnect(self, event): user = self.scope['user'] user.online = False user.save() async_to_sync(self.channel_layer.group_discard)(self.room_group_name, self.channel_name) raise StopConsumer("Consumer disconnected")
async def websocket_disconnect(self,event): print('disconnected',event) await self.channel_layer.group_discard( self.chat_room, self.channel_name ) print('DISCONNECT: ', self.chat_room) raise StopConsumer()
async def websocket_disconnect(self, message: dict): """ Called when a WebSocket connection is closed. """ # let all child applications close first await self._disconnect_consumers(message) # raise StopConsumer to halt the ASGI application cleanly and let the server clean it up raise StopConsumer()
async def websocket_disconnect(self, event): print("Gracefully disconnecting....") await self.channel_layer.group_discard( self.room_id, self.channel_name ) await self.send({"type": "websocket.close"}) # await self.add_viewer(-1) raise StopConsumer()
async def disconnect(self): # await self.send_body(json.dumps({"detail": "Connection timeout", "code": "timeout"}).encode('utf-8')) if self.lpt is not None: self.lpt.cancel() # закрываем терминатор лонг полла if not self.old_events and not self.scope['user'].is_anonymous: await self.channel_layer.group_discard( self.post_group_name, self.channel_name, ) raise StopConsumer()
async def http_request(self, message): if "body" in message: self.body.append(message["body"]) if not message.get("more_body"): try: await self.handle(b"".join(self.body)) finally: if not self.keepalive: await self.disconnect() raise StopConsumer()
async def websocket_disconnect(self, close_code): if self.chat: # if chat exists then close the chat channel await self.channel_layer.group_discard( str(self.chat.id).replace("-", ""), self.channel_name) await self.send({"type": "websocket.close", "code": close_code}) raise StopConsumer() print(f'[{self.sender}] Disconnected with code {close_code}')
async def websocket_disconnect(self,event): data_={ 'message_active':"left the chatroom.", 'user': self.scope["user"].username } await self.channel_layer.group_send( self.chat_room_name, { 'type' : 'incoming_msg_ws', 'message': json.dumps(data_), } ) raise StopConsumer()
def connect(self): if not self.user or not self.user.is_authenticated: raise StopConsumer("User was not logged in") login(self.scope, self.user) self.room_name = self.scope['url_route']['kwargs']['room_name'] self.user = self.scope['user'].username if not self.room_name: logout(self.scope) raise StopConsumer("No room name was selected") self.room_group_name = 'chat_%s' % self.room_name async_to_sync(self.channel_layer.group_add)(self.room_group_name, self.channel_name) self.accept() for log in ChatLogModel.objects.filter(timestamp__gte=now() - timedelta(days=1)): if log.group_name == self.room_group_name: event = { 'user': log.user.username, 'message': log.message, 'timestamp': str(log.timestamp) } self.chat_message(event)
async def http_request(self, message: Scope) -> None: """ Async entrypoint - concatenates body fragments and hands off control to ``self.handle`` when the body has been completely received. """ if "body" in message: self.body.append(message["body"]) if not message.get("more_body"): try: await self.handle(b"".join(self.body)) finally: await self.disconnect() raise StopConsumer()
async def get(self, channel: str) -> Any: """Maybe wait for a `put_channel()` on `channel`; return its data.""" if self._closed.is_set(): raise StopConsumer("Django Channel was shut down") if channel not in self._channels: self._channels[channel] = _ChannelQueue() try: return await self._channels[channel].get() finally: # Even if it raises StopConsumer if (channel in self._channels # it may have been deleted in await? and self._channels[channel].unused()): del self._channels[channel]
def websocket_disconnect(self, message): """ 客户端断开链接之后自动触发 :param message: """ # with open('log', 'a') as f : # f.write('In NOtificationConsumer disconnect, online client is ' # + str(clients.keys()) + '\n') # 客户端断开链接之后 应该将当前客户端对象从列表中移除 # clients.remove(self.user_id) if self.user_id in clients: clients.pop(self.user_id) raise StopConsumer() # 主动报异常 无需做处理 内部自动捕获
async def websocket_disconnect(self, event): print(event) await self.channel_layer.group_discard( f"user_{self.scope['user'].employee.id}", self.channel_name, ) await self.channel_layer.group_discard( 'data', self.channel_name, ) await self.close() raise StopConsumer()
async def websocket_disconnect(self, message): """ Called when a WebSocket connection is closed. Base level so you don't need to call super() all the time. """ try: for group in self.groups: await self.channel_layer.group_discard(group, self.channel_name) except AttributeError: raise InvalidChannelLayerError( "BACKEND is unconfigured or doesn't support groups") await self.disconnect(message["code"]) raise StopConsumer()
async def disconnect(self, close_code): congregation = self.scope["url_route"]["kwargs"]["congregation"] if self.task is not None and not self.task.done(): self.task.cancel() with suppress(asyncio.CancelledError): await self.task await self.channel_layer.group_discard(generate_channel_group_name("stage", congregation), self.channel_name) timeout = GLOBAL_TIMEOUT.get(congregation) if timeout is not None and "role" not in self.scope["url_route"]["kwargs"]: timeout.count = timeout.count - 1 if timeout.count == 0: timeout.cancel() GLOBAL_TIMEOUT.pop(congregation) await self.__disconnect_from_extractor() raise StopConsumer()