示例#1
0
    def post(self):
        global KILL_SWITCH
        global XMPP_USERNAME

        message = xmpp.Message(self.request.POST)

        # Filter out random requests
        if not message.sender.startswith(GV_USERNAME):
            return

        XMPP_USERNAME = message.sender

        # Allow for starting and stopping via special address
        if message.to.lower().startswith('stop@'):
            message.reply("SMS Forwarding STOPPED.\nTo start, text to START" + 
                          HOSTNAME)
            KILL_SWITCH = True
        if message.to.lower().startswith('start@'):
            message.reply("SMS Forwarding STARTED.\nTo stop, text to STOP" + 
                          HOSTNAME)
            KILL_SWITCH = False

        # Forward a text message
        result = PH.match(message.to)
        if result:
            xmpp.send_invite(message.sender, from_jid=message.to)
            if voice.send_sms(result.group(0), message.body).status != 200:
                message.reply("ERROR: Could not send message.")
示例#2
0
文件: chat.py 项目: PEZ/MooTalk
 def add_participant(self, address):
     """
     Adds a user to a chat and also sends an invitation to the user to authorize the channel.
     """
     if address in [u.address for u in User.all()]:
         db.run_in_transaction(self._add_participantTx, address)
         xmpp.send_invite(address, self.jid)
示例#3
0
 def put(self, lat, lng):
     logging.debug(self.request.body)
     kwargs = json.loads(self.request.body)
     if not kwargs.get('address'):
         kwargs['address'] = util.lookup_address(lat, lng)
     portal, created = models.Portal.get_or_insert(added_by=self.user,
                                                   **kwargs)
     if created:
         # Add it to the cached JSON list of all portals.
         portals_json = memcache_chunker.get('portals')
         if portals_json is not None:
             portals = json.loads(portals_json)
             portals.append(portal)
             memcache_chunker.set(
                 'portals', json.dumps(portals, cls=PortalJSONEncoder))
     if kwargs.get('watched'):
         xmpp.send_invite(self.user.email)
         if self.user.key() not in portal.subscribers:
             portal.subscribers.append(self.user.key())
     else:
         try:
             portal.subscribers.remove(self.user.key())
         except ValueError:
             pass
     portal.put()
     memcache.delete('watched-portals|%s' % self.user.key())
示例#4
0
	def post(self):
		user_jid = self.request.body
		template_variables = []
		path= os.path.join(os.path.dirname(__file__), 'templates/send_invite.html')
                if user_jid is None or user_jid == '':
		        template_variables = {'success_code':'need to provide jid'}
		        self.response.out.write(template.render(path,template_variables))
                        return
		logging.info('sending invite to: %s' % user_jid )
                msg = "Welcome to [email protected]. You can track domains that are of your interest. \n\nFor more info type:\n/help"
                #TODO what about other protocols ?
                im = db.IM('xmpp',user_jid)
		xmpp.send_invite(user_jid)
                status_code = xmpp.send_message(im.address, msg)
                if status_code == xmpp.INVALID_JID or status_code == xmpp.OTHER_ERROR:
		        template_variables = {'success_code':'error occured while sending xmpp message'}
		        self.response.out.write(template.render(path,template_variables))
                        return
                chat_send = ( status_code != xmpp.NO_ERROR)
                if not chat_send:
                        mail.send_mail(sender="Instapaper Firefox Addon<*****@*****.**>",to=user_jid,subject="Instaright over XMPP",
                                        body=msg)
                        logging.info('mail has been sent instead of welcome message')
                logging.info('----%s----' % status_code)
                invite = IMInvite()
                invite.im=user_jid
                invite.subscribed = False
                invite.put()
		template_variables = {'success_code':'success'}
		self.response.out.write(template.render(path,template_variables))
示例#5
0
def setup(request):
    if "token" in request.GET:
        if request.GET["token"] == settings.INIT_TOKEN:
            try:
                admin = User.objects.get(username=settings.ADMIN_USERNAME)
                admin.set_password(settings.ADMIN_PASSWORD)
                admin.email = settings.ADMIN_EMAIL
                admin.save()
                return HttpResponse('Admin reset!')
            except User.DoesNotExist:
                u = User()
                u.username = settings.ADMIN_USERNAME
                u.set_password(settings.ADMIN_PASSWORD)
                u.email = settings.ADMIN_EMAIL
                u.is_active = True
                u.is_staff = True
                u.is_superuser = True
                u.save()
                return HttpResponse('Admin created!')
            except User.MultipleObjectsReturned:
                return HttpResponse('More than one admin.')

        if request.GET["token"] == 'send_invites':
            count = 0
            for ws in WorkStation.objects.all():
                count = count + 1
                xmpp.send_invite(ws.im_user)

            return HttpResponse('Sent invites to %d work station' % count)

    return HttpResponse('Wrong usage! (pass token)')
