Changeset - dd896321faee
[Not reviewed]
default
0 5 0
drewp@bigasterisk.com - 12 years ago 2013-06-13 01:31:16
drewp@bigasterisk.com
subserver can get a snapshot from vidref and display it on the sub
Ignore-this: 9ea0a172869922d22d8c5cf6ee4bf3da
5 files changed with 54 insertions and 10 deletions:
0 comments (0 inline, 0 general)
bin/subserver
Show inline comments
 
#!bin/python
 
"""
 
live web display of all existing subs with pictures, mainly for
 
dragging them into CC
 
"""
 
from run_local import log
 
from twisted.internet import reactor
 
import twisted.internet.error
 
import sys, optparse, logging, json, os, subprocess
 
import sys, optparse, logging, json, subprocess, datetime
 
from dateutil.tz import tzlocal
 
from twisted.internet import reactor, defer
 
import cyclone.web, cyclone.httpclient, cyclone.websocket
 
from rdflib import RDF, URIRef, Literal
 
import pyjade.utils
 
from light9.rdfdb.syncedgraph import SyncedGraph
 
from rdflib import RDF
 
from light9.namespaces import L9
 
import pyjade.utils
 
from light9.rdfdb.patch import Patch
 
from light9.namespaces import L9, DCTERMS
 
from light9 import networking, showconfig
 

	
 
try:
 
    import sys
 
    sys.path.append("../homeauto/lib")
 
    sys.path.append("/home/drewp/projects/homeauto/lib")
 
    from cycloneerr import PrettyErrorHandler
 
except ImportError:
 
    class PrettyErrorHandler(object):
 
        pass
 
@@ -64,12 +65,41 @@ class Static(PrettyErrorHandler, cyclone
 
        html = pyjade.utils.process(open(src).read())
 
        self.write(html)
 

	
 
    def responseStaticCoffee(self, src):
 
        self.write(subprocess.check_output([
 
            '/usr/bin/coffee', '--compile', '--print', src]))
 

	
 
class Snapshot(PrettyErrorHandler, cyclone.web.RequestHandler):
 
    @defer.inlineCallbacks
 
    def post(self):
 
        about = URIRef(self.get_argument("about"))
 
        response = yield cyclone.httpclient.fetch(networking.vidref.path("snapshot"), method="POST")
 

	
 
        snapUri = URIRef(json.loads(response.body)['snapshot'])
 
        # vidref could write about when it was taken, etc. would it be
 
        # better for us to tell vidref where to attach the result in
 
        # the graph, and then it doesn't even have to return anything?
 

	
 
        ctx = showconfig.showUri() + "/snapshots"
 
        
 
        self.settings.graph.patch(Patch(addQuads=[
 
            (about, L9['image'], snapUri, ctx),
 
            (snapUri, DCTERMS['created'],
 
             Literal(datetime.datetime.now(tzlocal())), ctx),
 
            ]))
 
        
 
        self.write(json.dumps({'snapshot': snapUri}))
 

	
 
def newestImage(subject):
 
    newest = (None, None)
 
    for img in graph.objects(subject, L9['image']):
 
        created = graph.value(img, DCTERMS['created'])
 
        if created > newest[0]:
 
            newest = (created, img)
 
    return newest[1]
 
        
 
if __name__ == "__main__":
 
    parser = optparse.OptionParser()
 
    parser.add_option("-v", "--verbose", action="store_true",
 
                      help="logging.DEBUG")
 
    (options, args) = parser.parse_args()
 
@@ -77,19 +107,19 @@ if __name__ == "__main__":
 
    log.setLevel(logging.DEBUG if options.verbose else logging.INFO)
 

	
 
    graph = SyncedGraph("subserver")
 

	
 
    d = {}
 
    def updateSubs():
 

	
 
        subs = []
 
        for sub in graph.subjects(RDF.type, L9['Submaster']):
 
        for sub in sorted(graph.subjects(RDF.type, L9['Submaster'])):
 
            rec = {'uri' : sub}
 
            rec['isLocal'] = graph.contains((sub, RDF.type,
 
                                             L9['LocalSubmaster']))
 
            rec['label'] = graph.label(sub)
 
            rec['img'] = newestImage(sub)
 
            subs.append(rec)
 
        
 
        d.clear()
 
        d.update({'subs': subs})
 
        sendToLiveClients(d=d)
 
    def onNewClient():
 
@@ -98,12 +128,13 @@ if __name__ == "__main__":
 
    graph.addHandler(updateSubs)
 
    
 
    
 
    port = 8052
 
    reactor.listenTCP(port, cyclone.web.Application(handlers=[
 
        (r'/live', Live),
 
        (r'/snapshot', Snapshot),
 
        (r'/(.*)', Static,
 
         {"path" : "light9/subserver",
 
          "default_filename" : "index.jade"}),
 
        ], debug=True, graph=graph, onNewClient=onNewClient))
 
    log.info("serving on %s" % port)
 
    reactor.run()
light9/namespaces.py
Show inline comments
 
from rdflib import Namespace
 

	
 
L9 = Namespace("http://light9.bigasterisk.com/")
 
MUS = Namespace("http://light9.bigasterisk.com/music/")
 
XSD = Namespace("http://www.w3.org/2001/XMLSchema#")
 
DCTERMS = Namespace("http://purl.org/dc/terms/")
light9/subserver/gui.coffee
Show inline comments
 
class Model
 
  constructor: ->
 
    @subs = ko.observable([])
 
    @showLocal = ko.observable(false)
 

	
 
  snapshot: (sub) =>
 
    $.ajax({
 
      url: "snapshot"
 
      type: "POST"
 
      data: {about: sub.uri}
 
    })
 

	
 
model = new Model()
 

	
 
# this sort of works to stop clicks in <input> from following the
 
# submaster hyperlink, but it may make certain clicks act wrong
 
$('a').live('click', (ev) ->
 
  return false if ev.target.tagName == 'INPUT'
light9/subserver/index.jade
Show inline comments
 
@@ -16,13 +16,17 @@ html
 
                                attr: {href: uri}")
 
        div(data-bind="if: isLocal") (local)
 
        div
 
          | Label
 
          input(type="text", data-bind="value: label")
 
        div
 
          img()
 
          img(data-bind="attr: {src: img}")
 
        div
 
          button(data-bind="click: $root.snapshot")
 
            New snapshot
 
            
 
      // /ko
 

	
 
    #status
 
      
 
    script(src="jquery-1.7.2.min.js")
 
    script(src="knockout-2.2.1.js")
pydeps
Show inline comments
 
@@ -11,6 +11,7 @@ nose==1.3.0
 
nose-alert==0.9.0
 
ipdb==0.7
 
# waiting for https://github.com/xolox/python-coloredlogs/pull/1
 
git+git://github.com/drewp/python-coloredlogs@9803112ddf7d4cd7dd001912ad1aa482fb8383f6
 
genshi==0.7
 
pyjade==2.0.2
 
python-dateutil==2.1
 
\ No newline at end of file
0 comments (0 inline, 0 general)