示例#1
0
 def who_command(self, message=None):
     if self.set_chat_and_user(message):
         arg = message.arg.strip()
         if arg in ["", "am i", "online"]:
             if arg == "am i":
                 message.reply(messages.SYSTEM_MESSAGE %
                               ("You are " + user_listing([self.sender])))
             else:
                 who = "\nOnline:\n"
                 listeners = [
                     u for u in self.chat.listeners
                     if xmpp.get_presence(u.address, message.to)
                 ]
                 who += user_listing(listeners)
                 if arg != "online":
                     offlines = [
                         u for u in self.chat.users
                         if not xmpp.get_presence(u.address, message.to)
                     ]
                     who += "\n\nOffline:\n"
                     who += user_listing(offlines)
                 who += "\n\nOnline, but has muted this chat:\n"
                 non_listeners = [
                     User.user(address)
                     for address in self.chat.non_listeners
                     if xmpp.get_presence(address, message.to)
                 ]
                 who += user_listing(non_listeners)
                 message.reply(messages.SYSTEM_MESSAGE % who)
         else:
             message.reply(messages.HELP_MSG)
示例#2
0
  def post(self): 
    user_address = self.request.get('recipient')
    message = self.request.get('message')

    logging.info('User is logged in? %s' % str(xmpp.get_presence(user_address)))

    if xmpp.get_presence(user_address):
        status_code = xmpp.send_message(user_address, message)
        chat_message_sent = (status_code != xmpp.NO_ERROR)

    self.redirect('/')
示例#3
0
    def post(self):
        logging.debug("DeviceHandler PUT")
        resource = self.request.get('resource')

        user = users.get_current_user()
        jid = user.email()
        full_resource = model.get_full_resource(jid, resource)
        full_jid = '%s/%s' % (jid, full_resource)
        online, avail = xmpp.get_presence(full_jid, get_show=True)

        device = model.Device.from_resource(resource)

        msg = "OK"
        if device != None:
            logging.debug("Device %s allready in system", full_jid)
            msg = "JID %s is already added" % jid
            self.response.status = 200  #fixme

        else:
            logging.debug("Adding device %s", full_jid)
            device = model.Device(
                Ind_Device_Name=resource,
                Ind_Device_Description="**description not loaded yet**",
                Ind_Device_Elements="**elements not loaded yet**",
                owner=user,
                jid=jid,
                resource=resource,
                presence=avail)
            device.put()

        self.render_json({'msg': msg, "device": device})
示例#4
0
文件: views.py 项目: krukmat/HOD
def settings(request):
  account = models.Account.current_user_account
  if request.method != 'POST':
    nickname = account.nickname
    default_context = account.default_context
    default_column_width = account.default_column_width
    form = SettingsForm(initial={'nickname': nickname,
                                 'context': default_context,
                                 'column_width': default_column_width,
                                 'notify_by_email': account.notify_by_email,
                                 'notify_by_chat': account.notify_by_chat,
                                 })
    chat_status = None
    if account.notify_by_chat:
      try:
        presence = xmpp.get_presence(account.email)
      except Exception, err:
        logging.error('Exception getting XMPP presence: %s', err)
        chat_status = 'Error (%s)' % err
      else:
        if presence:
          chat_status = 'online'
        else:
          chat_status = 'offline'
    return respond(request, 'settings.html', {'form': form,
                                              'chat_status': chat_status})
示例#5
0
文件: ui.py 项目: EnerNOC/remoht.us
    def post(self):
        resource = self.request.get('resource')

        user = users.get_current_user()
        jid = user.email()

        full_resource = model.get_full_resource( jid, resource )
        
        full_jid = '%s/%s' % (jid, full_resource)

        online, avail = xmpp.get_presence(full_jid, get_show=True)

        device = model.Device.from_resource(resource)

        msg = "OK"
        if device != None:
            msg = "JID %s is already added" % jid
            self.response.status = 200 #fixme

        else:
            logging.debug("Adding device %s", full_jid)
            device = model.Device( 
                    owner = user,
                    jid = jid,
                    resource = resource,
                    presence = avail )
            device.put()

        self.render_json({'msg':msg,"device":device})
示例#6
0
    def post(self):
        cursor = int(self.request.get("cursor", default_value=0))
        tokens = OAuthAccessToken.all().fetch(10, offset = cursor)

        for token in tokens:
            if xmpp.get_presence(token.email):
                client = OAuthClient('twitter', self, token.email)
                
                user_cache = memcache.get("user_cache_" + token.email)
                
                if user_cache is not None and user_cache.since_id is not None:
                    #response = client.get('/statuses/home_timeline', count = 5, 
                    #                  since_id = last_sent_id)
                    logging.info('since_id:' +  str(user_cache.since_id))
                    response = self.fetchTweets(client, token.email, 
                                    '/statuses/home_timeline', count = 5, 
                                      since_id = user_cache.since_id)
                else:
                    response = self.fetchTweets(client, token.email, 
                                    '/statuses/home_timeline', count = 5)
                
                if len(response) > 0:
                    xmpp.send_message(token.email, 'Some recent tweets:' + getFormattedMessage(response))
        
        if len(tokens) == 10:
            taskqueue.add(url='/sendrecentworker', 
                          params={'cursor': cursor + 10})
