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
.core
.JsonProcessingException
;
6 import com
.fasterxml
.jackson
.databind
.*;
7 import org
.whispersystems
.libsignal
.InvalidKeyIdException
;
8 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
9 import org
.whispersystems
.libsignal
.state
.PreKeyStore
;
10 import org
.whispersystems
.signalservice
.internal
.util
.Base64
;
12 import java
.io
.IOException
;
13 import java
.util
.HashMap
;
16 class JsonPreKeyStore
implements PreKeyStore
{
18 private final Map
<Integer
, byte[]> store
= new HashMap
<>();
20 public JsonPreKeyStore() {
24 public void addPreKeys(Map
<Integer
, byte[]> preKeys
) {
25 store
.putAll(preKeys
);
29 public PreKeyRecord
loadPreKey(int preKeyId
) throws InvalidKeyIdException
{
31 if (!store
.containsKey(preKeyId
)) {
32 throw new InvalidKeyIdException("No such prekeyrecord!");
35 return new PreKeyRecord(store
.get(preKeyId
));
36 } catch (IOException e
) {
37 throw new AssertionError(e
);
42 public void storePreKey(int preKeyId
, PreKeyRecord
record) {
43 store
.put(preKeyId
, record.serialize());
47 public boolean containsPreKey(int preKeyId
) {
48 return store
.containsKey(preKeyId
);
52 public void removePreKey(int preKeyId
) {
53 store
.remove(preKeyId
);
56 public static class JsonPreKeyStoreDeserializer
extends JsonDeserializer
<JsonPreKeyStore
> {
59 public JsonPreKeyStore
deserialize(JsonParser jsonParser
, DeserializationContext deserializationContext
) throws IOException
, JsonProcessingException
{
60 JsonNode node
= jsonParser
.getCodec().readTree(jsonParser
);
62 Map
<Integer
, byte[]> preKeyMap
= new HashMap
<>();
64 for (JsonNode preKey
: node
) {
65 Integer preKeyId
= preKey
.get("id").asInt();
67 preKeyMap
.put(preKeyId
, Base64
.decode(preKey
.get("record").asText()));
68 } catch (IOException e
) {
69 System
.out
.println(String
.format("Error while decoding prekey for: %s", preKeyId
));
74 JsonPreKeyStore keyStore
= new JsonPreKeyStore();
75 keyStore
.addPreKeys(preKeyMap
);
82 public static class JsonPreKeyStoreSerializer
extends JsonSerializer
<JsonPreKeyStore
> {
85 public void serialize(JsonPreKeyStore jsonPreKeyStore
, JsonGenerator json
, SerializerProvider serializerProvider
) throws IOException
, JsonProcessingException
{
86 json
.writeStartArray();
87 for (Map
.Entry
<Integer
, byte[]> preKey
: jsonPreKeyStore
.store
.entrySet()) {
88 json
.writeStartObject();
89 json
.writeNumberField("id", preKey
.getKey());
90 json
.writeStringField("record", Base64
.encodeBytes(preKey
.getValue()));
91 json
.writeEndObject();