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)) {
39 if (segments.size() >= 2 && segments.get(1).contains("@")) {
40 // sample : https://conversations.im/i/foo@bar.com
41 try {
42 jid = Jid.fromString(segments.get(1)).toString();
43 } catch (Exception e) {
44 jid = null;
45 }
46 } else if (segments.size() >= 3) {
47 // sample : https://conversations.im/i/foo/bar.com
48 jid = segments.get(1) + "@" + segments.get(2);
49 }
50 } else if ("xmpp".equalsIgnoreCase(scheme)) {
51 // sample: xmpp:foo@bar.com
52 muc = "join".equalsIgnoreCase(uri.getQuery());
53 if (uri.getAuthority() != null) {
54 jid = uri.getAuthority();
55 } else {
56 jid = uri.getSchemeSpecificPart().split("\\?")[0];
57 }
58 fingerprint = parseFingerprint(uri.getQuery());
59 } else if ("imto".equalsIgnoreCase(scheme)) {
60 // sample: imto://xmpp/foo@bar.com
61 try {
62 jid = URLDecoder.decode(uri.getEncodedPath(), "UTF-8").split("/")[1];
63 } catch (final UnsupportedEncodingException ignored) {
64 jid = null;
65 }
66 } else {
67 try {
68 jid = Jid.fromString(uri.toString()).toBareJid().toString();
69 } catch (final InvalidJidException ignored) {
70 jid = null;
71 }
72 }
73 }
74
75 protected String parseFingerprint(String query) {
76 if (query == null) {
77 return null;
78 } else {
79 final String NEEDLE = "otr-fingerprint=";
80 int index = query.indexOf(NEEDLE);
81 if (index >= 0 && query.length() >= (NEEDLE.length() + index + 40)) {
82 return query.substring(index + NEEDLE.length(), index + NEEDLE.length() + 40);
83 } else {
84 return null;
85 }
86 }
87 }
88
89 public Jid getJid() {
90 try {
91 return this.jid == null ? null :Jid.fromString(this.jid.toLowerCase());
92 } catch (InvalidJidException e) {
93 return null;
94 }
95 }
96
97 public String getFingerprint() {
98 return this.fingerprint;
99 }
100}