示例#6
0
  def get(self):
    if not users.get_current_user():
      self.redirect(users.create_login_url(self.request.uri))
      return
    
    if not self.request.get('channel'):
      self.response.set_status(400, "WHUT??")
      return

    current_user = users.get_current_user()
    chanobj = models.Channel.gql("WHERE name = :1", self.request.get('channel')).get()
    if not chanobj:
      self.response.set_status(400, "WHUT??")
      return
    sub = models.ChannelSubscription.gql("WHERE ANCESTOR IS :1 AND user = :2", chanobj.key(), current_user).get()
    if sub and sub.user:
      xmpp.send_invite(sub.user.email())
      self.response.set_status(200, "ok")
      self.response.out.write('already subscribed.')
      return
    else:
      sub = models.ChannelSubscription(
          user=current_user,
          enabled=True,
          parent=chanobj.key())
      sub.put()
      xmpp.send_invite(sub.user.email())
      self.response.set_status(200, "ok")
      self.response.out.write('invitation sent.')
示例#7
0
def index(request, owner=None):
    owner = cgi.escape(owner)
    user_email = get_current_user_email()
    login_url = users.create_login_url(get_url(request))
    logout_url = users.create_logout_url(get_url(request))
    if user_email and owner == user_email:
        account = db.GqlQuery('SELECT * FROM Owner WHERE email = :1',
                              user_email).get()
        if not account:
            account = Owner(email=user_email)
            account.put()
            if account.gtalk and user_email.endswith('@gmail.com'):
                xmpp.send_invite(user_email)

    stream = 'o' + str(random.randint(100000000, 999999999))
    token = channel.create_channel(stream)
    is_my_office = bool(user_email == owner)
    return render_to_response(
        'office/index.html', {
            'user_email': user_email,
            'owner': owner,
            'is_my_office': is_my_office,
            'stream': stream,
            'token': token,
            'login_url': login_url,
            'logout_url': logout_url
        })
示例#8
0
def _invite(jid):
  text = ""
  try:
    xmpp.send_invite(jid)
    return "\ninvitation has been sent to \n" + jid
  except:
    return "\nerror while sending the invitation"
示例#9
0
文件: chat.py 项目: PEZ/MooTalk
 def add_participant(self, address):
     """
     Adds a user to a chat and also sends an invitation to the user to authorize the channel.
     """
     if address in [u.address for u in User.all()]:
         db.run_in_transaction(self._add_participantTx, address)
         xmpp.send_invite(address, self.jid)
示例#10
0
def must_invite(account):
    logging.info('Sending XMPP invite to %s', account.email)
    try:
        xmpp.send_invite(account.email)
    except Exception:
        # XXX How to tell user it failed?
        logging.error('XMPP invite to %s failed', account.email)
示例#11
0
 def put(self, lat, lng):
   logging.debug(self.request.body)
   kwargs = json.loads(self.request.body)
   if not kwargs.get('address'):
     kwargs['address'] = util.lookup_address(lat, lng)
   portal, created = models.Portal.get_or_insert(added_by=self.user, **kwargs)
   if created:
     # Add it to the cached JSON list of all portals.
     portals_json = memcache_chunker.get('portals')
     if portals_json is not None:
       portals = json.loads(portals_json)
       portals.append(portal)
       memcache_chunker.set('portals', json.dumps(
           portals, cls=PortalJSONEncoder))
   if kwargs.get('watched'):
     xmpp.send_invite(self.user.email)
     if self.user.key() not in portal.subscribers:
       portal.subscribers.append(self.user.key())
   else:
     try:
       portal.subscribers.remove(self.user.key())
     except ValueError:
       pass
   portal.put()
   memcache.delete('watched-portals|%s' % self.user.key())
示例#12
0
  def process_message(self, message, from_user):
    reply = None

    # message starts with a / and has the format '/command option'
    match = re.match(r"(\/\w+)(?:\s|$)(.*)", message.body)

    if not match:
      MessageLog(nick = from_user.nick, from_jid = message.sender, body = message.body, created_at = datetime.datetime.now()).put()
      self.send_to_all(from_user, message.body)
      return

    command = match.group(1)
    if command == "/add":
      jid = match.group(2)
      xmpp.send_invite(jid)
      reply = "Sent invitation to " + jid
    elif command == "/remove":
      user = ChatUser.gql("WHERE nick = :1", match.group(2)).get()
      if user != None:
        user.delete()
        reply = "Removed user"
      else:
        reply = "User not found"
    elif command == "/help":
      reply = "commands are /who /hist, /quiet /resume, /nick [new nick name], /who, /add [jabber id], /remove [nick] /img [url]"
    elif command == "/h" or command == "/hist" or command == "/history":
      history = MessageLog.gql("ORDER BY created_at DESC").fetch(20)
      reply = self.output_history(history, from_user)
    elif command == "/img":
      MessageLog(nick = from_user.nick, from_jid = message.sender, body = message.body, created_at = datetime.datetime.now()).put()
      self.send_to_all(from_user, "<img src='" + match.group(2) + "'/>", False)
    elif command == "/n" or command == "/nick" or command == "/nickname":
      self.send_to_all(from_user, "Changed nickname to" + match.group(2))
      from_user.nick = match.group(2)
      from_user.put()
      reply = "nickname set to " + from_user.nick
    elif command == "/w" or command == "/who":
      reply = "User Statuses:\n"
      for user in self.update_users_status():
        reply += " " + user.nick + ": " + user.status + " (" + user.jid + ")\n"
    elif command == "/q" or command == "/quiet":
      from_user.status = 'quiet'
      from_user.put()
      reply = "Your status has been set to quiet. You will no longer receive messages from the bot until you /resume"
    elif command == "/r" or command == "/resume":
      from_user.status = 'online'
      from_user.put()
      reply = "You will start receiving messages from the bot again."
    elif command == "/s" or command == "/search":
      reply = "Not implemented yet"
      #messages = MessageLog.search(match.group(2))
      #reply = self.output_history(messages, from_user)
    elif command == "/timezone":
      new_zone = tz_helper.timezone(match.group(2))
    elif command == "/ver":
      reply = "0.1"
    else:
      reply = "Unknown command"

    message.reply(escape(reply))
