aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/words/protocols/jabber/jid.py
blob: 9911cee94ab7fb690a0ea6c48789dd04e7719271 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# -*- test-case-name: twisted.words.test.test_jabberjid -*-
#
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Jabber Identifier support.

This module provides an object to represent Jabber Identifiers (JIDs) and
parse string representations into them with proper checking for illegal
characters, case folding and canonicalisation through L{stringprep<twisted.words.protocols.jabber.xmpp_stringprep>}.
"""

from twisted.words.protocols.jabber.xmpp_stringprep import nodeprep, resourceprep, nameprep

class InvalidFormat(Exception):
    """
    The given string could not be parsed into a valid Jabber Identifier (JID).
    """

def parse(jidstring):
    """
    Parse given JID string into its respective parts and apply stringprep.

    @param jidstring: string representation of a JID.
    @type jidstring: C{unicode}
    @return: tuple of (user, host, resource), each of type C{unicode} as
             the parsed and stringprep'd parts of the given JID. If the
             given string did not have a user or resource part, the respective
             field in the tuple will hold C{None}.
    @rtype: C{tuple}
    """
    user = None
    host = None
    resource = None

    # Search for delimiters
    user_sep = jidstring.find("@")
    res_sep  = jidstring.find("/")

    if user_sep == -1:
        if res_sep == -1:
            # host
            host = jidstring
        else:
            # host/resource
            host = jidstring[0:res_sep]
            resource = jidstring[res_sep + 1:] or None
    else:
        if res_sep == -1:
            # user@host
            user = jidstring[0:user_sep] or None
            host = jidstring[user_sep + 1:]
        else:
            if user_sep < res_sep:
                # user@host/resource
                user = jidstring[0:user_sep] or None
                host = jidstring[user_sep + 1:user_sep + (res_sep - user_sep)]
                resource = jidstring[res_sep + 1:] or None
            else:
                # host/resource (with an @ in resource)
                host = jidstring[0:res_sep]
                resource = jidstring[res_sep + 1:] or None

    return prep(user, host, resource)

def prep(user, host, resource):
    """
    Perform stringprep on all JID fragments.

    @param user: The user part of the JID.
    @type user: C{unicode}
    @param host: The host part of the JID.
    @type host: C{unicode}
    @param resource: The resource part of the JID.
    @type resource: C{unicode}
    @return: The given parts with stringprep applied.
    @rtype: C{tuple}
    """

    if user:
        try:
            user = nodeprep.prepare(unicode(user))
        except UnicodeError:
            raise InvalidFormat, "Invalid character in username"
    else:
        user = None

    if not host:
        raise InvalidFormat, "Server address required."
    else:
        try:
            host = nameprep.prepare(unicode(host))
        except UnicodeError:
            raise InvalidFormat, "Invalid character in hostname"

    if resource:
        try:
            resource = resourceprep.prepare(unicode(resource))
        except UnicodeError:
            raise InvalidFormat, "Invalid character in resource"
    else:
        resource = None

    return (user, host, resource)

__internJIDs = {}

def internJID(jidstring):
    """
    Return interned JID.

    @rtype: L{JID}
    """

    if jidstring in __internJIDs:
        return __internJIDs[jidstring]
    else:
        j = JID(jidstring)
        __internJIDs[jidstring] = j
        return j

class JID(object):
    """
    Represents a stringprep'd Jabber ID.

    JID objects are hashable so they can be used in sets and as keys in
    dictionaries.
    """

    def __init__(self, str=None, tuple=None):
        if not (str or tuple):
            raise RuntimeError("You must provide a value for either 'str' or "
                               "'tuple' arguments.")

        if str:
            user, host, res = parse(str)
        else:
            user, host, res = prep(*tuple)

        self.user = user
        self.host = host
        self.resource = res

    def userhost(self):
        """
        Extract the bare JID as a unicode string.

        A bare JID does not have a resource part, so this returns either
        C{user@host} or just C{host}.

        @rtype: C{unicode}
        """
        if self.user:
            return u"%s@%s" % (self.user, self.host)
        else:
            return self.host

    def userhostJID(self):
        """
        Extract the bare JID.

        A bare JID does not have a resource part, so this returns a
        L{JID} object representing either C{user@host} or just C{host}.

        If the object this method is called upon doesn't have a resource
        set, it will return itself. Otherwise, the bare JID object will
        be created, interned using L{internJID}.

        @rtype: L{JID}
        """
        if self.resource:
            return internJID(self.userhost())
        else:
            return self

    def full(self):
        """
        Return the string representation of this JID.

        @rtype: C{unicode}
        """
        if self.user:
            if self.resource:
                return u"%s@%s/%s" % (self.user, self.host, self.resource)
            else:
                return u"%s@%s" % (self.user, self.host)
        else:
            if self.resource:
                return u"%s/%s" % (self.host, self.resource)
            else:
                return self.host

    def __eq__(self, other):
        """
        Equality comparison.

        L{JID}s compare equal if their user, host and resource parts all
        compare equal.  When comparing against instances of other types, it
        uses the default comparison.
        """
        if isinstance(other, JID):
            return (self.user == other.user and
                    self.host == other.host and
                    self.resource == other.resource)
        else:
            return NotImplemented

    def __ne__(self, other):
        """
        Inequality comparison.

        This negates L{__eq__} for comparison with JIDs and uses the default
        comparison for other types.
        """
        result = self.__eq__(other)
        if result is NotImplemented:
            return result
        else:
            return not result

    def __hash__(self):
        """
        Calculate hash.

        L{JID}s with identical constituent user, host and resource parts have
        equal hash values.  In combination with the comparison defined on JIDs,
        this allows for using L{JID}s in sets and as dictionary keys.
        """
        return hash((self.user, self.host, self.resource))

    def __unicode__(self):
        """
        Get unicode representation.

        Return the string representation of this JID as a unicode string.
        @see: L{full}
        """

        return self.full()

    def __repr__(self):
        """
        Get object representation.

        Returns a string that would create a new JID object that compares equal
        to this one.
        """
        return 'JID(%r)' % self.full()