Remove a specific user from a Django Channels group? - django

I have a couple of Django Channels groups that I use to send various messages to the client with.
Can I remove a specific user from one of these groups, using only the ID of the user that I want to remove?
Another potential option would be to force disconnect the user's connection using just their ID.

First, you have to save the user's channel_name to their model
and we assume that you had the group_name of channels too
then you can use group_discard for deleting user from group like this:
group_name = 'name_of_channels_group'
user = User.objects.get(id=id)
channel_name = user.channel_name
async_to_sync(self.channel_layer.group_discard)(group_name, channel_name)
https://channels.readthedocs.io/en/stable/topics/channel_layers.html?highlight=group_send#groups

I have thought couple a days about this problem and have an idea how this can be implemented, but can't test it currently. You should try to change your receive() method like this:
async def receive(self, text_data=None, bytes_data=None):
text_data_json = json.loads(text_data)
message = text_data_json['message']
users_to_kick = text_data_json['kick']
# you should inspect scope['user'] cuz I am not sure in what place
# user's id is placed, but there is 'user' object.
if self.scope['user']['id'] in list(map(int, users_to_kick)):
await self.close()
else:
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'some_method',
'message': message
}
)
You have to have Authorisation system enabled, you can't kick Anonymous users. And you have to send from Front-End a list of users which you want to kick.

You need to prevent connect based on scope['user'] in consumer connect method like this:
class MyConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
id_cannot_connect = 1
if self.scope['user'] == id_cannot_connect:
await self.close()
else:
await self.accept()
If you want to make lists of users allowed to connect to specific groups you'll need to store groups and group users in your database and use it the same way in connect method like above.
edit: You can discard user's channel from the group with group_discard in receive_json where you still have access to self.scope['user'] to filter needed users.

I solved this in the end by storing each channel name (self.channel_name) on channel connection, and removing them on disconnect. These are then tied to a Django user object.
Now, if I want to remove a user from a group, I can just loop over all stored channel names tied to a user object, and run group_discard.

Related

Terminate previous Celery task with same task id and run again if created

In my django project, I have made a view class by using TemplateView class. Again, I am using django channels and have made a consumer class too. Now, I am trying to use celery worker to pull queryset data whenever a user refreshes the page. But the problem is, if user again refreshes the page before the task gets finished, it create another task which causes overload.
Thus I have used revoke to terminate the previous running task. But I see, the revoke permanently revoked the task id. I don't know how to clear this. Because, I want to run the task again whenever user call it.
views.py
class Analytics(LoginRequiredMixin,TemplateView):
template_name = 'app/analytics.html'
login_url = '/user/login/'
def get_context_data(self, **kwargs):
app.control.terminate(task_id=self.request.user.username+'_analytics')
print(app.control.inspect().revoked())
context = super().get_context_data(**kwargs)
context['sub_title'] = 'Analytics'
return context
consumers.py
class AppConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
await self.accept()
analytics_queryset_for_selected_devices.apply_async(
args=[self.scope['user'].username],
task_id=self.scope['user'].username+'_analytics'
)
Right now I am solving the problem in this following way. In the consumers.py I made a disconnect function which revoke the task when the web socket get closed.
counter = 0
class AppConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
await self.accept()
analytics_queryset_for_selected_devices.apply_async(args=[self.scope['user'].username],
task_id=self.scope['user'].username+str(counter))
async def disconnect(self, close_code):
global counter
app.control.terminate(task_id=self.scope['user'].username+str(counter), signal='SIGKILL')
counter += 1
await self.close()
counter is used for making new unique task id. But in this method, for every request makes a new task id is added in the revoke list which cause load in memory. To minimize the issue I limited the revoke list size to 20.
from celery.utils.collections import LimitedSet
from celery.worker import state
state.revoked = LimitedSet(maxlen=20, expires=3600)

Is it necessary to make the channel room name unique in django channels? I have a function which works fine but have some concerns