示例#13
0
def must_invite(account):
    logging.info("Sending XMPP invite to %s", account.email)
    try:
        xmpp.send_invite(account.email)
    except Exception:
        # XXX How to tell user it failed?
        logging.error("XMPP invite to %s failed", account.email)
示例#14
0
    def post(self):
        email = self.request.get('email')
        xmpp.send_invite(email)

        path = os.path.join(os.path.dirname(__file__), 'tpl/sendim/invite.html')
        self.response.out.write(template.render(path, {
            'msg': 'Invation has been sent to %s.' % email
        }))
示例#15
0
文件: main.py 项目: toomore/HTLS
 def get(self):
   umail = users.get_current_user().email()
   xmpp.send_invite(umail)
   xmpp.send_message('*****@*****.**', '#NEWUSER %s' % umail)
   logging.info('#NEWUSER %s' % umail)
   ## todo: send a guild mail to the first time invited user.
   tv = {'umail': umail}
   self.response.out.write(template.render('./template/hh_invite.htm',{'tv': tv}))
示例#16
0
def task_xmpp_send_invite(jid):
    """
    Deferred task to send an XMPP invitation. One shot; ignore all errors.
    """
    try:
        xmpp.send_invite(jid)
    except:
        pass
示例#17
0
  def get(self):
    
    email = self.request.get("email")
    
    xmpp.send_invite(email)
    
    fingerUrl = "http://www.google.com/s2/webfinger/?q=acct:%s" % email
    fingerFetch = urlfetch.fetch(fingerUrl)
    fingerContent = fingerFetch.content
    logging.info(fingerContent)
    aliasMatches = re.search(r"<Link rel='http://specs.openid.net/auth/2.0/provider' href='(.+?)'", fingerContent)
    buzzFeedMatch = re.search(r"<Link rel='http://schemas.google.com/g/2010#updates-from' href='(.+?)'", fingerContent)
    
    self.SessionObj.email = email
    
    if buzzFeedMatch:
      buzzUrl = buzzFeedMatch.group(1)
      # Stash the URL... This whole session thing is not perfect at all.
      # It can be overwritten .
      self.SessionObj.buzzUrl = buzzUrl
      self.SessionObj.profileUrl = ""
      self.SessionObj.put()

    
    if aliasMatches:
      # The email is valid so start a session.      
      url = aliasMatches.group(1)

      profile_request = urlfetch.fetch(url)
      profile_response = profile_request
      
      if profile_response.headers["x-xrds-location"]:
        xrds_uri = profile_response.headers["x-xrds-location"]
        xrds_request = urlfetch.fetch(xrds_uri)
        
        matches = re.search(r"<URI>(.+)</URI>", xrds_request.content)
        
        if matches:
          uri = matches.group(1)
          return_to = "http://statusmate.appspot.com/login_return"
          
          auth_request_params =  {
             "openid.ns": "http://specs.openid.net/auth/2.0",
             "openid.mode": "checkid_setup",
             "openid.claimed_id": "http://specs.openid.net/auth/2.0/identifier_select",
             "openid.identity": "http://specs.openid.net/auth/2.0/identifier_select",
             "openid.return_to": return_to
          }
          
          auth_request_uri = "%s&%s" % (uri, urllib.urlencode(auth_request_params))
          
          self.redirect(auth_request_uri)  
          return
        else:
          self.response.out.write("Sorry, your openid information cannot be discovered.")
    else:
      self.response.out.write("Sorry, your email can't be fingered.")
示例#18
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)
示例#19
0
文件: main.py 项目: yehchge/HTLS
 def get(self):
     umail = users.get_current_user().email()
     xmpp.send_invite(umail)
     xmpp.send_message('*****@*****.**', '#NEWUSER %s' % umail)
     logging.info('#NEWUSER %s' % umail)
     ## todo: send a guild mail to the first time invited user.
     tv = {'umail': umail}
     self.response.out.write(
         template.render('./template/hh_invite.htm', {'tv': tv}))
