def ws_add(message): print 'ws_add_terminal', message['path'] workspace_id, terminal_id = get_ids(message) c = Channel('terminal.connect') c.send({ 'reply_channel': message.reply_channel.name, 'user_id': message.user.id, 'workspace_id': workspace_id, 'terminal_id': terminal_id, })
def test_post_single(self): """ Tests a POST body contained within a single message. """ Channel("test").send({ "reply_channel": "test", "http_version": "1.1", "method": "POST", "path": b"/test2/", "query_string": b"django=great", "body": b"ponies=are+awesome", "headers": { "host": b"example.com", "content-type": b"application/x-www-form-urlencoded", "content-length": b"18", }, }) request = AsgiRequest(self.get_next_message("test")) self.assertEqual(request.path, "/test2/") self.assertEqual(request.method, "POST") self.assertEqual(request.body, b"ponies=are+awesome") self.assertEqual(request.META["HTTP_HOST"], "example.com") self.assertEqual(request.META["CONTENT_TYPE"], "application/x-www-form-urlencoded") self.assertEqual(request.GET["django"], "great") self.assertEqual(request.POST["ponies"], "are awesome") with self.assertRaises(KeyError): request.POST["django"] with self.assertRaises(KeyError): request.GET["ponies"]
def alert(request): if 'api_token' not in request.POST or request.POST[ 'api_token'] != settings.API_TOKEN: return HttpResponse('Unauthorized', status=401) mimetype = 'application/json' data = {} if request.method == 'POST' and 'entity' in request.POST and request.POST[ 'entity'] != '' and 'status' in request.POST and request.POST[ 'status'] != '': data['entity'] = request.POST['entity'] data['status'] = int(request.POST['status']) data['timestamp'] = datetime.datetime.now().timestamp() if 'output' in request.POST: data['output'] = request.POST['output'].rstrip('\n') if 'history' in request.POST: data['history'] = request.POST.getlist('history') if 'occurrences' in request.POST: data['occurrences'] = request.POST['occurrences'] data['result-text'] = "got it!" data['result-code'] = 0 Channel('background-alert').send(data) logger.debug('alert triggered entity: %s status: %s' % (request.POST['entity'], str(request.POST['status']))) return HttpResponse(json.dumps(data), mimetype)
def ws_receive(message): log.debug('received message: {}'.format(message.content['text'])) # Stick the message onto the processing queue Channel('chat-messages').send({ "room": message.channel_session['room'], "text": message.content['text'], })
def test_basic(self): """ Tests a simple request """ # Make stub request and desired response Channel("test").send({ "reply_channel": "test", "http_version": "1.1", "method": "GET", "path": b"/test/", }) response = HttpResponse(b"Hi there!", content_type="text/plain") # Run the handler handler = FakeAsgiHandler(response) reply_messages = list( handler(self.get_next_message("test", require=True))) # Make sure we got the right number of messages self.assertEqual(len(reply_messages), 1) reply_message = reply_messages[0] # Make sure the message looks correct self.assertEqual(reply_message["content"], b"Hi there!") self.assertEqual(reply_message["status"], 200) self.assertEqual(reply_message.get("more_content", False), False) self.assertEqual( reply_message["headers"], [ (b"Content-Type", b"text/plain"), ], )
def ws_receive_api(message): payload = json.loads(message['text']) payload['reply_channel'] = message.content['reply_channel'] payload['userId'] = message.user.id print("ws_receive_api", payload) # Stick the message onto the processing queue Channel("chat-api.receive").send(payload)
def add_new_notification(title,text,toUser=None,url=None): """ Füge eine neue Benachrichtungen an einen bestimmten User oder alle User hinzu :author Vincent :param title: Der Titel der Benachrichtigung :param text: Der Text der Benachrichtigung :param toUser: None, falls die Benachrichtigung an alle gehen soll, sonst eine bestimmte Benutzerinstanz :param url: None, falls keine URL, sonst die URL, die beim Klicken der Benachrichtigung aufgerufen werden sollen :return: -- """ message = {'title':title,'text':text} if toUser is not None: message['userid'] = toUser.id Channel("notification-messages").send({"title": title, "text": text, "userid": toUser.id,'url':url}) else: Channel("notification-messages").send({"title":title,"text":text,'url':url})
def ws_message(message): text = json.loads(message['text']) Channel('websocket.events').send({ 'reply_channel': message.reply_channel.name, 'event': text['event'], 'data': json.dumps(text['data']) })
def unlock_achievement(codeName, user): try: achievement = Achievement.objects.get(codeName=codeName) except Achievement.DoesNotExist: pass achievementUnlock, created = AchievementUnlock.objects.get_or_create(userExtend=user.UserExtend, achievement=achievement) if created: # Si l'achievement est débloqué, on crédite les phis associés userExtend = user.UserExtend userExtend.phi = userExtend.phi + (achievement.phi * userExtend.phi_multiplier) userExtend.save() message = { 'type': 'achievement', 'value': { 'agentUsername': userExtend.agentUsername, 'achievement': { 'name': achievement.name, 'condition': achievement.condition, 'phi': achievement.phi, 'codeName': achievement.codeName } } } Channel('send_message').send(message)
def _fire_triggersets(sender, instance=None, created=False, raw=False, **kwargs): if raw: return # We do not want to fire on loading raw data model = sender.__name__ for triggerset in TriggerSet.objects.filter(model=model): if triggerset.all_triggers_fire(instance, created): email_recipients = [] alert = TriggerAlert.objects.create(triggerset=triggerset, instance_id=instance.id) for subscription in triggerset.subscriptions.all(): alert.statuses.create(user=subscription.user, status=TriggerAlertStatus.ACTIVE, last_updated_by=subscription.user) if subscription.email: email_recipients.append(subscription.user.email) alert.save() if len(email_recipients) > 0: content = triggerset._complete_email_template( instance, alert.fired) message = { 'title': triggerset.email_title, 'content': content, 'recipients': email_recipients, } Channel('send-email').send(message)
def PostJobListAndroid(request): if request.method == 'GET': postjob = PostJob.objects.all() serializer = PostJobSerializer(postjob, many=True) return Response(serializer.data) elif request.method == 'POST': request.data.dict()['CreatedAt'] = timezone.now() request.data.dict()['user'] = request.user.id # print request.data.dict() serializer = PostJobSerializerAndroid(data=request.data.dict()) if serializer.is_valid(): serializer.save() try: print '........try.............' room_name = request.user.id jobname = serializer.validated_data['JobName'] jobid = 'None' import datetime createdat = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S") Channel("my-background-task").send({ "room": room_name, "jobname": jobname, "jobid": jobid, "username": room_name, "createdat": createdat, }) except: print '...................except.................' return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def send_messages(sender, instance, **kwargs): """When there is a message in a conversation we need to send it to any subscribed participants.""" message = instance conversation = message.conversation # TODO: use a serializer topic = 'conversations:message' payload = { 'id': message.id, 'content': message.content, 'author': message.author.id, 'conversation': { 'id': conversation.id } } for item in ChannelSubscription.objects.filter(user__in=conversation.participants.all()): Channel(item.reply_channel).send({ # TODO: use a serializer "text": json.dumps({ 'topic': topic, 'payload': payload }) })
def onClose(self, wasClean, code, reason): if hasattr(self, "reply_channel"): del self.factory.protocols[self.reply_channel] Channel("websocket.disconnect").send({ "reply_channel": self.reply_channel, })
def onMessage(self, payload, isBinary): if isBinary: Channel("websocket.receive").send({ "reply_channel": self.reply_channel, "content": payload, "binary": True, }) else: Channel("websocket.receive").send({ "reply_channel": self.reply_channel, "content": payload.decode("utf8"), "binary": False, })
def test_delay_message(self): """ Tests the message is delayed and dispatched when due """ Channel('asgi.delay').send( { 'channel': 'test', 'delay': 1000, 'content': { 'test': 'value' } }, immediately=True) worker = PatchedWorker(channel_layers[DEFAULT_CHANNEL_LAYER]) worker.termed = 1 worker.run() self.assertEqual(DelayedMessage.objects.count(), 1) with mock.patch('django.utils.timezone.now', return_value=timezone.now() + timedelta(milliseconds=1001)): worker.termed = 1 worker.run() self.assertEqual(DelayedMessage.objects.count(), 0) message = self.get_next_message('test', require=True) self.assertEqual(message.content, {'test': 'value'})
def add_data_to_channel(cls, data): evaluation_msg = { 'channel': 'evaluation', 'content': data, 'delay': 0 * 1000 } Channel('asgi.delay').send(evaluation_msg)
def crear_marca_task(name2, importacion, reply_channel): name = str(name2).upper() brand = MARCA.objects.filter(nombre=name) creado = "-" exito = "SI" if brand.exists(): creado = name + " ya existe" exito = "NO" else: br = MARCA() br.nombre = name if len(name) < 4: br.definicion = name else: br.definicion = name[0] + name[(len(name) - 1) / 2 + 1] + name[len(name) - 1] br.importacion = importacion br.save() creado = name + " fue creado con exito" if reply_channel is not None: Channel(reply_channel).send( {"text": json.dumps({ "exito": exito, "mensaje": creado, })})
def meauw(): """5 second test""" Channel('chat-messages').send({ 'room': 'cats', 'message': 'auto celery', }) logger.info('!@# MEAUW !@#')
def ws_message(message): '''Send a message via web sockets. Currently uses a group identified by notify-username. When a volume export form submission is received, the message is handed off to the volume-export channel, which is handled by :mod:`readux.books.consumers`. Otherwise, messages are routed to the user notification channel.''' # does this really need to be a group? can we just use the reply channel? notify = Group("notify-%s" % message.user.username) # check for volume export data (form submission) if 'volume_export' in message.content['text']: data = json.loads(message.content['text']) # parse_qs returns values as lists formdata = dict( (key, val[0]) for key, val in parse_qs(data['volume_export']).iteritems()) # breaking changes as of channels 1.0 # need to specify immediately=True to send messages before the consumer completes to the end Channel('volume-export').send( { # has to be json serializable, so send username rather than user 'user': message.user.username, 'formdata': formdata, # fixme: why is reply channel not automatically set? # 'reply_channel': message.reply_channel }, immediately=True) else: notify.send({ "text": "%s" % message.content['text'], }, immediately=True)
def send_data_site(message: ChannelMessageFormat) -> None: """ Informs all site users about changed data. """ collection_elements = from_channel_message(message) # Send data to site users. for user_id, channel_names in websocket_user_cache.get_all().items(): if not user_id: # Anonymous user user = None else: try: user = user_to_collection_user(user_id) except ObjectDoesNotExist: # The user does not exist. Skip him/her. continue output = [] for collection_element in collection_elements: formatted_data = collection_element.as_autoupdate_for_user(user) if formatted_data['action'] == 'changed': restricted_data_cache.update_element( user_id or 0, collection_element.collection_string, collection_element.id, formatted_data) else: restricted_data_cache.del_element( user_id or 0, collection_element.collection_string, collection_element.id) output.append(formatted_data) for channel_name in channel_names: send_or_wait( Channel(channel_name).send, {'text': json.dumps(output)})
def available_exams(self): if self.time_since_last_update().seconds > 30: Channel("editorlink.update_cache").send({'pk': self.pk}) if self.cached_available_exams: return json.loads(self.cached_available_exams) else: return []
def test_large(self): """ Tests a large response (will need chunking) """ # Make stub request and desired response Channel("test").send({ "reply_channel": "test", "http_version": "1.1", "method": "GET", "path": b"/test/", }) response = HttpResponse( b"Thefirstthirtybytesisrighthereandhereistherest") # Run the handler handler = FakeAsgiHandler(response) reply_messages = list( handler(self.get_next_message("test", require=True))) # Make sure we got the right number of messages self.assertEqual(len(reply_messages), 2) # Make sure the messages look correct self.assertEqual(reply_messages[0]["content"], b"Thefirstthirtybytesisrighthere") self.assertEqual(reply_messages[0]["status"], 200) self.assertEqual(reply_messages[0]["more_content"], True) self.assertEqual(reply_messages[1]["content"], b"andhereistherest") self.assertEqual(reply_messages[1].get("more_content", False), False)
def subscribe_toggle(request): mimetype = 'application/json' data = {} if request.method == 'POST' and 'entity' in request.POST and request.POST['entity'] != '' and 'status' in request.POST and request.POST['status'] != '': data['entity'] = request.POST['entity'] data['status'] = request.POST['status'] if Subscribe.objects.filter(entity=request.POST['entity'], status=int(request.POST['status'])).count() > 0: # change existing object obj = Subscribe.objects.get(entity=request.POST['entity'], status=int(request.POST['status'])) if request.user.pk not in obj.friends.values_list('pk', flat=True).all(): obj.friends.add(request.user.pk) data['result'] = "subscription added" logger.debug('%s subscribed to %s' % (request.user.username, request.POST['entity'])) else: obj.friends.remove(request.user.pk) data['result'] = "subscription removed" logger.debug('%s unsubscribed from %s' % (request.user.username, request.POST['entity'])) else: # create new object obj = Subscribe(entity=request.POST['entity'], status=int(request.POST['status'])) obj.save() obj.friends.add(request.user.pk) data['result'] = "subscription added" logger.debug('%s subscribed to new entity %s' % (request.user.username, request.POST['entity'])) Channel('background-build-entity-rules').send({'entity': request.POST['entity']}) return HttpResponse(json.dumps(data), mimetype)
def notify_status(request, user, status): request_data = request.POST if request.method == 'POST' else request.GET information = request_data['info'] receivers = request_data['receivers'] receivers = json.loads(receivers) response = {} for receiver in receivers: if attendance_register.hexists(ONLINE, receiver): #info={} if status == 'call': _receivers = receivers[:] _receivers.remove(receiver) info = {} info['info'] = information info['receivers'] = _receivers else: info = {} info['info'] = json.dumps({ 'status': 'disconnect', 'anotherLogin': '******' }) Channel(receiver).send({'text': json.dumps(info)}) response[receiver] = "Success" else: response[receiver] = "Offline" return HttpResponse(json.dumps(response))
def ack(request): mimetype = 'application/json' data = {} if request.method == 'POST' and 'entity' in request.POST and request.POST['entity'] != '' and 'ack_interval' in request.POST and request.POST['ack_interval'] != '': data['entity'] = request.POST['entity'] data['ack_interval'] = request.POST['ack_interval'] data['status'] = request.POST['status'] data['timestamp'] = datetime.datetime.now().timestamp() data['ack_by'] = request.user.username data['ack'] = True data['output'] = "acknowledged by %s for %s hours" % (request.user.username, request.POST['ack_interval']) if 'ack_comment' in request.POST: data['ack_comment'] = 'acknowledged by ' + request.user.username + ': ' + request.POST['ack_comment'] ack_data = { 'user_id': request.user.pk, 'user_name': request.user.username, 'timestamp': datetime.datetime.now().timestamp(), 'ack_interval': request.POST['ack_interval'], 'ack_comment': data['ack_comment'] } logger.debug('ack %s' % json.dumps(ack_data)) cache.set("ack_" + request.POST['entity'], ack_data, timeout=(float(data['ack_interval']) * 3600)) Channel('background-ack').send(data) return HttpResponse(json.dumps(data), mimetype)
def send_to_channel(channel, message): try: Channel(channel).send(message) except BaseChannelLayer.ChannelFull: logger.error('Channel Full. Sleeping for a bit') time.sleep(600) return send_to_channel(channel, message)
def test_disconnect(self): pages = self.get_pages() posts = self.get_posts() post = posts[0] post.enable_liveblog = True post.save() request = self.get_request(pages[0], user=self.user, lang='en') Channel('setup').send({'connect': 1, 'reply_channel': 'reply'}) message = self.get_next_message('setup', require=True) liveblog_connect(message, self.app_config_1.namespace, 'en', post.slug) plugin = add_plugin( post.liveblog, 'LiveblogPlugin', language='en', body='live text', publish=True ) __, admin = plugin.get_plugin_instance() admin.save_model(request, plugin, None, None) result = self.get_next_message(message.reply_channel.name, require=True) self.assertTrue(result['text']) liveblog_disconnect(message, self.app_config_1.namespace, 'en', post.slug) plugin.body = 'modified text' plugin.save() admin.save_model(request, plugin, None, None) result = self.get_next_message(message.reply_channel.name, require=False) self.assertIsNone(result)
def test_extended(self): """ Tests a more fully-featured GET request """ Channel("test").send({ "reply_channel": "test", "http_version": "1.1", "method": "GET", "path": b"/test2/", "query_string": b"x=1&y=foo%20bar+baz", "headers": { "host": b"example.com", "cookie": b"test-time=1448995585123; test-value=yeah", }, "client": ["10.0.0.1", 1234], "server": ["10.0.0.2", 80], }) request = AsgiRequest(self.get_next_message("test")) self.assertEqual(request.path, "/test2/") self.assertEqual(request.method, "GET") self.assertFalse(request.body) self.assertEqual(request.META["HTTP_HOST"], "example.com") self.assertEqual(request.META["REMOTE_ADDR"], "10.0.0.1") self.assertEqual(request.META["REMOTE_HOST"], "10.0.0.1") self.assertEqual(request.META["REMOTE_PORT"], 1234) self.assertEqual(request.META["SERVER_NAME"], "10.0.0.2") self.assertEqual(request.META["SERVER_PORT"], 80) self.assertEqual(request.GET["x"], "1") self.assertEqual(request.GET["y"], "foo bar baz") self.assertEqual(request.COOKIES["test-time"], "1448995585123") self.assertEqual(request.COOKIES["test-value"], "yeah") self.assertFalse(request.POST)
def test_add_plugin_no_publish(self): pages = self.get_pages() posts = self.get_posts() post = posts[0] post.enable_liveblog = True post.save() request = self.get_request(pages[0], user=self.user, lang='en') Channel('setup').send({'connect': 1, 'reply_channel': 'reply'}) message = self.get_next_message('setup', require=True) liveblog_connect(message, self.app_config_1.namespace, 'en', post.slug) plugin = add_plugin( post.liveblog, 'LiveblogPlugin', language='en', body='live text', publish=False ) __, admin = plugin.get_plugin_instance() admin.save_model(request, plugin, None, None) result = self.get_next_message(message.reply_channel.name, require=False) self.assertIsNone(result) plugin.publish = True plugin.save() admin.save_model(request, plugin, None, None) result = self.get_next_message(message.reply_channel.name, require=True) self.assertTrue(result['text']) rendered = json.loads(result['text']) self.assertEqual(plugin.pk, rendered['id']) self.assertEqual(plugin.creation_date.strftime(DATE_FORMAT), rendered['creation_date']) self.assertEqual(plugin.changed_date.strftime(DATE_FORMAT), rendered['changed_date']) self.assertTrue(rendered['content'].find('data-post-id="{}"'.format(plugin.pk)) > -1) self.assertTrue(rendered['content'].find('live text') > -1)
def chats(): # If user want to create a new chat if request.method == 'POST': chatname = request.form.get('chatname') chatname = chatname.strip() for chats in chatlist: if chatname in chats.name: return jsonify({"responce": "Chat is already created"}) # Create new channel class and append to existing one newchannel = Channel(chatname) chatlist.append(newchannel) chatls = [] # Create a dictionary for every object so then can be tranformed easily into JSON objects for object in chatlist: chatls.append(object.__dict__) chatls.append({'true': 'true'}) return jsonify(chatls) # If user promt for chatlist if request.method == 'GET': chatls = [] for object in chatlist: chatls.append(object.__dict__) return jsonify(chatls)
def join_queue(queue_name, player): if player.enrolled_queue != None: multiple_leave_queue_with_trust(player.enrolled_queue, [player]) queue = MatchMakingQueue.objects.get(name=queue_name) queue.total_players += 1 queue.save() player.enrolled_queue = queue player.save() if queue.total_players >= MAX_PLAYER_COUNT: with transaction.atomic(): players_to_join_game = list( queue.player_set.select_for_update().all()[0:MAX_PLAYER_COUNT]) multiple_leave_queue_with_trust(queue_name, players_to_join_game) new_game = Game() game_rules.setup(new_game, players_to_join_game) Channel('game_command').send({ 'command': 'start_game', 'command_args': { 'game_id': new_game.id } })
def onOpen(self): # Make sending channel self.reply_channel = Channel.new_name("!websocket.send") self.request_info["reply_channel"] = self.reply_channel self.last_keepalive = time.time() self.factory.protocols[self.reply_channel] = self # Send news that this channel is open Channel("websocket.connect").send(self.request_info)
def onOpen(self): # Make sending channel self.send_channel = Channel.new_name("django.websocket.send") self.factory.protocols[self.send_channel] = self # Send news that this channel is open Channel("django.websocket.connect").send( send_channel = self.send_channel, **self.request_info )
def parse_mentions(message): try: comment = IssueComment.objects.get(pk=message.content.get('pk')) except IssueComment.DoesNotExist: logger.error('Comment not found', message) return mentions = comment.get_mentions() users = User.objects.filter(username__in=mentions).distinct() orgs = Organisation.objects.filter(short_name__in=mentions).distinct() user_ids = set() channel = Channel('notifications.send_comment_notification') # handle user name mentions for u in users: user_ids.add(u.pk) channel.send({ 'comment_pk': comment.pk, 'user_pk': u.pk, 'user_mention': True }) # handle org name mentions for org in orgs: profiles = Profile.objects.filter(user__membership__org=org)\ .exclude(user_id__in=user_ids)\ .select_related('user') for p in profiles: u = p.user if u.pk not in user_ids: user_ids.add(u.pk) channel.send({ 'comment_pk': comment.pk, 'user_pk': u.pk, 'organisation_mention': True, 'organisation_pk': org.pk, }) return users
def wrapped(*args, **kwargs): reply_channel_name = self.channel_layer.new_channel('{}?'.format(uri)) payload = { 'func_path': func_path, 'uri': uri, 'args': args, 'kwargs': kwargs, 'reply_channel': reply_channel_name, } channel = Channel('wamp.events') channel.send(payload) d = Deferred() def cleanup(result): self.channels.remove(reply_channel_name) del self.reply_channels[reply_channel_name] self.log.info('result: {}'.format(result['total'])) d.addCallback(cleanup) self.channels.add(reply_channel_name) self.reply_channels[reply_channel_name] = d yield d
def ws_message(message): print 'terminal_input', message workspace_id, terminal_id = get_ids(message) if message['text'].startswith('@@RESIZE@@'): data = message['text'].split('@@RESIZE@@')[1].split(':') c = Channel('terminal.resize') c.send({ 'reply_channel': message.reply_channel.name, 'user_id': message.user.id, 'workspace_id': workspace_id, 'terminal_id': terminal_id, 'width': data[0], 'height': data[1] }) else: c = Channel('terminal.input') c.send({ 'reply_channel': message.reply_channel.name, 'user_id': message.user.id, 'workspace_id': workspace_id, 'terminal_id': terminal_id, 'input': message['text'] })
def __init__(self, *args, **kwargs): Request.__init__(self, *args, **kwargs) self.reply_channel = Channel.new_name("!http.response") self.channel.factory.reply_protocols[self.reply_channel] = self
def __init__(self, file, from_mem=False): handle = bass.BASS_StreamCreateFile(from_mem, file, c_longlong(0), c_longlong(0), 0) Channel.__init__(self, handle)
def get_response(self, request): request.response_channel = Channel.new_name("django.wsgi.response") Channel("django.wsgi.request", channel_backend=self.channel_backend).send(**request.channel_encode()) channel, message = self.channel_backend.receive_many_blocking([request.response_channel]) return HttpResponse.channel_decode(message)