1 6
import json
2 6
import logging
3

4 6
from channels import Group
5 6
from channels.auth import channel_session_user_from_http, channel_session_user
6 6
from cyborgbackup.main.auth_token import rest_auth
7

8 6
from django.core.serializers.json import DjangoJSONEncoder
9

10

11 6
logger = logging.getLogger('cyborgbackup.main.consumers')
12

13

14 6
def discard_groups(message):
15 0
    if 'groups' in message.channel_session:
16 0
        for group in message.channel_session['groups']:
17 0
            Group(group).discard(message.reply_channel)
18

19

20 6
@rest_auth
21
def ws_connect(message):
22 0
    message.reply_channel.send({"accept": True})
23 0
    message.content['method'] = 'FAKE'
24 0
    if message.user.is_authenticated:
25 0
        message.reply_channel.send(
26
            {"text": json.dumps({"accept": True, "user": message.user.id})}
27
        )
28
    else:
29 0
        logger.error("Request user is not authenticated to use websocket.")
30 0
        message.reply_channel.send({"close": True})
31 0
    return None
32

33

34 6
@channel_session_user
35
def ws_disconnect(message):
36 0
    discard_groups(message)
37

38

39 6
@channel_session_user
40
def ws_receive(message):
41 0
    raw_data = message.content['text']
42 0
    data = json.loads(raw_data)
43

44 0
    if 'groups' in data:
45 0
        discard_groups(message)
46 0
        groups = data['groups']
47 0
        current_groups = set(message.channel_session.pop('groups') if 'groups' in message.channel_session else [])
48 0
        for group_name, v in groups.items():
49 0
            if type(v) is list:
50 0
                for oid in v:
51 0
                    name = '{}-{}'.format(group_name, oid)
52 0
                    current_groups.add(name)
53 0
                    Group(name).add(message.reply_channel)
54
            else:
55 0
                current_groups.add(group_name)
56 0
                Group(group_name).add(message.reply_channel)
57 0
        message.channel_session['groups'] = list(current_groups)
58

59

60 6
def emit_channel_notification(group, payload):
61 6
    try:
62 6
        Group(group).send({"text": json.dumps(payload, cls=DjangoJSONEncoder)})
63 0
    except ValueError:
64 0
        logger.error("Invalid payload emitting channel {} on topic: {}".format(group, payload))

Read our documentation on viewing source code .

Loading