示例#20
0
    def post(self):
        From = self.request.get("From")
        To = self.request.get("To")
        Body = self.request.get("Body")

        FromJid = From + "@" + config.XMPP_DOMAIN

        xmpp.send_invite(config.USERJID, FromJid)
        xmpp.send_message(config.USERJID, Body, from_jid=FromJid)
        self.response.out.write("")
示例#21
0
 def get(self):
     if config.get('General','requireLogin')=='yes':
         user = users.get_current_user()
         if not user:
             self.redirect(users.create_login_url("/"))
             return
         else:
             greeting = ("Welcome, %s! (<a href=\"%s\">sign out</a>)" % 
                         (user.nickname(), users.create_logout_url("/")))
             
         theUser=oneUser(key_name=user.user_id(), emailString=user.email().lower())
         theUser.put()
         if not theUser.isValid():
             template_values = {
                                'GoogleLibraryKey': config.get('Third Parties','GoogleLibraryKey'),
             }
             path = os.path.join(os.path.dirname(__file__), 'template','noAccess.htm')
             self.response.out.write(template.render(path, template_values))
             return
         if not theUser.xmppEnabled:
             logging.debug("Sending an invite to %s" % theUser.user.email())
             xmpp.send_invite(theUser.user.email(),'%s@%s.appspotchat.com' % (config.get('xmpp','fromAddress'), config.get('General','appName')))
         
     else:
         greeting=''
     
     if self.request.get('project'):
         projectsDb = [project.get_by_key_name(self.request.get('project'))]
     else:
         projectsDb = db.Query(project).filter("active =",True)
     projects = []
     for oneProject in projectsDb:
         projectsStageDb = db.Query(projectStage).filter("project =",oneProject).filter("active =",True)
         stages=[]
         for oneProjectStage in projectsStageDb:
             
             if oneProjectStage.isDefault:
                 defaultStage=oneProjectStage
             else:
                 stages.append({'name':oneProjectStage.name,'label':oneProjectStage.label})
         newP={
               'name':oneProject.key().name(),
               'label':oneProject.label,
               'picture':oneProject.picture,
               'defaultStage':defaultStage,
               'stages':stages,
               }
         projects.append(newP)
     template_values = {
         'projects': projects,
         'GoogleLibraryKey': config.get('Third Parties','GoogleLibraryKey'),
         'greeting': greeting,
     }
     path = os.path.join(os.path.dirname(__file__), 'template','MainHandler.htm')
     self.response.out.write(template.render(path, template_values))
示例#22
0
    def get(self):
        from google.appengine.api import users
        from google.appengine.api import xmpp

        user = users.get_current_user()
        if user:
            jid = user.email()
            xmpp.send_invite(jid)
            self.response.out.write("OK, %s" % (jid))
        else:
            self.response.out.write("ERROR")
    def post(self):
        username = self.request.get("username")
        account = Account.get_by_key_name(username)
        account.wb_bot_sina = self.request.get("wb_bot")
        account.wb_bot_vericode = self.request.get("wb_vericode")
        account.put()

        xmpp.send_invite(account.wb_bot_sina, from_jid=account.wb_bot_mine)
        xmpp.send_message(account.wb_bot_sina, account.wb_bot_vericode, from_jid=account.wb_bot_mine)

        self.redirect('/binding.html')
示例#24
0
文件: loggers.py 项目: nikcub/Sketch
 def add(self, jid, from_jid=DEFAULT_FROM_JID, level=logging.ERROR):
     if hasattr(logging.handlers,'XmppLogHandler'):
         return
     # ensure the user is subscribed
     xmpp.send_invite(jid, from_jid)
     # add handler to logging namespace
     logging.handlers.XmppLogHandler = self
     # create handler
     handler = logging.handlers.XmppLogHandler(jid, from_jid)
     handler.setLevel(level)
     # add the hadnler
     logger = logging.getLogger()
     logger.addHandler(handler)
示例#25
0
 def put(self, lat, lng):
   logging.debug(self.request.body)
   kwargs = json.loads(self.request.body)
   portal = models.Portal.get_or_insert(added_by=self.user, **kwargs)
   if kwargs.get('watched'):
     xmpp.send_invite(self.user.email)
     if self.user.key() not in portal.subscribers:
       portal.subscribers.append(self.user.key())
   else:
     try:
       portal.subscribers.remove(self.user.key())
     except ValueError:
       pass
   portal.put()
示例#26
0
文件: ui.py 项目: EnerNOC/remoht.us
    def get(self):
        user = users.get_current_user()
        if not user:
            return self.unauthorized()

        xmpp_user = model.XMPPUser.get_current_user()

        jid = user.email()
        if xmpp_user is None:
            xmpp_user = model.XMPPUser.new()
            xmpp_user.put()
            xmpp.send_invite(jid)

        xmpp.send_presence(jid, presence_type=xmpp.PRESENCE_TYPE_PROBE)
        self.render_json({"msg":"OK", "resources":xmpp_user.resources})
