1 package org
.asamk
.signal
.storage
.protocol
;
3 import com
.fasterxml
.jackson
.core
.JsonGenerator
;
4 import com
.fasterxml
.jackson
.core
.JsonParser
;
5 import com
.fasterxml
.jackson
.databind
.DeserializationContext
;
6 import com
.fasterxml
.jackson
.databind
.JsonDeserializer
;
7 import com
.fasterxml
.jackson
.databind
.JsonNode
;
8 import com
.fasterxml
.jackson
.databind
.JsonSerializer
;
9 import com
.fasterxml
.jackson
.databind
.SerializerProvider
;
11 import org
.whispersystems
.libsignal
.InvalidKeyIdException
;
12 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
13 import org
.whispersystems
.libsignal
.state
.PreKeyStore
;
14 import org
.whispersystems
.util
.Base64
;
16 import java
.io
.IOException
;
17 import java
.util
.HashMap
;
20 class JsonPreKeyStore
implements PreKeyStore
{
22 private final Map
<Integer
, byte[]> store
= new HashMap
<>();
24 public JsonPreKeyStore() {
28 private void addPreKeys(Map
<Integer
, byte[]> preKeys
) {
29 store
.putAll(preKeys
);
33 public PreKeyRecord
loadPreKey(int preKeyId
) throws InvalidKeyIdException
{
35 if (!store
.containsKey(preKeyId
)) {
36 throw new InvalidKeyIdException("No such prekeyrecord!");
39 return new PreKeyRecord(store
.get(preKeyId
));
40 } catch (IOException e
) {
41 throw new AssertionError(e
);
46 public void storePreKey(int preKeyId
, PreKeyRecord
record) {
47 store
.put(preKeyId
, record.serialize());
51 public boolean containsPreKey(int preKeyId
) {
52 return store
.containsKey(preKeyId
);
56 public void removePreKey(int preKeyId
) {
57 store
.remove(preKeyId
);
60 public static class JsonPreKeyStoreDeserializer
extends JsonDeserializer
<JsonPreKeyStore
> {
63 public JsonPreKeyStore
deserialize(JsonParser jsonParser
, DeserializationContext deserializationContext
) throws IOException
{
64 JsonNode node
= jsonParser
.getCodec().readTree(jsonParser
);
66 Map
<Integer
, byte[]> preKeyMap
= new HashMap
<>();
68 for (JsonNode preKey
: node
) {
69 Integer preKeyId
= preKey
.get("id").asInt();
71 preKeyMap
.put(preKeyId
, Base64
.decode(preKey
.get("record").asText()));
72 } catch (IOException e
) {
73 System
.out
.println(String
.format("Error while decoding prekey for: %s", preKeyId
));
78 JsonPreKeyStore keyStore
= new JsonPreKeyStore();
79 keyStore
.addPreKeys(preKeyMap
);
86 public static class JsonPreKeyStoreSerializer
extends JsonSerializer
<JsonPreKeyStore
> {
89 public void serialize(JsonPreKeyStore jsonPreKeyStore
, JsonGenerator json
, SerializerProvider serializerProvider
) throws IOException
{
90 json
.writeStartArray();
91 for (Map
.Entry
<Integer
, byte[]> preKey
: jsonPreKeyStore
.store
.entrySet()) {
92 json
.writeStartObject();
93 json
.writeNumberField("id", preKey
.getKey());
94 json
.writeStringField("record", Base64
.encodeBytes(preKey
.getValue()));
95 json
.writeEndObject();