Source

ekkli-maps / common / services.py

Full commit
import logging
from django.http import HttpResponse
from django.utils import simplejson
from google.appengine.api import channel
from common.models import UserChannel

def connected(request):

    client_id = request.session.session_key

    if request.user.is_authenticated():
        obj, created = UserChannel.objects.get_or_create(user = request.user, defaults={'client_id' :client_id})
    else:
        obj, created = UserChannel.objects.get_or_create(client_id = client_id, defaults={})

    obj.page_url = request.POST['pathname']
    obj.client_id=client_id
    obj.connected = True

    obj.save()

    logging.info('client_id:%s %s' % (client_id,obj.user.username))

    check_online_users_event()

    return HttpResponse("i'm connected")

def disconnected(request):

    client_id = request.POST['from']
    obj = UserChannel.objects.get(client_id=client_id)
    obj.connected = False
    obj.save()
    logging.info('%s was disconnected' % client_id)
    check_online_users_event()
    return HttpResponse("i'm disconnected")

def check_online_users_event():

    msg = simplejson.dumps({'entity_type':'check_online_users'})
    for user_channel in UserChannel.objects.filter(connected=True):
        channel.send_message(user_channel.client_id, msg)