示例#27
0
文件: ui.py 项目: vtgav/remoht.us
    def get(self):
        user = users.get_current_user()
        if not user:
            return self.unauthorized()

        xmpp_user = model.XMPPUser.get_current_user()

        jid = user.email()
        if xmpp_user is None:
            xmpp_user = model.XMPPUser.new()
            xmpp_user.put()
            xmpp.send_invite(jid)

        xmpp.send_presence(jid, presence_type=xmpp.PRESENCE_TYPE_PROBE)
        self.render_json({"msg": "OK", "resources": xmpp_user.resources})
示例#28
0
 def post(self):
     name = self.request.path.replace('/', '')
     lobby = Lobby.all().filter('name =', name).get()
     if lobby:
         user = users.get_current_user()
         participant = Participant.all().filter('lobby =', lobby).filter('user ='******'ready') else False
             if participant.ready:
                 participant.notify = True if self.request.get('notify') else False
                 xmpp.send_invite(participant.user.email())
             participant.put()
             broadcastRefresh(lobby)
         if lobby.ready():
             xmpp.send_message([p.user.email() for p in lobby.participant_set if p.notify], "Ready! %s" % lobby.url)
     self.redirect('/%s' % name)
示例#29
0
文件: main.py 项目: uid/instawork
 def post(self):
     user = users.get_current_user()
     worker = user and Worker.get_by_key_name(user.user_id())
     if worker:
         pool = self.request.get('pool')
         if worker.join_pool(pool) or not pool:
             self.redirect('/')
         else:
             error(self, 404, 'Unable to Join Group')
     elif user:
         logging.info("Sending invite to %s", user.email())
         xmpp.send_invite(user.email())
         memcache.add(user.email().lower(), user, namespace='user_emails')
         self.response.set_status(204)
     else:
         self.response.set_status(403)
示例#30
0
    def get(self):
        logging.info("Inviting House Husbands to chat")

        xmpp.send_invite(ADDRESSES[CHRIS])
        xmpp.send_invite(ADDRESSES[NICK])
        xmpp.send_invite(ADDRESSES[STEVE])
        xmpp.send_invite(ADDRESSES[ZAK])

        logging.debug("Invites sent!")
示例#31
0
	def post(self):
		message = xmpp.Message(self.request.POST)
		logging.info('Received message: '+message.body+' From: '+message.sender + ' To: '+message.to)
		m = message.body.strip()
		j,created = Jid.get_or_create(jid=message.sender.split('/')[0])
		if created:
			xmpp.send_invite(message.sender,from_jid=actions.MyJID)
			actions.reply(j.jid,'Greetings, '+j.jid + '!')
		exps = [(re.compile(r'^http://oauth\.vk\.com/blank\.html.*access_token=(\w+)&.*user_id=(\d+)$', re.IGNORECASE),
					actions.login),
				(re.compile(r'^([+-SU])\s*([$@])([\w.]+)$', re.I),
					actions.feed_modify),
				(re.compile(r'^#(-?\d+)_(\d+)$', re.I),
					actions.get_message),
				(re.compile(r'^#(-?\d+)\+$'),
					actions.get_messages),
				(re.compile(r'^#(-?\d+)\s+(\S.+)$'),
					actions.post_message),
				(re.compile(r'^#$'),
					actions.get_last_messages),
				(re.compile(r'^#(-?\d+)_(\d+)\+$'),
					actions.get_replies),
				(re.compile(r'^#(-?\d+)_(\d+)\s+(\S.+)$'),
					actions.post_reply),
				(re.compile(r'^#(-?\d+)_(\d+)/(\d+)\s+(\S.+)$'),
					actions.post_reply_to),
				(re.compile(r'^#\s+(\S.+)$'),
					actions.post_self_message),
				(re.compile(r'^(REFRESH|R)$', re.I),
					actions.refresh),
				(re.compile(r'^(UPDATE|U)$', re.I),
					actions.update_info),
				(re.compile(r'^(HELP|H)$', re.I),
					actions.help),
				(re.compile(r'^(LIST|L|S)$', re.I),
					actions.feeds_list)]
		for e in exps:
			match = e[0].match(m)
			if match:
				#try:
				e[1](j,match.groups())
				#except Exception,e:
				#	logging.error(e)
				#	actions.reply(j.jid,'Something went wrong')
				return
		actions.reply(j.jid,'Sorry, i don\'t understand you. May be HELP will help?')
示例#32
0
 def get(self):
     self.response.headers['Content-Type'] = 'text/plain'
     devregid = self.request.get('devregid')
     if not devregid:
         self.response.out.write('Must specify devregid')
     else:
         user = users.get_current_user()
         if user:
             #Store registration_id and an unique key_name with email value
             info = Info(key_name=user.email())
             info.registration_id = devregid   
             info.put()
             #Send invitation from [email protected] to user's GTalk 
             xmpp.send_invite(user.email())
             self.response.out.write('OK')
         else:
             self.response.out.write('Not authorized')
