Exemple #1
0
def remote_connect(request, message):
    import sputnik

    ret = {}

    # does this work ?
    try:
        clientID = sputnik.incr("sputnik:client_id")
    except:
        sputnik.rcon.connect()
        clientID = sputnik.incr("sputnik:client_id")
        
    ret["clientID"] = clientID
    request.sputnikID = "%s:%s" % (request.session.session_key, clientID)

    if not clientID:
        return

    # subscribe to this channels
    for chnl in message["channels"]:
        if not sputnik.hasChannel(chnl):
            sputnik.createChannel(chnl)

        sputnik.addClientToChannel(chnl, request.sputnikID)

    # set our username
    if request.user and request.user.username.strip() != '' and request.sputnikID and request.sputnikID.find(' ') == -1:
        sputnik.set("ses:%s:username" % request.sputnikID, request.user.username)

    # set our last access
    if request.sputnikID and request.sputnikID.strip() != '' and request.sputnikID and request.sputnikID.find(' ') == -1:
        sputnik.set("ses:%s:last_access" % request.sputnikID, time.time())

    return ret
Exemple #2
0
def remote_unlock_chapter(request, message, bookid, version):
    import re

    if request.user.username == 'booki':
        for key in sputnik.rkeys("booki:%s:locks:%s:*" % (bookid, message["chapterID"])):
            m = re.match("booki:(\d+):locks:(\d+):(\w+)", key)

            if m:
                sputnik.set("booki:%s:killlocks:%s:%s" % (bookid, message["chapterID"], m.group(3)), 1)

    return {}
Exemple #3
0
def remote_connect(request, message):
    """
    Initializes sputnik connection for this client. Creates clientID for this connection. 

    Input:
     - chanels

    @type request: C{django.http.HttpRequest}
    @param request: Client Request object
    @type message: C{dict}
    @param message: Message object
    @rtype: C{string}
    @return: Returns unique Client ID for this connection
    """

    import sputnik

    ret = {}

    # does this work ?
    try:
        clientID = sputnik.incr("sputnik:client_id")
    except:
        sputnik.rcon.connect()
        clientID = sputnik.incr("sputnik:client_id")

    ret["clientID"] = clientID
    request.sputnikID = "%s:%s" % (request.session.session_key, clientID)

    if not clientID:
        return

    # subscribe to this channels
    for chnl in message["channels"]:
        if not sputnik.hasChannel(chnl):
            sputnik.createChannel(chnl)

        sputnik.addClientToChannel(chnl, request.sputnikID)

    # set our username
    if request.user and request.user.username.strip(
    ) != '' and request.sputnikID and request.sputnikID.find(' ') == -1:
        sputnik.set("ses:%s:username" % request.sputnikID,
                    request.user.username)

    # set our last access
    if request.sputnikID and request.sputnikID.strip(
    ) != '' and request.sputnikID and request.sputnikID.find(' ') == -1:
        sputnik.set("ses:%s:last_access" % request.sputnikID, time.time())

    return ret
Exemple #4
0
def remote_connect(request, message):
    """
    Initializes sputnik connection for this client. Creates clientID for this connection.

    Input:
     - chanels

    :Args:
      - request (:class:`django.http.HttpRequest`): Client Request object
      - message (dict): Message object

    :Returns:
      Returns unique Client ID for this connection
    """

    import sputnik

    ret = {}

    # does this work ?
    try:
        clientID = sputnik.incr("sputnik:client_id")
    except Exception as err:
        logger.warn("Not able to get cliend_id from sputnik. Msg: %s" % err)
        sputnik.rcon.connect()
        clientID = sputnik.incr("sputnik:client_id")

    ret["clientID"] = clientID
    request.sputnikID = "%s:%s" % (request.session.session_key, clientID)

    if not clientID:
        return

    # subscribe to this channels
    for chnl in message["channels"]:
        if not sputnik.hasChannel(chnl):
            sputnik.createChannel(chnl)

        sputnik.addClientToChannel(chnl, request.sputnikID)

    # set our username
    if request.user and request.user.username.strip() != '' and request.sputnikID and request.sputnikID.find(' ') == -1:
        sputnik.set("ses:%s:username" % request.sputnikID, request.user.username)

    # set our last access
    if request.sputnikID and request.sputnikID.strip() != '' and request.sputnikID and request.sputnikID.find(' ') == -1:
        sputnik.set("ses:%s:last_access" % request.sputnikID, time.time())

    return ret
