aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/pixart/messenger/entities/ServiceDiscoveryResult.java
blob: 50b118cba424024cc42294a33c50d22df3f41ff6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package de.pixart.messenger.entities;

import android.content.ContentValues;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.util.Base64;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import de.pixart.messenger.utils.Namespace;
import de.pixart.messenger.xml.Element;
import de.pixart.messenger.xmpp.forms.Data;
import de.pixart.messenger.xmpp.forms.Field;
import de.pixart.messenger.xmpp.stanzas.IqPacket;

public class ServiceDiscoveryResult {
    public static final String TABLENAME = "discovery_results";
    public static final String HASH = "hash";
    public static final String VER = "ver";
    public static final String RESULT = "result";
    protected final String hash;
    protected final byte[] ver;
    protected final List<String> features;
    protected final List<Data> forms;
    private final List<Identity> identities;

    public ServiceDiscoveryResult(final IqPacket packet) {
        this.identities = new ArrayList<>();
        this.features = new ArrayList<>();
        this.forms = new ArrayList<>();
        this.hash = "sha-1"; // We only support sha-1 for now

        final List<Element> elements = packet.query().getChildren();

        for (final Element element : elements) {
            if (element.getName().equals("identity")) {
                Identity id = new Identity(element);
                if (id.getType() != null && id.getCategory() != null) {
                    identities.add(id);
                }
            } else if (element.getName().equals("feature")) {
                if (element.getAttribute("var") != null) {
                    features.add(element.getAttribute("var"));
                }
            } else if (element.getName().equals("x") && element.getAttribute("xmlns").equals(Namespace.DATA)) {
                forms.add(Data.parse(element));
            }
        }
        this.ver = this.mkCapHash();
    }

    private ServiceDiscoveryResult(String hash, byte[] ver, JSONObject o) throws JSONException {
        this.identities = new ArrayList<>();
        this.features = new ArrayList<>();
        this.forms = new ArrayList<>();
        this.hash = hash;
        this.ver = ver;

        JSONArray identities = o.optJSONArray("identities");
        if (identities != null) {
            for (int i = 0; i < identities.length(); i++) {
                this.identities.add(new Identity(identities.getJSONObject(i)));
            }
        }
        JSONArray features = o.optJSONArray("features");
        if (features != null) {
            for (int i = 0; i < features.length(); i++) {
                this.features.add(features.getString(i));
            }
        }
        JSONArray forms = o.optJSONArray("forms");
        if (forms != null) {
            for (int i = 0; i < forms.length(); i++) {
                this.forms.add(createFormFromJSONObject(forms.getJSONObject(i)));
            }
        }
    }

    private ServiceDiscoveryResult() {
        this.hash = "sha-1";
        this.features = Collections.emptyList();
        this.identities = Collections.emptyList();
        this.ver = null;
        this.forms = Collections.emptyList();
    }

    public static ServiceDiscoveryResult empty() {
        return new ServiceDiscoveryResult();
    }

    public ServiceDiscoveryResult(Cursor cursor) throws JSONException {
        this(
                cursor.getString(cursor.getColumnIndex(HASH)),
                Base64.decode(cursor.getString(cursor.getColumnIndex(VER)), Base64.DEFAULT),
                new JSONObject(cursor.getString(cursor.getColumnIndex(RESULT)))
        );
    }

    private static String clean(String s) {
        return s.replace("<", "&lt;");
    }

    private static String blankNull(String s) {
        return s == null ? "" : clean(s);
    }