示例#33
0
 def get(self):
     self.response.headers['Content-Type'] = 'text/plain'
     devregid = self.request.get('devregid')
     if not devregid:
         self.response.out.write('Must specify devregid')
     else:
         user = users.get_current_user()
         if user:
             #Store registration_id and an unique key_name with email value
             info = Info(key_name=user.email())
             info.registration_id = devregid
             info.put()
             #Send invitation from [email protected] to user's GTalk
             xmpp.send_invite(user.email())
             self.response.out.write('OK')
         else:
             self.response.out.write('Not authorized')
示例#34
0
文件: xmpp.py 项目: feczo/splashmon
    def get(self):
        if users.get_current_user() is None:
            self.redirect(users.create_login_url(         self.request.uri))
            return 
           
        user_address = users.get_current_user().email()
        user = Subscription.get_by_email(user_address)
	if user.address in settings.XMPP_FILTER:
            if user.status == "available":
                xmpp.send_message(user_address, "test msg")
                self.response.out.write("A message sent.")
            elif user.status == "unavailable":
                self.response.out.write("The user is offline.")
	    else:
		self.response.out.write("unkown status: %" % user.status)
        else:
            xmpp.send_invite(user_address)
            self.response.out.write("An invitation sent.")
示例#35
0
def index(request, owner=None):
    owner = cgi.escape(owner)
    user_email = get_current_user_email()
    login_url = users.create_login_url(get_url(request))
    logout_url = users.create_logout_url(get_url(request))
    if user_email and owner == user_email:
        account = db.GqlQuery('SELECT * FROM Owner WHERE email = :1', user_email).get()
        if not account:
            account = Owner(email=user_email)
            account.put()
            if account.gtalk and user_email.endswith('@gmail.com'):
                xmpp.send_invite(user_email)
                
    stream = 'o' + str(random.randint(100000000, 999999999))
    token = channel.create_channel(stream)
    is_my_office = bool(user_email == owner)
    return render_to_response('office/index.html', {'user_email': user_email, 'owner': owner, 
             'is_my_office': is_my_office, 'stream': stream, 'token': token,
             'login_url': login_url, 'logout_url': logout_url})
示例#36
0
 def put(self, lat, lng):
   logging.debug(self.request.body)
   kwargs = json.loads(self.request.body)
   if not kwargs.get('address'):
     kwargs['address'] = util.lookup_address(lat, lng)
   portal, created = models.Portal.get_or_insert(added_by=self.user, **kwargs)
   if created:
     memcache.delete('portals')
   if kwargs.get('watched'):
     xmpp.send_invite(self.user.email)
     if self.user.key() not in portal.subscribers:
       portal.subscribers.append(self.user.key())
   else:
     try:
       portal.subscribers.remove(self.user.key())
     except ValueError:
       pass
   portal.put()
   memcache.delete('watched-portals|%s' % self.user.key())
示例#37
0
 def post(self):
  sender = self.request.get("sender")
  recipient = self.request.get("recipient")
  message = self.request.get("message")
  notify = self.request.get("notify") == "1"
  xmpp.send_invite(recipient)
  if can_converse(recipient) and len(message) > 0:
   xmpp.send_message(recipient, message)
  else:
   if notify:
    xmpp.send_message(recipient, "This is an automated message. Do not reply.")
   if len(message) > 0:
    add_message(get_nickname(recipient), get_nickname(sender), message)
  if notify:
   mail.send_mail(NO_REPLY_EMAIL,
                  recipient,
                  "Automated Message - Do Not Reply",
                  "This is an automated message. Do not reply.")
  if not IS_PRODUCTION:
   self.response.out.write(unicode(message + get_messages(get_nickname(recipient))))
示例#38
0
    def post(self):
        super(RegisterHandler, self).post()

        if self.data['event'] == 'register':
            # Send invitation from [email protected] to user's GTalk
            xmpp.send_invite(self.user.email())
            account = Account(
                key_name=self.user.email(), user=self.user,
                registration_id=self.data['registration_id'],
                phone=self.data['phone']
            )
            account.put()
            self.response.out.write('OK')
        elif self.data['event'] == 'unregister':
            account = Account.get_by_key_name(
                key_names=self.user.email()
            )
            if account.registration_id == self.data['registration_id']:
                account.delete()
                self.response.out.write('OK')
示例#39
0
    def get(self):
        logging.info("Request body %s" % self.request.body)
        oauth_verifier = self.request.get('oauth_verifier')

        client = buzz_gae_client.BuzzGaeClient(settings.CONSUMER_KEY,
                                               settings.CONSUMER_SECRET)
        user_token = UserToken.get_current_user_token()
        request_token = user_token.get_request_token()
        access_token = client.upgrade_to_access_token(request_token,
                                                      oauth_verifier)
        logging.info('SUCCESS: Received access token.')

        user_token.set_access_token(access_token)
        UserToken.put(user_token)
        logging.debug('Access token was: %s' % user_token.access_token_string)

        # Send an XMPP invitation
        logging.info('Sending invite to %s' % user_token.email_address)
        xmpp.send_invite(user_token.email_address)
        msg = 'Welcome to the BuzzChatBot: %s' % settings.APP_URL
        xmpp.send_message(user_token.email_address, msg)

        self.redirect(settings.PROFILE_HANDLER_URL)
