comparison src/tools/common/uri.py @ 2216:7e06eafef409

tools(common/uri): XMPP uri parsing module, first draft
author Goffi <goffi@goffi.org>
date Wed, 29 Mar 2017 21:04:43 +0200
parents
children bdc64c487e21
comparison
equal deleted inserted replaced
2215:5831e8fcc5f8 2216:7e06eafef409
1 #!/usr/bin/env python2
2 # -*- coding: utf-8 -*-
3
4 # SAT: a jabber client
5 # Copyright (C) 2009-2016 Jérôme Poisson (goffi@goffi.org)
6
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
16
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20 """ XMPP uri parsing tools """
21
22 import urlparse
23 import urllib
24
25 # FIXME: basic implementation, need to follow RFC 5122
26
27 def parseXMPPUri(uri):
28 """Parse an XMPP uri and return a dict with various information
29
30 @param uri(unicode): uri to parse
31 @return dict(unicode, unicode): data depending of the URI where key can be:
32 type: one of ("pubsub", TODO)
33 sub_type: can be:
34 - microblog
35 only used for pubsub for now
36 path: XMPP path (jid of the service or entity)
37 node: node used
38 id: id of the element (item for pubsub)
39 @raise ValueError: the scheme is not xmpp
40 """
41 uri_split = urlparse.urlsplit(uri.encode('utf-8'))
42 if uri_split.scheme != 'xmpp':
43 raise ValueError(u'this is not a XMPP URI')
44
45 data = {u'path': urllib.unquote(uri_split.path).decode('utf-8')}
46
47 query_end = uri_split.query.find(';')
48 query_type = uri_split.query[:query_end]
49 if query_end == -1 or '=' in query_type:
50 raise ValueError('no query type, invalid XMPP URI')
51
52 pairs = urlparse.parse_qs(uri_split.geturl())
53 for k, v in pairs.items():
54 if len(v) != 1:
55 raise NotImplementedError(u"multiple values not managed")
56 if k in ('path', 'type', 'sub_type'):
57 raise NotImplementedError(u"reserved key used in URI, this is not supported")
58 data[k.decode('utf-8')] = urllib.unquote(v[0]).decode('utf-8')
59
60 if query_type:
61 data[u'type'] = query_type.decode('utf-8')
62 elif u'node' in data:
63 data[u'type'] = u'pubsub'
64 else:
65 data[u'type'] = ''
66
67 if u'node' in data:
68 if data[u'node'].startswith(u'urn:xmpp:microblog:'):
69 data[u'sub_type'] = 'microblog'
70
71 return data