Skip to content

Commit

Permalink
Merge pull request #322 from xmtp-labs/rygine/objecturl-cache
Browse files Browse the repository at this point in the history
Add Blob cache for remote attachments
  • Loading branch information
rygine authored Jun 20, 2023
2 parents 941b11b + e3f83ac commit 88c3dd1
Showing 1 changed file with 22 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
RemoteAttachment,
RemoteAttachmentCodec,
} from "xmtp-content-type-remote-attachment";
import React from "react";
import { useClient } from "@xmtp/react-sdk";
import {
getContentTypeFromFileName,
Expand All @@ -25,6 +24,13 @@ type RemoteAttachmentMessageTileProps = {

type status = "unloaded" | "loadRequested" | "loading" | "loaded" | "error";

/**
* Creating object URLs from blobs is non-deterministic, so we store the
* generated URLs in a cache so that they can be reused, which results in
* a more consistent rendering of images/data and less memory usage.
*/
const blobCache = new WeakMap<Uint8Array, string>();

const RemoteAttachmentMessageTile = ({
content,
isSelf,
Expand All @@ -49,27 +55,34 @@ const RemoteAttachmentMessageTile = ({
client,
);

const objectURL = URL.createObjectURL(
new Blob([Buffer.from(attachment.data)], {
type: attachment.mimeType,
}),
);
if (!blobCache.get(attachment.data)) {
blobCache.set(
attachment.data,
URL.createObjectURL(
new Blob([Buffer.from(attachment.data)], {
type: attachment.mimeType,
}),
),
);
}

const objectURL = blobCache.get(attachment.data);

db.attachments
.add({
contentURL: content.url,
filename: attachment.filename,
mimetype: attachment.mimeType,
contentDataURL: objectURL,
contentDataURL: objectURL!,
})
.then(() => {
setURL(objectURL);
setURL(objectURL!);
setStatus("loaded");
})
.catch((e: Error) => {
// If error adding to cache, can silently fail and no need to display an error
console.log("Error caching image --> ", e);
setURL(objectURL);
setURL(objectURL!);
setStatus("loaded");
});
}
Expand Down

1 comment on commit 88c3dd1

@vercel
Copy link

@vercel vercel bot commented on 88c3dd1 Jun 20, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.