示例#7
0
    def post(self):
        super(HookHandler, self).post()
        kind = self.data['kind']
        phone = self.data['phone'].strip()
        email = self.data['email'].strip()
        sender_name = self.data['full_name'].strip()

        # Get the account
        account = Account.get_by_key_name(
            key_names=email
        )
        if kind == 'sms':
            content = unicode(self.data['content'])
            account.receive_message_from(
                phone=phone, sender=sender_name, content=content
            )
        else:
            account.call_from(
                phone=phone, sender=sender_name
            )

        if not DEBUG:
            if xmpp.get_presence(email):
                msg = "%s : %s" % (sender_name, content)
                status_code = xmpp.send_message(email, msg)
                chat_message_sent = (status_code != xmpp.NO_ERROR)
            logging.debug(chat_message_sent)

        self.response.out.write("OK")
示例#8
0
 def get(self):
         reminders = Reminder.all().filter('enabled =', True).fetch(1000)
         for reminder in reminders:
                 if xmpp.get_presence(reminder.recipient, from_jid=chatbot_name):
                         xmpp.send_message(reminder.recipient, reminder.text, from_jid=chatbot_name)
                 else:
                         logging.info(reminder.recipient + ' was not online.')
示例#9
0
 def func_on(self, args):
     if len(args):
         for a in args:
             if a == "home":
                 self._google_user.display_timeline |= MODE_HOME
             elif a == "mention":
                 self._google_user.display_timeline |= MODE_MENTION
             elif a == "dm":
                 self._google_user.display_timeline |= MODE_DM
             elif a == "list":
                 self._google_user.display_timeline |= MODE_LIST
     s = Session.get_by_key_name(self._google_user.jid)
     if (
         not s
         and self._google_user.display_timeline
         and self._google_user.enabled_user
         and self._google_user.msg_template.strip()
     ):
         try:
             flag = xmpp.get_presence(self._google_user.jid)
         except (xmpp.Error, DeadlineExceededError):
             flag = False
         if flag:
             Db.set_datastore(Session(key_name=self._google_user.jid, shard=self._google_user.shard))
     modes = []
     if self._google_user.display_timeline & MODE_LIST:
         modes.append("list")
     if self._google_user.display_timeline & MODE_HOME:
         modes.append("home")
     if self._google_user.display_timeline & MODE_MENTION:
         modes.append("mention")
     if self._google_user.display_timeline & MODE_DM:
         modes.append("dm")
     return _("ON_MODE") % ", ".join(modes)
示例#10
0
def get_chat_status(account):
    try:
        presence = xmpp.get_presence(account.email)
        return 'online' if presence else 'offline'
    except Exception as err:
        logging.error('Exception getting XMPP presence: %s', err)
        return 'Error (%s)' % err
示例#11
0
 def func_on(self, args):
     if len(args):
         for a in args:
             if a == 'home':
                 self._google_user.display_timeline |= MODE_HOME
             elif a == 'mention':
                 self._google_user.display_timeline |= MODE_MENTION
             elif a == 'dm':
                 self._google_user.display_timeline |= MODE_DM
             elif a == 'list':
                 self._google_user.display_timeline |= MODE_LIST
     s = Session.get_by_key_name(self._google_user.jid)
     if not s and self._google_user.display_timeline and self._google_user.enabled_user and self._google_user.msg_template.strip(
     ):
         try:
             flag = xmpp.get_presence(self._google_user.jid)
         except (xmpp.Error, DeadlineExceededError):
             flag = False
         if flag:
             Db.set_datastore(
                 Session(key_name=self._google_user.jid,
                         shard=self._google_user.shard))
     modes = []
     if self._google_user.display_timeline & MODE_LIST:
         modes.append('list')
     if self._google_user.display_timeline & MODE_HOME:
         modes.append('home')
     if self._google_user.display_timeline & MODE_MENTION:
         modes.append('mention')
     if self._google_user.display_timeline & MODE_DM:
         modes.append('dm')
     return _('ON_MODE') % ', '.join(modes)
示例#12
0
def get_chat_status(account):
  try:
    presence = xmpp.get_presence(account.email)
    return 'online' if presence else 'offline'
  except Exception as err:
    logging.error('Exception getting XMPP presence: %s', err)
    return 'Error (%s)' % err
示例#13
0
 def func_switch(self, args):
     length = len(args)
     if length > 1:
         raise NotImplementedError
     else:
         twitter_users = TwitterUser.get_by_jid(self._google_user.jid)
         twitter_users_name = [
             u.twitter_name for u in twitter_users
             if u.twitter_name is not None
         ]
         if not length:
             return _('NOW_USING') % self._google_user.enabled_user + '\n'\
             + _('ALL_TWITTER_USERS_NAME') % '\n'.join(twitter_users_name)
         elif _check_username(args[0]):
             twitter_users_name_ci = [x.lower() for x in twitter_users_name]
             twitter_name_ci = args[0].lower()
             if twitter_name_ci in twitter_users_name_ci:
                 i = twitter_users_name_ci.index(twitter_name_ci)
                 if not self._google_user.enabled_user and self._google_user.display_timeline and self._google_user.msg_template.strip(
                 ):
                     try:
                         flag = xmpp.get_presence(self._google_user.jid)
                     except (xmpp.Error, DeadlineExceededError):
                         flag = False
                     if flag:
                         Db.set_datastore(
                             Session(key_name=self._google_user.jid,
                                     shard=self._google_user.shard))
                 self._google_user.enabled_user = twitter_users_name[i]
                 return _('ENABLED_TWITTER_USER_CHANGED'
                          ) % self._google_user.enabled_user
     return _('NOT_ASSOCIATED_TWITTER_USER')
