source: ralphm-patches/copy_xmppim.patch @ 49:537d1413b661

Last change on this file since 49:537d1413b661 was 49:537d1413b661, checked in by Ralph Meijer <ralphm@…>, 9 years ago

Save work after moving stuff to keep from wokkel.xmppim to wokkel.im.

File size: 18.0 KB
  • .py

    # HG changeset patch
    # Parent 2c8dc93fbef4f2d5b7115c7afdd1b7fb799d47c3
    
    diff --git a/wokkel/xmppim.py b/wokkel/im.py
    copy from wokkel/xmppim.py
    copy to wokkel/im.py
    old new  
    2222NS_XML = 'http://www.w3.org/XML/1998/namespace'
    2323NS_ROSTER = 'jabber:iq:roster'
    2424
    25 class Presence(domish.Element):
    26     def __init__(self, to=None, type=None):
    27         domish.Element.__init__(self, (None, "presence"))
    28         if type:
    29             self["type"] = type
    30 
    31         if to is not None:
    32             self["to"] = to.full()
    33 
    34 class AvailablePresence(Presence):
    35     def __init__(self, to=None, show=None, statuses=None, priority=0):
    36         Presence.__init__(self, to, type=None)
    37 
    38         if show in ['away', 'xa', 'chat', 'dnd']:
    39             self.addElement('show', content=show)
    40 
    41         if statuses is not None:
    42             for lang, status in statuses.iteritems():
    43                 s = self.addElement('status', content=status)
    44                 if lang:
    45                     s[(NS_XML, "lang")] = lang
    46 
    47         if priority != 0:
    48             self.addElement('priority', content=unicode(int(priority)))
    49 
    50 class UnavailablePresence(Presence):
    51     def __init__(self, to=None, statuses=None):
    52         Presence.__init__(self, to, type='unavailable')
    53 
    54         if statuses is not None:
    55             for lang, status in statuses.iteritems():
    56                 s = self.addElement('status', content=status)
    57                 if lang:
    58                     s[(NS_XML, "lang")] = lang
    59 
    60 class PresenceClientProtocol(XMPPHandler):
    61 
    62     def connectionInitialized(self):
    63         self.xmlstream.addObserver('/presence', self._onPresence)
    64 
    65     def _getStatuses(self, presence):
    66         statuses = {}
    67         for element in presence.elements():
    68             if element.name == 'status':
    69                 lang = element.getAttribute((NS_XML, 'lang'))
    70                 text = unicode(element)
    71                 statuses[lang] = text
    72         return statuses
    73 
    74     def _onPresence(self, presence):
    75         type = presence.getAttribute("type", "available")
    76         try:
    77             handler = getattr(self, '_onPresence%s' % (type.capitalize()))
    78         except AttributeError:
    79             return
    80         else:
    81             handler(presence)
    82 
    83     def _onPresenceAvailable(self, presence):
    84         entity = JID(presence["from"])
    85 
    86         show = unicode(presence.show or '')
    87         if show not in ['away', 'xa', 'chat', 'dnd']:
    88             show = None
    89 
    90         statuses = self._getStatuses(presence)
    91 
    92         try:
    93             priority = int(unicode(presence.priority or '')) or 0
    94         except ValueError:
    95             priority = 0
    96 
    97         self.availableReceived(entity, show, statuses, priority)
    98 
    99     def _onPresenceUnavailable(self, presence):
    100         entity = JID(presence["from"])
    101 
    102         statuses = self._getStatuses(presence)
    103 
    104         self.unavailableReceived(entity, statuses)
    105 
    106     def _onPresenceSubscribed(self, presence):
    107         self.subscribedReceived(JID(presence["from"]))
    108 
    109     def _onPresenceUnsubscribed(self, presence):
    110         self.unsubscribedReceived(JID(presence["from"]))
    111 
    112     def _onPresenceSubscribe(self, presence):
    113         self.subscribeReceived(JID(presence["from"]))
    114 
    115     def _onPresenceUnsubscribe(self, presence):
    116         self.unsubscribeReceived(JID(presence["from"]))
    117 
    118 
    119     def availableReceived(self, entity, show=None, statuses=None, priority=0):
    120         """
    121         Available presence was received.
    122 
    123         @param entity: entity from which the presence was received.
    124         @type entity: {JID}
    125         @param show: detailed presence information. One of C{'away'}, C{'xa'},
    126                      C{'chat'}, C{'dnd'} or C{None}.
    127         @type show: C{str} or C{NoneType}
    128         @param statuses: dictionary of natural language descriptions of the
    129                          availability status, keyed by the language
    130                          descriptor. A status without a language
    131                          specified, is keyed with C{None}.
    132         @type statuses: C{dict}
    133         @param priority: priority level of the resource.
    134         @type priority: C{int}
    135         """
    136 
    137     def unavailableReceived(self, entity, statuses=None):
    138         """
    139         Unavailable presence was received.
    140 
    141         @param entity: entity from which the presence was received.
    142         @type entity: {JID}
    143         @param statuses: dictionary of natural language descriptions of the
    144                          availability status, keyed by the language
    145                          descriptor. A status without a language
    146                          specified, is keyed with C{None}.
    147         @type statuses: C{dict}
    148         """
    149 
    150     def subscribedReceived(self, entity):
    151         """
    152         Subscription approval confirmation was received.
    153 
    154         @param entity: entity from which the confirmation was received.
    155         @type entity: {JID}
    156         """
    157 
    158     def unsubscribedReceived(self, entity):
    159         """
    160         Unsubscription confirmation was received.
    161 
    162         @param entity: entity from which the confirmation was received.
    163         @type entity: {JID}
    164         """
    165 
    166     def subscribeReceived(self, entity):
    167         """
    168         Subscription request was received.
    169 
    170         @param entity: entity from which the request was received.
    171         @type entity: {JID}
    172         """
    173 
    174     def unsubscribeReceived(self, entity):
    175         """
    176         Unsubscription request was received.
    177 
    178         @param entity: entity from which the request was received.
    179         @type entity: {JID}
    180         """
    181 
    182     def available(self, entity=None, show=None, statuses=None, priority=0):
    183         """
    184         Send available presence.
    185 
    186         @param entity: optional entity to which the presence should be sent.
    187         @type entity: {JID}
    188         @param show: optional detailed presence information. One of C{'away'},
    189                      C{'xa'}, C{'chat'}, C{'dnd'}.
    190         @type show: C{str}
    191         @param statuses: dictionary of natural language descriptions of the
    192                          availability status, keyed by the language
    193                          descriptor. A status without a language
    194                          specified, is keyed with C{None}.
    195         @type statuses: C{dict}
    196         @param priority: priority level of the resource.
    197         @type priority: C{int}
    198         """
    199         self.send(AvailablePresence(entity, show, statuses, priority))
    200 
    201     def unavailable(self, entity=None, statuses=None):
    202         """
    203         Send unavailable presence.
    204 
    205         @param entity: optional entity to which the presence should be sent.
    206         @type entity: {JID}
    207         @param statuses: dictionary of natural language descriptions of the
    208                          availability status, keyed by the language
    209                          descriptor. A status without a language
    210                          specified, is keyed with C{None}.
    211         @type statuses: C{dict}
    212         """
    213         self.send(UnavailablePresence(entity, statuses))
    214 
    215     def subscribe(self, entity):
    216         """
    217         Send subscription request
    218 
    219         @param entity: entity to subscribe to.
    220         @type entity: {JID}
    221         """
    222         self.send(Presence(to=entity, type='subscribe'))
    223 
    224     def unsubscribe(self, entity):
    225         """
    226         Send unsubscription request
    227 
    228         @param entity: entity to unsubscribe from.
    229         @type entity: {JID}
    230         """
    231         self.send(Presence(to=entity, type='unsubscribe'))
    232 
    233     def subscribed(self, entity):
    234         """
    235         Send subscription confirmation.
    236 
    237         @param entity: entity that subscribed.
    238         @type entity: {JID}
    239         """
    240         self.send(Presence(to=entity, type='subscribed'))
    241 
    242     def unsubscribed(self, entity):
    243         """
    244         Send unsubscription confirmation.
    245 
    246         @param entity: entity that unsubscribed.
    247         @type entity: {JID}
    248         """
    249         self.send(Presence(to=entity, type='unsubscribed'))
    250 
    251 
    252 
    25325class BasePresence(Stanza):
    25426    """
    25527    Stanza of kind presence.
     
    605377        self.groups = set()
    606378
    607379
     380
    608381class RosterClientProtocol(XMPPHandler):
    609382    """
    610383    Client side XMPP roster protocol.
     
    614387        ROSTER_SET = "/iq[@type='set']/query[@xmlns='%s']" % NS_ROSTER
    615388        self.xmlstream.addObserver(ROSTER_SET, self._onRosterSet)
    616389
     390
    617391    def _parseRosterItem(self, element):
    618392        jid = JID(element['jid'])
    619393        item = RosterItem(jid)
     
    628402
    629403        return item
    630404
     405
    631406    def getRoster(self):
    632407        """
    633408        Retrieve contact list.
     
    683458            item = self._parseRosterItem(iq.query.item)
    684459            self.onRosterSet(item)
    685460
     461
    686462    def onRosterSet(self, item):
    687463        """
    688464        Called when a roster push for a new or update item was received.
     
    691467        @type item: L{RosterItem}
    692468        """
    693469
     470
    694471    def onRosterRemove(self, entity):
    695472        """
    696473        Called when a roster push for the removal of an item was received.
     
    698475        @param entity: The entity for which the roster item has been removed.
    699476        @type entity: L{JID}
    700477        """
    701 
    702 class MessageProtocol(XMPPHandler):
    703     """
    704     Generic XMPP subprotocol handler for incoming message stanzas.
    705     """
    706 
    707     messageTypes = None, 'normal', 'chat', 'headline', 'groupchat'
    708 
    709     def connectionInitialized(self):
    710         self.xmlstream.addObserver("/message", self._onMessage)
    711 
    712     def _onMessage(self, message):
    713         if message.handled:
    714             return
    715 
    716         messageType = message.getAttribute("type")
    717 
    718         if messageType == 'error':
    719             return
    720 
    721         if messageType not in self.messageTypes:
    722             message["type"] = 'normal'
    723 
    724         self.onMessage(message)
    725 
    726     def onMessage(self, message):
    727         """
    728         Called when a message stanza was received.
    729         """
  • .py

    diff --git a/wokkel/test/test_xmppim.py b/wokkel/test/test_im.py
    copy from wokkel/test/test_xmppim.py
    copy to wokkel/test/test_im.py
    old new  
    22# See LICENSE for details
    33
    44"""
    5 Tests for L{wokkel.xmppim}.
     5Tests for L{wokkel.im}.
    66"""
    77
    88from twisted.internet import defer
     
    1111from twisted.words.protocols.jabber.xmlstream import toResponse
    1212from twisted.words.xish import domish, utility
    1313
    14 from wokkel import xmppim
     14from wokkel import im
    1515from wokkel.generic import ErrorStanza, parseXml
    1616from wokkel.test.helpers import XmlStreamStub
    1717
    1818NS_XML = 'http://www.w3.org/XML/1998/namespace'
    1919NS_ROSTER = 'jabber:iq:roster'
    2020
    21 class PresenceClientProtocolTest(unittest.TestCase):
    22     def setUp(self):
    23         self.output = []
    24         self.protocol = xmppim.PresenceClientProtocol()
    25         self.protocol.parent = self
    26 
    27     def send(self, obj):
    28         self.output.append(obj)
    29 
    30     def test_unavailableDirected(self):
    31         """
    32         Test sending of directed unavailable presence broadcast.
    33         """
    34 
    35         self.protocol.unavailable(JID('user@example.com'))
    36         presence = self.output[-1]
    37         self.assertEquals("presence", presence.name)
    38         self.assertEquals(None, presence.uri)
    39         self.assertEquals("user@example.com", presence.getAttribute('to'))
    40         self.assertEquals("unavailable", presence.getAttribute('type'))
    41 
    42     def test_unavailableWithStatus(self):
    43         """
    44         Test sending of directed unavailable presence broadcast with status.
    45         """
    46 
    47         self.protocol.unavailable(JID('user@example.com'),
    48                                   {None: 'Disconnected'})
    49         presence = self.output[-1]
    50         self.assertEquals("presence", presence.name)
    51         self.assertEquals(None, presence.uri)
    52         self.assertEquals("user@example.com", presence.getAttribute('to'))
    53         self.assertEquals("unavailable", presence.getAttribute('type'))
    54         self.assertEquals("Disconnected", unicode(presence.status))
    55 
    56     def test_unavailableBroadcast(self):
    57         """
    58         Test sending of unavailable presence broadcast.
    59         """
    60 
    61         self.protocol.unavailable(None)
    62         presence = self.output[-1]
    63         self.assertEquals("presence", presence.name)
    64         self.assertEquals(None, presence.uri)
    65         self.assertEquals(None, presence.getAttribute('to'))
    66         self.assertEquals("unavailable", presence.getAttribute('type'))
    67 
    68     def test_unavailableBroadcastNoEntityParameter(self):
    69         """
    70         Test sending of unavailable presence broadcast by not passing entity.
    71         """
    72 
    73         self.protocol.unavailable()
    74         presence = self.output[-1]
    75         self.assertEquals("presence", presence.name)
    76         self.assertEquals(None, presence.uri)
    77         self.assertEquals(None, presence.getAttribute('to'))
    78         self.assertEquals("unavailable", presence.getAttribute('type'))
    79 
    80 
    81 
    8221class AvailabilityPresenceTest(unittest.TestCase):
    8322
    8423    def test_fromElement(self):
     
    8928                 </presence>
    9029              """
    9130
    92         presence = xmppim.AvailabilityPresence.fromElement(parseXml(xml))
     31        presence = im.AvailabilityPresence.fromElement(parseXml(xml))
    9332        self.assertEquals(JID('user@example.org'), presence.sender)
    9433        self.assertEquals(JID('user@example.com'), presence.recipient)
    9534        self.assertTrue(presence.available)
     
    9837        self.assertEquals(50, presence.priority)
    9938
    10039
     40
    10141class PresenceProtocolTest(unittest.TestCase):
    10242    """
    103     Tests for L{xmppim.PresenceProtocol}
     43    Tests for L{im.PresenceProtocol}
    10444    """
    10545
    10646    def setUp(self):
    10747        self.output = []
    108         self.protocol = xmppim.PresenceProtocol()
     48        self.protocol = im.PresenceProtocol()
    10949        self.protocol.parent = self
    11050        self.protocol.xmlstream = utility.EventDispatcher()
    11151        self.protocol.connectionInitialized()
     
    12262        xml = """<presence type="error"/>"""
    12363
    12464        def errorReceived(error):
    125             xmppim.PresenceProtocol.errorReceived(self.protocol, error)
     65            im.PresenceProtocol.errorReceived(self.protocol, error)
    12666            try:
    12767                self.assertIsInstance(error, ErrorStanza)
    12868            except:
     
    14383        xml = """<presence/>"""
    14484
    14585        def availableReceived(presence):
    146             xmppim.PresenceProtocol.availableReceived(self.protocol, presence)
     86            im.PresenceProtocol.availableReceived(self.protocol, presence)
    14787            try:
    148                 self.assertIsInstance(presence, xmppim.AvailabilityPresence)
     88                self.assertIsInstance(presence, im.AvailabilityPresence)
    14989            except:
    15090                d.errback()
    15191            else:
     
    164104        xml = """<presence type='unavailable'/>"""
    165105
    166106        def unavailableReceived(presence):
    167             xmppim.PresenceProtocol.unavailableReceived(self.protocol, presence)
     107            im.PresenceProtocol.unavailableReceived(self.protocol, presence)
    168108            try:
    169                 self.assertIsInstance(presence, xmppim.AvailabilityPresence)
     109                self.assertIsInstance(presence, im.AvailabilityPresence)
    170110            except:
    171111                d.errback()
    172112            else:
     
    185125        xml = """<presence type='subscribe'/>"""
    186126
    187127        def subscribeReceived(presence):
    188             xmppim.PresenceProtocol.subscribeReceived(self.protocol, presence)
     128            im.PresenceProtocol.subscribeReceived(self.protocol, presence)
    189129            try:
    190                 self.assertIsInstance(presence, xmppim.SubscriptionPresence)
     130                self.assertIsInstance(presence, im.SubscriptionPresence)
    191131            except:
    192132                d.errback()
    193133            else:
     
    206146        xml = """<presence type='unsubscribe'/>"""
    207147
    208148        def unsubscribeReceived(presence):
    209             xmppim.PresenceProtocol.unsubscribeReceived(self.protocol, presence)
     149            im.PresenceProtocol.unsubscribeReceived(self.protocol, presence)
    210150            try:
    211                 self.assertIsInstance(presence, xmppim.SubscriptionPresence)
     151                self.assertIsInstance(presence, im.SubscriptionPresence)
    212152            except:
    213153                d.errback()
    214154            else:
     
    227167        xml = """<presence type='subscribed'/>"""
    228168
    229169        def subscribedReceived(presence):
    230             xmppim.PresenceProtocol.subscribedReceived(self.protocol, presence)
     170            im.PresenceProtocol.subscribedReceived(self.protocol, presence)
    231171            try:
    232                 self.assertIsInstance(presence, xmppim.SubscriptionPresence)
     172                self.assertIsInstance(presence, im.SubscriptionPresence)
    233173            except:
    234174                d.errback()
    235175            else:
     
    248188        xml = """<presence type='unsubscribed'/>"""
    249189
    250190        def unsubscribedReceived(presence):
    251             xmppim.PresenceProtocol.unsubscribedReceived(self.protocol,
     191            im.PresenceProtocol.unsubscribedReceived(self.protocol,
    252192                                                         presence)
    253193            try:
    254                 self.assertIsInstance(presence, xmppim.SubscriptionPresence)
     194                self.assertIsInstance(presence, im.SubscriptionPresence)
    255195            except:
    256196                d.errback()
    257197            else:
     
    270210        xml = """<presence type='probe'/>"""
    271211
    272212        def probeReceived(presence):
    273             xmppim.PresenceProtocol.probeReceived(self.protocol, presence)
     213            im.PresenceProtocol.probeReceived(self.protocol, presence)
    274214            try:
    275                 self.assertIsInstance(presence, xmppim.ProbePresence)
     215                self.assertIsInstance(presence, im.ProbePresence)
    276216            except:
    277217                d.errback()
    278218            else:
     
    451391
    452392class RosterClientProtocolTest(unittest.TestCase):
    453393    """
    454     Tests for L{xmppim.RosterClientProtocol}.
     394    Tests for L{im.RosterClientProtocol}.
    455395    """
    456396
    457397    def setUp(self):
    458398        self.stub = XmlStreamStub()
    459         self.protocol = xmppim.RosterClientProtocol()
     399        self.protocol = im.RosterClientProtocol()
    460400        self.protocol.xmlstream = self.stub.xmlstream
    461401        self.protocol.connectionInitialized()
    462402
Note: See TracBrowser for help on using the repository browser.