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.List;
 21
 22import eu.siacs.conversations.xml.Element;
 23import eu.siacs.conversations.xml.Namespace;
 24import eu.siacs.conversations.xmpp.forms.Data;
 25import eu.siacs.conversations.xmpp.forms.Field;
 26import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 27
 28public class ServiceDiscoveryResult {
 29	public static final String TABLENAME = "discovery_results";
 30	public static final String HASH = "hash";
 31	public static final String VER = "ver";
 32	public static final String RESULT = "result";
 33	protected final String hash;
 34	protected final byte[] ver;
 35	protected final List<String> features;
 36	protected final List<Data> forms;
 37	private final List<Identity> identities;
 38	public ServiceDiscoveryResult(final IqPacket packet) {
 39		this.identities = new ArrayList<>();
 40		this.features = new ArrayList<>();
 41		this.forms = new ArrayList<>();
 42		this.hash = "sha-1"; // We only support sha-1 for now
 43
 44		final List<Element> elements = packet.query().getChildren();
 45
 46		for (final Element element : elements) {
 47			if (element.getName().equals("identity")) {
 48				Identity id = new Identity(element);
 49				if (id.getType() != null && id.getCategory() != null) {
 50					identities.add(id);
 51				}
 52			} else if (element.getName().equals("feature")) {
 53				if (element.getAttribute("var") != null) {
 54					features.add(element.getAttribute("var"));
 55				}
 56			} else if (element.getName().equals("x") && element.getAttribute("xmlns").equals(Namespace.DATA)) {
 57				forms.add(Data.parse(element));
 58			}
 59		}
 60		this.ver = this.mkCapHash();
 61	}
 62	private ServiceDiscoveryResult(String hash, byte[] ver, JSONObject o) throws JSONException {
 63		this.identities = new ArrayList<>();
 64		this.features = new ArrayList<>();
 65		this.forms = new ArrayList<>();
 66		this.hash = hash;
 67		this.ver = ver;
 68
 69		JSONArray identities = o.optJSONArray("identities");
 70		if (identities != null) {
 71			for (int i = 0; i < identities.length(); i++) {
 72				this.identities.add(new Identity(identities.getJSONObject(i)));
 73			}
 74		}
 75		JSONArray features = o.optJSONArray("features");
 76		if (features != null) {
 77			for (int i = 0; i < features.length(); i++) {
 78				this.features.add(features.getString(i));
 79			}
 80		}
 81		JSONArray forms = o.optJSONArray("forms");
 82		if (forms != null) {
 83			for (int i = 0; i < forms.length(); i++) {
 84				this.forms.add(createFormFromJSONObject(forms.getJSONObject(i)));
 85			}
 86		}
 87	}
 88	
 89	private ServiceDiscoveryResult() {
 90		this.hash = "sha-1";
 91		this.features = Collections.emptyList();
 92		this.identities = Collections.emptyList();
 93		this.ver = null;
 94		this.forms = Collections.emptyList();
 95	}
 96
 97	public static ServiceDiscoveryResult empty() {
 98		return new ServiceDiscoveryResult();
 99	}
100
101	public ServiceDiscoveryResult(Cursor cursor) throws JSONException {
102		this(
103				cursor.getString(cursor.getColumnIndex(HASH)),
104				Base64.decode(cursor.getString(cursor.getColumnIndex(VER)), Base64.DEFAULT),
105				new JSONObject(cursor.getString(cursor.getColumnIndex(RESULT)))
106		);
107	}
108
109	private static String clean(String s) {
110		return s.replace("<","&lt;");
111	}
112
113	private static String blankNull(String s) {
114		return s == null ? "" : clean(s);
115	}
116
117	private static Data createFormFromJSONObject(JSONObject o) {
118		Data data = new Data();
119		JSONArray names = o.names();
120		for (int i = 0; i < names.length(); ++i) {
121			try {
122				String name = names.getString(i);
123				JSONArray jsonValues = o.getJSONArray(name);
124				ArrayList<String> values = new ArrayList<>(jsonValues.length());
125				for (int j = 0; j < jsonValues.length(); ++j) {
126					values.add(jsonValues.getString(j));
127				}
128				data.put(name, values);
129			} catch (Exception e) {
130				e.printStackTrace();
131			}
132		}
133		return data;
134	}
135
136	private static JSONObject createJSONFromForm(Data data) {
137		JSONObject object = new JSONObject();
138		for (Field field : data.getFields()) {
139			try {
140				JSONArray jsonValues = new JSONArray();
141				for (String value : field.getValues()) {
142					jsonValues.put(value);
143				}
144				object.put(field.getFieldName(), jsonValues);
145			} catch (Exception e) {
146				e.printStackTrace();
147			}
148		}
149		try {
150			JSONArray jsonValues = new JSONArray();
151			jsonValues.put(data.getFormType());
152			object.put(Data.FORM_TYPE, jsonValues);
153		} catch (Exception e) {
154			e.printStackTrace();
155		}
156		return object;
157	}
158
159	public String getVer() {
160		return Base64.encodeToString(this.ver, Base64.NO_WRAP);
161	}
162
163	public List<Identity> getIdentities() {
164		return this.identities;
165	}
166
167	public List<String> getFeatures() {
168		return this.features;
169	}
170
171	public boolean hasIdentity(String category, String type) {
172		for (Identity id : this.getIdentities()) {
173			if ((category == null || id.getCategory().equals(category)) &&
174					(type == null || id.getType().equals(type))) {
175				return true;
176			}
177		}
178
179		return false;
180	}
181
182	public String getExtendedDiscoInformation(String formType, String name) {
183		for (Data form : this.forms) {
184			if (formType.equals(form.getFormType())) {
185				for (Field field : form.getFields()) {
186					if (name.equals(field.getFieldName())) {
187						return field.getValue();
188					}
189				}
190			}
191		}
192		return null;
193	}
194
195	private byte[] mkCapHash() {
196		StringBuilder s = new StringBuilder();
197
198		List<Identity> identities = this.getIdentities();
199		Collections.sort(identities);
200
201		for (Identity id : identities) {
202			s.append(blankNull(id.getCategory()))
203					.append("/")
204					.append(blankNull(id.getType()))
205					.append("/")
206					.append(blankNull(id.getLang()))
207					.append("/")
208					.append(blankNull(id.getName()))
209					.append("<");
210		}
211
212		List<String> features = this.getFeatures();
213		Collections.sort(features);
214
215		for (String feature : features) {
216			s.append(clean(feature)).append("<");
217		}
218
219		Collections.sort(forms, (lhs, rhs) -> lhs.getFormType().compareTo(rhs.getFormType()));
220
221		for (Data form : forms) {
222			s.append(clean(form.getFormType())).append("<");
223			List<Field> fields = form.getFields();
224			Collections.sort(fields, (lhs, rhs) -> Strings.nullToEmpty(lhs.getFieldName()).compareTo(Strings.nullToEmpty(rhs.getFieldName())));
225			for (Field field : fields) {
226				s.append(Strings.nullToEmpty(field.getFieldName())).append("<");
227				List<String> values = field.getValues();
228				Collections.sort(values);
229				for (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}