anbot

78ef64a / social-store.mjs

View file at this commit

diff --git a/social-store.mjs b/social-store.mjs
index 959a402..c43b729 100644
--- a/social-store.mjs
+++ b/social-store.mjs
@@ -1,15 +1,38 @@
 import { mkdirSync, readdirSync, readFileSync } from 'node:fs'
 import { join } from 'node:path'
 import { createPost, verifyPost } from './social.mjs'
-import { parseJson, persist, recordPath, requireThat, syncDirectory } from './storage.mjs'
+import { createFsStore, parseJson, recordPath, requireThat, syncDirectory } from './storage.mjs'
 
 export async function publishPost(root, identity, text, replyTo) {
   const record = await createPost(identity, text, replyTo)
+  await storePost(root, record)
+  return record.id
+}
+
+export async function storePost(root, { id, signature, content }) {
   const directory = join(root, 'posts')
   mkdirSync(directory, { mode: 0o700, recursive: true })
   syncDirectory(root)
-  persist(directory, recordPath(record.id), JSON.stringify(record))
-  return record.id
+  const store = createFsStore(root)
+  if (await store.putPost(id, Buffer.from(JSON.stringify({ id, signature, content })))) return true
+  const existing = parseJson(await store.getPost(id))
+  requireThat(existing.id === id && existing.signature === signature && existing.content === content,
+    'Stored post does not match its record ID')
+  return false
+}
+
+export async function submitPost(root, identity, id, url) {
+  const bytes = await createFsStore(root).getPost(id)
+  requireThat(bytes, 'Local post not found')
+  const post = await verifyPost(parseJson(bytes))
+  requireThat(post.id === id && post.author === identity.author, 'Post must be signed by this identity')
+  const endpoint = new URL('/posts', url.origin)
+  const response = await fetch(endpoint, {
+    method: 'POST', headers: { 'Content-Type': 'application/json' }, body: bytes,
+    redirect: 'error', signal: AbortSignal.timeout(15000)
+  })
+  requireThat(response.ok, `Post submission failed (HTTP ${response.status})`)
+  requireThat((await response.json()).id === id, 'Server returned the wrong post ID')
 }
 
 export async function readFeed(root) {

Git ยท Social feed