]> nmode's Git Repositories - signal-cli/blob - src/main/java/cli/JsonPreKeyStore.java
Improve receiving messages
[signal-cli] / src / main / java / cli / JsonPreKeyStore.java
1 package cli;
2
3 import org.json.JSONArray;
4 import org.json.JSONObject;
5 import org.whispersystems.libaxolotl.InvalidKeyIdException;
6 import org.whispersystems.libaxolotl.state.PreKeyRecord;
7 import org.whispersystems.libaxolotl.state.PreKeyStore;
8
9 import java.io.IOException;
10 import java.util.HashMap;
11 import java.util.Map;
12
13 public class JsonPreKeyStore implements PreKeyStore {
14
15 private final Map<Integer, byte[]> store = new HashMap<>();
16
17 public JsonPreKeyStore() {
18
19 }
20
21 public JsonPreKeyStore(JSONArray list) throws IOException {
22 for (int i = 0; i < list.length(); i++) {
23 JSONObject k = list.getJSONObject(i);
24 try {
25 store.put(k.getInt("id"), Base64.decode(k.getString("record")));
26 } catch (IOException e) {
27 System.out.println("Error while decoding prekey for: " + k.getString("name"));
28 }
29 }
30 }
31
32 public JSONArray getJson() {
33 JSONArray result = new JSONArray();
34 for (Integer id : store.keySet()) {
35 result.put(new JSONObject().put("id", id.toString()).put("record", Base64.encodeBytes(store.get(id))));
36 }
37 return result;
38 }
39
40 @Override
41 public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException {
42 try {
43 if (!store.containsKey(preKeyId)) {
44 throw new InvalidKeyIdException("No such prekeyrecord!");
45 }
46
47 return new PreKeyRecord(store.get(preKeyId));
48 } catch (IOException e) {
49 throw new AssertionError(e);
50 }
51 }
52
53 @Override
54 public void storePreKey(int preKeyId, PreKeyRecord record) {
55 store.put(preKeyId, record.serialize());
56 }
57
58 @Override
59 public boolean containsPreKey(int preKeyId) {
60 return store.containsKey(preKeyId);
61 }
62
63 @Override
64 public void removePreKey(int preKeyId) {
65 store.remove(preKeyId);
66 }
67 }