Exemple #5
0
def remote_connect(request, message):
    """
    Initializes sputnik connection for this client. Creates clientID for this connection. 

    Input:
     - chanels

    @type request: C{django.http.HttpRequest}
    @param request: Client Request object
    @type message: C{dict}
    @param message: Message object
    @rtype: C{string}
    @return: Returns unique Client ID for this connection
    """

    import sputnik

    ret = {}

    # does this work ?
    try:
        clientID = sputnik.incr("sputnik:client_id")
    except:
        sputnik.rcon.connect()
        clientID = sputnik.incr("sputnik:client_id")
        
    ret["clientID"] = clientID
    request.sputnikID = "%s:%s" % (request.session.session_key, clientID)

    if not clientID:
        return

    # subscribe to this channels
    for chnl in message["channels"]:
        if not sputnik.hasChannel(chnl):
            sputnik.createChannel(chnl)

        sputnik.addClientToChannel(chnl, request.sputnikID)

    # set our username
    if request.user and request.user.username.strip() != '' and request.sputnikID and request.sputnikID.find(' ') == -1:
        sputnik.set("ses:%s:username" % request.sputnikID, request.user.username)

    # set our last access
    if request.sputnikID and request.sputnikID.strip() != '' and request.sputnikID and request.sputnikID.find(' ') == -1:
        sputnik.set("ses:%s:last_access" % request.sputnikID, time.time())

    return ret
Exemple #6
0
def remote_book_notification(request, message, bookid, version):
    res = {}

    import time

    # rcon.delete(key)
    # set the initial timer for editor

    if request.user.username and request.user.username != '':
        sputnik.set("booki:%s:locks:%s:%s" % (bookid, message["chapterID"], request.user.username), time.time())

        if '%s' % sputnik.get("booki:%s:killlocks:%s:%s" % (bookid, message["chapterID"], request.user.username)) == '1':
            sputnik.rdelete("booki:%s:killlocks:%s:%s" % (bookid, message["chapterID"], request.user.username))
            res = {"kill": "please"}

    return res
Exemple #7
0
def remote_get_chapter(request, message, bookid, version):
    res = {}

    chapter = models.Chapter.objects.get(id=int(message["chapterID"]))
    res["title"] = chapter.title
    res["content"] = chapter.content

    if not message.get("lock", True):
        return res

    import time

    # set the initial timer for editor
    sputnik.set("booki:%s:locks:%s:%s" % (bookid, message["chapterID"], request.user.username), time.time())

    sputnik.addMessageToChannel(request, "/booki/book/%s/%s/" % (bookid, version),
                                {"command": "chapter_status",
                                 "chapterID": message["chapterID"],
                                 "status": "edit",
                                 "username": request.user.username})

    return res
 def _set(self, key, value):
     sputnik.set(key, value)