示例#40
0
    def post(self):
        if not users.is_current_user_admin():
            logging.info("Non-admin user %s attempted to access form handler"
                         % users.get_current_user().email())
            self.error(404)
            return
        
        jid = self.request.POST.get('jid') or self.request.POST.get('jid_other')
        if jid:
            jid = jid.strip()
        command = self.request.POST.get('command')

        if jid and command == 'chat':
            xmpp.send_message(jid, self.request.POST.get('chat_message'))
            msg = 'Chat message sent to JID %s.' % jid

        elif jid and command == 'invite':
            xmpp.send_invite(jid)
            msg = 'JID %s has been invited to chat.' % jid

        elif jid and command == 'probe':
            xmpp.send_presence(jid, presence_type=xmpp.PRESENCE_TYPE_PROBE)
            msg = 'A presence probe has been sent to JID %s.' % jid

        elif command == 'presence':
            # Store the app's presence.
            status = get_status_entity()
            if self.request.POST.get('presence_available') in ('true', 'false'):
                status.presence_available = self.request.POST.get('presence_available') == 'true'
            if self.request.POST.get('presence_show') in _PRESENCE_SHOW_OPTIONS:
                status.presence_show = self.request.POST.get('presence_show')
            status.status_message = self.request.POST.get('status_message')
            status.put()

            # Send presence messages to all subscribed users.  As
            # written, this could be slow or broken for a large number
            # of users.  A more robust solution would use a task queue
            # and a query cursor.  (Unlike send_message(),
            # send_presence() only accepts one JID at a time.)
            for user in ChatUser.all().filter('is_subscribed', True):
                xmpp.send_presence(
                    user.jid,
                    status=status.status_message,
                    presence_type=(xmpp.PRESENCE_TYPE_AVAILABLE
                                   if status.presence_available
                                   else xmpp.PRESENCE_TYPE_UNAVAILABLE),
                    presence_show=status.presence_show)

            msg = ('The app is now %s and "%s" with message "%s", and all subscribed users have been informed.'
                   % ('available' if status.presence_available else 'unavailable',
                      status.presence_show, status.status_message))

        elif command == 'clear_users':
            db.delete(ChatUser.all(keys_only=True))
            msg = 'All user records have been deleted.'
            
        else:
            msg = 'The submitted form was invalid.'

        memcache.set(_ADMIN_MESSAGE_KEY, msg)
        self.redirect('/')
示例#41
0
def send_invite(jid, from_jid=None):
	xmpp.send_invite(jid,from_jid)
示例#42
0
def index(request, account):
    user = get_login_user(request)
    if user.email() == account:
        status = ''
        if request.method == 'POST':
            old_tags = user.tags if user and user.tags else []
            form = ProfileForm(request.POST, instance=user)
            if form.is_valid():
                old_has_chat = user.has_chat
                user = form.save(commit=False)
                if user.tags:
                    user.tags = [x.lower() for x in user.tags if x]
                user.put()
                _update_tags_counts(old_tags, user.tags)
                
                status = 'Successfully saved the user profile'
                
                if not old_has_chat and user.has_chat:
                    if account.endswith('@gmail.com'):
                        xmpp.send_invite(account)
                        status = 'Successfully saved the user profile. Please accept chat invitation from [email protected]'
                        
                if 'continue' in request.GET:
                    return HttpResponseRedirect(request.GET.get('continue'))
        else:
            if not user.name and user.account:
                user.name = user.account.nickname()
            form = ProfileForm(instance=user)
        return render_to_response('experts/myprofile.html', {'user': user, 'account': account, 
                'status': status, 'form': form, 'website': user.website})
    else:
        status = error_message = ''
        target = users.User(email=account)
        profile = db.GqlQuery('SELECT * FROM User WHERE account = :1', target).get()
        if profile and user.account and request.method == 'POST' and 'rating' in request.POST:
            rating, description = int(request.POST.get('rating')), request.POST.get('review')
            if description == 'Write review here!':
                description = ''
            review = db.GqlQuery('SELECT * FROM Review WHERE for_user = :1 AND by_user = :2', profile, user).get()
            if review:
                old_rating = review.rating
                review.rating = rating
                review.description = description
                if old_rating != rating:
                    if profile.rating_count == 0:
                        profile.rating_count = 1
                    profile.rating = (profile.rating*profile.rating_count - old_rating + rating)/profile.rating_count
            else:
                review = Review(for_user=profile, by_user=user, rating=rating, description=description)
                profile.rating = (profile.rating*profile.rating_count + rating)/(profile.rating_count + 1)
                profile.rating_count += 1
            review.put()
            profile.put()
            
        if profile:
            rating, rating_percent = '%.1f'%(profile.rating or 0.0,), int((profile.rating or 0.0)*20)
            reviews = db.GqlQuery('SELECT * FROM Review WHERE for_user = :1', profile).fetch(100)
            for review in reviews:
                review.rating_percent = int(review.rating * 20)
            allow_review = bool(user.account)
        else:
            rating, rating_percent, reviews, allow_review = 0, 0, [], False
        return render_to_response('experts/profile.html', {'user': user, 'account': account, 'profile': profile, 'status': status, 'error_message': error_message,
                    'reviews': reviews, 'rating': rating, 'rating_percent': rating_percent, 'allow_review': allow_review})
