def delete(self, cloud_id = None): # lookup user's auth info user_info = User.get_by_id(long(self.user_id)) # pull the entry from the db cloud = Cloud.get_by_id(long(cloud_id)) # check the number of instances count = Instance.get_count_by_cloud(cloud.key) # deny if it has instances if count > 0: self.add_message('You may not delete a cloud with instances!', 'info') # if we found it and own it, delete elif cloud and cloud.owner == user_info.key: cloud.key.delete() self.add_message('Cloud successfully deleted!', 'success') else: self.add_message('Cloud was not deleted. Something went horribly wrong somewhere!', 'warning') # hangout for a second time.sleep(1) # use the channel to tell the browser we are done and reload channel_token = self.request.get('channel_token') channel.send_message(channel_token, 'reload') return
def broadcastTwitterAuth(user): response = {} response['type'] = 'twitter_auth' response['success'] = True channels = memcache.get('web_channels') or {} if user.id in channels.iterkeys(): webchannel.send_message(user.id, simplejson.dumps(response))
def post(self): channel_uuid, channel_payload = self.restore_channel() if not channel_uuid: return if channel_payload["channel_state"] != "established": logging.error("Publishing on an unestablished channel: %s" % channel_uuid) self.respond_error("channel is not established yet") return received_state = simplejson.loads(self.request.get("payload")) channel_payload["viz_state"] = received_state if not self.save_channel_payload(channel_uuid, channel_payload): return # The list of listeners may contain stale entries, if a listener forgot # to unregister itself. for listener_uuid in channel_payload["listeners"].iterkeys(): try: channel.send_message(listener_uuid, simplejson.dumps(received_state)) except channel.Error: logging.error("Error while sendinng message from %s to %s" % (channel_uuid, listener_uuid)) self.respond_ok()
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): #retrieve parameters new_message = self.request.get('new_message') author = self.request.get('author') sid = int(self.request.get('sid')) # store message im_message = IMMessage() im_message.im_session_id = sid im_message.message = new_message im_message.author = author im_message.message_id = str(uuid.uuid4()) im_message.put() # update last_activity of sender to prevent automatic logout current_user = db.GqlQuery("select * from IMUser where nickname=:1", author)[0] current_user.last_activity = datetime.datetime.now() current_user.put() # get recipient list im_sessions = db.GqlQuery("select * from IMSession where im_session_id=:1", sid)[0] chatters = im_sessions.users # send message to all recipients for chatter in chatters: imuser = db.GqlQuery("select * from IMUser where nickname=:1", chatter)[0] logging.info(__file__ + " " + chatter) channel.send_message(imuser.channel_id, simplejson.dumps({ "message": new_message, "author": author, "timestamp": datetime.datetime.now().strftime("%A, %B %d, %Y %H:%M:%S"), }))
def remove_node(map_id, node_id): """ TODO """ map_id = db.Node[node_id].id_map if(auth.has_permission('update', db.Map, map_id)): db(db.Connection.id_first_node == node_id).delete() db(db.Connection.id_second_node == node_id).delete() del db.Node[node_id] updated_map_info = dict(date_modified = datetime.utcnow(), modified_by = auth.user.email) if db(db.Node.id_map == map_id).count() > 0: updated_map_info['is_empty'] = False else: updated_map_info['is_empty'] = True db.Map[map_id] = updated_map_info if settings.web2py_runtime_gae: maplisteners = memcache.get('map_%s_listeners' % map_id) if maplisteners is not None: message = { 'type': 'noderemove', 'nodeid': node_id } for to_id in maplisteners: channel.send_message(to_id, gluon.contrib.simplejson.dumps(message)) return dict(success=True) else: return dict(success=False)
def post(self): # request取得を連想配列で取得 req_data = simplejson.loads(self.request.body) # Channelで他のユーザに通知 #channel.send_message('draw',simplejson.dumps(req_data)) channel.send_message(req_data["bname"],self.request.body)
def post(self): user = users.get_current_user() if not user: self.response.set_status(401) return text = self.request.get("text") line = ChatLine(user=user, text=text) db.put(line) # Send an update to everyone who's listening. # TODO(danvk): write a function to do this. msg = { 'lines': [ "%s: %s" % (user.nickname(), text) ] } active_users=db.GqlQuery("SELECT * FROM ActiveUsers") for user in active_users: if (datetime.datetime.now() - user.last_update_time > datetime.timedelta(hours=1)): logging.info("Removing inactive user: "******"Sending message on channel: " + user.user.user_id()) try: channel.send_message(user.user.user_id(), simplejson.dumps(msg)) except channel.InvalidChannelKeyError: # This happens when you restart the server and sever connections. pass self.response.out.write('ok')
def add_node(map_id, token, x, y, width, height, name): ''' By default set valences to 0 for new nodes ''' if(auth.has_permission('update', db.Map, map_id)): map = db.Map(map_id) node_id = db.Node.insert(id_map=map_id, valence = 0, x = x, y = y, width = width, height = height, name = name) db.Map[map_id] = dict(date_modified = datetime.utcnow(), modified_by = auth.user.email, is_empty = False) if settings.web2py_runtime_gae: maplisteners = memcache.get('map_%s_listeners' % map_id) if maplisteners is not None: node = { 'id': node_id, 'text': name, 'valence': 0, 'dim': { 'x': float(x), 'y': float(y), 'width' : float(width), 'height' : float(height), }, 'selected': False, 'newNode': False, } message = { 'type': 'nodeadd', 'node': node } for to_id in maplisteners: channel.send_message(to_id, gluon.contrib.simplejson.dumps(message)) return dict(success=True, token=token, node_id=node_id) else: return dict(success=False, token=token)
def post(self): message = Message() eventkey = self.request.get("eventkey") message_content = self.request.get("message") user = users.get_current_user() if not user: user = "******" time = datetime.datetime.now() # preformatting for ease of posting message.content = ( "<span>" + str(user) + ":" + self.request.get("message") + " - " + time.strftime("%H:%M") + "</span>" ) message.event = eventkey message.put() # pushing through channel clientquery = ChatUser.query(ChatUser.event == eventkey) clients = clientquery.fetch() for client in clients: channel.send_message( client.uuid, "<span>" + str(user) + ":" + self.request.get("message") + " - " + time.strftime("%H:%M") + "</span>", )
def game_newPlayer(gameId): """ POST action of the Choose nickname form (presented when a user joins a game, if it's not full already) """ if gameId not in GameInProgress.games: return redirect(url_for("index")) # fetch game informations game = GameInProgress.games[gameId] user = game.getCurrentUser() if not user or user.playerId is not None: return Response(status=400) # add the player to the game model playerId = game.model.addPlayer(request.form["name"]) if playerId is False: # the game is full, return an error return Response(status=400) # store the player ID in the user object user.playerId = playerId # refresh the game for everyone else to show the new player for u in game.users.values(): if u.channelId and u is not user: channel.send_message(u.channelId, "reload") return redirect(url_for("gameview", gameId=gameId))
def sendMessageTo(user, call, data): msg = { "call" : call, "data" : data } channel.send_message(user.uid, json.dumps(msg))
def post(self): channel_id = self.request.get('channel_id'); clientSeq = self.request.get('clientSeq'); timestamp = self.request.get('timestamp'); msg = self.request.get('msg'); logging.info('Received MESSAGE [%s %s]' % (channel_id, clientSeq)) sequence = memcache.incr("sequence", initial_value=0) if sequence is None: sequence = 0 scene_k = ndb.Key('Scene', 'scene1') scene = scene_k.get() # echo message back to all users message = json.dumps({ 'type' : 'echo', 'sequence' : sequence, 'timestamp' : timestamp, 'clientSeq' : int(clientSeq), 'channel_id' : channel_id, 'msg' : msg, 'server_time' : int(time.time() * 1000) }); tStart = datetime.now() channel.send_message(channel_id, message) tTotal = datetime.now() - tStart logging.info(' responded to sender [%s] (%dms)' % (channel_id, tTotal.microseconds/1000)) if len(scene.connections)>1: logging.info(' broadcasting to %i clients' % (len(scene.connections)-1)) for c in scene.connections: if c.channel_id != channel_id: tStart = datetime.now() channel.send_message(c.channel_id, message) tTotal = datetime.now() - tStart logging.info(' broadcast to [%s] (%dms)' % (c.channel_id, tTotal.microseconds/1000))
def post(self): # Client MUST ENFORCE correct syntax for commands, and ensure usernames and channelnames exist # Perhaps that's a dangerous statement? message = urllib.unquote(self.request.get('message')) username = urllib.unquote(self.request.get('username')) identifier = urllib.unquote(self.request.get('identifier')) logging.info("Username: "******" Message: "+message) if not (message and username and identifier): return user = get_user(username) if not user or (user and identifier != user.identifier): return COMMANDS = {"JOIN": user_join, "LEAVE": user_leave, "PRIVMSG": user_privmsg, "CHANNELMSG": user_channelmsg, "QUIT": user_quit, "PING": user_ping, "PONG": user_pong } command = message.split(' ')[0].upper() arg = '' if ' ' not in message else message[message.index(' ')+1:] if command in COMMANDS: COMMANDS[command](username, arg) else: channel_api.send_message(username, "NOTICE Command not supported by server: "+message) # Echo, for testing
def user_quit(username, args): '''User has quit''' # This may take a while to execute user = get_user(username) username = user.username # Use actual name user.connected = False for channelname in user.get_channel_names(): # Remove the user from channel channel = get_channel(channelname) channel.remove_user(username) # Do this first to prevent infinite loops for u in channel.get_user_names(): # Let the people in the channel know channel_api.send_message(u, "QUIT "+username+" "+channelname) for contactname in user.get_contact_names(): # Remove user from their contacts' contact lists # Possible double-handling, but that's ok because remove_contact checks for that contact = get_user(contactname) if contact: contact.remove_contact(username) try: channel_api.send_message(username, "NOTICE You have quit") except: # POKEMON exception! # Not really needed since send_message does not throw exceptions pass user.store()
def post(self): game_name = self.request.get('game_name') game_key = db.Key.from_path('Game', game_name) game = db.get(game_key) user = users.get_current_user() logging.info('Player {0} playing move for game: {1}'.format(game, user.nickname())) move_type = self.request.get('move_type') selected_cards = self.request.get('selected_cards') players = Player.all().ancestor(game).run() for player in players: if player.user == user: this_player = player if not this_player: raise Exception("Player not found: {0}".format(user.nickname())) gamestate = { "players": players, "current_hand": this_player.cards, "player_turn": game.player_turn } for player in players: channel.send_message("{0}:{1}".format(game_name, player.user.user_id()), json.dumps(gamestate))
def alone_match(self): self.balance += 1 self.match_counter += 1 self.challenger = None free_win = {} free_win['player'] = { 'id':self.player.id, 'nickname': self.player.nickname, 'status': self.id, 'shots': self.shots, 'balance': self.balance, 'match_counter': self.match_counter, } free_win['game'] = { 'id': self.game.id, 'name': self.game.name, 'slug': self.game.slug, 'players_counter': self.game.players_counter, 'online_players': self.game.online_players, 'match_counter': self.game.match_counter, 'match_round': self.game.match_round, 'datetime': self.game.last_match.strftime("%d/%m/%y %I:%M:%S %p"), } message = {'free_win': free_win} send_message(self.player.id, json.dumps(message)) # When player do not play, it increments its match counter? # match_counter += 1 self.put()
def send_update(self): message = self.get_game_message() channel.send_message( self.game.userX.user_id() + self.game.key().id_or_name(), message) if self.game.userO: channel.send_message(self.game.userO.user_id() + self.game.key().id_or_name(), message)
def get(self): req =self.request.get('id') if(req != ''): qry = chatRoom.query(chatRoom.roomID == req) if(qry): clientID = randomString(5) token = channel.create_channel(clientID) msg = clientID + " has joined the chat" res = qry.get() res.participants.append(clientID) res.participantTokens.append(token) res.histChat+="\n"+msg for participantToken in res.participantTokens: channel.send_message(participantToken, msg) template_values = {'token': token, 'appid': clientID, 'message': res.histChat, 'roomID': req} res.put() path = os.path.join(os.path.dirname(__file__), 'mychat.html') self.response.out.write(template.render(path, template_values))
def post(self): #get the client_key from client client_key = self.request.get('client_key') if not client_key: client_key = users.get_current_user().email() #save Channel new_key = ChannelKey(ch_key=str(client_key)) new_key.put() #retrieve 7 days of messages from datastore date1 = datetime.datetime.now() - datetime.timedelta(days=7) m_history = MessageNDB.query(MessageNDB.date > date1) m_history2 = m_history.order(MessageNDB.date) result = m_history2.fetch(1000) #send data to client #Store log messages in one string marray = "&log" for m in result: marray = marray+"&"+str(m.message) #send via the channel channel.send_message(str(client_key), marray)
def user_points(user_ref, points, title, acc): if not user_ref or not acc: return None try: image = acc.pointsImage except: acc.pointsImage = constants.IMAGE_PARAMS.POINTS_IMAGE accounts_dao.save(acc) diction = {'event':'notify_points', 'user':user_ref.userid, 'account':acc.key().name(), 'points':points, 'widget':'notifier', 'is_api':'no', 'details':"title: "+title, 'success':'true'} message = {'note':"+" + str(points) + " Points", 'image': image, 'title': title} message = json.dumps(message) try: channel.send_message(user_ref.key().name(), message) logs.create(diction) except channel.InvalidChannelClientIdError: diction['success'] = "false" logging.error("Bad Channel ID for acc %s and user %s"%(acc.key().name(), user_ref.key().name())) logs.create(diction) return
def sendFeedbackToStudents(self): for studentName in self.students: student = getStudent(studentName, self.lesson) exerciseAnswers = [ a.content for a in student.answers if a.exercise == self.key.id() ] if exerciseAnswers and exerciseAnswers[0] != "MISSING": answer = exerciseAnswers[0] message = { "type": "validAnswer", "message": { "validAnswer": self.validatedAnswer, "myAnswer": answer, "dict": getAnswersProposed(self.type) } } else: message = { "type": "exerciseExpired", "message": { "validAnswer": self.validatedAnswer, "dict": getAnswersProposed(self.type) } } message = json.dumps(message) channel.send_message(student.token, message)
def post(self): ids = ('1', '2') key = self.request.get('key') is_pressed = self.request.get('pressed') time = self.request.get('time') id = [id for id in ids if id != self.request.get('id')][0] channel.send_message(id, json.dumps({'key': key, 'pressed': is_pressed, 'time': time}))
def _update_clients(self, canvas, sender_channel_id, segments): clients = CanvasClient.query(ancestor=canvas.key) segments_msg = json.dumps(segments) for client in clients: if client.channel_id == sender_channel_id: continue channel.send_message(client.channel_id, segments_msg)
def post(self): data = json.loads(self.request.body) user = users.get_current_user() client_id = data['id'] chat = ndb.Key(urlsafe=client_id[:-8]).get() if user: Activity( user = user, chat = chat.key).put() for client in chat.clients: channel.send_message( client, json.dumps( {"clients":len(chat.clients)+1, "name": chat.name, "cursor": False, "message": [] } ) ) last_message_when = Message.query_time_from_chat(chat.key) if last_message_when < ( datetime.datetime.now()-datetime.timedelta(hours=4)): logging.info('Reset clients in chat {}'.format(chat.key.urlsafe())) chat.reset_clients() chat.add_client(client_id)
def get(self): user = users.get_current_user() game_id = self.request.get('game') token = '' other_player = '' user = users.get_current_user() #logout_url = users.create_logout_url("/") game_hand = '' if game_id: game = Game.get_by_id(int(game_id)) if game: game_hand = game.hand if game.may_join(user): token = create_channel(str(game.key().id()) + user.user_id()) other_player = game.player1 key = get_other_player_channel_key(game, user.user_id()) channel.send_message(key, simplejson.dumps({'type':'join', 'user':get_user_dump(user, format='dict')})) else: self.redirect('/netplay') else: self.redirect('/netplay') context = { 'token': token, 'game_id': game_id, 'game_hand': game_hand, 'other_player': other_player, 'user': user, 'user_id': user.user_id(), 'login': users.create_login_url(self.request.uri), 'logout': users.create_logout_url(self.request.uri), } tmpl = path.join(path.dirname(__file__), 'netplay.html') self.response.write(render(tmpl, context))
def push(record, channel_id=None): """Send a log record via channel API. record -- log record to push channel_id If channel_id is supplied, the message will only be sent to the corresponding channel. """ template_values = { 'message': cgi.escape(record.message), 'filename': cgi.escape(record.filename), 'funcname': cgi.escape(record.funcName), 'levelname': cgi.escape(record.levelname), 'lineno': str(record.lineno), } data = { 'html' : render_to_string('log_record_li.html', template_values) } if channel_id: channel.send_message(channel_id, simplejson.dumps(data)) else: [channel.send_message(channel_id, simplejson.dumps(data)) for channel_id in _get_channels()]
def post(self, setting, val): user = users.get_current_user() if user: if (Settings.gql('WHERE user = :1', user).count() > 0): settings = Settings.gql('WHERE user = :1', user).get() if not settings.msg: settings.msg = '' if not settings.font: settings.font = 'sans-serif' if not settings.disps: settings.disps = '' else: settings = Settings() settings.user = user settings.msg = '' settings.font = 'sans-serif' settings.color = 'black' settings.disps = '' setattr(settings, setting, val)#urllib.unquote(val)) settings.put() userDisps = settings.disps.split(',') # -------------------------------- get the list of displays for disp in userDisps: # ----------------------------------------------- and for each one... if disp != '': # --------------------------------------------------- ...assuming it exists channel.send_message(user.user_id() + disp, setting[:3] + val) # send the new value prefixed with the first three letters of the setting self.response.out.write('') else: self.error(403)
def timeline_insert(self, card): """Insert a card for the current user.""" if card.id is not None: raise endpoints.BadRequestException("ID is not allowed in request body.") if card.menuItems is not None: for menuItem in card.menuItems: if menuItem.action == MenuAction.CUSTOM: if menuItem.id is None: raise endpoints.BadRequestException("For custom actions id needs to be provided.") if menuItem.values is None or len(menuItem.values) == 0: raise endpoints.BadRequestException("For custom actions at least one value needs to be provided.") for value in menuItem.values: if value.displayName is None or value.iconUrl is None: raise endpoints.BadRequestException("Each value needs to contain displayName and iconUrl.") if card.htmlPages is not None and len(card.htmlPages) > 0 and card.bundleId is not None: raise endpoints.BadRequestException("Can't mix HTML and Card bundle.") card.isDeleted = False card.put() channel.send_message(card.user.email(), json.dumps({"id": card.id})) return card
def post(self): post = matcher.get_document(self.request.form) send = post.data for sub_id in self.request.form.getlist('id'): logging.info("send post to %s" % sub_id) if send.get('evt') == 'online' and '@' in sub_id: continue if '@' in sub_id: jid = sub_id.split('/')[0] whoami = '%(board)[email protected]' % send MSG = """Posted http://42ch.org/%(board)s/%(thread)d/#p%(last)d\n\n%(text)s""" % send xmpp.send_message(jid, MSG, from_jid=whoami) continue try: channel.send_message(sub_id, dumps(send)) except channel.InvalidChannelClientIdError: logging.error("inval client id %r" % sub_id) except channel.InvalidMessageError: logging.error("inval msg: %r" % dumps(send)) return Response("ok")
def send_update(self): message = self.get_game_message() channel.send_message(self.game.player1.user_id() + self.game.key().id_or_name(), message) if self.game.player2: channel.send_message(self.game.player2.user_id() + self.game.key().id_or_name(), message)
def run(self): channel.send_message(self.client,self.message)
def post(self): body = json.loads(self.request.body) client_id = body['from'] chat = ndb.Key(urlsafe=client_id[:-8]).get() if body['to'] in chat.clients: newchat = ChatManager() newchat.name = 'Private' newchat.active = True newchat.private = True newchat.owner = users.User("*****@*****.**") newchat.save = False newchat.options = {"save": False, "conversations": False, "persistent": False} newchat_key = newchat.put() channel.send_message( body['from'], json.dumps( {"clients":len(chat.clients), "name": chat.name, "cursor": False, "message": [ {"author": 'ADMIN', "id": '0', "when": self.print_time(), "text": 'You have sent a private <a target="_blank" href="/chat?key={}">room</a>'.format(newchat_key.urlsafe()) } ] } ) ) channel.send_message( body['to'], json.dumps( {"clients":len(chat.clients), "name": chat.name, "cursor": False, "message": [ {"author": 'ADMIN', "id": '0', "when": self.print_time(), "text": 'You have been invited to a private <a target="_blank" href="/chat?key={}">room</a> by {}'.format(newchat_key.urlsafe(),body['author']) } ] } ) ) else: channel.send_message( body['from'], json.dumps( {"clients":len(chat.clients), "name": chat.name, "cursor": False, "message": [{"author": 'ADMIN', "id": '0', "when": self.print_time(), "text": 'This user is no longer connected' }] } ) )
def call(self, instance, callbacks): channel.send_message(instance.channel, jsondumps(callbacks))
def notifyUser(self, user_id, notification_type, notification): try: notification['type'] = notification_type channel.send_message(user_id, self.asJson(notification)) except Exception: pass
def action_insert(self, action): """Perform an action on a timeline card for the current user. This isn't part of the actual Mirror API but necessary for the emulator to send actions to the subscribed services. Returns just a simple success message """ current_user = endpoints.get_current_user() if current_user is None: raise endpoints.UnauthorizedException("Authentication required.") card = ndb.Key("TimelineItem", action.itemId).get() if card is None or card.user != current_user: raise endpoints.NotFoundException("Card not found.") data = None operation = None if action.action == MenuAction.SHARE: operation = Operation.UPDATE data = {} data["collection"] = "timeline" data["itemId"] = action.itemId data["operation"] = operation.name data["userActions"] = [{"type": MenuAction.SHARE.name}] if action.action == MenuAction.REPLY or action.action == MenuAction.REPLY_ALL: operation = Operation.INSERT data = {} data["collection"] = "timeline" data["itemId"] = action.itemId data["operation"] = operation.name data["userActions"] = [{"type": MenuAction.REPLY.name}] if action.action == MenuAction.DELETE: operation = Operation.DELETE data = {} data["collection"] = "timeline" data["itemId"] = action.itemId data["operation"] = operation.name data["userActions"] = [{"type": MenuAction.DELETE.name}] if action.action == MenuAction.CUSTOM: operation = Operation.UPDATE data = {} data["collection"] = "timeline" data["itemId"] = action.itemId data["operation"] = operation.name data["userActions"] = [{"type": MenuAction.CUSTOM.name, "payload": action.value}] if data is not None and operation is not None: header = {"Content-type": "application/json"} query = Subscription.query().filter(Subscription.user == current_user) query = query.filter(Subscription.collection == "timeline") query = query.filter(Subscription.operation == operation) for subscription in query.fetch(): data["userToken"] = subscription.userToken data["verifyToken"] = subscription.verifyToken req = urllib2.Request(subscription.callbackUrl, json.dumps(data), header) try: urllib2.urlopen(req) except: logging.error(sys.exc_info()[0]) # Report back to Glass emulator channel.send_message(current_user.email(), json.dumps({"id": action.itemId})) return ActionResponse(success=True)
def timeline_delete(self, card): """Remove an existing card for the current user. This will set all properties except the ID to None and set isDeleted to true """ if not card.from_datastore or card.user != endpoints.get_current_user(): raise endpoints.NotFoundException("Contact not found.") if card.isDeleted: raise endpoints.NotFoundException("Card has been deleted") # Delete attachments keys = [] if card.attachments is not None: for att in card.attachments: keys.append(blobstore.BlobKey(att.id)) blobstore.delete_async(keys) card.attachments = [] card.bundleId = None card.canonicalUrl = None card.created = None card.creator = None card.displayTime = None card.html = None card.htmlPages = [] card.inReplyTo = None card.isBundleCover = None card.isPinned = None card.menuItems = [] card.notification = None card.recipients = [] card.sourceItemId = None card.speakableText = None card.text = None card.title = None card.updated = None card.isDeleted = True card.put() # Notify Glass emulator channel.send_message(card.user.email(), json.dumps({"id": card.id})) # Notify timeline DELETE subscriptions data = {} data["collection"] = "timeline" data["itemId"] = card.id operation = Operation.DELETE data["operation"] = operation.name header = {"Content-type": "application/json"} query = Subscription.query().filter(Subscription.user == endpoints.get_current_user()) query = query.filter(Subscription.collection == "timeline") query = query.filter(Subscription.operation == operation) for subscription in query.fetch(): data["userToken"] = subscription.userToken data["verifyToken"] = subscription.verifyToken req = urllib2.Request(subscription.callbackUrl, json.dumps(data), header) try: urllib2.urlopen(req) except: logging.error(sys.exc_info()[0]) return card
def log_channel_send(action, orig=None, dest=None): msg = {'action': action, 'orig': orig, 'dest': dest} channel.send_message(log_channel_client, json.dumps(msg))
def send_saved_messages(client_id): messages = get_saved_messages(client_id) for message in messages: channel.send_message(client_id, message.msg) logging.info('Delivered saved message to ' + client_id) message.delete()
def get(self): self.sess = session.Session('enginesession') if self.sess.load(): template_values = {} users=UserDB() user = users.getUserByKey(self.sess.user) template_values['user'] = user #Si el usuario le da al boton de salir, eliminamos su asociacion con la sala if self.request.get('e', default_value='0')!='0': #Le decimos al resto de jugadores que se ha ido game_key = user.idSala if game_key: sala = SalasDB().getSalaById(game_key) if sala: user = None self.sess = session.Session('enginesession') if self.sess.load(): user = UserDB().getUserByKey(self.sess.user) users = UserDB() user_list = users.getUsersBySala(sala.idSala) if UserDB().userExistsInSala(sala.idSala, user.nick): messageRaw = { "type": "salaExit", "content": { "userKey": str(user.key()), "userNick": user.nick } } message = json.dumps(messageRaw) for r in user_list: channel.send_message(str(r.key()), message); #Eliminamos al usuario de la sala user2 = UserDB().getUserByNick(user.nick) UsersInGameDB().deleteUserInGame(user2) numUsers = UserDB().getUsersBySala(user.idSala) res = numUsers.count() #Si no queda nadie en la sala la eliminamos ademas del juego if res == 1: SalasDB().deleteSala(user.idSala) GameDB().deleteGame(user.idSala) #Asignamos none a la sala del usuario user.idSala="None" user.put() #Redirigimos al inicio self.redirect('/') #Comprobamos si la sala existe sala = SalasDB().getSalaById(self.request.get('id')) if sala: #Actualizamos la vista del resto de usuarios game_key = sala.idSala if game_key: sala = SalasDB().getSalaById(game_key) if sala: user = None self.sess = session.Session('enginesession') if self.sess.load(): user = UserDB().getUserByKey(self.sess.user) users = UserDB() user_list = users.getUsersBySala(sala.idSala) if not UserDB().userExistsInSala(sala.idSala, user.nick): if user.avatar: messageRaw = { "type": "sala", "content": { "userKey": str(user.key()), "userNick": user.nick, "userAvatar": 1 } } else: messageRaw = { "type": "sala", "content": { "userKey": str(user.key()), "userNick": user.nick, "userAvatar": 0 } } message = json.dumps(messageRaw) for r in user_list: channel.send_message(str(r.key()), message); #Si el usuario aun no esta asociado a las sala lo asociamos if user and user.idSala=="None" and UsersInGameDB().UserExist(user)==False: user.idSala=self.request.get('id') user.put() idSala = self.request.get('id') game = GameDB().getGameBySala(idSala) inGame = UsersInGameDB() inGame.AddUserInGame(user, game) #Guardamos la partida en la lista de partidas miSala = SalasDB().getSalaById(self.request.get('id')) misPuntos = UsersInGameDB().getPuntos(user) PartidasJugadasDB().setPartida(user, miSala.nombre, misPuntos, False) #Cambiamos el estado del usuario UsersInGameDB().changeState(user, "sala") #Obtenemos el id del juego asociado a la sala game = GameDB().getGameBySala(self.request.get('id')) template_values['gamekey']=game.key() #Ponemos la puntuacion parcial del usuario a 0 UsersInGameDB().scoreReset(user) #Listamos los usuarios en la sala user_list=users.getUsersBySala(self.request.get('id')) template_values['user_list']=user_list # Si el usuario identificado esta asignado al juego token = channel.create_channel(str(user.key())) template_values['token'] = token template_values['game_key'] = sala.idSala else: self.redirect('/') path = os.path.join(os.path.dirname(__file__), 'salajuego.html') self.response.out.write(template.render(path, template_values)) else: self.redirect("/salas?p=1")
def send_update(self): message = self.get_game_message() channel.send_message(self.game.userX.user_id() + self.game.key().id_or_name(), message) if self.game.userO: channel.send_message(self.game.userO.user_id() + self.game.key().id_or_name(), message)
def post(self, session): data = {"img": self.request.get("img"), "url": self.request.get("url")} logging.info(session) logging.info(json.dumps(data)) channel.send_message(session, json.dumps(data))
def announce_call(cls, call): msg = call.to_operator_json() operators = cls.query(cls.is_on_call == True).fetch() for operator in operators: channel.send_message(operator.on_call_channel_token, msg)
def get(self): channels = json.loads(memcache.get('channels') or '{}') for channel_id in channels.iterkeys(): channel.send_message(channel_id, json.dumps({'function': 'reload'}))
def message(root_pipeline_id, template, *args, **kwargs): message = jinja2.Template(template).render( root_pipeline_id=root_pipeline_id, **kwargs) logging.debug(message) client_id = memcache.get('client_id') channel.send_message(client_id, "%s,%s" % (root_pipeline_id, message))
def refresh_calls(self, last_call_datetime): for c in ChatCall.calls_since(last_call_datetime): msg = c.to_operator_json(is_historic=True) channel.send_message(self.on_call_channel_token, msg)
def send_start(self): message = "start" channel.send_message(self.game.user1 + self.game.key.id(), message) if self.game.user2: channel.send_message(self.game.user2 + self.game.key.id(), message)
def user_ping(username, args): user = get_user(username) username = user.username # Use actual name channel_api.send_message(username, "PONG " + args)
def get(self): if (self.request.get('get') == 'livecode'): # token = channel.create_channel('crowdbot') # print out a mini-page about the current program, which refreshes every few minutes by default or by Channel API livesketch = CrowdBotProgram().gql( "WHERE hasRun = 'True' ORDER BY uploaded DESC").get() sketchtitle = "" if (livesketch is not None): sketchtitle = cgi.escape(livesketch.programname) self.response.out.write('''<!DOCTYPE html> <html> <head> <meta http-equiv="refresh" content="60"/> <title>Current CrowdBot Program</title> <script type="text/javascript" src="/shCore.js"></script> <script type="text/javascript" src="/shBrushCpp.js"></script> <link rel='stylesheet' type='text/css' href='/shCore.css'/> <link rel='stylesheet' type='text/css' href='/shThemeDefault.css'/> </head> <body> <span id="codetitle" style="font-family:courier;">''' + sketchtitle + '''</span> <input type="button" value="Refresh" onclick="window.location.reload()"/> <hr/> <pre class="brush: cpp">\n''') # find the last sketch to be downloaded to the board - print program name and source code if (livesketch is not None): #self.response.out.write(cgi.escape(livesketch.programname) + '<hr/>') #self.response.out.write(cgi.escape(livesketch.programtext.replace('\n','<br/>')).replace('<br/>','<br/>').replace(' ',' ')) self.response.out.write(cgi.escape(livesketch.programtext)) else: self.response.out.write('No program loaded\n') self.response.out.write(''' </pre> <script type="text/javascript"> SyntaxHighlighter.all() </script> </body> </html>''') elif (self.request.get('get') == 'livedata'): # display any data relayed by the CrowdBot host try: token = channel.create_channel('crowdbot_data') self.response.out.write('''<!DOCTYPE html> <html> <head> <title>CrowdBot Data Stream</title> <script type="text/javascript" src="/_ah/channel/jsapi"></script> <script type="text/javascript"> function init(){ channel = new goog.appengine.Channel("''' + token + '''"); socket = channel.open(); socket.onmessage = function(msg){ if(msg.data == "CLEAR-DATA"){ while($("datadiv").childNodes.length >= 1){ $("datadiv").removeChild($("datadiv").firstChild); } var dataline = document.createElement('p'); dataline.innerHTML = "Awaiting data..."; $("datadiv").appendChild(dataline); } else{ var dataline = document.createElement('p'); dataline.innerHTML = msg.data; $("datadiv").appendChild(dataline); window.scrollBy(0,50); } }; } function $(id){ return document.getElementById(id); } </script> <style type="text/css"> html, body{ font-family: courier; } </style> </head> <body onload="init()"> <div id="datadiv"> <p>Awaiting data...</p> </div> </body> </html>''') except: # over channel connection limit (100 connections in 24 hours) # show feed of last program to send data lastread = CrowdBotProgram().gql( "WHERE hasRun = 'Complete' ORDER BY uploaded DESC") found = 0 for program in lastread: if (program.feed is not None): if (len(str(program.feed)) > 3): found = 1 self.redirect('/crowdbot/out?get=feed&id=' + str(program.key().id())) break if (found == 0): self.response.out.write( 'Over channel limit and no archived data') elif (self.request.get('get') == 'current'): # send the current program to the function given by jsonp self.response.out.write( cgi.escape(self.request.get('jsonp')) + '("') livesketch = CrowdBotProgram().gql( "WHERE hasRun = 'True' ORDER BY uploaded DESC").get() if (livesketch is not None): self.response.out.write( livesketch.programtext.replace('"', '\\"').replace( '\r', '|~|').replace('\n', '|~|')) self.response.out.write('")') elif (self.request.get('get') == 'feed'): sketch = CrowdBotProgram.get_by_id(long(self.request.get('id'))) self.response.out.write( cgi.escape(sketch.feed.replace('\n', '<br/>')).replace( '<br/>', '<br/>').replace(' ', ' ')) else: # output the earliest-submitted pending sketch ( will be updated to include more information about user, sketch name ) sketch = CrowdBotProgram().gql( "WHERE hasRun = 'False' ORDER BY uploaded ASC").get() livesketch = CrowdBotProgram().gql( "WHERE hasRun = 'True' ORDER BY uploaded DESC").get() if (sketch is not None): # write metadata about sketch self.response.out.write(str(sketch.key().id()) + "|") self.response.out.write( sketch.username.replace('|', '-') + "|") if (sketch.dosend == 'on'): self.response.out.write("TRUE|") else: self.response.out.write("FALSE|") if (sketch.dostream == 'on'): self.response.out.write("TRUE|") else: self.response.out.write("FALSE|") # write sketch self.response.out.write(sketch.programtext) # move pending sketch to live sketch.hasRun = 'True' sketch.put() if (livesketch is not None): # move live sketch to 'Complete' livesketch.hasRun = 'Complete' livesketch.put() # use Channel API to update live code and data views #channel.send_message('crowdbot', cgi.escape(sketch.programname) + '<hr/>' + cgi.escape(sketch.programtext)) channel.send_message('crowdbot_data', 'CLEAR-DATA') # send Tweets to authors of latest and next sketch, if Twitter was provided # based on Anil Shanbhag's Twitter Bot: http://anilattech.wordpress.com/2011/10/29/making-a-twitter-bot-using-appengine/ if (sketch.username.find('@') == 0): starting_format = "%s: your sketch '%s' will run on #CrowdBot for the next 2+ minutes" # oauth client released by Mike Knapp (see twitteroauth.py for more information) client = twitteroauth.TwitterClient( crowdbotconfig.consumer_key, crowdbotconfig.consumer_secret, crowdbotconfig.callback_url) additional_params = { "status": starting_format % (sketch.username, sketch.programname.replace( '@', '').replace('#', '').replace('/', '')) } result = client.make_request( "http://twitter.com/statuses/update.json", token=crowdbotconfig.access_token, secret=crowdbotconfig.access_token_secret, additional_params=additional_params, method=POST) logging.info(result.content) else: # there are no pending programs self.response.out.write('no new program')
def send(event): for l in event.listeners: channel.send_message(str(l), msg) return event.listeners
def get(self): increment() channels = get_registered_channels() for channel_id in channels.iterkeys(): channel.send_message(channel_id, str(get_count()))
def sendmessage(user, roomid): """sends a message that is useless""" message = request.form['message'] channel.send_message(user + roomid, message)
def broadcast(msg, key): channel.send_message(key, msg)
def post(self): if (self.request.get('livedata') != ''): # update live data channel.send_message('crowdbot_data', cgi.escape(self.request.get('livedata'))) elif (self.request.get('mail') != ''): # send saved data logging.info(self.request.get('mail')) sketch = CrowdBotProgram.get_by_id(long(self.request.get('id'))) sketch.feed = db.Text(self.request.get('data')) sketch.put() if (self.request.get('mail').find('@') == 0): # Twitter name if (self.request.get('data').replace('\n', '').replace( ' ', '').replace(' ', '') == ''): # no data recorded finished_format = "%s: #CrowdBot ran your sketch, '%s'. No data was returned." else: # send data record finished_format = "%s: #CrowdBot ran your sketch, '%s'. Data stored at http://mapmeld.com/crowdbot/out?get=feed&id=" + self.request.get( 'id') # oauth client released by Mike Knapp (see twitteroauth.py for more information) client = twitteroauth.TwitterClient( crowdbotconfig.consumer_key, crowdbotconfig.consumer_secret, crowdbotconfig.callback_url) additional_params = { "status": finished_format % (sketch.username.replace( ' ', ''), sketch.programname.replace('@', '').replace( '#', '').replace('/', '')) } result = client.make_request( "http://twitter.com/statuses/update.json", token=crowdbotconfig.access_token, secret=crowdbotconfig.access_token_secret, additional_params=additional_params, method=POST) #logging.info(result.content) elif (self.request.get('mail').find('@') > -1): # e-mail if (self.request.get('data').replace('\n', '').replace( ' ', '').replace(' ', '') == ''): # no data recorded finished_text = "CrowdBot ran your sketch, '" + cgi.escape( sketch.programname).replace('@', '').replace( '#', '').replace('/', '') + """'. No data was returned by your sketch. Use the Serial functions to report data from CrowdBot's Arduino.""" else: # send data record finished_text = "CrowdBot ran your sketch, '" + cgi.escape( sketch.programname).replace('@', '').replace( '#', '').replace('/', '') + """'. Data returned by your sketch is stored at http://mapmeld.com/crowdbot/out?get=feed&id=""" + self.request.get( 'id') mail.send_mail(sender=crowdbotconfig.mail, to=self.request.get('mail'), subject="CrowdBot ran your sketch", body=finished_text) else: # accept a new sketch from the form sketch = CrowdBotProgram() sketch.programname = self.request.get('sketchname') sketch.username = self.request.get('identify') sketch.programtext = db.Text(self.request.get('mysketch')) sketch.dostream = self.request.get('dostream') sketch.dosend = self.request.get('dosend') sketch.hasRun = 'False' sketch.put() # live data stream visible if user's program includes data streaming if ((self.request.get('dostream') == 'on') and (self.request.get('mysketch').find('Serial.begin') > -1)): self.redirect('/crowdbot?screen=watch&data=show') else: self.redirect('/crowdbot?screen=watch')
def sendmessage(user, gameid): """sends a message that is useless""" message = request.form['message'] channel.send_message(user + gameid, message) return "message sent"
def post(self): remote_id = self.request.get('remoteClientId') data = self.request.body channel.send_message(remote_id, data)
def post(self): self.response.headers['Content-Type'] = 'application/json' user = users.get_current_user() crossienum = self.request.get('crossienum') if crossienum is None or len(crossienum) == 0: # Cannot proceed self.response.out.write( simplejson.dumps({'error': 'Crossienum should specified.'})) return crossienum = int(crossienum) crossiedata = None q = UserCrossie.all() q.filter('user', user) q.filter('crossienum', crossienum) usercrossie = q.get() if usercrossie is None: # FIXME: No transaction model used here. crossiedata = CrossieData(crossienum=crossienum, acl=[user]) crossiedata.put() usercrossie = UserCrossie(crossienum=crossienum, user=user, crossiedata=crossiedata) usercrossie.put() crossieid = usercrossie.crossiedata.key().id() updates = self.request.get('updates') if updates is None or len(updates) == 0: updates = [] else: updates = simplejson.loads(updates) try: crossiedata = db.run_in_transaction( CrossieData.getAndUpdateCrossie, crossieid, user, updates) except NoSuchCrossieException: self.response.out.write( simplejson.dumps({'error': 'Crossie data not found.'})) return except PermissionDeniedException: self.response.out.write( simplejson.dumps({'error': 'Permission denied.'})) return except db.TransactionFailedError: self.response.out.write( simplejson.dumps({'error': 'DB error. Try again.'})) if crossiedata is not None: self.response.out.write(crossiedata.getJSON()) for usr in crossiedata.acl: if usr != user: try: channel.send_message( usr.email().lower(), simplejson.dumps({ 'crossieupdate': { 'updates': updates, 'crossienum': crossienum } })) except: # Does not matter if all collabs don't get the message pass
def send_message(stream, data): try: # logging.info('send_message %r %r'%(stream.clientId, data)) channel.send_message(stream.clientId, data) except channel.InvalidChannelClientIdError: pass
def post(self): self.response.headers['Content-Type'] = 'application/json' user = users.get_current_user() crossienum = self.request.get('crossienum') if crossienum is None or len(crossienum) == 0: # Cannot proceed self.response.out.write( simplejson.dumps({'error': 'Crossienum should specified.'})) return sharee = self.request.get('sharedWith') if sharee is None or len(sharee) == 0: # Cannot proceed self.response.out.write( simplejson.dumps({'error': 'SharedWith should specified.'})) return crossienum = int(crossienum) q = UserCrossie.all() q.filter('user', user) q.filter('crossienum', crossienum) usercrossie = q.get() if usercrossie is None: # Cannot proceed self.response.out.write( simplejson.dumps({'error': 'This crossie does not exist.'})) return sharee = sharee.lower() # Check if already shared with this user. q = ShareCrossie.all() q.filter('sharer', user) q.filter('sharee', sharee) q.filter('crossienum', crossienum) previousshares = q.get() if previousshares is not None: # Cannot proceed self.response.out.write( simplejson.dumps({'error': 'Pending invite exists.'})) return for usr in usercrossie.crossiedata.acl: if usr.email().lower() == sharee: # Cannot proceed self.response.out.write( simplejson.dumps({'error': 'User already in ACL list.'})) return sharecrossie = ShareCrossie(sharer=user, sharee=sharee, crossienum=crossienum) sharecrossie.put() try: channel.send_message( sharee, simplejson.dumps({ 'sharedcrossie': { 'shareId': sharecrossie.key().id(), 'sharer': user.email(), 'crossienum': crossienum } })) except: # Does not matter if sharee gets the message right away. pass self.response.out.write( simplejson.dumps({'shareId': sharecrossie.key().id()}))
def post(self): obj = json.loads(self.request.body) if(obj["msgType"] == "chat"): #do chat fanout room = Room.get_by_id(obj["destination"]) jmsg = { 'msgType':'chat', 'destination':obj["destination"], 'user':obj["userdisplayname"], 'msg': obj["content"], 'timestamp': int(time.mktime(datetime.datetime.utcnow().timetuple())) * 1000 } for puser in room.users: channel.send_message(puser.userID+puser.channelID+'0',json.dumps(jmsg)) #add to logs here room.messages.append(Message(author=obj["userdisplayname"],content=obj["content"])) room.put() pass elif (obj["msgType"] == "joinRoom"): #create and/or join room #get list of rooms room=Room.get_by_id(obj["destination"]) if(room and obj["userid"]): #room exists #get existing users presentUsers = list(room.users) #add the current user to the room room.users.append(User( displayName = obj["userdisplayname"], userID=obj["userid"], channelID=obj["channelguid"] )) rpop = len(room.users) #send a joined message to all the other users jmsg = { 'msgType':'joinedRoom', 'destination':obj["destination"], 'username':obj["userdisplayname"], 'population': str(rpop) } for puser in presentUsers: channel.send_message(puser.userID+puser.channelID+'0',json.dumps(jmsg)) #send last 5 messages in the room to the new user todisplay =5 if len(room.messages) < 5: todisplay=len(room.messages) for msg in room.messages[(0-todisplay):]: jmsg = { 'msgType':'chat', 'destination':room.name, 'user':msg.author, 'msg': msg.content, 'timestamp': int(time.mktime(msg.timestamp.timetuple())) * 1000 } channel.send_message(obj["userid"]+obj["channelguid"]+'0',json.dumps(jmsg)) #send a successful join response to the original user jmsg2 = { 'msgType':'joinRoom', 'destination':obj["destination"], 'username':obj["userdisplayname"], 'population': str(rpop) } channel.send_message(obj["userid"]+obj["channelguid"]+'0',json.dumps(jmsg2)) obj["population"] = rpop room.put() else: #room doesn't exist - let's create it with one member room = Room(id=obj["destination"], name=obj["destination"], users=[User( displayName = obj["userdisplayname"], userID = obj["userid"], channelID=obj["channelguid"] )], messages=[]) rpop = len(room.users) jmsg2 = { 'msgType':'joinRoom', 'destination':obj["destination"], 'username':obj["userdisplayname"], 'population': str(rpop) } channel.send_message(obj["userid"]+obj["channelguid"]+'0',json.dumps(jmsg2)) obj["population"] =str(rpop) room.put() pass elif (obj("msgType") == "leaveRoom"): #leave room pass return self.response.out.write(json.dumps(obj))