Hey guys I have made a small feed system which uses websockets and opens at the moment someone visits the website and login, all the new feeds will be send live and is updated realtime to those people who are subscribed to a particular user. I am using django-channels for this and have a non-unique room_name as of now, so that it is accessible to every user who is logged in and visits the website. but is it a good practice to do have a non unique room_name for such a system? Does it affect the performance or becomes obsolete if large number of users visits the website at the same time?
OR
Should I create a new table with the current user and a manyTomanyField which contains the subscribed users? if that's the case how do I add all the users to a channel group?
This is the code I have which is working fine now,
async def connect(self):
print('connected')
user = self.scope["user"]
self.user = user
room_name = f'sub-feeds'
self.room_name = room_name
await self.accept()
for now, I am checking a condition which returns True if the user is subscribed to me else it returns False.
async def external_feed(self, event): # sending from outside the consumer
user = self.user
oth_user = event['user']
condition = await self.get_subs_status(user, oth_user)
if condition == True:
await self.send_json({
'newFeed': event['feeds'],
})
I am actually concerned whether this breaks if the number of users increases a lot and using a separate room with subscribed users (new db table) will resolve the issue.
Please ask if you need more info. Help is much appreciated.
Thanks
If I was implementing this, I would use the username(which is assumed to be unique) as the room name. The implementation would be something like this,
from collections import defaultdict
class LiveFeedConsumer(WebsocketConsumer):
# map which uses the subscribed user's username as a key and stores the set of all users' username's who subscribed to their feeds as value.
# Ex - users 1, 2, 3, 4 are available
# __subscriptions[1] = {2, 3} -> Means 2 and 3 have subscribed to 1's feeds
__subscriptions = defaultdict(set)
def connect(self):
# authenticate
user_to_which_to_subscribe_to = get_user_somehow()
self.scope["session"]["room_name"] = user_to_which_to_subscribe_to.username
# Accept connection
self.__subscriptions[user_to_which_to_subscribe_to.username].add(self.scope["user"].username) # To extract users and their subscriptions
def disconnect(self, message):
# Disconnection logic
self.__subscriptions[ self.scope["session"]["room_name"] ].remove(self.scope["user"].username)
def get_subs_status(self, user, other_user):
return user.username in self.__subscriptions[other_user.username]
def external_feed(self, event): # sending from outside the consumer
user = self.user
oth_user = event['user']
condition = self.get_subs_status(user, oth_user)
if condition is True:
self.send_json({
'newFeed': event['feeds'],
})
# publish to pub/sub mechanism to support multiple processes/nodes
You can add the async/await parts of the code. You get the logic.
This way you'll have separate rooms for each user's live feed. Any user can subscribe to multiple other users. Furthermore, you can add a pub/sub listener to scale this horizontally, adding multiple nodes/processes.

Adding multiple groups with django channels and websocket

I try to development a notificaiton system. I would like the system administrator to be able to send notifications to different groups. For this, I create only one websocket connection, and when socket is connected(during login) I want to add the user to the groups it belongs to. I wrote the code as below but I'm not sure it's correct. I am already getting this error: "AttributeError: 'WebSocketProtocol' object has no attribute 'handshake_deferred'"
class MyConsumer(AsyncWebsocketConsumer):
async def connect(self):
if self.scope["user"].is_anonymous:
await self.close()
else:
groups = await sync_to_async(list)(self.scope["user"].channel_groups.all())
for group in groups:
await self.channel_layer.group_add(group.name,self.channel_name)
await self.accept()
print("###CONNECTED")
Can you help me? Am i on the right way? If so how do i fix this error?

Sending a message to a single user using django-channels