示例#14
0
 def func_switch(self, args):
     length = len(args)
     if length > 1:
         raise NotImplementedError
     else:
         twitter_users = TwitterUser.get_by_jid(self._google_user.jid)
         twitter_users_name = [u.twitter_name for u in twitter_users if u.twitter_name is not None]
         if not length:
             return (
                 _("NOW_USING") % self._google_user.enabled_user
                 + "\n"
                 + _("ALL_TWITTER_USERS_NAME") % "\n".join(twitter_users_name)
             )
         elif _check_username(args[0]):
             twitter_users_name_ci = [x.lower() for x in twitter_users_name]
             twitter_name_ci = args[0].lower()
             if twitter_name_ci in twitter_users_name_ci:
                 i = twitter_users_name_ci.index(twitter_name_ci)
                 if (
                     not self._google_user.enabled_user
                     and self._google_user.display_timeline
                     and self._google_user.msg_template.strip()
                 ):
                     try:
                         flag = xmpp.get_presence(self._google_user.jid)
                     except (xmpp.Error, DeadlineExceededError):
                         flag = False
                     if flag:
                         Db.set_datastore(Session(key_name=self._google_user.jid, shard=self._google_user.shard))
                 self._google_user.enabled_user = twitter_users_name[i]
                 return _("ENABLED_TWITTER_USER_CHANGED") % self._google_user.enabled_user
     return _("NOT_ASSOCIATED_TWITTER_USER")
示例#15
0
文件: main.py 项目: ahyangyi/killard
 def get(self):
   #xmpp.send_invite('*****@*****.**')
   status = xmpp.get_presence('*****@*****.**')
   print 'status = ' + str(status)
   #xmpp.send_message('*****@*****.**', 'hello' + str(status))
   print '------------------'
   return
示例#16
0
def get_chat_status(account):
    try:
        presence = xmpp.get_presence(account.email)
        return "online" if presence else "offline"
    except Exception as err:
        logging.error("Exception getting XMPP presence: %s", err)
        return "Error (%s)" % err
示例#17
0
文件: ui.py 项目: vtgav/remoht.us
    def post(self):
        resource = self.request.get('resource')

        user = users.get_current_user()
        jid = user.email()

        full_resource = model.get_full_resource(jid, resource)

        full_jid = '%s/%s' % (jid, full_resource)

        online, avail = xmpp.get_presence(full_jid, get_show=True)

        device = model.Device.from_resource(resource)

        msg = "OK"
        if device != None:
            msg = "JID %s is already added" % jid
            self.response.status = 200  #fixme

        else:
            logging.debug("Adding device %s", full_jid)
            device = model.Device(owner=user,
                                  jid=jid,
                                  resource=resource,
                                  presence=avail)
            device.put()

        self.render_json({'msg': msg, "device": device})
示例#18
0
def sendInviteIM(user, invite):
    toEmail = invite.toEmail
    if xmpp.get_presence(toEmail):
        xmpp.send_message(
            toEmail,
            user.nickname() +
            ' has invited you to play a game of chess. http://your-move.appspot.com?i='
            + str(invite.key()))
示例#19
0
def cached_xmpp_user_check(username):
    xc=XmppStatusCache()
    if (xc.get_cached_xmpp_status(username)):
        return xc.Status;
    else:
        r=xmpp.get_presence(username)
        set_cached_xmpp_status(username,r)
        return r;
示例#20
0
def cached_xmpp_user_check(username):
	xc=XmppStatusCache()
	if (xc.get_cached_xmpp_status(username)):
		return xc.Status
	else:
		r=xmpp.get_presence(username)
		set_cached_xmpp_status(username,r)
		return r
示例#21
0
def isOnline(gtalk):
	ret = False
	try:
		ret = xmpp.get_presence(gtalk)
	except:
		pass

	return ret
示例#22
0
文件: loggers.py 项目: nikcub/Sketch
 def emit(self, record):
     # prevent recursive logging
     if self.is_logging:
         return
     self.is_logging = True
     # if user is online send a message
     if xmpp.get_presence(self.jid, from_jid=self.from_jid):
         status_code = xmpp.send_message(self.jid, self.format(record), from_jid=self.from_jid)
     self.is_logging = False
示例#23
0
 def dispatch(cls, notice):
     jid = notice.channel.outlet.get_param('jid')
     if xmpp.get_presence(jid):
         body = "%s: %s" % (notice.title,
                            notice.text) if notice.title else notice.text
         xmpp.send_message(
             jid, "%s %s [%s]" %
             (body, notice.link or '', notice.source.source_name))
     return None
示例#24
0
    def post(self):
        user_address = self.request.get('jid')
        user_msg = self.request.get('msg')

        if not xmpp.get_presence(user_address):
            xmpp.send_invite(user_address)
        else:
            status_code = xmpp.send_message(user_address, user_msg)
            self.response.out.write(status_code)
示例#25
0
文件: tagliner.py 项目: PEZ/MooTalk
 def get(self):
     chats = get_chats_with_taglines()
     for chat in chats:
         tagline = get_random_tagline(chat)
         addresses = [
             u.address for u in chat.listeners
             if xmpp.get_presence(u.address, chat.jid)
         ]
         xmpp.send_message(addresses, messages.TAGLINE_MESSAGE % tagline,
                           chat.jid)
