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
.*;
6 import org
.whispersystems
.libsignal
.InvalidKeyIdException
;
7 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
8 import org
.whispersystems
.libsignal
.state
.PreKeyStore
;
9 import org
.whispersystems
.signalservice
.internal
.util
.Base64
;
11 import java
.io
.IOException
;
12 import java
.util
.HashMap
;
15 class JsonPreKeyStore
implements PreKeyStore
{
17 private final Map
<Integer
, byte[]> store
= new HashMap
<>();
19 public JsonPreKeyStore() {
23 private void addPreKeys(Map
<Integer
, byte[]> preKeys
) {
24 store
.putAll(preKeys
);
28 public PreKeyRecord
loadPreKey(int preKeyId
) throws InvalidKeyIdException
{
30 if (!store
.containsKey(preKeyId
)) {
31 throw new InvalidKeyIdException("No such prekeyrecord!");
34 return new PreKeyRecord(store
.get(preKeyId
));
35 } catch (IOException e
) {
36 throw new AssertionError(e
);
41 public void storePreKey(int preKeyId
, PreKeyRecord
record) {
42 store
.put(preKeyId
, record.serialize());
46 public boolean containsPreKey(int preKeyId
) {
47 return store
.containsKey(preKeyId
);
51 public void removePreKey(int preKeyId
) {
52 store
.remove(preKeyId
);
55 public static class JsonPreKeyStoreDeserializer
extends JsonDeserializer
<JsonPreKeyStore
> {
58 public JsonPreKeyStore
deserialize(JsonParser jsonParser
, DeserializationContext deserializationContext
) throws IOException
{
59 JsonNode node
= jsonParser
.getCodec().readTree(jsonParser
);
61 Map
<Integer
, byte[]> preKeyMap
= new HashMap
<>();
63 for (JsonNode preKey
: node
) {
64 Integer preKeyId
= preKey
.get("id").asInt();
66 preKeyMap
.put(preKeyId
, Base64
.decode(preKey
.get("record").asText()));
67 } catch (IOException e
) {
68 System
.out
.println(String
.format("Error while decoding prekey for: %s", preKeyId
));
73 JsonPreKeyStore keyStore
= new JsonPreKeyStore();
74 keyStore
.addPreKeys(preKeyMap
);
81 public static class JsonPreKeyStoreSerializer
extends JsonSerializer
<JsonPreKeyStore
> {
84 public void serialize(JsonPreKeyStore jsonPreKeyStore
, JsonGenerator json
, SerializerProvider serializerProvider
) throws IOException
{
85 json
.writeStartArray();
86 for (Map
.Entry
<Integer
, byte[]> preKey
: jsonPreKeyStore
.store
.entrySet()) {
87 json
.writeStartObject();
88 json
.writeNumberField("id", preKey
.getKey());
89 json
.writeStringField("record", Base64
.encodeBytes(preKey
.getValue()));
90 json
.writeEndObject();