1package eu.siacs.conversations.entities;
2
3import android.content.ContentValues;
4import android.database.Cursor;
5import android.util.Base64;
6
7import androidx.annotation.NonNull;
8
9import com.google.common.base.Strings;
10
11import org.json.JSONArray;
12import org.json.JSONException;
13import org.json.JSONObject;
14
15import java.nio.charset.StandardCharsets;
16import java.security.MessageDigest;
17import java.security.NoSuchAlgorithmException;
18import java.util.ArrayList;
19import java.util.Collections;
20import java.util.Comparator;
21import java.util.List;
22
23import eu.siacs.conversations.xml.Element;
24import eu.siacs.conversations.xml.Namespace;
25import eu.siacs.conversations.xmpp.forms.Data;
26import eu.siacs.conversations.xmpp.forms.Field;
27import im.conversations.android.xmpp.model.stanza.Iq;
28
29public class ServiceDiscoveryResult {
30 public static final String TABLENAME = "discovery_results";
31 public static final String HASH = "hash";
32 public static final String VER = "ver";
33 public static final String RESULT = "result";
34 protected final String hash;
35 protected final byte[] ver;
36 protected final List<String> features;
37 protected final List<Data> forms;
38 private final List<Identity> identities;
39 public ServiceDiscoveryResult(final Iq packet) {
40 this.identities = new ArrayList<>();
41 this.features = new ArrayList<>();
42 this.forms = new ArrayList<>();
43 this.hash = "sha-1"; // We only support sha-1 for now
44
45 final List<Element> elements = packet.query().getChildren();
46
47 for (final Element element : elements) {
48 if (element.getName().equals("identity")) {
49 Identity id = new Identity(element);
50 if (id.getType() != null && id.getCategory() != null) {
51 identities.add(id);
52 }
53 } else if (element.getName().equals("feature")) {
54 if (element.getAttribute("var") != null) {
55 features.add(element.getAttribute("var"));
56 }
57 } else if (element.getName().equals("x") && element.getAttribute("xmlns").equals(Namespace.DATA)) {
58 forms.add(Data.parse(element));
59 }
60 }
61 this.ver = this.mkCapHash();
62 }
63 private ServiceDiscoveryResult(String hash, byte[] ver, JSONObject o) throws JSONException {
64 this.identities = new ArrayList<>();
65 this.features = new ArrayList<>();
66 this.forms = new ArrayList<>();
67 this.hash = hash;
68 this.ver = ver;
69
70 JSONArray identities = o.optJSONArray("identities");
71 if (identities != null) {
72 for (int i = 0; i < identities.length(); i++) {
73 this.identities.add(new Identity(identities.getJSONObject(i)));
74 }
75 }
76 JSONArray features = o.optJSONArray("features");
77 if (features != null) {
78 for (int i = 0; i < features.length(); i++) {
79 this.features.add(features.getString(i));
80 }
81 }
82 JSONArray forms = o.optJSONArray("forms");
83 if (forms != null) {
84 for (int i = 0; i < forms.length(); i++) {
85 this.forms.add(createFormFromJSONObject(forms.getJSONObject(i)));
86 }
87 }
88 }
89
90 private ServiceDiscoveryResult() {
91 this.hash = "sha-1";
92 this.features = Collections.emptyList();
93 this.identities = Collections.emptyList();
94 this.ver = null;
95 this.forms = Collections.emptyList();
96 }
97
98 public static ServiceDiscoveryResult empty() {
99 return new ServiceDiscoveryResult();
100 }
101
102 public ServiceDiscoveryResult(Cursor cursor) throws JSONException {
103 this(
104 cursor.getString(cursor.getColumnIndexOrThrow(HASH)),
105 Base64.decode(cursor.getString(cursor.getColumnIndexOrThrow(VER)), Base64.DEFAULT),
106 new JSONObject(cursor.getString(cursor.getColumnIndexOrThrow(RESULT)))
107 );
108 }
109
110 private static String clean(String s) {
111 return s.replace("<","<");
112 }
113
114 private static String blankNull(String s) {
115 return s == null ? "" : clean(s);
116 }
117
118 private static Data createFormFromJSONObject(JSONObject o) {
119 Data data = new Data();
120 JSONArray names = o.names();
121 for (int i = 0; i < names.length(); ++i) {
122 try {
123 String name = names.getString(i);
124 JSONArray jsonValues = o.getJSONArray(name);
125 ArrayList<String> values = new ArrayList<>(jsonValues.length());
126 for (int j = 0; j < jsonValues.length(); ++j) {
127 values.add(jsonValues.getString(j));
128 }
129 data.put(name, values);
130 } catch (Exception e) {
131 e.printStackTrace();
132 }
133 }
134 return data;
135 }
136
137 private static JSONObject createJSONFromForm(Data data) {
138 JSONObject object = new JSONObject();
139 for (Field field : data.getFields()) {
140 try {
141 JSONArray jsonValues = new JSONArray();
142 for (String value : field.getValues()) {
143 jsonValues.put(value);
144 }
145 object.put(field.getFieldName(), jsonValues);
146 } catch (Exception e) {
147 e.printStackTrace();
148 }
149 }
150 try {
151 JSONArray jsonValues = new JSONArray();
152 jsonValues.put(data.getFormType());
153 object.put(Data.FORM_TYPE, jsonValues);
154 } catch (Exception e) {
155 e.printStackTrace();
156 }
157 return object;
158 }
159
160 public String getVer() {
161 return Base64.encodeToString(this.ver, Base64.NO_WRAP);
162 }
163
164 public List<Identity> getIdentities() {
165 return this.identities;
166 }
167
168 public List<String> getFeatures() {
169 return this.features;
170 }
171
172 public Identity getIdentity(String category, String type) {
173 for (Identity id : this.getIdentities()) {
174 if ((category == null || id.getCategory().equals(category)) &&
175 (type == null || id.getType().equals(type))) {
176 return id;
177 }
178 }
179
180 return null;
181 }
182
183 public boolean hasIdentity(String category, String type) {
184 return getIdentity(category, type) != null;
185 }
186
187 public String getExtendedDiscoInformation(String formType, String name) {
188 for (Data form : this.forms) {
189 if (formType.equals(form.getFormType())) {
190 for (Field field : form.getFields()) {
191 if (name.equals(field.getFieldName())) {
192 return field.getValue();
193 }
194 }
195 }
196 }
197 return null;
198 }
199
200 private byte[] mkCapHash() {
201 StringBuilder s = new StringBuilder();
202
203 List<Identity> identities = this.getIdentities();
204 Collections.sort(identities);
205
206 for (Identity id : identities) {
207 s.append(blankNull(id.getCategory()))
208 .append("/")
209 .append(blankNull(id.getType()))
210 .append("/")
211 .append(blankNull(id.getLang()))
212 .append("/")
213 .append(blankNull(id.getName()))
214 .append("<");
215 }
216
217 final List<String> features = this.getFeatures();
218 Collections.sort(features);
219 for (final String feature : features) {
220 s.append(clean(feature)).append("<");
221 }
222
223 Collections.sort(forms, Comparator.comparing(Data::getFormType));
224 for (final Data form : forms) {
225 s.append(clean(form.getFormType())).append("<");
226 final List<Field> fields = form.getFields();
227 Collections.sort(
228 fields, Comparator.comparing(lhs -> Strings.nullToEmpty(lhs.getFieldName())));
229 for (final Field field : fields) {
230 s.append(Strings.nullToEmpty(field.getFieldName())).append("<");
231 final List<String> values = field.getValues();
232 Collections.sort(values, Comparator.comparing(ServiceDiscoveryResult::blankNull));
233 for (final String value : values) {
234 s.append(blankNull(value)).append("<");
235 }
236 }
237 }
238
239 MessageDigest md;
240 try {
241 md = MessageDigest.getInstance("SHA-1");
242 } catch (NoSuchAlgorithmException e) {
243 return null;
244 }
245
246 return md.digest(s.toString().getBytes(StandardCharsets.UTF_8));
247 }
248
249 private JSONObject toJSON() {
250 try {
251 JSONObject o = new JSONObject();
252
253 JSONArray ids = new JSONArray();
254 for (Identity id : this.getIdentities()) {
255 ids.put(id.toJSON());
256 }
257 o.put("identities", ids);
258
259 o.put("features", new JSONArray(this.getFeatures()));
260
261 JSONArray forms = new JSONArray();
262 for (Data data : this.forms) {
263 forms.put(createJSONFromForm(data));
264 }
265 o.put("forms", forms);
266
267 return o;
268 } catch (JSONException e) {
269 return null;
270 }
271 }
272
273 public ContentValues getContentValues() {
274 final ContentValues values = new ContentValues();
275 values.put(HASH, this.hash);
276 values.put(VER, getVer());
277 JSONObject jsonObject = toJSON();
278 values.put(RESULT, jsonObject == null ? "" : jsonObject.toString());
279 return values;
280 }
281
282 public static class Identity implements Comparable<Identity> {
283 protected final String type;
284 protected final String lang;
285 protected final String name;
286 final String category;
287
288 Identity(final String category, final String type, final String lang, final String name) {
289 this.category = category;
290 this.type = type;
291 this.lang = lang;
292 this.name = name;
293 }
294
295 Identity(final Element el) {
296 this(
297 el.getAttribute("category"),
298 el.getAttribute("type"),
299 el.getAttribute("xml:lang"),
300 el.getAttribute("name")
301 );
302 }
303
304 Identity(final JSONObject o) {
305
306 this(
307 o.optString("category", null),
308 o.optString("type", null),
309 o.optString("lang", null),
310 o.optString("name", null)
311 );
312 }
313
314 public String getCategory() {
315 return this.category;
316 }
317
318 public String getType() {
319 return this.type;
320 }
321
322 public String getLang() {
323 return this.lang;
324 }
325
326 public String getName() {
327 return this.name;
328 }
329
330 JSONObject toJSON() {
331 try {
332 JSONObject o = new JSONObject();
333 o.put("category", this.getCategory());
334 o.put("type", this.getType());
335 o.put("lang", this.getLang());
336 o.put("name", this.getName());
337 return o;
338 } catch (JSONException e) {
339 return null;
340 }
341 }
342
343 @Override
344 public int compareTo(final Identity o) {
345 int r = blankNull(this.getCategory()).compareTo(blankNull(o.getCategory()));
346 if (r == 0) {
347 r = blankNull(this.getType()).compareTo(blankNull(o.getType()));
348 }
349 if (r == 0) {
350 r = blankNull(this.getLang()).compareTo(blankNull(o.getLang()));
351 }
352 if (r == 0) {
353 r = blankNull(this.getName()).compareTo(blankNull(o.getName()));
354 }
355
356 return r;
357 }
358 }
359}