示例#26
0
 def update_users_status(self):
   all_users = ChatUser.all().fetch(100)
   for user in all_users:
     if user.status != 'quiet':
       if xmpp.get_presence(user.jid):
         user.status = 'online'
       else:
         user.status = 'offline'
       user.put()
   return all_users
示例#27
0
    def post(self):
        commentary_url = self.request.get('url')
        match = self.request.get('title')
        comments = getNewComments(commentary_url)

        users = getUsers()
        for user in users:
            if xmpp.get_presence(user.userid):
                for track in user.trackers:
                    if match.upper().find(track.upper()) > -1 and comments != '':
                        xmpp.send_message(user.userid, comments)
示例#28
0
 def who_command(self, message=None):
     if self.set_chat_and_user(message):
         arg = message.arg.strip()
         if arg in ["", "am i", "online"]:
             if arg == "am i":
                 message.reply(messages.SYSTEM_MESSAGE % ("You are " + user_listing([self.sender])))
             else:
                 who = "\nOnline:\n"
                 listeners = [u for u in self.chat.listeners if xmpp.get_presence(u.address, message.to)]
                 who += user_listing(listeners)
                 if arg != "online":
                     offlines = [u for u in self.chat.users if not xmpp.get_presence(u.address, message.to)]
                     who += "\n\nOffline:\n"
                     who += user_listing(offlines)
                 who += "\n\nOnline, but has muted this chat:\n"
                 non_listeners = [User.user(address) for address in self.chat.non_listeners if xmpp.get_presence(address, message.to)]
                 who += user_listing(non_listeners)
                 message.reply(messages.SYSTEM_MESSAGE % who)
         else:
             message.reply(messages.HELP_MSG)
示例#29
0
 def get(self):
   self.response.headers['Content-Type'] = 'text/plain'
   for u in gaetalk.User.all():
     if u.jid.endswith('@gmail.com'):
       if u.avail != gaetalk.OFFLINE and 'fakeresouce' not in u.resources:
         if not xmpp.get_presence(u.jid):
           del u.resources[:]
           u.avail = gaetalk.OFFLINE
           u.last_offline_date = datetime.datetime.now()
           u.put()
           self.response.out.write(u.jid + ' should be offline.\n')
   self.response.out.write(u'OK.'.encode('utf-8'))
示例#30
0
def CheckAccountOnline(account):
	accstr = "onlineAccount:%s" % account
	data = memcache.get(accstr)
	if account == data:
		return True
	
	if xmpp.get_presence(account):
		memcache.set(accstr,account,20)
		#memcache.add("onlineAccount",account,90)
		return True
	else:
		return False
示例#31
0
  def get(self, cron_id):
    def add_task_by_jid(jid):
      self.jids.append(jid)
      if len(self.jids) >= USERS_NUM_IN_TASK:
        flush_jids()
      if len(self.tasks) >= 100:
        flush_tasks()

    def flush_jids():
      if self.jids:
        self.tasks.append(taskqueue.Task(url='/worker', params={'jid': self.jids}))
        self.jids = list()

    def flush_tasks():
      def db_op():
        while db.WRITE_CAPABILITY:
          try:
            self.queues[self.queue_pointer].add(self.tasks)
          except taskqueue.TransientError:
            continue
          break

      if self.tasks:
        db.run_in_transaction(db_op)
        self.tasks = list()
        self.queue_pointer = (self.queue_pointer + 1) % TASK_QUEUE_NUM

    cron_id = int(cron_id)
    self.queues = [taskqueue.Queue('fetch' + str(id)) for id in xrange(TASK_QUEUE_NUM)]
    self.queue_pointer = cron_id % TASK_QUEUE_NUM
    self.tasks = list()
    self.jids = list()
    from db import GoogleUser, Db
    data = GoogleUser.get_all(shard=cron_id)
    try:
      for u in data:
        if u.display_timeline or u.msg_template.strip():
          time_delta = int(time()) - u.last_update
          if time_delta >= u.interval * 60 - 30:
            try:
              flag = xmpp.get_presence(u.jid)
            except xmpp.Error:
              flag = False
            if not flag:
              continue
            Db.set_cache(u)
            add_task_by_jid(u.jid)
      flush_jids()
      flush_tasks()
    except DeadlineExceededError:
      self.response.clear()
      self.response.set_status(500)
      self.response.out.write("This operation could not be completed in time...")
