def get(self): # 表示するHTMLファイルのパス取得 path = os.path.join(os.path.dirname(__file__),'drawing.html') # リクエストからtoken(ボード名称)取得 boardname = self.request.get('bname') # ユーザID生成 user = time.time() # Channel生成(リクエストにボード名称がない場合、tokenには固定値"draw"を設定) if (boardname): token = channel.create_channel(boardname) else: token = channel.create_channel('draw') boardname = 'draw' # response生成 res_values = { 'token': token, 'bname':boardname, 'user': user, 'startx': [], 'starty': [], 'endx': [], 'endy': [] } self.response.out.write(template.render(path,res_values))
def get(self, room_name): # get the current user user_id = get_user_id(None) gae_user = create_or_get_user(user_id) if not room_name: room_name = 'lobby' user_room = Room.gql('where user_id = :1 and room_name = :2', user_id, room_name).get() # i'm in my current room, send back my current token if user_room: token = channel.create_channel(user_id) user_room.token = token user_room.put() else: token = channel.create_channel(user_id) user_room = Room() user_room.user_id = user_id user_room.room_name = room_name user_room.token = token user_room.put() obj = { 'user_id': user_id, 'token': token, 'user': gae_user.to_dict() } self.response.out.write(json.dumps(obj))
def get(self, gameId): """ Display game each player """ game = models.Game.get_by_id(int(gameId)) player = '' token = '' template = jinja_environment.get_template('cw.game.html') if game.player1Here == False: log(INFO, 'Player1 connection ; channel creation') game.player1Here = True game.put() player = 'player1' token = channel.create_channel(gameId + 'player1') elif game.player2Here == False: log(INFO, 'Player2 connection ; channel creation') game.player2Here = True game.put() player = 'player2' token = channel.create_channel(gameId + 'player2') else: log(ERROR, 'There are already two players !') raise Exception() self.response.out.write(template.render({ 'id' : game.key().id(), # can't use gameId, makes it buggy 'token' : token, 'player' : player, 'grid' : json.dumps(game.grid) }))
def get(self): """GET request handling method. Receive authentication code from user with GET['code']. Save credential if code exchange is successful. Redirect to previous page user visited. """ if 'code' in self.request.GET: try: credential = FLOW.step2_exchange(self.request.GET.get('code')) except FlowExchangeError: pass else: # Save credential to session data if code exchange succeeded. self.session['credential'] = pickle.dumps(credential) # Retrieve basic information about the user http = httplib2.Http() http = credential.authorize(http) users_service = build('oauth2', 'v2', http=http) user_document = users_service.userinfo().get().execute() # Create channel to push results back to the user channel_id = hashlib.sha1(user_document['id']).hexdigest() token_all = channel.create_channel(channel_id+'all') token_specific = channel.create_channel(channel_id+'specific') self.session['token_all'] = token_all self.session['token_specific'] = token_specific self.redirect('/'+(self.request.GET.get('state') or ''))
def test_connected_handler(self): channel_stub = self.testbed.get_stub('channel') token1 = channel.create_channel('1') channel_stub.connect_channel(token1) self.testapp.post('/_ah/channel/connected/', {'from': '1'}, {'Content-Type': 'application/x-www-form-urlencoded'}) self.assertIs(True, memcache.get( mcchannel._config.NAMESPACE + 'connected_1')) channel_messages = channel_stub.get_channel_messages(token1) self.assertEquals([], channel_messages) self.time += (mcchannel._CHANNEL_LIFESPAN + mcchannel._CHANNEL_RECONNECT_TIMEOUT) self.assertIs(None, memcache.get( mcchannel._config.NAMESPACE + 'connected_1')) token2 = channel.create_channel('2') channel_stub.connect_channel(token2) memcache.set(mcchannel._config.NAMESPACE + 'buffered_messages_2', {'service1': ['message1']}) self.testapp.post('/_ah/channel/connected/', {'from': '2'}, {'Content-Type': 'application/x-www-form-urlencoded'}) channel_messages = channel_stub.get_channel_messages(token2) self.assertEquals([json.dumps({'service1': ['message1']})], channel_messages) self.assertIs(None, memcache.get(mcchannel._config.NAMESPACE + 'buffered_messages_2'))
def chatroom_and_name(roomid,name): """Return a chat page""" token = channel.create_channel(name + roomid) template_values = { "roomid":roomid, "token": channel.create_channel(name + roomid), "yourname": name } return render_template("chat.html",values=template_values)
def get(self): #get datastore entities guestbook_name=self.request.get('guestbook_name') greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('date') greetings = greetings_query.run() connects_name=self.request.get('connects_name') connects_query = ConnectedUser.all().ancestor(connects_key(connects_name)) #get login/logout links if users.get_current_user(): url = users.create_logout_url(self.request.uri) url_linktext = 'Logout' else: url = users.create_login_url(self.request.uri) url_linktext = 'Login' #get current user user = users.get_current_user() #if the user is logged in if user: #create a token, get nickname and id userID = user.user_id() salt = 'thisIsaVeryLongSaltThatWillBeUsedToSalt' my_id = hashlib.sha1('%s$%s' % (userID, salt)).hexdigest() token = channel.create_channel(my_id) nickname = user.nickname() #if the user is not logged in (anonymous) else: #if the anonymous user has been around before and has an id stored in cookie if self.request.cookies.get('user_id'): my_id = self.request.cookies.get('user_id') #if not create a cookie else: my_id = str(uuid.uuid4()).replace("-",'') self.response.headers.add_header( 'Set-Cookie', 'user_id='+my_id+'; expires=31-Dec-2020 23:59:59 GMT') #create a token and assign a nickname token = channel.create_channel(my_id) nickname = "Anonymous" #inject thes values into client template_values = { 'token' : token, 'me': nickname, 'my_id': my_id, 'greetings': greetings, 'url': url, 'url_linktext': url_linktext, } template = jinja_environment.get_template('index.html') self.response.out.write(template.render(template_values))
def join_game(gameid,hostplayer): """Return a game page""" user_db = auth.current_user_db() name = user_db.name token = channel.create_channel(name + gameid) template_values = { "gameid":gameid, "token": channel.create_channel(name + gameid), "yourname": name, "hostplayer":hostplayer } return render_template("player.html", values=template_values)
def get(self): current_user = users.get_current_user() sid = int(self.request.get("sid")) token = channel.create_channel(str(sid)) archived_messages = db.GqlQuery("select * from IMMessage where im_session_id=:1 order by timestamp desc limit 10", sid) q = db.GqlQuery("select * from IMSession where im_session_id=:1", sid) if q.count() > 0: # joining a session chatters = q[0].users if not current_user.nickname() in chatters: pass else: initial_message = "%s has joined the IM session" % current_user.nickname() imuser = db.GqlQuery("select * from IMUser where nickname=:1", current_user.nickname())[0] token = channel.create_channel(imuser.channel_id) else: # creating a new session nickname = self.request.get("nickname") self.create_new_session(sid, current_user.nickname(), nickname, token) recipient = db.GqlQuery("select * from IMUser where nickname=:1", nickname) recipient_channel = recipient[0].channel_id logging.info("recipient_channel: %s" % (recipient_channel)) message = { "host": current_user.nickname(), "sid": sid } # send invite channel.send_message(recipient_channel, simplejson.dumps(message)) initial_message = "waiting for %s to join the IM session" % (nickname) # list comprhension FTW archives = [ { "timestamp": msg.timestamp.strftime("%A, %B %d, %Y %H:%M:%S"), "author": msg.author, "message": msg.message } for msg in archived_messages ] template_path = os.path.join(os.path.dirname(__file__), 'templates/im.html') template_values = { "token": token, "archived_messages": archives, "initial_message": initial_message, "current_user": current_user.nickname(), "sid": sid } self.response.out.write(template.render(template_path, template_values))
def get(self): if not onTeam(): return self.redirect('/') user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) return def formatter(person): JSON = {} key = getattr(person, 'key') JSON['id'] = key.urlsafe() JSON['kind'] = key.kind() JSON.update(person.asDict(['email', 'name', 'checked_in'])) return JSON from models import Volunteer, Rep source = map(formatter, Hacker.query(Hacker.checked_in == False).fetch()) source += map(formatter, Rep.query(Rep.checked_in == False).fetch()) source += map(formatter, Volunteer.query(Volunteer.checked_in == False).fetch()) total_checked_in = getTotal() session = models.CheckInSession() session.user = user.email() session.put() token = channel.create_channel(session.key.urlsafe()) self.response.write(template("checkin.html", {"source" : json.dumps(source), 'total_checked_in' : total_checked_in, 'token' : token}))
def get(self): """Renders the main page. When this page is shown, we create a new channel to push asynchronous updates to the client.""" user = UserFromSession(get_current_session()).get_user() game = GameFromRequest(self.request).get_game() # Assign player O if user != game.userX and not game.userO: game.userO = user game.put() if game: token = channel.create_channel(str(user.key().id()) + str(game.key())) template_values = {'token': token, 'me': user.key().id(), 'my_piece': 'X' if game.userX == user else 'O', 'game_id': str(game.key().id()), 'game_link': self.request.url, 'initial_message': GameUpdater(game).get_game_message() } path = os.path.join(os.path.dirname(__file__), 'game.html') self.response.out.write(template.render(path, template_values)) else: self.response.out.write('No such game')
def CreateChannelToken(self): """Create a new channel token to let a client connect to a channel. We create a channel per user with the assumption that there is one client per user. More advanced applications could create more finely-grained channels to support multiple clients per user.""" logging.info("Create channel: " + self.user) return channel.create_channel(self.user)
def get(self, game_name): global games user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) return if not game_name in games: self.error(404) self.response.out.write('Could not find game "%s"' % game_name) return game = games[game_name] if game.player1 is None: game.player1 = user elif game.player1.user_id() == user.user_id(): pass elif game.player2 is None: game.player2 = user elif game.player2.user_id() == user.user_id(): pass else: self.error(500) self.response.out.write('Game is full') return token = channel.create_channel(user.user_id()) self.response.out.write(template.render('ingame.html', { 'token': token, 'nickname': user.nickname(), }))
def get(self): user = users.get_current_user() #Redirect the user if they aren't logged in. if not user: self.redirect(users.create_login_url(self.request.uri)) return #Setup tokbox tokens. tokbox_session_id = opentok_sdk.create_session().session_id tokbox_token = opentok_sdk.generate_token(tokbox_session_id) sub_tokbox_token = opentok_sdk.generate_token(tokbox_session_id, OpenTokSDK.RoleConstants.SUBSCRIBER) #Create the room. room_key = user.user_id() room = Room(key_name = room_key, current_user = user, session_id = tokbox_session_id, pub_token = tokbox_token, sub_token = sub_tokbox_token ) room.put() #Display the template. token = channel.create_channel(room_key) template_values = {'token': token, 'tokbox_api_key': tokbox_api_key, 'tokbox_session_id': tokbox_session_id, 'tokbox_token': tokbox_token, 'room_key': room_key, 'initial_message': RoomUpdater(room).get_room_message_for_room(), } template = jinja_environment.get_template('nav-pub-with-playback.html') self.response.out.write(template.render(template_values))
def get(self, vendorid, deviceid): try: namespace_manager.set_namespace(vendorid) except: self.error(400) return if not validate_did(deviceid): self.error(400) return deviceid = deviceid.lower() node = DeviceNode.get_by_id(deviceid) last_update = None if node is not None: last_update = datetime.datetime.now() - node.last_seen logging.info('last_update: ' + str(last_update)) clientid = vendorid + deviceid token = channel.create_channel(clientid) # logging.info('token ' + token) template_values = { 'token': token, 'vendorid': vendorid, 'deviceid': deviceid, 'node': node, 'last_update': fuzzy_readable_time(last_update), } template = JINJA_ENVIRONMENT.get_template('index.html') self.response.write(template.render(template_values)) return
def aChan(): token = channel.create_channel(xID,1440) msg = Msg() msg.info = 'ho' tomsg = json.dumps(msg.__dict__) channel.send_message(xID, tomsg) return token
def post(self): """Used by the host to create the room.""" user = users.get_current_user() if not user: #Handle the user not being logged in. TODO return #Setup tokbox tokens. tokbox_session_id = opentok_sdk.create_session().session_id tokbox_token = opentok_sdk.generate_token(tokbox_session_id) sub_tokbox_token = opentok_sdk.generate_token(tokbox_session_id, OpenTokSDK.RoleConstants.SUBSCRIBER) #Create the room. room_key = user.user_id() room = Room(key_name = room_key, current_user = user, session_id = tokbox_session_id, pub_token = tokbox_token, sub_token = sub_tokbox_token ) room.put() #Create the channel token. token = channel.create_channel(room_key) #Respond with room information. room_data = {'token': token, 'tokbox_api_key': tokbox_api_key, 'tokbox_session_id': tokbox_session_id, 'tokbox_token': tokbox_token, 'room_key': room_key, 'initial_message': RoomUpdater(room).get_room_message_for_room(), } self.response.out.write(json.dumps(room_data))
def get(self, gid): pid = self.request.get('player_id') if pid: self.response.headers['Content/Type'] = 'application/json' self.response.out.write(channel.create_channel(pid))
def connect(self): clientid = self.request.get('id') if clientid is None: self.response.out.write(json.dumps({})) return; token = channel.create_channel(clientid) self.response.out.write(json.dumps({'token':token}))
def post(self, playlist_id): """Return a channel token.""" channel_id = channelutils.create_channel_id() memcacheutils.update_memcache( channel_id, playlist_id, self.current_user_id, self.current_display_name, self.people ) webutils.render_json_to_response(self, dict(channelToken=channel.create_channel(channel_id)))
def get(self): if (self.request.path == '/mp.create'): # user = users.get_current_user() game_key = '123' token = channel.create_channel(game_key + '.0') self.response.out.write(game_key + ',' + token) elif (self.request.path == '/mp.join'): game_key = self.request.get('k') # user = users.get_current_user() token = channel.create_channel(game_key + '.1') self.response.out.write(token) elif (self.request.path == '/mp.joined'): game_key = self.request.get('k') channel.send_message(game_key + '.0', 'hallo-hallo! i joined!')
def post(self): user = users.get_current_user() if not user: self.redirect(users.create_login_url("/")) return game_name = self.request.get("game_name") if not game_name: self.response.write("No game name specified") return game_key = db.Key.from_path("Game", game_name) game = db.get(game_key) if not game: game = Game(key_name=game_name) game.put() logging.info("Game: {0}".format(game)) player = Player(user=user, parent=game) player.put() token = channel.create_channel("{0}:{1}".format(game_name, user.user_id())) logging.info("/game?gamename={0}&token={1}".format(game.key().id_or_name(), token)) self.redirect("/game?gamename={0}&token={1}".format(game.key().id_or_name(), token))
def get(self, cloud_id = None): # lookup user's auth info user_info = User.get_by_id(long(self.user_id)) # get the cloud in question cloud = Cloud.get_by_id(long(cloud_id)) # bail if cloud doesn't exist or not owned by this user if not cloud or cloud.owner != user_info.key: return self.redirect_to('account-clouds') # look up cloud's instances instances = Instance.get_by_cloud(cloud.key) # setup channel to do page refresh channel_token = user_info.key.urlsafe() refresh_channel = channel.create_channel(channel_token) # params build out params = { 'cloud': cloud, 'instances': instances, 'refresh_channel': refresh_channel, 'channel_token': channel_token } return self.render_template('cloud/edit.html', **params)
def get(self): """Renders the main page. When this page is shown, we create a new channel to push asynchronous updates to the client.""" user = users.get_current_user() game_key = self.request.get("g") game = None if user: if not game_key: game_key = user.user_id() game = Game(key_name=game_key, userX=user, moveX=True, board=" ") game.put() else: game = Game.get_by_key_name(game_key) if not game.userO: game.userO = user game.put() game_link = "http://localhost:8080/?g=" + game_key if game: token = channel.create_channel(user.user_id() + game_key) template_values = { "token": token, "me": user.user_id(), "game_key": game_key, "game_link": game_link, "initial_message": GameUpdater(game).get_game_message(), } path = os.path.join(os.path.dirname(__file__), "index.html") self.response.out.write(template.render(path, template_values)) else: self.response.out.write("No such game") else: self.redirect(users.create_login_url(self.request.uri))
def CreateChannel(self): """Creates a new channel with a given key. This should be called when a browser client wants to receive updates about a given resource (identified by self.channel_key). A new Channel object is saved to the datastore and memcache. Returns: A string that can be used by browser clients as a token for connecting to the new channel. This corresponds to the "token" value which is passed to the JavaScript goog.appengine.Channel() constructor, documented at http://code.google.com/appengine/docs/python/channel/javascript.html """ channel_id = uuid4().get_hex() new_channel = Channel(channel_key=self.channel_key, channel_id=channel_id) new_channel.put() current_channels = self.GetActiveChannels() already_in_memcache = False for current_channel in current_channels: if current_channel.channel_id == channel_id: already_in_memcache = True if not already_in_memcache: current_channels.append(new_channel) memcache.set(self.channel_key, current_channels) return channel.create_channel(channel_id)
def post(self): '''Displays chat UI''' username = self.request.get('username') channelname = self.request.get('channel') usernameerror = "" if not username: usernameerror="Please enter a username" elif not re.compile(r'^[a-zA-Z0-9_-]{3,20}$').match(username): usernameerror = "Username must consist of 3-20 alphanumeric characters." elif get_user(username): usernameerror="Username already in use" channelerror = "" if channelname and not re.compile(r'^#[\w]{3,20}$').match(channelname): channelerror="Channel must consist of 3-20 alpha_numeric characters and start with a #" if len(usernameerror+channelerror) > 0: self.response.out.write(render("main.html", username=username, usernameerror=usernameerror, channel=channelname, channelerror=channelerror)) else: token = channel_api.create_channel(username) # Expires after 120 minutes identifier = os.urandom(16).encode('hex') user = ChatUser(key_name=username.lower(), username=username, identifier=identifier, startingchannel=channelname, connected=True, contacts=json.dumps([ ]), channels=json.dumps([ ])) user.store() self.response.out.write(render("chat.html", token=token, username=username, identifier=identifier, server="!AwesomeServer"))
def get(self): user = users.get_current_user() if not isUserSetup(user): self.redirect('/user') return key = self.request.get('key'); result = data.Map.get_by_id(long(key)) if result is None: self.error(404) self.response.out.write('Game not found.') return # if result.owner != user: # self.error(404) # self.response.out.write('You have to be an owner to start multiplay using this map.') # return # token = channel.create_channel(user.user_id() + key) token = channel.create_channel(result.owner.user_id() + key) template_values = { 'username': user.nickname(), 'user_id': user.user_id(), 'map_owner_id': result.owner.user_id(), 'key': key, 'channel_token': token, 'is_owner': result.owner == user } template = JINJA_ENVIRONMENT.get_template('multiplay.html') self.response.write(template.render(template_values))
def get(self): user = users.get_current_user() if checkUserLoggedIn(self, user): token = channel.create_channel(user.nickname() + user.user_id()) ret = handleTestMainPageGet(users.create_logout_url(self.request.uri), token, user) template = jinja_environment.get_template('index.html') self.response.out.write(template.render(ret))
def index(self): logging.info('Home.index ------------------()') token = channel.create_channel('foo') logging.info('token = ' + token) c = {} c['token'] = token self.rendertemplate(context=c)
def get(self): tokensalt = randint(1561, 8644242454) mytoken = 'ebiduh' + str(tokensalt) token = channel.create_channel(mytoken) data = { 'token':token, 'clientID':mytoken } self.response.out.write(json.dumps(data))
def get(self): # lookup user's auth info user_info = User.get_by_id(long(self.user_id)) # look up user's articles flavors = Flavor.get_all() # setup channel to do page refresh channel_token = user_info.key.urlsafe() refresh_channel = channel.create_channel(channel_token) params = { 'flavors': flavors, 'refresh_channel': refresh_channel, 'channel_token': channel_token } return self.render_template('admin/flavors.html', **params)
def post(self, project_id): project = Project.get_by_id(int(project_id)) user_id = self.request.get('user_id') if self.request.get('updating') == '': token = channel.create_channel(project.channel_key(user_id)) project.connect_user(int(user_id)) else: token = None if project: self.response.headers['Content-Type'] = 'application/json' self.render_json({ 'points': json.loads(project.data), 'token': token, 'connected_users': project.connected_users() })
def add_user_key(self, user_key): # TODO: this should be a transaction probably c = self.has_user_key(user_key) if c: return c.channel_token, False tok = channel.create_channel(self.get_channel_id(user_key), ChatSettings.CHAT_CHANNEL_MINUTES) if not tok: return None, None self.chat_channels.append( ChatChannel(user_key=user_key, room_key=self.key, channel_token=tok)) self.put() return tok, True
def authorization(self, chat_token): """ User authorization. :return: ChatMemberModel """ members = db.GqlQuery('select * from ChatMemberModel where token = :1 limit 1', chat_token).fetch(1) if members is None or len(members) == 0: # insert a new member member = ChatMemberModel() member.name = 'Guest %s' % str(random.randint(0,10000)) member.name_lower = member.name.lower() member.token = str(uuid.uuid4()) member.channel_token = channel.create_channel(member.token) member.put() return member else: # return exist member return members[0]
def get(self, chatroom="main"): channel_id = uuid.uuid4().hex token = channel.create_channel(channel_id) ckey = chatroom_key(chatroom) # Store the connection connection = Connection(parent=ckey) connection.channel_id = channel_id connection.put() template_values = { 'chatroom': urllib.quote_plus(chatroom), 'token': token } template = JINJA_ENVIRONMENT.get_template('index.html') self.response.write(template.render(template_values))
def get(self): client_id = self.request.get("client_id") if client_id: current_user = ConnectedUser.all().filter("client_id = ", client_id).get() if current_user: token = channel.create_channel(client_id) connected_users = ConnectedUser.all().fetch(50) flash_path = os.path.join(os.path.dirname(__file__),'flash/bin-debug/studentsconnect.html') flash_content = template.render(flash_path, {}) template_values = { 'current_user': current_user, 'connected_users': connected_users, 'token': token , 'flash_content': flash_content } path = os.path.join(os.path.dirname(__file__), 'chat.html') self.response.out.write(template.render(path, template_values))
def get(self): from google.appengine.api import channel from uuid import uuid4 user_id = users.get_current_user().user_id() channel_id = user_id + uuid4().hex token = channel.create_channel(channel_id) # We will send Activity to everyone event.subscribe("ACTIVITY", channel_id) # We will send results from aggregations just to the # user who created the data. event.subscribe("SUMMARY-%s" % user_id, channel_id) self.response.out.write(json.dumps({"token": token}))
def index(): user = users.get_current_user() if not user: login_url = users.create_login_url(request.url) return redirect(login_url) user_name = user.nickname() logout_url = users.create_logout_url(request.url) channel_id = user.user_id() token = channel.create_channel(channel_id, CHANNEL_TIMEOUT) app.channel_clients.add(channel_id) send_to_all({'type': 'connect', 'who': user.nickname()}) # print app.channel_clients return render_template('chat.html', user_name=user_name, logout_url=logout_url, token=token)
def get(self): clientId = self.request.get("clientId") wsUrl = self.request.get("wsUrl") callback = self.request.get("callback") # create the record # TODO should i detect a collision on the clientid ? client = Client(clientId=clientId, wsUrl=wsUrl, timestamp=datetime.datetime.now()) client.put() # create the channel token = channel.create_channel(clientId) # queue a /clientPurge task taskqueue.add(url='/clientPurge') # build the jsonp answer self.response.headers['Content-Type'] = 'application/json' self.response.out.write("%s({token:'%s', clientAliveRefresh: %d});\n" % (callback, token, clientAliveRefresh))
def get(self): # lookup user's auth info user_info = User.get_by_id(long(self.user_id)) # look up appliances appliances = Appliance.get_by_user(user_info.key) # setup channel to do page refresh channel_token = user_info.key.urlsafe() refresh_channel = channel.create_channel(channel_token) # params build out params = { 'appliances': appliances, 'refresh_channel': refresh_channel, 'channel_token': channel_token } return self.render_template('appliance/list.html', **params)
def get(self, game=""): user = users.get_current_user() logging.info(user) gameBoardID = self.request.cookies.get('gameBoardID') if not gameBoardID: gameBoardID = str(uuid.uuid1()) self.response.set_cookie('gameBoardID', gameBoardID, max_age=360) '''gameObject=rkey.get() logging.info(gameObject) info=gameObject.getData() dic=json.dumps({'status':info}) pat=gamePlayers() road=pat.path''' gObj = gamePlayers() gameInfo = gObj.getGameState(game, gameBoardID=gameBoardID) tok = channel.create_channel('board-' + gameBoardID + '-' + gameInfo.key.urlsafe()) self.renderResponse({'n': user, 'token': tok})
def get(self, game_id): self.check_user() game = games.Game.load(game_id) player = game.add_player(self.current_user) token = channel.create_channel(player.user_id + game_id) game_link = app_identity.get_default_version_hostname() + game.get_url( ) template_values = { 'token': token, 'game_id': game_id, 'game_link': game_link, 'me': player.user_id, 'game_state': game.get_user_view(player.user) } path = os.path.join(os.path.dirname(__file__), 'game.html') self.response.out.write(template.render(path, template_values))
def post(self): user = users.get_current_user() if user: num = int(self.request.get('RoomNo')) query = Battle.query(ancestor=get_battle()) query = query.filter(Battle.roomNo == num) rooms = query.fetch() if len(rooms) == 0: self.response.out.write("Error1") elif len(rooms) > 1: self.response.out.write("Error2") else: room = rooms[0] attr1 = room.tempAtt1 attr2 = room.tempAtt2 if room.user1 == users.get_current_user().nickname(): p = 1 elif room.user2 == users.get_current_user().nickname(): p = 2 else: p = 0 #error query = UserRole.query().order(-UserRole.wins) roles = query.fetch(10) ranklist = [] for role in roles: ranklist.append(role.name + ": " + str(role.wins)) token = channel.create_channel( users.get_current_user().nickname() + str(num)) template_values = { "attr1": attr1, "attr2": attr2, "player": p, "token": token, "roomNum": room.roomNo, "ranklist": ranklist } # reading and rendering the template render_template(self, template_values) else: self.redirect('/nosign')
def get(self): user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) return template = jinja_environment.get_template('index.html') core_sections = [ 'input', 'cryptanalysis', 'options_samples', 'options_samples-cipher_challenge' ] main_sections = ['caesar'] template_values = { 'token': channel.create_channel(user.user_id() + 'stream'), 'user': user, 'signout_url': users.create_logout_url(self.request.uri), 'core_sections': core_sections, 'main_sections': main_sections } self.response.out.write(template.render(template_values))
def post(self): context = dict() context['url'] = self.request.POST.get("url") context['search_id'] = self.request.POST.get("search_id") context['deep'] = int(self.request.POST.get("deep")) context['words'] = self.request.POST.get("words") #Clear counters memcache.set('%s-links' % context['search_id'], 0) for word in context['words'].split(','): memcache.set("%s-word-%s" % (context['search_id'], word), 0) deferred.defer(read_web_site, **context) context['token'] = channel.create_channel("%s-search" % context['search_id']) template = jinja_environment.get_template('index.html') self.response.write(template.render(context))
def post(self): '''Displays chat UI''' username = self.request.get('username') channelname = self.request.get('channel') usernameerror = "" if not username: usernameerror = "Please enter a username" elif not re.compile(r'^[a-zA-Z0-9_-]{3,20}$').match(username): usernameerror = "Username must consist of 3-20 alphanumeric characters." elif get_user(username): usernameerror = "Username already in use" channelerror = "" if channelname and not re.compile(r'^#[\w]{3,20}$').match(channelname): channelerror = "Channel must consist of 3-20 alpha_numeric characters and start with a #" if len(usernameerror + channelerror) > 0: self.response.out.write( render("main.html", username=username, usernameerror=usernameerror, channel=channelname, channelerror=channelerror)) else: token = channel_api.create_channel( username) # Expires after 120 minutes logging.info("%s is a token. type of token: %s" % (token, type(token))) identifier = os.urandom(16).encode('hex') user = ChatUser(key_name=username.lower(), username=username, identifier=identifier, startingchannel=channelname, connected=True, contacts=json.dumps([]), channels=json.dumps([])) user.store() self.response.out.write( render("chat.html", token=token, username=username, identifier=identifier, server="!AwesomeServer"))
def get(self): user = users.get_current_user() system_param = self.request.get('system') if not system_param: template = JINJA_ENVIRONMENT.get_template( "templates/not_found.html") template_values = { "user": user, "users": users, "not_found_msg": "Please select a system" } self.response.write(template.render(template_values)) return system = System.get_by_id(system_param) if system is None: template = JINJA_ENVIRONMENT.get_template( "templates/not_found.html") template_values = { "user": user, "users": users, "not_found_msg": "The system #{0} not exists".format(system_param) } self.response.write(template.render(template_values)) return #logs = Log.query(ancestor = system.key).fetch() logs = [] template_values = { "system": system, "logs": logs, "token": channel.create_channel(system.key.id()), "user": user, "users": users } template = JINJA_ENVIRONMENT.get_template("templates/logs.html") self.response.write(template.render(template_values)) return
def get(self): # lookup user's auth info user_info = User.get_by_id(long(self.user_id)) # setup channel to do page refresh channel_token = user_info.key.urlsafe() refresh_channel = channel.create_channel(channel_token) # insert images into list for wisp self.form.image.choices=[('custom', "Dynamic Image URL")] images = Image.get_all() for image in images: self.form.image.choices.insert(0, (str(image.key.id()), image.description)) # params build out params = { 'refresh_channel': refresh_channel, 'channel_token': channel_token } return self.render_template('wisp/new.html', **params)
def get(self): user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) return client_id = "%s" % user.user_id() memcache.set('client_id', client_id) now = time.time() yesterday = now - 3600 * 24 channel_token = channel.create_channel(client_id) template_values = { 'channel_token': channel_token, 'date': time.strftime("%Y%m%d", time.localtime(yesterday)), 'bqdataset': bqdataset } template = jinja_environment.get_template('index.html') self.response.out.write(template.render(template_values))
def get(self): clientID = randomString(5) tempRmID = randomString(5) token = channel.create_channel(clientID) msg = clientID + " has joined the chat" newRoom = chatRoom(roomID=tempRmID, participants=[clientID], participantTokens=[token], histChat=msg) newRoom.put() template_values = { 'token': token, 'appid': clientID, 'message': msg, 'roomID': tempRmID } path = os.path.join(os.path.dirname(__file__), 'mychat.html') self.response.out.write(template.render(path, template_values))
def get(self): channel_token = self.session.get('channel_token') if channel_token is None: # if the session user does not have a channel token, create it and save it in the session store. client_id = str(uuid.uuid4()).replace("-", '') channel_token = channel.create_channel(client_id) self.session['channel_token'] = channel_token self.session['client_id'] = client_id client_id = self.session['client_id'] # Put some messages in the deferred queue which will appear in the browser a few seconds after loading the page. deferred.defer(channel.send_message, client_id, "Mediator: Choose your path.", _countdown=1) self.render_response( 'home.html', **{ "token": channel_token, "client_id": client_id })
def get(self): scene_k = ndb.Key('Scene', 'scene1') scene = scene_k.get() if scene is None: logging.info('MainHandler creating Scene') scene = Scene(name='Scene 1', id='scene1') # take this opportunity to cull expired channels removed = remove_expired_connections(scene.connections) if removed: send_client_list(scene.connections) channel_id = str(scene.next_id) scene.next_id += 1 scene.connections.append(Connection(channel_id=channel_id)) token = channel.create_channel(channel_id) scene.put() logging.info('MainHandler channel_id=%s' % channel_id) path = os.path.join(os.path.dirname(__file__), "main.html") template_values = {'token': token, 'channel_id': channel_id} self.response.out.write(template.render(path, template_values))
def __init__(self, address, generate=True, override_quota=False): self.address = address if generate: self.token = memcache.get("token_%s" % self.address) if self.token is None: device = models.getDevice(self.address) if device.token and device.tokenValid(): self.token = device.token else: if models.getQuota().amount > models.getStats( 'channels').count or override_quota: self.token = channel.create_channel(self.address) stats.record( "channel_created", simplejson.dumps({"channel": self.address})) self.cached = False device.updateToken(self.token) else: raise OverQuotaError() return False memcache.set("token_%s" % self.address, self.token, time=7200)
def get(self): """Renders the main page. When this page is shown, we create a new channel to push asynchronous updates to the client.""" user = users.get_current_user() game_key = self.request.get('g') game = None if user: if not game_key: game_key = user.user_id() game = Game(key_name=game_key, userX=user, moveX=True, board=' ') game.put() else: game = Game.get_by_key_name(game_key) # if not game.userO: if not game.userO and game.userX != user: game.userO = user game.put() global CLOUD_PROJECT_ID game_link = ('https://' + CLOUD_PROJECT_ID + '.appspot.com/?g=' + game_key) if game: token = channel.create_channel(user.user_id() + game_key) template_values = { 'token': token, 'me': user.user_id(), 'game_key': game_key, 'game_link': game_link, 'initial_message': GameUpdater(game).get_game_message() } template = jinja_environment.get_template('index.html') self.response.out.write(template.render(template_values)) else: self.response.out.write('No such game') else: self.redirect(users.create_login_url(self.request.uri))
def get(self, token = None): # lookup up bid bid = InstanceBid.get_by_token(token) if not bid: self.add_message("Instance reservation token %s has expired." % token, 'error') return self.redirect_to('projects') # grab the project from the bid project = Project.get_by_id(bid.wisp.get().project.id()) # grab the instance instance = Instance.get_by_token(token) if not instance: self.add_message("All available instance reservations are in use. Please try again in a few minutes.", 'error') return self.redirect_to('projects') # grab and render the README.md file content = urlfetch.fetch('http://10.0.1.80:8079/wisps/6048757061779456/README.md').content readme_html = bleach.clean( markdown.markdown( unicode(content, 'utf-8') ), config.bleach_tags, config.bleach_attributes ) # setup channel to do page refresh channel_token = token refresh_channel = channel.create_channel(channel_token) params = { 'instance': instance, 'bid': bid, 'project': project, 'readme_html': readme_html, 'refresh_channel': refresh_channel, 'channel_token': channel_token } return self.render_template('project/bid.html', **params)
def get(self): """Renders the main page. When this page is shown, we create a new channel to push asynchronous updates to the client.""" user = users.get_current_user() #game_key = self.request.get('g') game = None if user: if not UserStack: game_key = user.user_id() game = Game(key_name=game_key, userX=user, moveX=True, board=' ', big_win=' ') game.put() UserStack.append(game_key) else: game_key = UserStack.pop() game = Game.get_by_key_name(game_key) if not game.userO: game.userO = user game.put() game_link = 'http://localhost:8080/game?g=' + game_key if game: token = channel.create_channel(user.user_id() + game_key) template_values = {'token': token, 'me': user.user_id(), 'game_key': game_key, 'game_link': game_link, 'initial_message': GameUpdater(game).get_game_message() } path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values)) else: self.response.out.write('No such game') else: self.redirect(users.create_login_url(self.request.uri))
def get(self): """Renders the main page. When this page is shown, we create a new channel to push asynchronous updates to the client.""" game_key = self.request.get('g') game = None user = None if game_key: game = Game.get_by_key_name(game_key) if game: user = game.userO if not user: user = uuid.uuid4().hex game.userO = user game.put() if not game: game_key = uuid.uuid4().hex user = uuid.uuid4().hex game = Game(key_name=game_key, moveX=True, userX=user, complete=False, board=' ') game.put() game_link = 'http://localhost:8080/?g=' + game_key if game: token = channel.create_channel(user + game_key) values = { 'token': token, 'me': user, 'game_key': game_key, 'game_link': game_link, 'initial_message': GameUpdater(game).get_game_message() } self.response.out.write(simplejson.dumps(values)) else: self.response.out.write(simplejson.dumps({'error': 'No such game'}))
def get(self, project_id = None): # lookup user's auth info user_info = User.get_by_id(long(self.user_id)) # get the project in question project = Project.get_by_id(long(project_id)) # bail if project doesn't exist or not owned by this user if not project or project.owner != user_info.key: return self.redirect_to('account-projects') # load form values self.form.name.data = project.name self.form.description.data = project.description self.form.address.data = project.address self.form.amount.data = project.amount self.form.vpus.data = project.vpus self.form.memory.data = project.memory self.form.disk.data = project.disk self.form.port.data = project.port self.form.dynamic_image_url.data = project.dynamic_image_url # insert images into list self.form.image.choices=[('custom', "Dynamic Image URL")] images = Image.get_all() for image in images: self.form.image.choices.insert(0, (str(image.key.id()), image.description)) # setup channel to do page refresh channel_token = user_info.key.urlsafe() refresh_channel = channel.create_channel(channel_token) # params build out params = { 'project': project, 'refresh_channel': refresh_channel, 'channel_token': channel_token } return self.render_template('project/edit.html', **params)
def passenger_home(request): if not request.mobile and CURRENT_PASSENGER_KEY in request.session: del request.session[CURRENT_PASSENGER_KEY] hidden_fields = HIDDEN_FIELDS form = OrderForm() not_a_user, not_a_passenger = NOT_A_USER, NOT_A_PASSENGER waze_token = settings.WAZE_API_TOKEN telmap_user = settings.TELMAP_API_USER telmap_password = settings.TELMAP_API_PASSWORD telmap_languages = 'he' if str( get_language_from_request(request)) == 'he' else 'en' country_code = settings.DEFAULT_COUNTRY_CODE service_cities = ", ".join( set([s.city.name for s in Station.objects.filter(show_on_list=True)])) passenger = Passenger.from_request(request) if not passenger and request.GET.get("show_login", False): show_login = True if passenger and passenger.business: PENDING = models.PENDING ASSIGNED = models.ASSIGNED ACCEPTED = models.ACCEPTED ORDER_FAILED = models.FAILED # groups together FAILED, ERROR and TIMED_OUT ORDER_MAX_WAIT_TIME = models.ORDER_MAX_WAIT_TIME FAILED_MSG = _(order_tracker.STATUS_MESSAGES[models.FAILED]) show_tracker = True channel_key = get_channel_key(Passenger.from_request(request), request.session.session_key) init_token = channel.create_channel(channel_key) init_tracker_history = [ simplejson.dumps(msg) for msg in order_tracker.get_tracker_history(passenger) ] return custom_render_to_response("passenger_home.html", locals(), context_instance=RequestContext(request))
def get(self): if not onTeam(): return self.redirect('/') user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) return def formatter(person): JSON = {} key = getattr(person, 'key') JSON['id'] = key.urlsafe() JSON['kind'] = key.kind() JSON.update(person.asDict(['email', 'name', 'checked_in'])) return JSON from models import Volunteer, Rep source = map(formatter, Hacker.query(Hacker.checked_in == False).fetch()) source += map(formatter, Rep.query(Rep.checked_in == False).fetch()) source += map(formatter, Volunteer.query(Volunteer.checked_in == False).fetch()) total_checked_in = getTotal() session = models.CheckInSession() session.user = user.email() session.put() token = channel.create_channel(session.key.urlsafe()) self.response.write( template( "checkin.html", { "source": json.dumps(source), 'total_checked_in': total_checked_in, 'token': token }))