--- a/tweetcast/server/tweetcast.py Thu Oct 06 11:56:48 2011 +0200
+++ b/tweetcast/server/tweetcast.py Thu Oct 06 12:39:29 2011 +0200
@@ -9,7 +9,7 @@
connectstring = "dbname='tweet_live' user='postgres' host='localhost' password='doiteshimashite'"
columns = [ 'id', 'created_at', 'text', 'user_id', 'screen_name' ]
-lastid = 0L
+selectcommon = "SELECT tweet_tweet.id, tweet_tweet.created_at, text, user_id, screen_name FROM tweet_tweet JOIN tweet_user ON tweet_tweet.user_id = tweet_user.id"
dbpool = adbapi.ConnectionPool("psycopg2",connectstring)
@@ -25,7 +25,7 @@
task.LoopingCall(self.scheduleTweets).start(1)
def scheduleTweets(self):
- dbpool.runQuery("SELECT tweet_tweet.id, tweet_tweet.created_at, text, user_id, screen_name FROM tweet_tweet JOIN tweet_user ON tweet_tweet.user_id = tweet_user.id WHERE tweet_tweet.id > %d ORDER BY tweet_tweet.id ASC"%self.lastid).addCallback(self.callbackTweets)
+ dbpool.runQuery("%s WHERE tweet_tweet.id > %d ORDER BY tweet_tweet.id ASC"%(selectcommon, self.lastid)).addCallback(self.callbackTweets)
def callbackTweets(self, result):
if result:
@@ -36,15 +36,26 @@
self.serverfactory.broadcast(anyjson.serialize(data))
class TweetcastServerProtocol(WebSocketServerProtocol):
-
- def onOpen(self):
- self.factory.register(self)
-
- def connectionLost(self, reason):
- WebSocketServerProtocol.connectionLost(self, reason)
- self.factory.unregister(self)
- def onMessage(self, msg, binary):
- print "Got message: " + msg
+
+ def onOpen(self):
+ self.factory.register(self)
+ dbpool.runQuery("%s WHERE tweet_tweet.id <= %d ORDER BY tweet_tweet.id DESC LIMIT 100"%(selectcommon, self.factory.tweetcast.lastid)).addCallback(self.callbackOldTweets)
+
+ def callbackOldTweets(self, result):
+ if result:
+ data = [dict((columns[i], str(ligne[i])) for i in range(len(columns))) for ligne in result]
+ data.reverse()
+ else:
+ data = None
+ self.sendMessage(anyjson.serialize(data))
+ print "sending old tweets to new client"
+
+ def connectionLost(self, reason):
+ WebSocketServerProtocol.connectionLost(self, reason)
+ self.factory.unregister(self)
+
+ def onMessage(self, msg, binary):
+ print "Got message: " + msg
class TweetcastServerFactory(WebSocketServerFactory):
@@ -53,7 +64,7 @@
def __init__(self, tweetcast=None):
WebSocketServerFactory.__init__(self)
self.clients = []
-# self.tweetcast = tweetcast
+ self.tweetcast = tweetcast
def register(self, client):
if not client in self.clients:
@@ -66,7 +77,7 @@
self.clients.remove(client)
def broadcast(self, msg):
- # print "broadcasting message '%s' .." % msg
+ print "broadcasting ids up to %d" % self.tweetcast.lastid
for c in self.clients:
print "send to " + c.peerstr
c.sendMessage(msg)