Exemple #9
0
def dispatcher(request, **sputnik_dict):
    """
    Main Sputnik dispatcher. Every Sputnik request goes through this dispatcher. 

    Input arguments are passed through C{request.POST}:
      - C{request.POST['messages']} 
          List of messages client is sending to server.
      - C{request.POST['clientID']} 
          Unique client ID for this connection.

    This is just another Django view.

    @todo: Change logging and error handling.

    @type request: C{django.http.HttpRequest}
    @param request: Client Request object
    @type sputnik_dict: C{dict}
    @param sputnik_dict: Mapping of channels with specific python modules.
    @rtype: C{HttpResponse}
    @return: Return C{django.http.HttpResponse} object.
    """

    try:
        inp =  request.POST
    except IOError:
        return HttpResponse(simplejson.dumps({"result": False, "messages": []}), mimetype="text/json")

    results = []

    clientID = None
    messages = simplejson.loads(inp.get("messages", "[]"))

    if inp.has_key("clientID") and inp["clientID"]:
        clientID = inp["clientID"]


    for message in messages:
        ret = None
        for mpr in sputnik_dict['map']:
            mtch = re.match(mpr[0], message["channel"])

            if mtch:
                a =  mtch.groupdict()
                _m = __import__(mpr[1])

                for nam in mpr[1].split('.')[1:]:
                    _m = getattr(_m, nam)

                if _m:
                    # should do hasattr first and then getattr
                    fnc = getattr(_m, "remote_%s" % message['command'])

                    if not hasattr(request, "sputnikID"):
                        request.sputnikID = "%s:%s" % (request.session.session_key, clientID)
                        request.clientID  = clientID

                    if fnc:
                        ret = fnc(request, message, **a)
                        if not ret:
                            ret = {}

                        ret["uid"] = message.get("uid")
                        break
                    else:
                        import logging
                        logging.getLogger("booki").error("Could not find function '%s' for Sputnik channel '%d'!" % (message['command'], message['channel']))

        if ret:
            results.append(ret)
        else:
            import logging
            logging.getLogger("booki").error("Sputnik - %s." % simplejson.dumps(message))

    n = 0

    while True:
        v = None

        try:
            if clientID and clientID.find(' ') == -1:
                v = sputnik.rpop("ses:%s:%s:messages" % (request.session.session_key, clientID))
        except:
            if n > 20:
                break


            import logging
            logging.getLogger("booki").debug("Sputnik - Coult not get the latest message from the queue session: %s clientID:%s" %(request.session.session_key, clientID))

#            from booki.utils.log import printStack
#            printStack(None)


        n += 1

        if not v: break
        try:
            results.append(simplejson.loads(v))
        except:

            import logging
            logging.getLogger("booki").debug(v)

#            from booki.utils.log import printStack
#            printStack(None)


    import time, decimal
    try:
        if request.sputnikID and request.sputnikID.find(' ') == -1:
            sputnik.set("ses:%s:last_access" % request.sputnikID, time.time())
    except:

        import logging
        logging.getLogger("booki").debug("Sputnik - CAN NOT SET TIMESTAMP.")

#        from booki.utils.log import printStack
#        printStack(None)


    # this should not be here!
    # timeout old edit locks

    locks = {}

    _now = time.time() 
    try:
        for k in sputnik.rkeys("ses:*:last_access"):
            tm = sputnik.get(k)

            if type(tm) in [type(' '), type(u' ')]:
                try:
                    tm = decimal.Decimal(tm)
                except:
                    continue

        # timeout after 2 minute
            if  tm and decimal.Decimal("%f" % _now) - tm > 60*2:
                sputnik.removeClient(request, k[4:-12])
    except:
        import logging
        logging.getLogger("booki").debug("Sputnik - can not get all the last accesses")

#        from booki.utils.log import printStack
#        printStack(None)


    ret = {"result": True, "messages": results}

    try:
        return HttpResponse(simplejson.dumps(ret), mimetype="text/json")
    except:
        transaction.rollback()
    finally:
        transaction.commit()
Exemple #10
0
 def _set(self, key, value):
     sputnik.set(key, value)
Exemple #11
0
def set_last_access(request):
    try:
        if request.sputnikID and request.sputnikID.find(' ') == -1:
            sputnik.set("ses:%s:last_access" % request.sputnikID, time.time())
    except:
        logger.error("Can not set timestamp.")
