I want to use the channel api to push updates to open pages, What I have done so far is to store the page client ids in ndb - I have included a code summary
My question is: How do I manage closed pages and expired tokens?
and is this the best way to push updates to many open pages?
open page code:
import webapp2
import uuid
from google.appengine.api import channel
from google.appengine.ext import ndb
class Frame(ndb.Model):
clientID = ndb.StringProperty()
date = ndb.DateTimeProperty(auto_now_add=True)
class MainHandler(BaseHandler):
def get(self):
client_id = str(uuid.uuid4())
channel_token = channel.create_channel(client_id)
frame = Frame(clientID = client_id)
frame.put()
self.render_response('home.html',** "token":channel_token,"client_id":client_id)
send message code:
from google.appengine.api import channel
from google.appengine.ext import ndb
class Frame(ndb.Model):
clientID = ndb.StringProperty()
date = ndb.DateTimeProperty(auto_now_add=True)
frames = Frame.query().fetch(10)
for i in frames:
channel.send_message(i.clientID, "some message to update")
When you enable channel_presence, your application receives POSTs to the following URL paths:
POSTs to /_ah/channel/connected/
POSTs to /_ah/channel/disconnected/
These signal that the client has connected to the channel and can receive messages or has dicsonnected.
Tracking_Client_Connections_and_Disconnections
Dealing with expired tokens:
By default, tokens expire in two hours, unless you explicitly set an expiration time by providing the duration_minutes argument to the create_channel() function when generating the token. If a client remains connected to a channel for longer than the token duration, the socket’s onerror() and onclose() callbacks are called. At this point, the client can make an XHR request to the application to request a new token and open a new channel.
So on your onerror
function you basically do it all over again just like the original connection.
To send updates to many open pages simply iterate round your list of connected users and send them the message individually. There is no "transmit to all" functionality.
You may also want to build in a "heartbeat" that sends messages to supposedly connected clients and remove them if no reply. This is because sometimes (apparently) the disconnected messages are not sent (power failure, whatever) when the browser window is closed.