tauri-app: 8a review fixes
- fetchBlob cache keyed by (did, cid), not just cid. Security: future per-DID access control on getBlob would otherwise leak the first responder's bytes to subsequent viewers. - EmbedImage: pass did to releaseBlob, release previous cid on cid change (no leaked URLs). - ComposeBox: releaseBlob called with both did and cid. - pds-server: rename test get_blob_after_upload_with_different_did -> get_blob_returns_404_for_cross_did_cid_lookup. The docstring was misleading — the test only verifies the (did,cid) PK on the PDS row, not auth. The renamed name matches what the test actually checks. - vitest: update releaseBlob call sites to the new (did, cid) signature.
This commit is contained in:
@@ -112,15 +112,24 @@ async fn current_session(state: tauri::State<'_, AppState>) -> Result<Option<Acc
|
||||
async fn post_create(
|
||||
state: tauri::State<'_, AppState>,
|
||||
text: String,
|
||||
embed: Option<serde_json::Value>,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
let sess = state
|
||||
.store
|
||||
.load()
|
||||
.ok_or_else(|| "not logged in".to_string())?;
|
||||
let record = serde_json::json!({
|
||||
let mut record = serde_json::json!({
|
||||
"text": text,
|
||||
"createdAt": chrono::Utc::now().to_rfc3339(),
|
||||
});
|
||||
if let Some(emb) = embed {
|
||||
// Only attach when the caller passes a non-null object — null
|
||||
// / missing means "no embed". The lexicon's `embed` field is
|
||||
// optional, so leaving it absent is the safe default.
|
||||
if !emb.is_null() {
|
||||
record["embed"] = emb;
|
||||
}
|
||||
}
|
||||
let resp = state
|
||||
.pds
|
||||
.create_record(&sess.did, "app.twi.post", record, &sess.access_jwt)
|
||||
@@ -348,6 +357,115 @@ async fn fetch_blob(
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// `pick_and_upload_image()` — open a native file picker, read the
|
||||
/// chosen file, and upload its bytes to the user's PDS via
|
||||
/// `com.atproto.uploadBlob`.
|
||||
///
|
||||
/// Returns the parsed `com.atproto.uploadBlob` response verbatim —
|
||||
/// `{ blob: { $type, ref: { $link }, mimeType, size } }` — so the
|
||||
/// frontend can drop the blob reference straight into a record's
|
||||
/// `embed.images[].image` field. Returns `None` when the user
|
||||
/// cancels the dialog.
|
||||
///
|
||||
/// MIME-type resolution:
|
||||
/// 1. Sniff the file extension (`.png` → `image/png`, `.jpg`/`.jpeg`
|
||||
/// → `image/jpeg`, `.gif` → `image/gif`, `.webp` → `image/webp`).
|
||||
/// 2. If the extension is unknown, fall back to
|
||||
/// `application/octet-stream`. The PDS will then re-sniff via
|
||||
/// its magic-byte detector (`at_blob::detect_mime`).
|
||||
///
|
||||
/// Size cap: the dialog plugin's selection isn't bounded; the PDS
|
||||
/// enforces a 1 MiB body limit (`MAX_BLOB_SIZE` in
|
||||
/// `pds-server/src/routes/blob.rs`) and returns 413 if exceeded.
|
||||
/// We pre-check here so we can surface a clean error before the
|
||||
/// upload round trip.
|
||||
#[tauri::command]
|
||||
async fn pick_and_upload_image(
|
||||
app: tauri::AppHandle,
|
||||
state: tauri::State<'_, AppState>,
|
||||
) -> Result<Option<pds_client::UploadBlobResp>, String> {
|
||||
use tauri_plugin_dialog::DialogExt;
|
||||
|
||||
// Confirm we have a session — uploading without auth is a no-op
|
||||
// on the server side (401), but we'd rather tell the caller
|
||||
// upfront than surface a confusing PDS error.
|
||||
let sess = state
|
||||
.store
|
||||
.load()
|
||||
.ok_or_else(|| "not logged in".to_string())?;
|
||||
|
||||
// `blocking_pick_file` is the documented way to drive the
|
||||
// dialog plugin's file picker from a Tauri command. We constrain
|
||||
// the picker to common image extensions — a future change can
|
||||
// allow arbitrary file types if we add a video / audio embed
|
||||
// pipeline.
|
||||
let picked = app
|
||||
.dialog()
|
||||
.file()
|
||||
.add_filter("Image", &["png", "jpg", "jpeg", "gif", "webp"])
|
||||
.set_title("Attach image")
|
||||
.blocking_pick_file();
|
||||
|
||||
let Some(file_path) = picked else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
// The dialog plugin returns a `FilePath` enum (Path | Url). On
|
||||
// desktop we always get a path; the URL branch exists for the
|
||||
// mobile / scoped-access pickers but those don't apply here.
|
||||
let path = match file_path.into_path() {
|
||||
Ok(p) => p,
|
||||
Err(e) => return Err(format!("invalid picked file: {e}")),
|
||||
};
|
||||
|
||||
let bytes = tokio::fs::read(&path)
|
||||
.await
|
||||
.map_err(|e| format!("read {}: {e}", path.display()))?;
|
||||
|
||||
if bytes.is_empty() {
|
||||
return Err("picked file is empty".into());
|
||||
}
|
||||
// Mirror the PDS body cap (1 MiB) locally so we fail fast instead
|
||||
// of sending the request only to receive a 413.
|
||||
const MAX_BLOB_SIZE: usize = 1024 * 1024;
|
||||
if bytes.len() > MAX_BLOB_SIZE {
|
||||
return Err(format!(
|
||||
"file is {} bytes; max is {MAX_BLOB_SIZE}",
|
||||
bytes.len()
|
||||
));
|
||||
}
|
||||
|
||||
let mime = mime_from_extension(&path);
|
||||
let resp = state
|
||||
.pds
|
||||
.upload_blob(bytes, &mime, &sess.access_jwt)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(Some(resp))
|
||||
}
|
||||
|
||||
/// Map a file extension to a MIME type. Returns
|
||||
/// `application/octet-stream` when the extension is unrecognised —
|
||||
/// the PDS's magic-byte sniffer will take over from there.
|
||||
fn mime_from_extension(path: &std::path::Path) -> String {
|
||||
let ext = path
|
||||
.extension()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("")
|
||||
.to_ascii_lowercase();
|
||||
match ext.as_str() {
|
||||
"png" => "image/png",
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"gif" => "image/gif",
|
||||
"webp" => "image/webp",
|
||||
// The PDS still accepts the upload and stores the bytes; the
|
||||
// sniffed MIME type from magic-byte detection will fill in
|
||||
// `mime_type` server-side on the next getBlob.
|
||||
_ => "application/octet-stream",
|
||||
}
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Fire a native OS notification with an optional click target. The
|
||||
/// payload is also broadcast as an `app://notification` event so the
|
||||
/// frontend can route to `url` on click (via a notification listener
|
||||
@@ -514,6 +632,7 @@ pub fn run() {
|
||||
unrepost_post,
|
||||
status_pds,
|
||||
fetch_blob,
|
||||
pick_and_upload_image,
|
||||
show_notification,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
|
||||
@@ -322,4 +322,66 @@ impl PdsHttpClient {
|
||||
let bytes = resp.bytes().await?;
|
||||
Ok(bytes.to_vec())
|
||||
}
|
||||
|
||||
/// `POST /xrpc/com.atproto.uploadBlob`
|
||||
///
|
||||
/// Authenticated; the server derives the DID from the JWT `sub`
|
||||
/// claim and writes the block to `(did, sha256(cid))` in
|
||||
/// `repo_blocks`. The body is the raw blob bytes and the
|
||||
/// `Content-Type` header is mandatory — the PDS uses it as the
|
||||
/// authoritative MIME type for the row.
|
||||
///
|
||||
/// Returns the parsed `com.atproto.uploadBlob` response verbatim:
|
||||
/// `{ blob: { $type, ref: { $link }, mimeType, size } }`. The
|
||||
/// caller is expected to forward this to the Svelte UI so it can
|
||||
/// drop the blob ref straight into a record's `embed.images[]`.
|
||||
pub async fn upload_blob(
|
||||
&self,
|
||||
bytes: Vec<u8>,
|
||||
content_type: &str,
|
||||
jwt: &str,
|
||||
) -> Result<UploadBlobResp> {
|
||||
let resp = self
|
||||
.client
|
||||
.post(format!("{}/xrpc/com.atproto.uploadBlob", self.base_url))
|
||||
.bearer_auth(jwt)
|
||||
.header(reqwest::header::CONTENT_TYPE, content_type)
|
||||
.body(bytes)
|
||||
.send()
|
||||
.await?;
|
||||
if !resp.status().is_success() {
|
||||
let status = resp.status();
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
anyhow::bail!("uploadBlob failed: {} {}", status, body);
|
||||
}
|
||||
Ok(resp.json::<UploadBlobResp>().await?)
|
||||
}
|
||||
}
|
||||
|
||||
/// `com.atproto.uploadBlob` response. Spec'd at
|
||||
/// <https://atproto.com/specs/blob>. The server returns a `blob`
|
||||
/// object that mirrors what an `app.bsky.embed.images#image` entry
|
||||
/// expects on the wire — the Tauri command forwards this verbatim so
|
||||
/// the UI can drop it into the post record with no further
|
||||
/// transformation.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct UploadBlobResp {
|
||||
pub blob: UploadedBlob,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct UploadedBlob {
|
||||
#[serde(rename = "$type")]
|
||||
pub ty: String,
|
||||
#[serde(rename = "ref")]
|
||||
pub blob_ref: UploadedBlobRef,
|
||||
#[serde(rename = "mimeType")]
|
||||
pub mime_type: String,
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct UploadedBlobRef {
|
||||
#[serde(rename = "$link")]
|
||||
pub link: String,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
// Unit tests for the image-blob fetch pipeline in `client.ts`.
|
||||
// We mock `@tauri-apps/api/core` so we don't need a running Tauri
|
||||
// shell for the test, and we mock `URL.createObjectURL` /
|
||||
// `URL.revokeObjectURL` so the test doesn't depend on a browser
|
||||
// implementation (vitest's jsdom doesn't always wire these up).
|
||||
//
|
||||
// The tests cover:
|
||||
// * the happy path — a successful `fetch_blob` invoke produces an
|
||||
// object URL and the cache is populated so a second call is a no-op;
|
||||
// * the cached path — a second `fetchBlob` for the same CID does not
|
||||
// call `invoke` again;
|
||||
// * the empty-blob error path — an empty payload throws;
|
||||
// * `releaseBlob` / `clearBlobCache` keep the cache honest.
|
||||
//
|
||||
// Run with:
|
||||
// npm test
|
||||
// (or `npx vitest run src/lib/api/client.test.ts`)
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const invokeMock = vi.fn();
|
||||
|
||||
vi.mock("@tauri-apps/api/core", () => ({
|
||||
invoke: (...args: unknown[]) => invokeMock(...args),
|
||||
}));
|
||||
|
||||
// Capture object URLs so the test can assert the cache is wired up.
|
||||
// `createObjectURL` returns a fresh URL per call; tests should rely
|
||||
// on the spy to know what URL was returned.
|
||||
const createdUrls: string[] = [];
|
||||
let _urlCounter = 0;
|
||||
|
||||
beforeEach(() => {
|
||||
invokeMock.mockReset();
|
||||
createdUrls.length = 0;
|
||||
_urlCounter = 0;
|
||||
|
||||
// `URL.createObjectURL` exists in jsdom (vitest default) but
|
||||
// returns the empty string — stub it so the test sees real-ish
|
||||
// URLs and we can spot leaks.
|
||||
vi.stubGlobal(
|
||||
"URL",
|
||||
class {
|
||||
static createObjectURL(_blob: Blob): string {
|
||||
const u = `blob:mock/${++_urlCounter}`;
|
||||
createdUrls.push(u);
|
||||
return u;
|
||||
}
|
||||
static revokeObjectURL(url: string): void {
|
||||
const i = createdUrls.indexOf(url);
|
||||
if (i >= 0) createdUrls.splice(i, 1);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("fetchBlob", () => {
|
||||
it("invokes the fetch_blob Tauri command and returns an object URL", async () => {
|
||||
const { fetchBlob, clearBlobCache } = await import("./client");
|
||||
clearBlobCache();
|
||||
|
||||
const cid = "bafyreifake";
|
||||
const fakeBytes = new Uint8Array([1, 2, 3, 4]);
|
||||
invokeMock.mockResolvedValueOnce(Array.from(fakeBytes));
|
||||
|
||||
const url = await fetchBlob("did:plc:alice", cid);
|
||||
|
||||
expect(url).toMatch(/^blob:mock\/\d+$/);
|
||||
expect(createdUrls).toContain(url);
|
||||
expect(invokeMock).toHaveBeenCalledTimes(1);
|
||||
expect(invokeMock).toHaveBeenCalledWith("fetch_blob", {
|
||||
did: "did:plc:alice",
|
||||
cid,
|
||||
});
|
||||
});
|
||||
|
||||
it("caches the object URL — second call for the same cid is a no-op", async () => {
|
||||
const { fetchBlob, clearBlobCache } = await import("./client");
|
||||
clearBlobCache();
|
||||
|
||||
const cid = "bafyreicached";
|
||||
invokeMock.mockResolvedValueOnce(Array.from(new Uint8Array([9, 9, 9])));
|
||||
|
||||
const first = await fetchBlob("did:plc:bob", cid);
|
||||
const second = await fetchBlob("did:plc:bob", cid);
|
||||
|
||||
expect(second).toBe(first);
|
||||
// Only the first call should have round-tripped through the
|
||||
// Tauri shell; the cache hit short-circuits everything else.
|
||||
expect(invokeMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("rejects on an empty payload from the Tauri shell", async () => {
|
||||
const { fetchBlob, clearBlobCache } = await import("./client");
|
||||
clearBlobCache();
|
||||
|
||||
invokeMock.mockResolvedValueOnce([]);
|
||||
await expect(
|
||||
fetchBlob("did:plc:carol", "bafyreifake"),
|
||||
).rejects.toThrow(/empty blob/);
|
||||
});
|
||||
|
||||
it("propagates a Tauri-side error verbatim", async () => {
|
||||
const { fetchBlob, clearBlobCache } = await import("./client");
|
||||
clearBlobCache();
|
||||
|
||||
invokeMock.mockRejectedValueOnce(new Error("sync.getBlob failed: 400"));
|
||||
await expect(
|
||||
fetchBlob("did:plc:dave", "bafyreifake"),
|
||||
).rejects.toThrow(/sync\.getBlob failed: 400/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("releaseBlob / clearBlobCache", () => {
|
||||
it("drops the cached URL on releaseBlob", async () => {
|
||||
const { fetchBlob, releaseBlob, clearBlobCache } = await import("./client");
|
||||
clearBlobCache();
|
||||
|
||||
invokeMock.mockResolvedValueOnce(Array.from(new Uint8Array([1])));
|
||||
const cid = "bafyreirel";
|
||||
const url = await fetchBlob("did:plc:e", cid);
|
||||
expect(createdUrls).toContain(url);
|
||||
|
||||
releaseBlob("did:plc:e", cid);
|
||||
expect(createdUrls).not.toContain(url);
|
||||
});
|
||||
|
||||
it("clearBlobCache evicts every cached URL", async () => {
|
||||
const { fetchBlob, clearBlobCache } = await import("./client");
|
||||
clearBlobCache();
|
||||
|
||||
invokeMock.mockResolvedValueOnce(Array.from(new Uint8Array([1])));
|
||||
invokeMock.mockResolvedValueOnce(Array.from(new Uint8Array([2])));
|
||||
|
||||
await fetchBlob("did:plc:f", "bafyreia");
|
||||
await fetchBlob("did:plc:f", "bafyreib");
|
||||
expect(createdUrls).toHaveLength(2);
|
||||
|
||||
clearBlobCache();
|
||||
expect(createdUrls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("makeImagesEmbed", () => {
|
||||
it("wraps a blob reference in an app.bsky.embed.images embed", async () => {
|
||||
const { makeImagesEmbed } = await import("./client");
|
||||
const blob = { cid: "bafyreicid", mimeType: "image/png", size: 42 };
|
||||
const e = makeImagesEmbed(blob) as any;
|
||||
expect(e.$type).toBe("app.bsky.embed.images");
|
||||
expect(e.images).toHaveLength(1);
|
||||
expect(e.images[0].image.$type).toBe("blob");
|
||||
expect(e.images[0].image.ref.$link).toBe("bafyreicid");
|
||||
expect(e.images[0].image.mimeType).toBe("image/png");
|
||||
expect(e.images[0].image.size).toBe(42);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pickAndUploadImage", () => {
|
||||
it("returns null when the user cancels the picker", async () => {
|
||||
const { pickAndUploadImage } = await import("./client");
|
||||
invokeMock.mockResolvedValueOnce(null);
|
||||
const r = await pickAndUploadImage();
|
||||
expect(r).toBeNull();
|
||||
// `invoke` is called with the command name and an empty
|
||||
// argument bag (the Tauri runtime serialises the JS-side
|
||||
// options, and `pick_and_upload_image` takes none).
|
||||
expect(invokeMock).toHaveBeenCalledTimes(1);
|
||||
expect(invokeMock.mock.calls[0][0]).toBe("pick_and_upload_image");
|
||||
});
|
||||
|
||||
it("returns the parsed {cid, mimeType, size} on success", async () => {
|
||||
const { pickAndUploadImage } = await import("./client");
|
||||
invokeMock.mockResolvedValueOnce({
|
||||
blob: {
|
||||
$type: "blob",
|
||||
ref: { $link: "bafyblob" },
|
||||
mimeType: "image/jpeg",
|
||||
size: 1234,
|
||||
},
|
||||
});
|
||||
const r = await pickAndUploadImage();
|
||||
expect(r).toEqual({
|
||||
cid: "bafyblob",
|
||||
mimeType: "image/jpeg",
|
||||
size: 1234,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -135,11 +135,71 @@ export type ThreadResponse = {
|
||||
repost_count?: number;
|
||||
};
|
||||
|
||||
export async function createPost(text: string): Promise<Post> {
|
||||
export async function createPost(
|
||||
text: string,
|
||||
embed?: unknown | null,
|
||||
): Promise<Post> {
|
||||
// The Rust post_create command returns a different shape (uri+cid
|
||||
// only), but we keep the call simple: it gives us the cid we need
|
||||
// to show the "ok" toast.
|
||||
return await invoke<any>("post_create", { text });
|
||||
// `embed` is forwarded verbatim; the caller is responsible for
|
||||
// shaping it as an `app.bsky.embed.images` / `.external` / etc.
|
||||
// record. Pass `null` or `undefined` to omit.
|
||||
return await invoke<any>("post_create", {
|
||||
text,
|
||||
embed: embed ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
/// `com.atproto.uploadBlob` wrapped with a file picker. Opens a
|
||||
/// native OS dialog (via `tauri-plugin-dialog`), uploads the chosen
|
||||
/// file to the user's PDS, and returns the parsed blob reference.
|
||||
///
|
||||
/// Returns `null` when the user cancels the picker. The Tauri shell
|
||||
/// enforces a 1 MiB cap (matching the PDS's `MAX_BLOB_SIZE`) and
|
||||
/// surfaces other errors via the rejected promise.
|
||||
export async function pickAndUploadImage(): Promise<{
|
||||
cid: string;
|
||||
mimeType: string;
|
||||
size: number;
|
||||
} | null> {
|
||||
const r = await invoke<{
|
||||
blob: {
|
||||
$type: string;
|
||||
ref: { $link: string };
|
||||
mimeType: string;
|
||||
size: number;
|
||||
};
|
||||
} | null>("pick_and_upload_image");
|
||||
if (!r) return null;
|
||||
return {
|
||||
cid: r.blob.ref.$link,
|
||||
mimeType: r.blob.mimeType,
|
||||
size: r.blob.size,
|
||||
};
|
||||
}
|
||||
|
||||
/// Helper that builds the `app.bsky.embed.images` embed for a single
|
||||
/// image blob, ready to drop into a post record.
|
||||
export function makeImagesEmbed(blob: {
|
||||
cid: string;
|
||||
mimeType: string;
|
||||
size: number;
|
||||
}): Record<string, unknown> {
|
||||
return {
|
||||
$type: "app.bsky.embed.images",
|
||||
images: [
|
||||
{
|
||||
alt: "",
|
||||
image: {
|
||||
$type: "blob",
|
||||
ref: { $link: blob.cid },
|
||||
mimeType: blob.mimeType,
|
||||
size: blob.size,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
export async function describeServer(): Promise<any> {
|
||||
@@ -294,23 +354,31 @@ export async function listenNotification(
|
||||
// frontend never has to know the PDS URL.
|
||||
//
|
||||
// We cache the *resolved object URL* (not the raw bytes) keyed
|
||||
// by CID, because:
|
||||
// * the blob bytes are addressed by content hash, so the same
|
||||
// CID always resolves to the same bytes regardless of DID;
|
||||
// by `(did, cid)`, NOT just `cid`:
|
||||
// * the blob *bytes* are addressed by content hash, so the same
|
||||
// CID *usually* resolves to the same bytes regardless of DID;
|
||||
// * BUT in the atproto sync spec, `com.atproto.sync.getBlob` is
|
||||
// intentionally unauthenticated and keyed by `(did, cid)` on
|
||||
// the server. A future change to a per-DID access control
|
||||
// model would make the bytes differ per DID — caching by CID
|
||||
// alone would then leak the first responder's bytes to every
|
||||
// subsequent viewer.
|
||||
// * the `<img>` element takes an object URL, not raw bytes, so
|
||||
// handing the URL straight back to the caller saves a
|
||||
// Blob/URL.createObjectURL call per render.
|
||||
const _blobUrlCache = new Map<string, string>();
|
||||
const _blobKey = (did: string, cid: string) => `${did}/${cid}`;
|
||||
|
||||
/// Fetch the raw blob bytes for `cid` and return an object URL
|
||||
/// suitable for `<img src={...}>`. Caches the URL in-process so
|
||||
/// navigating the timeline doesn't re-download already-seen
|
||||
/// images.
|
||||
/// images. Keyed by `(did, cid)` for the security reason above.
|
||||
export async function fetchBlob(
|
||||
did: string,
|
||||
cid: string,
|
||||
): Promise<string> {
|
||||
const cached = _blobUrlCache.get(cid);
|
||||
const key = _blobKey(did, cid);
|
||||
const cached = _blobUrlCache.get(key);
|
||||
if (cached) return cached;
|
||||
const bytes: number[] = await invoke<number[]>("fetch_blob", {
|
||||
did,
|
||||
@@ -322,7 +390,7 @@ export async function fetchBlob(
|
||||
}
|
||||
const blob = new Blob([u8]);
|
||||
const url = URL.createObjectURL(blob);
|
||||
_blobUrlCache.set(cid, url);
|
||||
_blobUrlCache.set(key, url);
|
||||
return url;
|
||||
}
|
||||
|
||||
@@ -331,11 +399,11 @@ export async function fetchBlob(
|
||||
/// underlying Blob. For a Tauri WebView with at most a few
|
||||
/// dozen visible images the OS cleans up anyway, but explicit
|
||||
/// revocation makes long sessions friendlier on memory.
|
||||
export function releaseBlob(cid: string): void {
|
||||
const url = _blobUrlCache.get(cid);
|
||||
export function releaseBlob(did: string, cid: string): void {
|
||||
const url = _blobUrlCache.get(_blobKey(did, cid));
|
||||
if (url) {
|
||||
URL.revokeObjectURL(url);
|
||||
_blobUrlCache.delete(cid);
|
||||
_blobUrlCache.delete(_blobKey(did, cid));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,41 @@
|
||||
<script lang="ts">
|
||||
import { createPost, type Post } from "../api/client";
|
||||
import {
|
||||
createPost,
|
||||
fetchBlob,
|
||||
pickAndUploadImage,
|
||||
makeImagesEmbed,
|
||||
showError,
|
||||
releaseBlob,
|
||||
session,
|
||||
type Post,
|
||||
} from "../api/client";
|
||||
|
||||
const MAX = 160;
|
||||
let { onPosted }: { onPosted?: () => void } = $props();
|
||||
let text: string = $state("");
|
||||
let isPosting: boolean = $state(false);
|
||||
let isAttaching: boolean = $state(false);
|
||||
let status: { kind: "ok" | "err" | "info"; msg: string } | null = $state(null);
|
||||
|
||||
// Currently logged-in user. We need the DID for `fetchBlob` (the
|
||||
// PDS endpoint keys blobs by `(did, cid)`), so the compose box
|
||||
// subscribes to the session store rather than taking a prop.
|
||||
let did: string = $state("");
|
||||
$effect(() => {
|
||||
const u = $session;
|
||||
did = u?.did ?? "";
|
||||
});
|
||||
|
||||
// The currently-attached image. `null` = no attachment. We hold
|
||||
// the blob reference + a local object URL for the preview so the
|
||||
// user sees the image before they post.
|
||||
let attachment: {
|
||||
cid: string;
|
||||
mimeType: string;
|
||||
size: number;
|
||||
previewUrl: string;
|
||||
} | null = $state(null);
|
||||
|
||||
let remaining = $derived(MAX - text.length);
|
||||
let counterClass = $derived(
|
||||
remaining < 0 ? "counter counter--err" :
|
||||
@@ -20,17 +49,66 @@
|
||||
}
|
||||
}
|
||||
|
||||
function fmtBytes(n: number): string {
|
||||
if (n < 1024) return `${n} B`;
|
||||
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`;
|
||||
return `${(n / (1024 * 1024)).toFixed(2)} MiB`;
|
||||
}
|
||||
|
||||
async function attach() {
|
||||
if (isAttaching || attachment) return;
|
||||
if (!did) {
|
||||
status = { kind: "err", msg: "> log in first" };
|
||||
return;
|
||||
}
|
||||
isAttaching = true;
|
||||
status = { kind: "info", msg: "> picking…" };
|
||||
try {
|
||||
const blob = await pickAndUploadImage();
|
||||
if (!blob) {
|
||||
// User cancelled — restore the previous status rather than
|
||||
// leaving the "picking…" message on screen.
|
||||
status = null;
|
||||
return;
|
||||
}
|
||||
// Fetch the bytes back from the PDS so we can render the
|
||||
// preview. `fetchBlob` caches by CID, so re-rendering the
|
||||
// preview after a re-attach is cheap.
|
||||
const previewUrl = await fetchBlob(did, blob.cid);
|
||||
attachment = { ...blob, previewUrl };
|
||||
status = { kind: "info", msg: `> attached (${fmtBytes(blob.size)})` };
|
||||
} catch (e) {
|
||||
status = { kind: "err", msg: `> ${String(e)}` };
|
||||
} finally {
|
||||
isAttaching = false;
|
||||
}
|
||||
}
|
||||
|
||||
function removeAttachment() {
|
||||
if (attachment) {
|
||||
// Revoke the object URL. `fetchBlob` may have evicted the
|
||||
// cache entry for a different reason, so tolerate a no-op.
|
||||
// The user can re-attach — the next fetch will allocate a
|
||||
// fresh URL.
|
||||
releaseBlob(did, attachment.cid);
|
||||
attachment = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function post() {
|
||||
if (!text.trim() || remaining < 0 || isPosting) return;
|
||||
isPosting = true;
|
||||
status = { kind: "info", msg: "> posting…" };
|
||||
try {
|
||||
const r: Post = await createPost(text);
|
||||
const embed = attachment ? makeImagesEmbed(attachment) : null;
|
||||
const r: Post = await createPost(text, embed);
|
||||
status = { kind: "ok", msg: `> ok (cid: ${(r as any).cid?.slice?.(0, 8) ?? "?"}…)` };
|
||||
text = "";
|
||||
removeAttachment();
|
||||
onPosted?.();
|
||||
} catch (e) {
|
||||
status = { kind: "err", msg: `> ${String(e)}` };
|
||||
showError(`post failed: ${e}`);
|
||||
} finally {
|
||||
isPosting = false;
|
||||
}
|
||||
@@ -53,9 +131,39 @@
|
||||
maxlength="500"
|
||||
></textarea>
|
||||
</div>
|
||||
{#if attachment}
|
||||
<div class="compose__attach">
|
||||
<img
|
||||
class="compose__preview"
|
||||
src={attachment.previewUrl}
|
||||
alt="attachment preview"
|
||||
/>
|
||||
<div class="compose__attach-meta">
|
||||
<span class="compose__attach-cid" title={attachment.cid}>cid: {attachment.cid.slice(0, 10)}…</span>
|
||||
<span class="compose__attach-mime">{attachment.mimeType}</span>
|
||||
<span class="compose__attach-size">{fmtBytes(attachment.size)}</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="compose__attach-remove"
|
||||
onclick={removeAttachment}
|
||||
disabled={isPosting}
|
||||
title="remove attachment"
|
||||
>×</button>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="compose__foot">
|
||||
<span class="hint">⌘↵ to post</span>
|
||||
<div class="actions">
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn--ghost"
|
||||
onclick={attach}
|
||||
disabled={isAttaching || !!attachment || isPosting}
|
||||
title={attachment ? "image already attached" : "attach image"}
|
||||
>
|
||||
{isAttaching ? "picking…" : "📎"}
|
||||
</button>
|
||||
<button class="btn btn--ghost" onclick={() => (text = "")} disabled={!text || isPosting}>draft</button>
|
||||
<button class="btn btn--primary" onclick={post} disabled={!text.trim() || remaining < 0 || isPosting}>
|
||||
{isPosting ? "posting…" : "post"}
|
||||
@@ -114,6 +222,51 @@
|
||||
padding: 0;
|
||||
}
|
||||
textarea::placeholder { color: var(--text-dim); }
|
||||
.compose__attach {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--s-3);
|
||||
padding: var(--s-3) var(--s-4);
|
||||
background: var(--bg-deep);
|
||||
border-top: 1px dashed var(--line);
|
||||
}
|
||||
.compose__preview {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
object-fit: cover;
|
||||
border-radius: var(--r-sm);
|
||||
border: 1px solid var(--line-2);
|
||||
background: var(--bg);
|
||||
}
|
||||
.compose__attach-meta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
flex: 1;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-50);
|
||||
color: var(--text-dim);
|
||||
}
|
||||
.compose__attach-cid { color: var(--cid-fg); }
|
||||
.compose__attach-mime,
|
||||
.compose__attach-size { font-variant-numeric: tabular-nums; }
|
||||
.compose__attach-remove {
|
||||
background: transparent;
|
||||
border: 1px solid var(--line-2);
|
||||
color: var(--text-dim);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-100);
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: var(--r-sm);
|
||||
cursor: pointer;
|
||||
line-height: 1;
|
||||
}
|
||||
.compose__attach-remove:hover:not(:disabled) {
|
||||
color: var(--red);
|
||||
border-color: var(--red);
|
||||
}
|
||||
.compose__attach-remove:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
.compose__foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -146,4 +299,4 @@
|
||||
.status--ok { color: var(--green); }
|
||||
.status--err { color: var(--red); }
|
||||
.status--info { color: var(--orange); }
|
||||
</style>
|
||||
</style>
|
||||
@@ -81,8 +81,8 @@
|
||||
// cache bounded to the visible images. The browser will
|
||||
// free the underlying blob either way when the WebView
|
||||
// navigates; this is just hygiene.
|
||||
if (currentCid) {
|
||||
releaseBlob(currentCid);
|
||||
if (currentCid && did) {
|
||||
releaseBlob(did, currentCid);
|
||||
currentCid = null;
|
||||
}
|
||||
objectUrl = null;
|
||||
|
||||
Reference in New Issue
Block a user