Skip to content

Commit

Permalink
feat: add timestamp to prepared messages
Browse files Browse the repository at this point in the history
  • Loading branch information
dmccartney committed Sep 11, 2023
1 parent 6c3fb33 commit d912adb
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -352,11 +352,13 @@ class XMTPModule : Module() {
content = sending.content,
options = SendOptions(contentType = sending.type)
)
val preparedAtMillis = prepared.envelopes[0].timestampNs / 1_000_000
val preparedFile = File.createTempFile(prepared.messageId, null)
preparedFile.writeBytes(prepared.toSerializedData())
PreparedLocalMessage(
messageId = prepared.messageId,
preparedFileUri = preparedFile.toURI().toString(),
preparedAt = preparedAtMillis,
).toJson()
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,22 @@ import com.google.gson.JsonParser
class PreparedLocalMessage(
val messageId: String,
val preparedFileUri: String,
val preparedAt: Long,
) {
companion object {
fun fromJson(json: String): PreparedLocalMessage {
val obj = JsonParser.parseString(json).asJsonObject
return PreparedLocalMessage(
obj.get("messageId").asString,
obj.get("preparedFileUri").asString,
obj.get("preparedAt").asNumber.toLong(),
)
}
}

fun toJson(): String = GsonBuilder().create().toJson(mapOf(
"messageId" to messageId,
"preparedFileUri" to preparedFileUri,
"preparedAt" to preparedAt,
))
}
3 changes: 3 additions & 0 deletions example/src/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ test("canPrepareMessage", async () => {
await delayToPropogate();

const prepared = await bobConversation.prepareMessage("hi");
if (!prepared.preparedAt) {
throw new Error("missing `preparedAt` on prepared message");
}

// Either of these should work:
await bobConversation.sendPreparedMessage(prepared);
Expand Down
7 changes: 5 additions & 2 deletions ios/Wrappers/DecodedMessageWrapper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -273,20 +273,23 @@ struct DecryptedLocalAttachment {
struct PreparedLocalMessage {
var messageId: String
var preparedFileUri: String
var preparedAt: UInt64

static func fromJson(_ json: String) throws -> PreparedLocalMessage {
let data = json.data(using: .utf8)!
let obj = (try? JSONSerialization.jsonObject(with: data) as? [String: Any]) ?? [:]
return PreparedLocalMessage(
messageId: obj["messageId"] as? String ?? "",
preparedFileUri: obj["preparedFileUri"] as? String ?? ""
preparedFileUri: obj["preparedFileUri"] as? String ?? "",
preparedAt: UInt64(truncating: obj["preparedAt"] as? NSNumber ?? 0)
)
}

func toJson() throws -> String {
let obj: [String: Any] = [
"messageId": messageId,
"preparedFileUri": preparedFileUri
"preparedFileUri": preparedFileUri,
"preparedAt": preparedAt
]
return try obj.toJson()
}
Expand Down
52 changes: 36 additions & 16 deletions ios/XMTPModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ public class XMTPModule: Module {
)
let encoded = try RemoteAttachment.decryptEncoded(encrypted: encrypted)
let attachment: Attachment = try encoded.decoded()
let file = FileManager.default.temporaryDirectory.appendingPathComponent(attachment.filename)
let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try attachment.data.write(to: file)
return try DecryptedLocalAttachment(
fileUri: file.absoluteString,
Expand Down Expand Up @@ -254,9 +254,14 @@ public class XMTPModule: Module {
before: beforeDate,
after: afterDate)

let messages = try decodedMessages.map { (msg) in try DecodedMessageWrapper.encode(msg) }

return messages
return decodedMessages.compactMap { (msg) in
do {
return try DecodedMessageWrapper.encode(msg)
} catch {
print("discarding message, unable to encode wrapper \(msg.id)")
return nil
}
}
}

AsyncFunction("loadBatchMessages") { (clientAddress: String, topics: [String]) -> [String] in
Expand Down Expand Up @@ -299,9 +304,14 @@ public class XMTPModule: Module {

let decodedMessages = try await client.conversations.listBatchMessages(topics: topicsList)

let messages = try decodedMessages.map { (msg) in try DecodedMessageWrapper.encode(msg) }

return messages
return decodedMessages.compactMap { (msg) in
do {
return try DecodedMessageWrapper.encode(msg)
} catch {
print("discarding message, unable to encode wrapper \(msg.id)")
return nil
}
}
}

AsyncFunction("sendMessage") { (clientAddress: String, conversationTopic: String, contentJson: String) -> String in
Expand Down Expand Up @@ -329,12 +339,14 @@ public class XMTPModule: Module {
content: sending.content,
options: SendOptions(contentType: sending.type)
)
let preparedAtMillis = prepared.envelopes[0].timestampNs / 1_000_000
let preparedData = try prepared.serializedData()
let preparedFile = FileManager.default.temporaryDirectory.appendingPathComponent(prepared.messageID)
try preparedData.write(to: preparedFile)
return try PreparedLocalMessage(
messageId: prepared.messageID,
preparedFileUri: preparedFile.absoluteString
preparedFileUri: preparedFile.absoluteString,
preparedAt: preparedAtMillis
).toJson()
}

Expand Down Expand Up @@ -515,10 +527,14 @@ public class XMTPModule: Module {
subscriptions["messages"] = Task {
do {
for try await message in try await client.conversations.streamAllMessages() {
sendEvent("message", [
"clientAddress": clientAddress,
"message": try DecodedMessageWrapper.encodeToObj(message)
])
do {
sendEvent("message", [
"clientAddress": clientAddress,
"message": try DecodedMessageWrapper.encodeToObj(message)
])
} catch {
print("discarding message, unable to encode wrapper \(message.id)")
}
}
} catch {
print("Error in all messages subscription: \(error)")
Expand All @@ -536,10 +552,14 @@ public class XMTPModule: Module {
subscriptions[conversation.cacheKey(clientAddress)] = Task {
do {
for try await message in conversation.streamMessages() {
sendEvent("message", [
"clientAddress": clientAddress,
"message": try DecodedMessageWrapper.encodeToObj(message)
])
do {
sendEvent("message", [
"clientAddress": clientAddress,
"message": try DecodedMessageWrapper.encodeToObj(message)
])
} catch {
print("discarding message, unable to encode wrapper \(message.id)")
}
}
} catch {
print("Error in messages subscription: \(error)")
Expand Down
1 change: 1 addition & 0 deletions src/XMTP.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ export type RemoteAttachmentContent = RemoteAttachmentMetadata & {
export type PreparedLocalMessage = {
messageId: string;
preparedFileUri: `file://${string}`;
preparedAt: number; // timestamp in milliseconds
}

// This contains the contents of a message.
Expand Down

0 comments on commit d912adb

Please sign in to comment.