Exemple #12
0
def dispatcher(request, **sputnik_dict):
    """
    Main Sputnik dispatcher. Every Sputnik request goes through this dispatcher. 

    Input arguments are passed through C{request.POST}:
      - C{request.POST['messages']} 
          List of messages client is sending to server.
      - C{request.POST['clientID']} 
          Unique client ID for this connection.

    This is just another Django view.

    @todo: Change logging and error handling.

    @type request: C{django.http.HttpRequest}
    @param request: Client Request object
    @type sputnik_dict: C{dict}
    @param sputnik_dict: Mapping of channels with specific python modules.
    @rtype: C{HttpResponse}
    @return: Return C{django.http.HttpResponse} object.
    """

    try:
        inp =  request.POST
    except IOError:
        return HttpResponse(simplejson.dumps({"result": False, "messages": []}), mimetype="text/json")

    results = []

    clientID = None

    try:
        messages = simplejson.loads(inp.get("messages", "[]"))
    except ValueError:
        return HttpResponse(simplejson.dumps({"result": False, "messages": []}), mimetype="text/json")

    if inp.has_key("clientID") and inp["clientID"]:
        clientID = inp["clientID"]


    for message in messages:
        ret = None
        for mpr in sputnik_dict['map']:
            mtch = re.match(mpr[0], message["channel"])

            if mtch:
                a =  mtch.groupdict()
                _m = __import__(mpr[1])

                for nam in mpr[1].split('.')[1:]:
                    _m = getattr(_m, nam)

                if _m:
                    # should do hasattr first and then getattr
                    fnc = getattr(_m, "remote_%s" % message['command'])

                    if not hasattr(request, "sputnikID"):
                        request.sputnikID = "%s:%s" % (request.session.session_key, clientID)
                        request.clientID  = clientID

                    if fnc:
                        ret = fnc(request, message, **a)
                        if not ret:
                            ret = {}

                        ret["uid"] = message.get("uid")
                        break
                    else:
                        import logging
                        logging.getLogger("booki").error("Could not find function '%s' for Sputnik channel '%d'!" % (message['command'], message['channel']))

        if ret:
            results.append(ret)
        else:
            import logging
            logging.getLogger("booki").error("Sputnik - %s." % simplejson.dumps(message))

    n = 0

    while True:
        v = None

        try:
            if clientID and clientID.find(' ') == -1:
                v = sputnik.rpop("ses:%s:%s:messages" % (request.session.session_key, clientID))
        except:
            if n > 20:
                break


            import logging
            logging.getLogger("booki").debug("Sputnik - Coult not get the latest message from the queue session: %s clientID:%s" %(request.session.session_key, clientID))

#            from booki.utils.log import printStack
#            printStack(None)


        n += 1

        if not v: break
        try:
            results.append(simplejson.loads(v))
        except:

            import logging
            logging.getLogger("booki").debug(v)

#            from booki.utils.log import printStack
#            printStack(None)


    import time, decimal
    try:
        if request.sputnikID and request.sputnikID.find(' ') == -1:
            sputnik.set("ses:%s:last_access" % request.sputnikID, time.time())
    except:

        import logging
        logging.getLogger("booki").debug("Sputnik - CAN NOT SET TIMESTAMP.")

#        from booki.utils.log import printStack
#        printStack(None)


    # this should not be here!
    # timeout old edit locks

    locks = {}

    _now = time.time() 
    try:
        for k in sputnik.rkeys("ses:*:last_access"):
            tm = sputnik.get(k)

            if type(tm) in [type(' '), type(u' ')]:
                try:
                    tm = decimal.Decimal(tm)
                except:
                    continue

        # timeout after 2 minute
            if  tm and decimal.Decimal("%f" % _now) - tm > 60*2:
                sputnik.removeClient(request, k[4:-12])
    except:
        import logging
        logging.getLogger("booki").debug("Sputnik - can not get all the last accesses")

#        from booki.utils.log import printStack
#        printStack(None)


    ret = {"result": True, "messages": results}

    try:
        return HttpResponse(simplejson.dumps(ret), mimetype="text/json")
    except:
        transaction.rollback()
    finally:
        transaction.commit()