view light9/rdfdb/patchreceiver.py @ 966:16c771461cde

attempt to fix zoom corruption when CC song changes, but this didn't work Ignore-this: 819c2ecbb657cae8ca4c4bd7e32c3486
author drewp@bigasterisk.com
date Sat, 15 Jun 2013 08:51:31 +0000
parents ba7ff8c1d8f8
children f554ddf74097
line wrap: on
line source

import logging, cyclone.httpclient, traceback, urllib
from twisted.internet import reactor
from light9.rdfdb.rdflibpatch import patchQuads
from light9.rdfdb.patch import Patch
log = logging.getLogger('syncedgraph')

class PatchReceiver(object):
    """
    runs a web server in this process and registers it with the rdfdb
    master. See onPatch for what happens when the rdfdb master sends
    us a patch
    """
    def __init__(self, label, onPatch):
        """
        label is what we'll call ourselves to the rdfdb server

        onPatch is what we call back when the server sends a patch
        """
        listen = reactor.listenTCP(0, cyclone.web.Application(handlers=[
            (r'/update', makePatchEndpoint(onPatch)),
        ]))
        port = listen._realPortNumber  # what's the right call for this?
        self.updateResource = 'http://localhost:%s/update' % port
        log.info("listening on %s" % port)
        self._register(label)

    def _register(self, label):

        cyclone.httpclient.fetch(
            url='http://localhost:8051/graphClients',
            method='POST',
            headers={'Content-Type': ['application/x-www-form-urlencoded']},
            postdata=urllib.urlencode([('clientUpdate', self.updateResource),
                                       ('label', label)]),
            ).addCallbacks(self._done, log.error)
        log.info("registering with rdfdb")

    def _done(self, x):
        log.debug("registered with rdfdb")
    
        
def makePatchEndpointPutMethod(cb):
    def put(self):
        try:
            p = Patch(jsonRepr=self.request.body)
            log.debug("received patch -%d +%d" % (len(p.delGraph), len(p.addGraph)))
            cb(p)
        except:
            traceback.print_exc()
            raise
    return put

def makePatchEndpoint(cb):
    class Update(cyclone.web.RequestHandler):
        put = makePatchEndpointPutMethod(cb)
    return Update