示例#32
0
文件: hexbug.py 项目: bnmrrs/HexBugNc
  def get(self):
    hexbug_avaliable = False

    if xmpp.get_presence(HEXBUG_XMPP_ADDR):
      hexbug_avaliable = True

    template_values = {
        'hexbug_avaliable': hexbug_avaliable
        }

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))
示例#33
0
    def post(self):
        message = xmpp.Message(self.request.POST)
        user_address = self.request.get('from').split('/')[0]       
        msg = ""
        
        if message.body[0:6].lower() == 'status':
            # Look up their URL(s) and list status(es)
            q = db.GqlQuery("SELECT * FROM LogUser " + 
                "WHERE userName = :1", 
                string.lower(user_address)) 

            msg = "For user: '******'\n"
            if q.count()>0:
                results = q.fetch(500)
                for p in results:
                    msg += "URL: " + p.serverName + ":"
                    if p.userActive:
                        msg += "Active"
                    else:
                        msg += "Inactive"
                    msg += "\n"
            else:
                msg += "No URLs defined for user\n"
            chat_message_sent = False
        elif message.body[0:4].lower() == 'stop':
            # Look up their URL(s) and disable them
            q = db.GqlQuery("SELECT * FROM LogUser " + 
                "WHERE userName = :1", 
                string.lower(user_address))
            results = q.fetch(500)
            for p in results:
                p.userActive = False
                p.put() 
            msg = "Alerts disabled for user: '******'\n"  
        elif message.body[0:5].lower() == 'start':
            # Look up their URL(s) and disable them
            q = db.GqlQuery("SELECT * FROM LogUser " + 
                "WHERE userName = :1", 
                string.lower(user_address))
            results = q.fetch(500)
            for p in results:
                p.userActive = True
                p.put() 
            msg = "Alerts enabled for user: '******'\n" 
        else:
            msg = "Available messages are:\n'Status' to list current conditions\n'Start' to enable messages\n'Stop' to disable messages."
            
        if msg != "":
            if xmpp.get_presence(user_address):
                status_code = xmpp.send_message(user_address, msg)
                chat_message_sent = (status_code == xmpp.NO_ERROR)            
                chat_message_sent = False
