Make the structure that we pass over the channel or pseudo-channel called an "event".

Make the string that we pass through pubsub called a "message".
This commit is contained in:
Ian Gulliver
2014-05-09 15:00:48 -07:00
parent e6885042f5
commit 6a6fdc1c41
3 changed files with 36 additions and 37 deletions

25
api.py
View File

@@ -30,21 +30,20 @@ def CreateChannel(google_user, client, args):
token = channel.create_channel( token = channel.create_channel(
client_id=str(client.key()), client_id=str(client.key()),
duration_minutes=config.CHANNEL_DURATION_SECONDS / 60) duration_minutes=config.CHANNEL_DURATION_SECONDS / 60)
messages = [x.ToMessage() events = [x.ToEvent() for x in client.parent().GetStateEntries()]
for x in client.parent().GetStateEntries()]
if google_user: if google_user:
messages.append({ events.append({
'message_type': 'login', 'event_type': 'login',
'google_user': google_user.email(), 'google_user': google_user.email(),
}) })
else: else:
messages.append({ events.append({
'message_type': 'logout', 'event_type': 'logout',
}) })
return { return {
'token': token, 'token': token,
'messages': messages, 'events': events,
} }
@@ -79,11 +78,11 @@ def SetValue(google_user, client, args):
public=public) public=public)
entry.put() entry.put()
msg = entry.ToMessage() event = entry.ToEvent()
clients = (models.Client.all() clients = (models.Client.all()
.ancestor(client.parent_key())) .ancestor(client.parent_key()))
for client in clients: for client in clients:
client.SendMessage(msg) client.SendEvent(event)
return {} return {}
@@ -93,7 +92,7 @@ def Subscribe(google_user, client, args):
messages = args.get('messages', 0) messages = args.get('messages', 0)
return { return {
'messages': models.Subscription.FindOrCreate(subject, client, messages), 'events': models.Subscription.FindOrCreate(subject, client, messages),
} }
@@ -117,7 +116,7 @@ class APIWrapper(webapp2.RequestHandler):
ret = { ret = {
'status': 'ok', 'status': 'ok',
'responses': [], 'responses': [],
'messages': [], 'events': [],
} }
for command in self.request_json['commands']: for command in self.request_json['commands']:
callback = self._COMMANDS[command['command']] callback = self._COMMANDS[command['command']]
@@ -125,9 +124,9 @@ class APIWrapper(webapp2.RequestHandler):
self.verified_google_user, self.verified_google_user,
self.client, self.client,
command.get('arguments', {})) command.get('arguments', {}))
# Magic: if result contains "messages", haul them up a level so the # Magic: if result contains "events", haul them up a level so the
# client can see them as a single stream. # client can see them as a single stream.
ret['messages'].extend(result.pop('messages', [])) ret['events'].extend(result.pop('events', []))
ret['responses'].append(result) ret['responses'].append(result)
return ret return ret

View File

