Beispiel #1
0
 def send_status(self, statustext, to=None):
     if to:
         to_jid = JID(to)
         p = Presence(status=statustext, to_jid=to_jid)
     else:
         p = Presence(status=statustext)
     self._stream.send(p)
Beispiel #2
0
 def send_unsubscribe(self, jid):
     p1 = Presence(from_jid=self.my_jid,
                   to_jid=jid,
                   stanza_type='unsubscribe')
     p = Presence(from_jid=self.my_jid,
                  to_jid=jid,
                  stanza_type='unsubscribed')
     self._stream.send(p)
     self._stream.send(p1)
Beispiel #3
0
 def invite_member(self, jid):
     logging.info('invite {0}'.format(jid))
     p1 = Presence(from_jid=self.my_jid,
                   to_jid=jid,
                   stanza_type='subscribe')
     p = Presence(from_jid=self.my_jid,
                  to_jid=jid,
                  stanza_type='subscribed')
     self.stream.send(p)
     self.stream.send(p1)
Beispiel #4
0
 def send_subscribe(self, jid):
     """ 发送订阅 """
     p1 = Presence(from_jid=self.bot_jid,
                   to_jid=jid,
                   stanza_type='subscribe')
     p = Presence(from_jid=self.bot_jid,
                  to_jid=jid,
                  stanza_type='subscribed')
     self._stream.send(p)
     self._stream.send(p1)
Beispiel #5
0
 def accept_friend_request(self, jid):
     if not isinstance(jid, JID):
         jid = JID(jid)
     stanza = Presence(stanza_type=ACCEPT_RESPONSES["subscribe"],
                       to_jid=jid.bare())
     self.send(stanza)
     self.request_add_friend(jid)
Beispiel #6
0
 def add_contact(self):
     roster_client = self.client.roster_client
     roster_client.add_item(jid = JID(self.args.contact),
             name = self.args.name, groups = self.args.groups,
                                     callback = self._add_success,
                                         error_callback = self._add_error)
     if self.args.subscribe:
         presence = Presence(to_jid = self.args.contact,
                                         stanza_type = 'subscribe')
         self.client.send(presence)
     if self.args.approve:
         if "pre-approvals" not in roster_client.server_features:
             logging.error("Subscription pre-approvals not available")
         else:
             presence = Presence(to_jid = self.args.contact,
                                             stanza_type = 'subscribed')
             self.client.send(presence)
Beispiel #7
0
 def test_presence_full(self):
     pres = Presence(
             from_jid = JID("[email protected]/res"),
             to_jid = JID("*****@*****.**"),
             stanza_type = None,
             stanza_id = u"1",
             show = u"away",
             status = u"The Status",
             priority = 10)
     payload = ElementTree.Element(
                             "{http://pyxmpp.jajcus.net/xmlns/test}payload")
     ElementTree.SubElement(payload, 
                                 "{http://pyxmpp.jajcus.net/xmlns/test}abc")
     payload = XMLPayload(payload)
     pres.add_payload(payload)
     self.check_presence_full(pres)
     xml = pres.as_xml()
     self.check_presence_full(Presence(xml))
Beispiel #8
0
 def handle_presence_subscribe(self, stanza):
     """
     上下线状态预定请求
     :param stanza:
     :return:
     """
     presence = Presence(to_jid=stanza.from_jid.bare(),
                         stanza_type="subscribe")
     return [stanza.make_accept_response(), presence]
Beispiel #9
0
 def del_roster(self, Jid):
     """
     删除好友
     :param Jid: 删除的jid
     :return:
     """
     UserService().del_roster(self.JID.local, Jid.bare().as_string())
     UserService().del_roster(Jid.local, self.JID.as_string())
     self.xmpp_client.stream._send(Presence(to_jid=Jid, stanza_type='unsubscribe'))
Beispiel #10
0
 def handle_presence_subscribe(self, stanza):
     """
     上下线状态预定请求
     :param stanza:
     :return:
     """
     logger.info("XMPPClient::handle_presence_subscribe: %s requested %s presence subscription" % (stanza.from_jid, stanza.to_jid))
     presence = Presence(to_jid=stanza.from_jid.bare(), stanza_type="subscribe")
     return [stanza.make_accept_response(), presence]
Beispiel #11
0
 def handle_presence_unsubscribe(self, stanza):
     self.logger.info(u"{0} canceled presence subscription".format(
         stanza.from_jid))
     presence = Presence(to_jid=stanza.from_jid.bare(),
                         stanza_type="unsubscribe")
     nick = Logics.get_one(stanza.from_jid).nick
     self.message_bus.send_sys_msg(stanza, u'{0} 离开群'.format(nick))
     Logics.drop(stanza.from_jid.bare())
     r = [stanza.make_accept_response(), presence]
     return r