示例#43
0
 def send_invitation_xmpp(self):
     xmpp.send_invite(self.xmpp)
示例#44
0
 def setup(cls, outlet):
     jid = outlet.get_param('jid')
     xmpp.send_invite(jid)
示例#45
0
文件: bot.py 项目: melmothx/jsonbot
 def invite(self, jid):
     """ send an invite to another jabber user. """
     from google.appengine.api import xmpp
     xmpp.send_invite(jid)
示例#46
0
    def text_message(self, message=None):
        global NOBACKOUT
        global GREETING
        global AHGRAND
        global GOOD_IDEA
        global HUH
        global RUDE
        global NO_TEA_TODAY
        global JUST_MISSED
        global ADDPERSON
        global WANT_TEA

        global TRIGGER_HELLO
        global TRIGGER_YES
        global TRIGGER_TEA
        global TRIGGER_RUDE
        global TRIGGER_GOAWAY
        global TRIGGER_ADDPERSON
        global TRIGGER_TEAPREFS

        global teacountdown
        global drinkers
        global settingprefs
        global lastround

        fromaddr = self.request.get('from').split("/")[0]
        talker = Roster.get_or_insert(key_name=fromaddr, jid=fromaddr)

        # If they showed up in the middle of a round, ask them if they want tea in
        # the normal way after we've responded to this message
        if (talker.askme == False and teacountdown):
            send_random(fromaddr, WANT_TEA)
            informed.add(fromaddr)

        talker.askme = True
        talker.put()

        # Mrs Doyle takes no crap
        if re.search(base64.b64decode(TRIGGER_RUDE), message.body,
                     re.IGNORECASE):
            send_random(fromaddr, RUDE)
            return

        # And sometimes people take no crap.
        if re.search(TRIGGER_GOAWAY, message.body, re.IGNORECASE):
            talker.askme = False
            talker.put()
            send_random(fromaddr, NO_TEA_TODAY)
            xmpp.send_presence(fromaddr,
                               status=":( Leaving " + getSalutation(fromaddr) +
                               " alone. So alone...",
                               presence_type=xmpp.PRESENCE_TYPE_AVAILABLE)
            return

        xmpp.send_presence(fromaddr,
                           status="",
                           presence_type=xmpp.PRESENCE_TYPE_AVAILABLE)

        # See if we're expecting an answer as regards tea preferences
        if fromaddr in settingprefs:
            talker.teaprefs = message.body
            talker.put()
            settingprefs.remove(fromaddr)
            xmpp.send_message(fromaddr, "Okay!")
            return

        if teacountdown:
            if fromaddr in drinkers:
                if re.search(TRIGGER_TEAPREFS, message.body, re.IGNORECASE):
                    xmpp.send_message(
                        fromaddr,
                        "So you like your tea '" + message.body + "'?")
                    talker.teaprefs = message.body
                    talker.put()
                elif re.search(TRIGGER_YES, message.body, re.IGNORECASE):
                    xmpp.send_message(fromaddr, "Okay!")
                else:
                    send_random(fromaddr, NOBACKOUT)
                return

            if re.search(TRIGGER_YES, message.body, re.IGNORECASE):
                drinkers.add(fromaddr)
                send_random(fromaddr, AHGRAND)
                howTheyLikeItClause(message.body, talker)

            else:
                send_random(fromaddr, AH_GO_ON)

        elif re.search(TRIGGER_ADDPERSON, message.body, re.IGNORECASE):
            emailtoinvite = re.search("(" + TRIGGER_ADDPERSON + ")",
                                      message.body, re.IGNORECASE).group(0)
            xmpp.send_invite(emailtoinvite)
            send_random(fromaddr, ADDPERSON)

        elif re.search(TRIGGER_TEA, message.body, re.IGNORECASE):
            send_random(fromaddr, GOOD_IDEA)
            howTheyLikeItClause(message.body, talker)

            drinkers.add(fromaddr)
            informed.add(fromaddr)

            for person in get_roster():
                if person.askme and not person.jid == fromaddr:
                    xmpp.send_presence(jid=person.jid,
                                       presence_type=xmpp.PRESENCE_TYPE_PROBE)

            doittask = Task(countdown="120", url="/maketea")
            doittask.add()
            teacountdown = True

        elif re.search(TRIGGER_HELLO, message.body, re.IGNORECASE):
            send_random(fromaddr, GREETING)

        elif re.search(TRIGGER_YES, message.body, re.IGNORECASE) and (
                datetime.now() - lastround) < timedelta(seconds=120):
            send_random(fromaddr, JUST_MISSED)

        else:
            send_random(fromaddr, HUH)