ServiceDiscoveryResult.java

  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 eu.siacs.conversations.xmpp.stanzas.IqPacket;
 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 IqPacket 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("<","&lt;");
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 boolean hasIdentity(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 true;
177			}
178		}
179
180		return false;
181	}
182
183	public String getExtendedDiscoInformation(String formType, String name) {
184		for (Data form : this.forms) {
185			if (formType.equals(form.getFormType())) {
186				for (Field field : form.getFields()) {
187					if (name.equals(field.getFieldName())) {
188						return field.getValue();
189					}
190				}
191			}
192		}
193		return null;
194	}
195
196	private byte[] mkCapHash() {
197		StringBuilder s = new StringBuilder();
198
199		List<Identity> identities = this.getIdentities();
200		Collections.sort(identities);
201
202		for (Identity id : identities) {
203			s.append(blankNull(id.getCategory()))
204					.append("/")
205					.append(blankNull(id.getType()))
206					.append("/")
207					.append(blankNull(id.getLang()))
208					.append("/")
209					.append(blankNull(id.getName()))
210					.append("<");
211		}
212
213		final List<String> features = this.getFeatures();
214		Collections.sort(features);
215		for (final String feature : features) {
216			s.append(clean(feature)).append("<");
217		}
218
219		Collections.sort(forms, Comparator.comparing(Data::getFormType));
220		for (final Data form : forms) {
221			s.append(clean(form.getFormType())).append("<");
222			final List<Field> fields = form.getFields();
223			Collections.sort(
224                    fields, Comparator.comparing(lhs -> Strings.nullToEmpty(lhs.getFieldName())));
225			for (final Field field : fields) {
226				s.append(Strings.nullToEmpty(field.getFieldName())).append("<");
227				final List<String> values = field.getValues();
228				Collections.sort(values, Comparator.comparing(ServiceDiscoveryResult::blankNull));
229				for (final String value : values) {
230					s.append(blankNull(value)).append("<");
231				}
232			}
233		}
234
235		MessageDigest md;
236		try {
237			md = MessageDigest.getInstance("SHA-1");
238		} catch (NoSuchAlgorithmException e) {
239			return null;
240		}
241
242        return md.digest(s.toString().getBytes(StandardCharsets.UTF_8));
243    }
244
245	private JSONObject toJSON() {
246		try {
247			JSONObject o = new JSONObject();
248
249			JSONArray ids = new JSONArray();
250			for (Identity id : this.getIdentities()) {
251				ids.put(id.toJSON());
252			}
253			o.put("identities", ids);
254
255			o.put("features", new JSONArray(this.getFeatures()));
256
257			JSONArray forms = new JSONArray();
258			for (Data data : this.forms) {
259				forms.put(createJSONFromForm(data));
260			}
261			o.put("forms", forms);
262
263			return o;
264		} catch (JSONException e) {
265			return null;
266		}
267	}
268
269	public ContentValues getContentValues() {
270		final ContentValues values = new ContentValues();
271		values.put(HASH, this.hash);
272		values.put(VER, getVer());
273		JSONObject jsonObject = toJSON();
274		values.put(RESULT, jsonObject == null ? "" : jsonObject.toString());
275		return values;
276	}
277
278	public static class Identity implements Comparable {
279		protected final String type;
280		protected final String lang;
281		protected final String name;
282		final String category;
283
284		Identity(final String category, final String type, final String lang, final String name) {
285			this.category = category;
286			this.type = type;
287			this.lang = lang;
288			this.name = name;
289		}
290
291		Identity(final Element el) {
292			this(
293					el.getAttribute("category"),
294					el.getAttribute("type"),
295					el.getAttribute("xml:lang"),
296					el.getAttribute("name")
297			);
298		}
299
300		Identity(final JSONObject o) {
301
302			this(
303					o.optString("category", null),
304					o.optString("type", null),
305					o.optString("lang", null),
306					o.optString("name", null)
307			);
308		}
309
310		public String getCategory() {
311			return this.category;
312		}
313
314		public String getType() {
315			return this.type;
316		}
317
318		public String getLang() {
319			return this.lang;
320		}
321
322		public String getName() {
323			return this.name;
324		}
325
326		public int compareTo(@NonNull Object other) {
327			Identity o = (Identity) other;
328			int r = blankNull(this.getCategory()).compareTo(blankNull(o.getCategory()));
329			if (r == 0) {
330				r = blankNull(this.getType()).compareTo(blankNull(o.getType()));
331			}
332			if (r == 0) {
333				r = blankNull(this.getLang()).compareTo(blankNull(o.getLang()));
334			}
335			if (r == 0) {
336				r = blankNull(this.getName()).compareTo(blankNull(o.getName()));
337			}
338
339			return r;
340		}
341
342		JSONObject toJSON() {
343			try {
344				JSONObject o = new JSONObject();
345				o.put("category", this.getCategory());
346				o.put("type", this.getType());
347				o.put("lang", this.getLang());
348				o.put("name", this.getName());
349				return o;
350			} catch (JSONException e) {
351				return null;
352			}
353		}
354	}
355}