@@ -111,9 +111,9 @@ class StateEntry(db.Model):
entry_value = db.StringProperty() entry_value = db.StringProperty()
public = db.BooleanProperty(required=True, default=False) public = db.BooleanProperty(required=True, default=False)
def ToMessage(self): def ToEvent(self):
return { return {
'message_type': 'state', 'event_type': 'state',
'key': self.entry_key, 'key': self.entry_key,
'value': self.entry_value, 'value': self.entry_value,
'last_set': self.last_set, 'last_set': self.last_set,
@@ -146,10 +146,10 @@ class Subject(db.Model):
obj = Message(parent=self, message=message) obj = Message(parent=self, message=message)
obj.put() obj.put()
json_message = obj.ToMessage() event = obj.ToEvent()
for subscription in Subscription.all().ancestor(self): for subscription in Subscription.all().ancestor(self):
Client.SendByKey(Subscription.client.get_value_for_datastore(subscription), json_message) Client.SendByKey(Subscription.client.get_value_for_datastore(subscription), event)
class Subscription(db.Model): class Subscription(db.Model):
@@ -170,7 +170,7 @@ class Subscription(db.Model):
cls(parent=subject, client=client).put() cls(parent=subject, client=client).put()
if messages == 0: if messages == 0:
return [] return []
return [m.ToMessage() for m in subject.RecentMessages(messages)] return [m.ToEvent() for m in subject.RecentMessages(messages)]
class Message(db.Model): class Message(db.Model):
@@ -179,9 +179,9 @@ class Message(db.Model):
created = db.DateTimeProperty(required=True, auto_now_add=True) created = db.DateTimeProperty(required=True, auto_now_add=True)
message = db.TextProperty(required=True) message = db.TextProperty(required=True)
def ToMessage(self): def ToEvent(self):
return { return {
'message_type': 'message', 'event_type': 'message',
'subject': self.parent_key().name(), 'subject': self.parent_key().name(),
'created': self.created, 'created': self.created,
'message': self.message, 'message': self.message,

View File

@@ -70,7 +70,7 @@ cosmopolite.Client.prototype.registerMessageHandlers_ = function() {
'Received message from bad origin:', e.originalEvent.origin); 'Received message from bad origin:', e.originalEvent.origin);
return; return;
} }
console.log('Received message:', e.originalEvent.data); console.log('Received browser message:', e.originalEvent.data);
this.onReceiveMessage_(e.originalEvent.data); this.onReceiveMessage_(e.originalEvent.data);
}, this)); }, this));
}; };
@@ -134,9 +134,9 @@ cosmopolite.Client.prototype.sendRPCs_ = function(commands, delay) {
this.$.proxy(commands[i]['onSuccess'], this)(data.responses[i]); this.$.proxy(commands[i]['onSuccess'], this)(data.responses[i]);
} }
} }
// Handle messages that were immediately available as if they came over the // Handle events that were immediately available as if they came over the
// channel. // channel.
data['messages'].forEach(this.onServerMessage_, this); data['events'].forEach(this.onServerEvent_, this);
}) })
.fail(function(xhr) { .fail(function(xhr) {
var intDelay = var intDelay =
@@ -218,24 +218,24 @@ cosmopolite.Client.prototype.onSocketClose_ = function() {
}; };
cosmopolite.Client.prototype.onSocketMessage_ = function(msg) { cosmopolite.Client.prototype.onSocketMessage_ = function(msg) {
this.onServerMessage_(JSON.parse(msg.data)); this.onServerEvent_(JSON.parse(msg.data));
}; };
cosmopolite.Client.prototype.onServerMessage_ = function(msg) { cosmopolite.Client.prototype.onServerEvent_ = function(e) {
switch (msg.message_type) { switch (e.event_type) {
case 'state': case 'state':
var key = msg['key']; var key = e['key'];
if (this.stateCache_[key] && if (this.stateCache_[key] &&
this.stateCache_[key]['value'] == msg['value'] && this.stateCache_[key]['value'] == e['value'] &&
this.stateCache_[key]['last_set'] == msg['last_set'] && this.stateCache_[key]['last_set'] == e['last_set'] &&
this.stateCache_[key]['public'] == msg['public']) { this.stateCache_[key]['public'] == e['public']) {
// Duplicate message. // Duplicate event.
break; break;
} }
this.stateCache_[key] = { this.stateCache_[key] = {
'value': msg['value'], 'value': e['value'],
'last_set': msg['last_set'], 'last_set': e['last_set'],
'public': msg['public'], 'public': e['public'],
} }
if ('onStateChange' in this.callbacks_) { if ('onStateChange' in this.callbacks_) {
this.callbacks_['onStateChange'](key, this.stateCache_[key]); this.callbacks_['onStateChange'](key, this.stateCache_[key]);
@@ -244,7 +244,7 @@ cosmopolite.Client.prototype.onServerMessage_ = function(msg) {
case 'login': case 'login':
if ('onLogin' in this.callbacks_) { if ('onLogin' in this.callbacks_) {
this.callbacks_['onLogin']( this.callbacks_['onLogin'](
msg.google_user, e.google_user,
this.urlPrefix_ + '/auth/logout'); this.urlPrefix_ + '/auth/logout');
} }
break; break;
@@ -256,7 +256,7 @@ cosmopolite.Client.prototype.onServerMessage_ = function(msg) {
break; break;
default: default:
// Client out of date? Force refresh? // Client out of date? Force refresh?
console.log('Unknown channel message:', msg); console.log('Unknown channel event:', e);
break; break;
} }
}; };