Beispiel #12
0
 def handle_presence_unsubscribe(self, stanza):
     """
     上下线状态取消预定请求
     :param stanza:
     :return:
     """
     if not self.is_jid_in_roster(stanza.from_jid):
         return True
     presence = Presence(to_jid=stanza.from_jid.bare(),
                         stanza_type="unsubscribe")
     return [stanza.make_accept_response(), presence]
Beispiel #13
0
 def handle_presence_unsubscribe(self, stanza):
     """
     上下线状态取消预定请求
     :param stanza:
     :return:
     """
     logger.info("XMPPClient::handle_presence_unsubscribe: %s canceled %s subscription request" % (stanza.from_jid, stanza.to_jid))
     if not self.is_jid_in_roster(stanza.from_jid):
         return True
     presence = Presence(to_jid=stanza.from_jid.bare(), stanza_type="unsubscribe")
     return [stanza.make_accept_response(), presence]
Beispiel #14
0
    def handle_subscribe(self, stanza):
        logging.info(u"{0} request presence subscripiton ".format(
            stanza.from_jid))

        sender = stanza.from_jid
        bare_jid = sender.bare().as_string()
        self.add_user(bare_jid)

        presence = Presence(to_jid=stanza.from_jid.bare(),
                            stanza_type="subscribe")
        return [stanza.make_accept_response(), presence]
Beispiel #15
0
 def handle_presence_subscribe(self, stanza):
     self.logger.info(u"{0} join us".format(stanza.from_jid))
     frm = stanza.from_jid
     presence = Presence(to_jid=frm, stanza_type="subscribe")
     Logics.add(frm, None, stanza.show)
     r = [stanza.make_accept_response(), presence]
     if frm not in self.sended:
         self.message_bus.send_sys_msg(stanza, new_member(frm))
         self.message_bus.send_back_msg(stanza, welcome(frm))
         self.sended.append(frm)
     return r
Beispiel #16
0
    def handle_subscribe(self,stanza):
        logger.info(u"{0} request presence subscripiton ".format(stanza.from_jid))

        if self.check_user_exist(stanza.from_jid.bare().as_string()):
            self.send_message(stanza.from_jid,statements.get('USER_EXIST'))
        else:
            sender = stanza.from_jid
            bare_jid = sender.bare().as_string()
            self.add_user(bare_jid)

        presence = Presence(to_jid=stanza.from_jid.bare(),stanza_type="subscribe")
        return [stanza.make_accept_response(),presence]
Beispiel #17
0
    def handle_presence_unsubscribe(self, stanza):
        logging.info('%s unsubscribe', stanza.from_jid)
        sender = stanza.from_jid
        self.current_jid = sender
        self.now = datetime.datetime.utcnow()
        self.handle_userleave(action=stanza.stanza_type)

        if stanza.stanza_type.endswith('ed'):
            return stanza.make_accept_response()

        presence = Presence(to_jid=stanza.from_jid.bare(),
                            stanza_type='unsubscribe')
        return [stanza.make_accept_response(), presence]
Beispiel #18
0
    def add_roster(self, Jid, name=None, groups=None):
        """
        添加好友
        :param Jid: 添加的jid
        :param name: 添加的用户名
        :param groups: 添加的用户组
        :return:
        """
        if self.is_jid_in_roster(Jid):
            return

        self.xmpp_client.roster_client.add_item(Jid, name, groups)
        self.xmpp_client.stream._send(
            Presence(to_jid=Jid, stanza_type='subscribe'))
Beispiel #19
0
 def handle_roster_received(self, event):
     dbstatus = Logics.get_global_info('status').value
     if not dbstatus:
         status = STATUS
     else:
         status = dbstatus
     p = Presence(status=status)
     self.client.stream.send(p)
     ret = [x.jid.bare() for x in self.roster if x.subscription == 'both']
     self.logger.info(' -- roster:{0}'.format(ret))
     members = Logics.get_members()
     members = [m.email for m in members]
     [Logics.add(frm) for frm in ret if not Logics.get_one(frm)]
     if IMPORT:
         [self.invite_member(JID(m)) for m in members if JID(m) not in ret]
