1package eu.siacs.conversations.utils;
2
3import android.net.Uri;
4
5import java.io.UnsupportedEncodingException;
6import java.net.URLDecoder;
7import java.util.List;
8
9import eu.siacs.conversations.xmpp.jid.InvalidJidException;
10import eu.siacs.conversations.xmpp.jid.Jid;
11
12public class XmppUri {
13
14 protected String jid;
15 protected boolean muc;
16 protected String fingerprint;
17
18 public XmppUri(String uri) {
19 try {
20 parse(Uri.parse(uri));
21 } catch (IllegalArgumentException e) {
22 try {
23 jid = Jid.fromString(uri).toBareJid().toString();
24 } catch (InvalidJidException e2) {
25 jid = null;
26 }
27 }
28 }
29
30 public XmppUri(Uri uri) {
31 parse(uri);
32 }
33
34 protected void parse(Uri uri) {
35 String scheme = uri.getScheme();
36 String host = uri.getHost();
37 List<String> segments = uri.getPathSegments();
38 if ("https".equalsIgnoreCase(scheme) && "conversations.im".equalsIgnoreCase(host) && segments.size() >= 3) {
39 // sample : https://conversations.im/i/foo/bar.com
40 jid = segments.get(1)+"@"+segments.get(2);
41 } else if ("xmpp".equalsIgnoreCase(scheme)) {
42 // sample: xmpp:foo@bar.com
43 muc = "join".equalsIgnoreCase(uri.getQuery());
44 if (uri.getAuthority() != null) {
45 jid = uri.getAuthority();
46 } else {
47 jid = uri.getSchemeSpecificPart().split("\\?")[0];
48 }
49 fingerprint = parseFingerprint(uri.getQuery());
50 } else if ("imto".equalsIgnoreCase(scheme)) {
51 // sample: imto://xmpp/foo@bar.com
52 try {
53 jid = URLDecoder.decode(uri.getEncodedPath(), "UTF-8").split("/")[1];
54 } catch (final UnsupportedEncodingException ignored) {
55 jid = null;
56 }
57 } else {
58 try {
59 jid = Jid.fromString(uri.toString()).toBareJid().toString();
60 } catch (final InvalidJidException ignored) {
61 jid = null;
62 }
63 }
64 }
65
66 protected String parseFingerprint(String query) {
67 if (query == null) {
68 return null;
69 } else {
70 final String NEEDLE = "otr-fingerprint=";
71 int index = query.indexOf(NEEDLE);
72 if (index >= 0 && query.length() >= (NEEDLE.length() + index + 40)) {
73 return query.substring(index + NEEDLE.length(), index + NEEDLE.length() + 40);
74 } else {
75 return null;
76 }
77 }
78 }
79
80 public Jid getJid() {
81 try {
82 return this.jid == null ? null :Jid.fromString(this.jid.toLowerCase());
83 } catch (InvalidJidException e) {
84 return null;
85 }
86 }
87
88 public String getFingerprint() {
89 return this.fingerprint;
90 }
91}