    private static Data createFormFromJSONObject(JSONObject o) {
        Data data = new Data();
        JSONArray names = o.names();
        for (int i = 0; i < names.length(); ++i) {
            try {
                String name = names.getString(i);
                JSONArray jsonValues = o.getJSONArray(name);
                ArrayList<String> values = new ArrayList<>(jsonValues.length());
                for (int j = 0; j < jsonValues.length(); ++j) {
                    values.add(jsonValues.getString(j));
                }
                data.put(name, values);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return data;
    }

    private static JSONObject createJSONFromForm(Data data) {
        JSONObject object = new JSONObject();
        for (Field field : data.getFields()) {
            try {
                JSONArray jsonValues = new JSONArray();
                for (String value : field.getValues()) {
                    jsonValues.put(value);
                }
                object.put(field.getFieldName(), jsonValues);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            JSONArray jsonValues = new JSONArray();
            jsonValues.put(data.getFormType());
            object.put(Data.FORM_TYPE, jsonValues);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    public String getVer() {
        return new String(Base64.encode(this.ver, Base64.DEFAULT)).trim();
    }

    public List<Identity> getIdentities() {
        return this.identities;
    }

    public List<String> getFeatures() {
        return this.features;
    }

    public boolean hasIdentity(String category, String type) {
        for (Identity id : this.getIdentities()) {
            if ((category == null || id.getCategory().equals(category)) &&
                    (type == null || id.getType().equals(type))) {
                return true;
            }
        }

        return false;
    }

    public String getExtendedDiscoInformation(String formType, String name) {
        for (Data form : this.forms) {
            if (formType.equals(form.getFormType())) {
                for (Field field : form.getFields()) {
                    if (name.equals(field.getFieldName())) {
                        return field.getValue();
                    }
                }
            }
        }
        return null;
    }

    private byte[] mkCapHash() {
        StringBuilder s = new StringBuilder();

        List<Identity> identities = this.getIdentities();
        Collections.sort(identities);

        for (Identity id : identities) {
            s.append(blankNull(id.getCategory()))
                    .append("/")
                    .append(blankNull(id.getType()))
                    .append("/")
                    .append(blankNull(id.getLang()))
                    .append("/")
                    .append(blankNull(id.getName()))
                    .append("<");
        }

        List<String> features = this.getFeatures();
        Collections.sort(features);

        for (String feature : features) {
            s.append(clean(feature)).append("<");
        }

        Collections.sort(forms, (lhs, rhs) -> lhs.getFormType().compareTo(rhs.getFormType()));

        for (Data form : forms) {
            s.append(clean(form.getFormType())).append("<");
            List<Field> fields = form.getFields();
            Collections.sort(fields, (lhs, rhs) -> lhs.getFieldName().compareTo(rhs.getFieldName()));
            for (Field field : fields) {
                s.append(clean(field.getFieldName())).append("<");
                List<String> values = field.getValues();
                Collections.sort(values);
                for (String value : values) {
                    s.append(blankNull(value)).append("<");
                }
            }
        }

        MessageDigest md;
        try {
            md = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            return null;
        }

        try {
            return md.digest(s.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    private JSONObject toJSON() {
        try {
            JSONObject o = new JSONObject();

            JSONArray ids = new JSONArray();
            for (Identity id : this.getIdentities()) {
                ids.put(id.toJSON());
            }
            o.put("identities", ids);

            o.put("features", new JSONArray(this.getFeatures()));

            JSONArray forms = new JSONArray();
            for (Data data : this.forms) {
                forms.put(createJSONFromForm(data));
            }
            o.put("forms", forms);

            return o;
        } catch (JSONException e) {
            return null;
        }
    }

    public ContentValues getContentValues() {
        final ContentValues values = new ContentValues();
        values.put(HASH, this.hash);
        values.put(VER, getVer());
        JSONObject jsonObject = toJSON();
        values.put(RESULT, jsonObject == null ? "" : jsonObject.toString());
        return values;
    }

    public static class Identity implements Comparable {
        protected final String type;
        protected final String lang;
        protected final String name;
        final String category;

        Identity(final String category, final String type, final String lang, final String name) {
            this.category = category;
            this.type = type;
            this.lang = lang;
            this.name = name;
        }

        Identity(final Element el) {
            this(
                    el.getAttribute("category"),
                    el.getAttribute("type"),
                    el.getAttribute("xml:lang"),
                    el.getAttribute("name")
            );
        }

        Identity(final JSONObject o) {

            this(
                    o.optString("category", null),
                    o.optString("type", null),
                    o.optString("lang", null),
                    o.optString("name", null)
            );
        }

        public String getCategory() {
            return this.category;
        }

        public String getType() {
            return this.type;
        }

        public String getLang() {
            return this.lang;
        }

        public String getName() {
            return this.name;
        }

        public int compareTo(@NonNull Object other) {
            Identity o = (Identity) other;
            int r = blankNull(this.getCategory()).compareTo(blankNull(o.getCategory()));
            if (r == 0) {
                r = blankNull(this.getType()).compareTo(blankNull(o.getType()));
            }
            if (r == 0) {
                r = blankNull(this.getLang()).compareTo(blankNull(o.getLang()));
            }
            if (r == 0) {
                r = blankNull(this.getName()).compareTo(blankNull(o.getName()));
            }

            return r;
        }

        JSONObject toJSON() {
            try {
                JSONObject o = new JSONObject();
                o.put("category", this.getCategory());
                o.put("type", this.getType());
                o.put("lang", this.getLang());
                o.put("name", this.getName());
                return o;
            } catch (JSONException e) {
                return null;
            }
        }
    }
}