Beispiel #20
0
    def del_roster(self, Jid):
        """
        删除好友
        :param Jid: 删除的jid
        :return:
        """
        if isinstance(Jid, str) or isinstance(Jid, unicode):
            Jid = JID(Jid)

        if not self.is_jid_in_roster(Jid):
            return
        UserService().del_roster(self.JID.local, Jid.bare().as_string())
        UserService().del_roster(Jid.local, self.JID.as_string())
        self.xmpp_client.stream._send(
            Presence(to_jid=Jid, stanza_type='unsubscribe'))
Beispiel #21
0
    def handle_presence_subscribe(self, stanza):
        logging.info('%s subscribe', stanza.from_jid)
        sender = stanza.from_jid
        bare = sender.bare()

        # avoid repeated request
        invited = False
        if bare not in self.subscribes:
            invited = self.invited.get(bare, False)
            if invited is not False:
                if invited == 2:
                    self.invited[bare] = 1
                else:
                    del self.invited[bare]
                    return stanza.make_accept_response()
                # We won't deny inivted members
                self.handle_userjoin_before()
            else:
                if config.private and str(bare) != config.root:
                    self.send_message(
                        sender,
                        _('Sorry, this is a private group, and you are not invited.'
                          ))
                    return stanza.make_deny_response()
                if not self.handle_userjoin_before():
                    return stanza.make_deny_response()

            self.current_jid = sender
            self.now = datetime.datetime.utcnow()
            try:
                self.handle_userjoin(action=stanza.stanza_type)
            except ValidationError:
                #The server is subscribing
                pass
            self.subscribes[bare] = True

        if stanza.stanza_type.endswith('ed'):
            return stanza.make_accept_response()

        if invited is False:
            presence = Presence(to_jid=stanza.from_jid.bare(),
                                stanza_type='subscribe')
            return [stanza.make_accept_response(), presence]
Beispiel #22
0
 def test_presence_full(self):
     pres = Presence(from_jid=JID("[email protected]/res"),
                     to_jid=JID("*****@*****.**"),
                     stanza_type=None,
                     stanza_id=u"1",
                     show=u"away",
                     status=u"The Status",
                     priority=10)
     payload = ElementTree.Element(
         "{http://pyxmpp.jajcus.net/xmlns/test}payload")
     ElementTree.SubElement(payload,
                            "{http://pyxmpp.jajcus.net/xmlns/test}abc")
     payload = XMLPayload(payload)
     pres.add_payload(payload)
     self.check_presence_full(pres)
     xml = pres.as_xml()
     self.check_presence_full(Presence(xml))
Beispiel #23
0
def main():
    gp = models.connection.Group.one()
    if gp and gp.status:
        st = gp.status
    else:
        st = None
    settings = dict(
        # deliver here even if the admin logs in
        initial_presence=Presence(priority=30, status=st),
        poll_interval=3,
    )
    botsettings = {
        'presence': settings['initial_presence'],
    }
    settings.update(config.settings)
    settings = XMPPSettings(settings)

    if config.trace:
        logging.info('enabling trace')
        for logger in ('pyxmpp2.IN', 'pyxmpp2.OUT'):
            logger = logging.getLogger(logger)
            logger.setLevel(logging.DEBUG)

    for logger in (
            'pyxmpp2.mainloop.base',
            'pyxmpp2.expdict',
            'pyxmpp2.mainloop.poll',
            'pyxmpp2.mainloop.events',
            'pyxmpp2.transport',
            'pyxmpp2.mainloop.events',
    ):
        logger = logging.getLogger(logger)
        logger.setLevel(max((logging.INFO, config.logging_level)))

    if config.logging_level > logging.DEBUG:
        restart_if_failed(runit, 3, args=(settings, botsettings))
    else:
        runit(settings, botsettings)
Beispiel #24
0
 def handle_presence_unsubscribe(self, stanza):
     logging.info("{0} canceled presence subscription".format(
         stanza.from_jid))
     presence = Presence(to_jid=stanza.from_jid.bare(),
                         stanza_type="unsubscribe")
     return [stanza.make_accept_response(), presence]