I have been trying out django-channels including reading the docs and playing around with the examples.
I want to be able to send a message to a single user that is triggered by saving a new instance to a database.
My use case is creating a new notification (via a celery task) and once the notification has saved, sending this notification to a single user.
This sounds like it is possible (from the django-channels docs)
...the crucial part is that you can run code (and so send on
channels) in response to any event - and that includes ones you
create. You can trigger on model saves, on other incoming messages, or
from code paths inside views and forms.
However reading the docs further and playing around with the django-channels examples, I can't see how I can do this. The databinding and liveblog examples demonstrate sending to a group, but I can't see how to just send to a single user.
Little update since Groups work differently with channels 2 than they did with channels 1. There is no Group class anymore, as mentioned here.
The new groups API is documented here. See also here.
What works for me is:
# Required for channel communication
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
def send_channel_message(group_name, message):
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
'{}'.format(group_name),
{
'type': 'channel_message',
'message': message
}
)
Do not forget to define a method to handle the message type in the Consumer!
# Receive message from the group
def channel_message(self, event):
message = event['message']
# Send message to WebSocket
self.send(text_data=json.dumps({
'message': message
}))
Expanding on #Flip's answer of creating a group for that particular user.
In your python function in your ws_connect function you can add that user into a a group just for them:
consumers.py
from channels.auth import channel_session_user_from_http
from channels import Group
#channel_session_user_from_http
def ws_connect(message):
if user.is_authenticated:
Group("user-{}".format(user.id)).add(message.reply_channel)
To send that user a message from your python code:
my view.py
import json
from channels import Group
def foo(user):
if user.is_authenticated:
Group("user-{}".format(user.id)).send({
"text": json.dumps({
"foo": 'bar'
})
})
If they are connected they will receive the message. If the user is not connected to a websocket it will fail silently.
You will need to also ensure that you only connect one user to each user's Group, otherwise multiple users could receive a message that you intended for only a specific user.
Have a look at django channels examples, particularly multichat for how to implement routing, creating the websocket connection on the client side and setting up django_channels.
Make sure you also have a look at the django channels docs.
In Channels 2, you can save self.channel_name in a db on connect method that is a specific hash for each user. Documentation here
from asgiref.sync import async_to_sync
from channels.generic.websocket import AsyncJsonWebsocketConsumer
import json
class Consumer(AsyncJsonWebsocketConsumer):
async def connect(self):
self.room_group_name = 'room'
if self.scope["user"].is_anonymous:
# Reject the connection
await self.close()
else:
# Accept the connection
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
print( self.channel_name )
Last line returns something like specific.WxuYsxLK!owndoeYTkLBw
This specific hash you can save in user's table.
The best approach is to create the Group for that particular user. When ws_connect you can add that user into Group("%s" % <user>).add(message.reply_channel)
Note: My websocket url is ws://127.0.0.1:8000/<user>
Just to extend #luke_aus's answer, if you are working with ResourceBindings, you can also make it so, that only users "owning" an object retrieve updates for these:
Just like #luke_aus answer we register the user to it's own group where we can publish actions (update, create) etc that should only be visible to that user:
from channels.auth import channel_session_user_from_http,
from channels import Group
#channel_session_user_from_http
def ws_connect(message):
Group("user-%s" % message.user).add(message.reply_channel)
Now we can change the corresponding binding so that it only publishes changes if the bound object belongs to that user, assuming a model like this:
class SomeUserOwnedObject(models.Model):
owner = models.ForeignKey(User)
Now we can bind this model to our user group and all actions (update, create, etc) will only be published to this one user:
class SomeUserOwnedObjectBinding(ResourceBinding):
# your binding might look like this:
model = SomeUserOwnedObject
stream = 'someuserownedobject'
serializer_class = SomeUserOwnedObjectSerializer
queryset = SomeUserOwnedObject.objects.all()
# here's the magic to only publish to this user's group
#classmethod
def group_names(cls, instance, action):
# note that this will also override all other model bindings
# like `someuserownedobject-update` `someuserownedobject-create` etc
return ['user-%s' % instance.owner.pk]
Although it's late but I have a direct solution for channels 2 i.e using send instead of group_send
send(self, channel, message)
| Send a message onto a (general or specific) channel.
use it as -
await self.channel_layer.send(
self.channel_name,
{
'type':'bad_request',
'user':user.username,
'message':'Insufficient Amount to Play',
'status':'400'
}
)
handel it -
await self.send(text_data=json.dumps({
'type':event['type'],
'message': event['message'],
'user': event['user'],
'status': event['status']
}))
Thanks

Control a function (E.g send mail) from a users profile page

I have a profile page like so: http://i.stack.imgur.com/Rx4kg.png . In management I would like a option "Notify by mail" that would control my send_email functions in every application I want. As example I'm using django-messages and it sends private messages aswell as emails when you send a message. I would like for the user to be able to specify if he wants emails aswell when he gets a message.
messages/utils.py
def new_message_email(sender, instance, signal,
subject_prefix=_(u'New Message: %(subject)s'),
template_name="messages/new_message.html",
default_protocol=None,
*args, **kwargs):
"""
This function sends an email and is called via Django's signal framework.
Optional arguments:
``template_name``: the template to use
``subject_prefix``: prefix for the email subject.
``default_protocol``: default protocol in site URL passed to template
"""
if default_protocol is None:
default_protocol = getattr(settings, 'DEFAULT_HTTP_PROTOCOL', 'http')
if 'created' in kwargs and kwargs['created']:
try:
current_domain = Site.objects.get_current().domain
subject = subject_prefix % {'subject': instance.subject}
message = render_to_string(template_name, {
'site_url': '%s://%s' % (default_protocol, current_domain),
'message': instance,
})
if instance.recipient.email != "":
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
[instance.recipient.email,])
except Exception, e:
#print e
pass #fail silently
Apparently instance.recipient.email is the email for the recipient user. So my questions are: How do I go about creating an option in my profile management that can be used in my new_message_email to check if the user wants emails or not? My own thoughts are that I need to save a value in the database for the user and then check for that value in new_message_email function. How I do that isn't clear though. Do I create a new function in my userprofile/views.py and class in userprofile/forms.py? And have my userprofile/overview.html template change them? Some specifics and thoughts if this is the right approach would help alot!
You probably want to start off by creating a user profile so that you have a good way to store weather or not the user wants these emails sent to them. This is done using the AUTH_PROFILE_MODULE setting in your settings.py.
Once you have the data stored, you should be able to access it from instance.recipient (assuming that instance.recipient is a User object). So you could change your code to:
if instance.recipient.get_profile().wants_emails and instance.recipient.email != "":
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL,
[instance.recipient.email,])
Done and done.