示例#34
0
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'

        logging.debug("TASK: refreshUsers")
        now = datetime.datetime.now()

        logging.debug("now %s" % now)
        self.response.out.write("now %s<br />" % now)
        logging.info("now %s" % now)
        localtime = now + timedelta(hours=UTC_OFFSET)
        logging.debug("localtime %s" % localtime)
        self.response.out.write("localtime %s<br />" % localtime)
        logging.info("localtime %s" % localtime)

        past = now - timedelta(minutes=2)
        # Retrieve all users who haven't sent a keepalive in the past 2 minutes
        #q = db.GqlQuery("SELECT * FROM CurrentUsers WHERE date < :1 AND xmpp = NULL", past)
        q = CurrentUsers.all().filter("date < ", past).filter("xmpp = ", None)
        results = q.fetch(1000)
        for currentUser in results:
            # Get user's preferences
            prefs = UserPrefs.all().filter("user = "******"Unknown"

            logging.info("deleting user " + nickname)

            msg = TIMEOUT_MSG % (nickname, localtime.strftime("%H:%M, %a, %b %d %Y"))
            chatMsg = ChatMsg.createMsg(msg, "chat.getUsers", isAnon=True)

            currentUser.delete()

        xmppUsers = CurrentUsers.all().filter("xmpp != ", None)
        for xmppUser in xmppUsers:
            past = now - timedelta(minutes=30)
            if not xmpp.get_presence(xmppUser.user.email()):
                logging.info("deleting XMPP user " + xmppUser.user.nickname())
                xmppUser.delete()
            elif xmppUser.date < past:
                xmpp.send_message(xmppUser.xmpp, XMPP_TIMEOUT_MSG) 
                xmppUser.delete()
                msg = TIMEOUT_MSG % (nickname, localtime.strftime("%H:%M, %a, %b %d %Y"))
                chatMsg = ChatMsg.createMsg(msg, "chat.getUsers", isAnon=True)

                

        logging.info("Users who didn't ping since %s were deleted." % past)
示例#35
0
    def get(self):
        for task in models.Task.tasks_due():
            settings = models.UserSettings.get_or_create(task.user.email())
            tz = settings.get_timezone()

            if xmpp.get_presence(task.user.email()):
                xmpp.send_message(task.user.email(), XMPP_MESSAGE % (task.description, task.show_due_on(tz)))
            else:
                mail.send_mail('*****@*****.**', task.user.email(),
                                 'Task due', EMAIL_MESSAGE % (task.description, task.show_due_on(tz)))

            task.finished = True
            task.put()
示例#36
0
文件: hexbug.py 项目: bnmrrs/HexBugNc
  def post(self):
    cmd = cgi.escape(self.request.get('command'))
    message_success = False
    self.response.headers['Content-Type'] = 'text/plain'

    if xmpp.get_presence(HEXBUG_XMPP_ADDR):
      status_code = xmpp.send_message(HEXBUG_XMPP_ADDR, cmd)
      message_success = (status_code != xmpp.NO_ERROR)

    if message_success:
      self.response.out.write('Command successfully sent!')
    else:
      self.response.out.write('Unable to send command')
示例#37
0
 def post(self):
     jid = self.request.get("from").split("/")[0]
     s = Session.get_by_key_name(jid)
     if s:
         u = GoogleUser.get_by_jid(jid)
         if u:
             try:
                 flag = xmpp.get_presence(jid)
             except xmpp.Error:
                 flag = False
             if not flag:
                 s.delete()
         else:
             s.delete()
示例#38
0
 def post(self):
   jid = self.request.get('from').split('/')[0]
   s = Session.get_by_key_name(jid)
   if s:
     u = User.get_by_key_name(jid)
     if u:
       try:
         presence = xmpp.get_presence(jid)
       except xmpp.Error:
         presence = False
       if not presence:
         s.delete()
     else:
       s.delete()
示例#39
0
 def post(self):
     jid = self.request.get('from').split('/')[0]
     s = Session.get_by_key_name(jid)
     if s:
         u = GoogleUser.get_by_jid(jid)
         if u:
             try:
                 flag = xmpp.get_presence(jid)
             except xmpp.Error:
                 flag = False
             if not flag:
                 s.delete()
         else:
             s.delete()
示例#40
0
    def post(self):
        message = xmpp.Message(self.request.POST)
        user_address = self.request.get('from').split('/')[0]
        msg = ""

        if message.body[0:6].lower() == 'status':
            # Look up their URL(s) and list status(es)
            q = db.GqlQuery("SELECT * FROM LogUser " + "WHERE userName = :1",
                            string.lower(user_address))

            msg = "For user: '******'\n"
            if q.count() > 0:
                results = q.fetch(500)
                for p in results:
                    msg += "URL: " + p.serverName + ":"
                    if p.userActive:
                        msg += "Active"
                    else:
                        msg += "Inactive"
                    msg += "\n"
            else:
                msg += "No URLs defined for user\n"
            chat_message_sent = False
        elif message.body[0:4].lower() == 'stop':
            # Look up their URL(s) and disable them
            q = db.GqlQuery("SELECT * FROM LogUser " + "WHERE userName = :1",
                            string.lower(user_address))
            results = q.fetch(500)
            for p in results:
                p.userActive = False
                p.put()
            msg = "Alerts disabled for user: '******'\n"
        elif message.body[0:5].lower() == 'start':
            # Look up their URL(s) and disable them
            q = db.GqlQuery("SELECT * FROM LogUser " + "WHERE userName = :1",
                            string.lower(user_address))
            results = q.fetch(500)
            for p in results:
                p.userActive = True
                p.put()
            msg = "Alerts enabled for user: '******'\n"
        else:
            msg = "Available messages are:\n'Status' to list current conditions\n'Start' to enable messages\n'Stop' to disable messages."

        if msg != "":
            if xmpp.get_presence(user_address):
                status_code = xmpp.send_message(user_address, msg)
                chat_message_sent = (status_code == xmpp.NO_ERROR)
                chat_message_sent = False
示例#41
0
文件: talk.py 项目: stallboy/h5demo
 def get(self):
   jid = "*****@*****.**"
   self.response.out.write('<html><body>')
   pre = xmpp.get_presence(jid)
   self.response.out.write("%s presence: %d<br>"%(jid, pre))
   self.response.out.write("""
         <form action="/talk/sign" method="post">
           jid:<input name="jid" ><br>
           <textarea name="msg" rows="2" cols="60"></textarea><br>
           <input type="submit" value="talk">
         </form>
         """)
   self.response.out.write("""
       </body>
     </html>""")
示例#42
0
文件: bot.py 项目: pulilab/gaelord
def send(record, jid):
    """Send a log record to the given jid"""
    if xmpp.get_presence(jid, FROM_JID):
        template_values = {
            'message': record.message,
            'filename': record.filename,
            'funcname': record.funcName,
            'levelname': record.levelname,
            'lineno' : record.lineno
            }

        xmpp.send_message(jid,
                          render_to_string('bot_log_record.plain',
                                           template_values),
                          FROM_JID)
示例#43
0
def send_xmpp_message(request):
    to = request.POST.get("to")
    sender = request.POST.get("sender")
    msg  = request.Post.get("body")
    chat_message_sent = False

    if xmpp.get_presence(to):
        status_code = xmpp.send_message(to, msg, sender)
        chat_message_sent = (status_code != xmpp.NO_ERROR)

    if not chat_message_sent:
        # Send an email message instead...
        return HttpResponse("message error!")
    else:
        return HttpResponse("message was sent successfully!")
示例#44
0
 def resume(self):
   u = User.get_by_key_name(self._jid)
   if u:
     u.enabled = True
     u.put()
     try:
       presence = xmpp.get_presence(self._jid)
     except xmpp.Error:
       presence = False
     if presence:
       try:
         Session(key_name=self._jid).put()
       except db.BadKeyError:
         pass
     return 'Gmail notification is resumed.'
示例#45
0
 def func_msgtpl(self, args):
     if len(args):
         tpl = ' '.join(args)
         while tpl[-2::] == r'\n':
             tpl = tpl[:len(tpl) - 2] + '\n'
         self._google_user.msg_template = tpl
         s = Session.get_by_key_name(self._google_user.jid)
         if not s and tpl.strip(
         ) and self._google_user.display_timeline and self._google_user.enabled_user:
             try:
                 flag = xmpp.get_presence(self._google_user.jid)
             except (xmpp.Error, DeadlineExceededError):
                 flag = False
             if flag:
                 Db.set_datastore(
                     Session(key_name=self._google_user.jid,
                             shard=self._google_user.shard))
     return _('MSG_TEMPLATE') % self._google_user.msg_template
示例#46
0
 def post(self):
     user = self.request.get('user')
     phone = self.request.get('phone')
     sender = handle_unicode(self.request.get('sender'))  #sender's name
     sms = handle_unicode(self.request.get('sms'))
     if user:
         user_address = '*****@*****.**' % (user)
         #Store the most recent sender
         incoming = Incoming(key_name=user_address)
         incoming.last_sender = phone
         incoming.put()
         # Send the received SMS to GTalk
         chat_message_sent = False
         if xmpp.get_presence(user_address):
             msg = "%s : %s" % (sender, sms)
             status_code = xmpp.send_message(user_address, msg)
             chat_message_sent = (status_code != xmpp.NO_ERROR)
         logging.debug(chat_message_sent)
示例#47
0
文件: views.py 项目: abelenki/sirc
    def handle_exception(self, exception, debug_mode):
        logging.info('WOO')
        from google.appengine.api import xmpp

        exception_name = sys.exc_info()[0].__name__
        exception_details = str(sys.exc_info()[1])
        exception_traceback = ''.join(
            traceback.format_exception(*sys.exc_info()))
        logging.error(exception_traceback)
        self.error(500)

        user_gtalk = '*****@*****.**'
        if xmpp.get_presence(user_gtalk):
            logging.info('got it')
            msg = "%s: %s\n\n%s" % (exception_name, exception_details,
                                    exception_traceback)
            xmpp.send_message(user_gtalk, msg)
        logging.info('done')
示例#48
0
    def get(self):
        admin_message = memcache.get(_ADMIN_MESSAGE_KEY)
        memcache.delete(_ADMIN_MESSAGE_KEY)

        app_id = os.environ['APPLICATION_ID']
        if app_id.startswith('dev~'):
            app_id = app_id[len('dev~'):]
        version_id = os.environ['CURRENT_VERSION_ID']
        version_id = version_id[:version_id.find('.')]

        app_xmpp_address = ('something@%s.latest.%s.appspotchat.com'
                            % (version_id, app_id))
        current_time = datetime.datetime.now()
        is_dev_server = os.environ['SERVER_SOFTWARE'].startswith('Development')

        chat_users = ChatUser.all().order('jid').fetch(100)
        for user in chat_users:
            # TODO: this is always returning False when on App Engine?
            user._gtalk_presence = xmpp.get_presence(user.jid)

        status = get_status_entity()

        template = template_env.get_template('home.html')
        context = {
            'admin_message': admin_message,
            'app_id': app_id,
            'app_xmpp_address': app_xmpp_address,
            'current_time': current_time,
            'is_dev_server': is_dev_server,

            'has_chat_users': len(chat_users) > 0,
            'chat_users': chat_users,
            'status': status,

            'current_user': users.get_current_user(),
            'is_user_admin': users.is_current_user_admin(),
            'signout_url': users.create_logout_url('/'),
        }
        self.response.out.write(template.render(context))
示例#49
0
    def process(self, u):
        jid = u.key().name()
        try:
            flag = xmpp.get_presence(jid)
        except (xmpp.Error, DeadlineExceededError):
            flag = True
        if not flag:
            u.delete()
            return
        google_user = GoogleUser.get_by_jid(jid)
        if google_user is None:
            u.delete()
            return
        time_delta = int(time()) - google_user.last_update
        if time_delta < google_user.interval * 60 - 30:
            return
        _ = lambda x: gettext(x, locale=google_user.locale)
        twitter_user = TwitterUser.get_by_twitter_name(
            google_user.enabled_user, google_user.jid)
        if twitter_user is None:
            google_user.enabled_user = ''
            Db.set_datastore(google_user)
            return
        api = twitter.Api(consumer_key=config.OAUTH_CONSUMER_KEY,
                          consumer_secret=config.OAUTH_CONSUMER_SECRET,
                          access_token_key=twitter_user.access_token_key,
                          access_token_secret=twitter_user.access_token_secret)
        try:
            self._user = api.verify_credentials()
            if not self._user or 'screen_name' not in self._user:
                raise twitter.TwitterError
        except twitter.TwitterError:
            google_user.retry += 1
            if google_user.retry >= config.MAX_RETRY:
                GoogleUser.disable(jid=google_user.jid)
                xmpp.send_message(google_user.jid, _('NO_AUTHENTICATION'))
            else:
                Db.set_cache(google_user)
            return
        finally:
            if google_user.retry > 0:
                google_user.retry = 0
                Db.set_cache(google_user)
        if twitter_user.twitter_name != self._user['screen_name']:
            twitter_user.twitter_name = self._user['screen_name']
            Db.set_cache(twitter_user)
            google_user.enabled_user = self._user['screen_name']
            Db.set_cache(google_user)
        utils.set_jid(google_user.jid)
        home_statuses = []
        home_mention_statuses = []
        all_statuses = []
        at_username = '******' + google_user.enabled_user

        if google_user.display_timeline & MODE_HOME or google_user.display_timeline & MODE_MENTION:
            home_rpc = api.get_home_timeline(since_id=google_user.last_msg_id,
                                             async=True)
        else:
            home_rpc = None
        if google_user.display_timeline & MODE_LIST:
            list_rpc = api.get_list_statuses(user=google_user.list_user,
                                             id=google_user.list_id,
                                             since_id=google_user.last_list_id,
                                             async=True)
        else:
            list_rpc = None
        if google_user.display_timeline & MODE_MENTION:
            mention_rpc = api.get_mentions(
                since_id=google_user.last_mention_id, async=True)
        else:
            mention_rpc = None
        if google_user.display_timeline & MODE_DM:
            dm_rpc = api.get_direct_messages(since_id=google_user.last_dm_id,
                                             async=True)
        else:
            dm_rpc = None
        if google_user.display_timeline & MODE_HOME:
            try:
                home_statuses = api._process_result(home_rpc)
                if home_statuses:
                    all_statuses.extend(home_statuses)
                    if home_statuses[0]['id'] > google_user.last_msg_id:
                        google_user.last_msg_id = home_statuses[0]['id']
            except twitter.TwitterInternalServerError:
                pass
            except BaseException:
                err = StringIO('')
                traceback.print_exc(file=err)
                logging.error(google_user.jid + ' Home:\n' + err.getvalue())
        if google_user.display_timeline & MODE_MENTION:
            try:
                statuses = api._process_result(mention_rpc)
                if statuses:
                    all_statuses.extend(statuses)
                    if statuses[0]['id'] > google_user.last_mention_id:
                        google_user.last_mention_id = statuses[0]['id']
                if not google_user.display_timeline & MODE_HOME:
                    try:
                        home_statuses = api._process_result(home_rpc)
                    except twitter.TwitterInternalServerError:
                        pass
                    except BaseException:
                        err = StringIO('')
                        traceback.print_exc(file=err)
                        logging.error(google_user.jid + ' Home:\n' +
                                      err.getvalue())
                    else:
                        if home_statuses:
                            if home_statuses[0]['id'] > google_user.last_msg_id:
                                google_user.last_msg_id = home_statuses[0][
                                    'id']
                            home_mention_statuses = [
                                x for x in home_statuses
                                if at_username in x['text']
                                and x['id'] > google_user.last_mention_id
                            ]
                        if home_mention_statuses:
                            all_statuses.extend(home_mention_statuses)
            except twitter.TwitterInternalServerError:
                pass
            except BaseException:
                err = StringIO('')
                traceback.print_exc(file=err)
                logging.error(google_user.jid + ' Mention:\n' + err.getvalue())
        if google_user.display_timeline & MODE_LIST:
            try:
                statuses = api._process_result(list_rpc)
                if statuses:
                    if statuses[0]['id'] > google_user.last_list_id:
                        google_user.last_list_id = statuses[0]['id']
                    for i in range(len(statuses) - 1, -1, -1):
                        if at_username in statuses[i]['text'] and statuses[i][
                                'id'] <= google_user.last_mention_id:
                            del statuses[i]
                    all_statuses.extend(statuses)
            except twitter.TwitterInternalServerError:
                pass
            except BaseException, e:
                if 'Not found' not in e.message:
                    err = StringIO('')
                    traceback.print_exc(file=err)
                    logging.error(google_user.jid + ' List:\n' +
                                  err.getvalue())
示例#50
0
 def post(self):
     msg = self.request.get("input")
     status_code = xmpp.send_message("[email protected]/bot",
                                     msg)
     self.response.out.write("status=" + str(status_code) + \
             " presence=" + str(xmpp.get_presence("*****@*****.**")))
示例#51
0
 def notifyUser(self, address, message):
     sent = False
     if xmpp.get_presence(address):
         status_code = xmpp.send_message(address, message)
         sent = (status_code != xmpp.NO_ERROR)
示例#52
0
def sendYourMoveIM(movePlayer, opponent, gameKey):
    if xmpp.get_presence(movePlayer.email()):
        xmpp.send_message(
            movePlayer.email(),
            "Your Move. http://your-move.appspot.com/game?id=" + gameKey)
示例#53
0
            # fail gracefully if insert fails
            errMsg = "// Insert failed: " + err + "\n"
            pass
            
        self.response.out.write("jsErrLog.removeScript(" + Qi + ") // jsErrRpt\n")
        if errMsg !="":
            self.response.out.write(errMsg)
            
        q = db.GqlQuery("SELECT * FROM LogUser " + 
            "WHERE serverName = :1 AND userActive = True", 
            string.lower(QserverName)) 
        results = q.get() 
        if results != None:
            # Send alert via XMPP/GTalk
            chat_message_sent = False
            user_address = results.userName
            if xmpp.get_presence(user_address):
                msg = ("An error was just reported for " + QserverName + " at line " + QlineNo + " in " + QfileLoc + ".\nVisit http://jsErrLog.appspot.com/report.html?sn=" + QserverName + " for more details.")
                status_code = xmpp.send_message(user_address, msg)
                chat_message_sent = (status_code == xmpp.NO_ERROR)
                

def main():
    application = webapp.WSGIApplication([('/logger.js', MainHandler)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
示例#54
0
文件: repo.py 项目: rca/appscale
        logging.error("urlfetch API FAILED %s"%(str(e)))

    if capability == "all" or capability == "users":
      try:
        user = users.get_current_user()
        users.create_login_url("/")
        users.create_logout_url("/")
        health['users'] = RUNNING
      except Exception, e:
        health['users'] = FAILED
        logging.error("users API FAILED %s"%(str(e)))


    if capability == "all" or capability == "xmpp":
      try:
        xmpp.get_presence("[email protected]")
        health['xmpp'] = RUNNING
      except Exception, e:
        health['xmpp'] = FAILED
        logging.error("xmpp API FAILED %s"%(str(e)))

    if capability == "all" or capability == "mapreduce":
      try:
        if mapreduce.can_run_jobs():
          health['mapreduce'] = RUNNING
        else:
          health['mapreduce'] = FAILED
      except Exception, e:
        health['mapreduce'] = FAILED
        logging.error("mapreduce API FAILED %s"%(str(e)))
示例#55
0
 def create(user):
     user = canonical_user(user)
     UpdateSubscriber(key_name=user,
                      available=xmpp.get_presence(user)).put()