Beispiel #25
0
def main():
    """Parse the command-line arguments and run the bot."""
    parser = argparse.ArgumentParser(description = 'XMPP echo bot',
                                    parents = [XMPPSettings.get_arg_parser()])
    parser.add_argument('--debug',
                        action = 'store_const', dest = 'log_level',
                        const = logging.DEBUG, default = logging.INFO,
                        help = 'Print debug messages')
    parser.add_argument('--quiet', const = logging.ERROR,
                        action = 'store_const', dest = 'log_level',
                        help = 'Print only error messages')
    parser.add_argument('--trace', action = 'store_true',
                        help = 'Print XML data sent and received')
    parser.add_argument('--roster-cache', 
                        help = 'Store roster in this file')
    parser.add_argument('jid', metavar = 'JID', 
                                        help = 'The bot JID')
    subparsers = parser.add_subparsers(help = 'Action', dest = "action")
    show_p = subparsers.add_parser('show', help = 'Show roster and exit')
    show_p.add_argument('--presence', action = 'store_true',
                        help = 'Wait 5 s for contact presence information'
                                ' and display it with the roster')
    mon_p = subparsers.add_parser('monitor', help = 
                                        'Show roster and subsequent changes')
    mon_p.add_argument('--presence', action = 'store_true',
                        help = 'Show contact presence changes too')
    add_p = subparsers.add_parser('add', help = 'Add an item to the roster')
    add_p.add_argument('--subscribe', action = 'store_true', dest = 'subscribe',
                        help = 'Request a presence subscription too')
    add_p.add_argument('--approve', action = 'store_true', dest = 'approve',
                        help = 'Pre-approve subscription from the contact'
                                                ' (requires server support)')
    add_p.add_argument('contact', metavar = 'CONTACT', help = 'The JID to add')
    add_p.add_argument('name', metavar = 'NAME', nargs = '?',
                                            help = 'Contact name')
    add_p.add_argument('groups', metavar = 'GROUP', nargs = '*',
                                            help = 'Group names')
    rm_p = subparsers.add_parser('remove',
                                    help = 'Remove an item from the roster')
    rm_p.add_argument('contact', metavar = 'CONTACT',
                                    help = 'The JID to remove')
    upd_p = subparsers.add_parser('update', 
                                    help = 'Update an item in the roster')
    upd_p.add_argument('contact', metavar = 'CONTACT',
                                    help = 'The JID to update')
    upd_p.add_argument('name', metavar = 'NAME', nargs = '?',
                                            help = 'Contact name')
    upd_p.add_argument('groups', metavar = 'GROUP', nargs = '*',
                                            help = 'Group names')

    args = parser.parse_args()
    settings = XMPPSettings()
    settings.load_arguments(args)

    if settings.get("password") is None:
        password = getpass("{0!r} password: "******"utf-8")
        settings["password"] = password

    if sys.version_info.major < 3:
        args.jid = args.jid.decode("utf-8")
        if getattr(args, "contact", None):
            args.contact = args.contact.decode("utf-8")
        if getattr(args, "name", None):
            args.name = args.name.decode("utf-8")
        if getattr(args, "groups", None):
            args.groups = [g.decode("utf-8") for g in args.groups]

    logging.basicConfig(level = args.log_level)
    if args.trace:
        print "enabling trace"
        handler = logging.StreamHandler()
        handler.setLevel(logging.DEBUG)
        for logger in ("pyxmpp2.IN", "pyxmpp2.OUT"):
            logger = logging.getLogger(logger)
            logger.setLevel(logging.DEBUG)
            logger.addHandler(handler)
            logger.propagate = False
           
    if args.action == "monitor" or args.action == "show" and args.presence:
        # According to RFC6121 it could be None for 'monitor' (no need to send
        # initial presence to request roster), but Google seems to require that
        # to send roster pushes
        settings["initial_presence"] = Presence(priority = -1)
    else:
        settings["initial_presence"] = None

    tool = RosterTool(JID(args.jid), args, settings)
    try:
        tool.run()
    except KeyboardInterrupt:
        tool.disconnect()
Beispiel #26
0
 def test_presence_full_from_xml(self):
     pres = Presence(ElementTree.XML(PRESENCE1))
     self.check_presence_full(pres)
Beispiel #27
0
 def test_presence_empty_from_xml(self):
     pres = Presence(ElementTree.XML(PRESENCE2))
     self.check_presence_empty(pres)
Beispiel #28
0
 def test_presence_subscribe_from_xml(self):
     pres = Presence(ElementTree.XML(PRESENCE3))
     self.check_presence_subscribe(pres)
Beispiel #29
0
 def deny_friend_request(self, jid):
     if not isinstance(jid, JID):
         jid = JID(jid)
     stanza = Presence(stanza_type=DENY_RESPONSES["subscribe"],
                       to_jid=jid.bare())
     self.send(stanza)
Beispiel #30
0
 def test_presence_empty(self):
     pres = Presence()
     self.check_presence_empty(pres)
     xml = pres.as_xml()
     self.check_presence_empty(Presence(xml))
Beispiel #31
0
 def generate_presence(self, jid, stanza_type):
     if not isinstance(jid, JID):
         jid = JID(jid)
     return Presence(to_jid=jid.bare(), stanza_type=stanza_type)