Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content-editor): upload an image or an author's photo instead of pasting its address (00272) (#1474)
Cihan7c6f904d6c5d
diff --git a/supabase/migrations/00272_content_images_storage.sql b/supabase/migrations/00272_content_images_storage.sqlnew file mode 100644index 000000000..899c125cd--- /dev/null+++ b/supabase/migrations/00272_content_images_storage.sql@@ -0,0 +1,46 @@+-- ============================================================================+-- 00272: Content images — upload an image instead of pasting its address+-- ============================================================================+-- Most people have the screenshot or photo on their computer, not at an+-- address. The Content Editor's image dialogs and an author's photo upload+-- it here: a public bucket (the page and the CMS show it by its address),+-- JPEG, PNG, WebP or GIF, 5 MB at most.+--+-- Each organization's images go under its own folder ({organization_id}/+-- {id}.{ext}). Members have no policy here: the app gives a one-time+-- upload address for a name it makes, and says who may upload and how+-- much (on the managed cloud, an organization with an active or trialing+-- subscription, a number a day; only the app knows a cloud from a+-- self-host). Nothing is overwritten or deleted from the app; anyone with+-- an image's address can see it, as any image on a published page.++insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types)+values (+ 'content-images',+ 'content-images',+ true,+ 5242880,+ array['image/jpeg', 'image/png', 'image/webp', 'image/gif']+)+-- Run again, it leaves the bucket as an admin may have set it.+on conflict (id) do nothing;++-- Each one-time upload address the app gives, on the managed cloud: the+-- day's cap counts them, not the files arrived (an address may be used+-- later). Only the service role reads and writes it.+create table if not exists public.content_image_uploads (+ id uuid primary key default gen_random_uuid(),+ organization_id uuid not null references public.organizations(id) on delete cascade,+ path text not null,+ created_at timestamptz not null default now()+);++create index if not exists content_image_uploads_org_created_idx+ on public.content_image_uploads (organization_id, created_at);++alter table public.content_image_uploads enable row level security;++comment on table public.content_image_uploads is+ 'Content images (00272): each one-time upload address given on the managed cloud, for the daily cap. Service role only.';++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 9879fa2fa..ff2ec3c89 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -39188,3 +39188,53 @@ create trigger content_drafts_author_confirmednotify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00272_content_images_storage.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00272: Content images — upload an image instead of pasting its address+-- ============================================================================+-- Most people have the screenshot or photo on their computer, not at an+-- address. The Content Editor's image dialogs and an author's photo upload+-- it here: a public bucket (the page and the CMS show it by its address),+-- JPEG, PNG, WebP or GIF, 5 MB at most.+--+-- Each organization's images go under its own folder ({organization_id}/+-- {id}.{ext}). Members have no policy here: the app gives a one-time+-- upload address for a name it makes, and says who may upload and how+-- much (on the managed cloud, an organization with an active or trialing+-- subscription, a number a day; only the app knows a cloud from a+-- self-host). Nothing is overwritten or deleted from the app; anyone with+-- an image's address can see it, as any image on a published page.++insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types)+values (+ 'content-images',+ 'content-images',+ true,+ 5242880,+ array['image/jpeg', 'image/png', 'image/webp', 'image/gif']+)+-- Run again, it leaves the bucket as an admin may have set it.+on conflict (id) do nothing;++-- Each one-time upload address the app gives, on the managed cloud: the+-- day's cap counts them, not the files arrived (an address may be used+-- later). Only the service role reads and writes it.+create table if not exists public.content_image_uploads (+ id uuid primary key default gen_random_uuid(),+ organization_id uuid not null references public.organizations(id) on delete cascade,+ path text not null,+ created_at timestamptz not null default now()+);++create index if not exists content_image_uploads_org_created_idx+ on public.content_image_uploads (organization_id, created_at);++alter table public.content_image_uploads enable row level security;++comment on table public.content_image_uploads is+ 'Content images (00272): each one-time upload address given on the managed cloud, for the daily cap. Service role only.';++notify pgrst, 'reload schema';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex e4844fa37..8435fff3c 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -5023,6 +5023,18 @@}},"content": {+ "imageUpload": {+ "button": "Upload from your computer",+ "uploading": "Uploading…",+ "hint": "JPG, PNG, WebP or GIF, up to 5 MB. Anyone with its address can see it, like any image on a web page.",+ "errors": {+ "type": "Use a JPG, PNG, WebP or GIF image.",+ "size": "That image is over 5 MB. Use a smaller one.",+ "plan": "Uploads come with an active plan. Paste the image's address instead.",+ "limit": "That's today's uploads for your workspace. Paste the image's address, or upload again tomorrow.",+ "failed": "Couldn't upload the image. Try again."+ }+ },"title": "Content Opportunities","description": "AI-powered content recommendations to improve your visibility in AI-generated answers.","opportunities": "Opportunities",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsxindex 05d0eaf10..4ed05c5dd 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx@@ -25,6 +25,7 @@ import {Trash2,type LucideIcon,} from 'lucide-react';+import { ImageUploadButton } from '@/components/content/image-upload-button';import { Button } from '@/components/ui/button';import {Dialog,@@ -438,9 +439,10 @@ function LinkDialog({ editor, onClose }: { editor: Editor; onClose: () => void });}-/** Insert an image by its address; uploads come with attachments (CE-006). */+/** Insert an image by its address, or uploaded from the person's computer (00272). */function ImageDialog({ editor, onClose }: { editor: Editor; onClose: () => void }) {const t = useTranslations('contentEditor.editor.image');+ const tUpload = useTranslations('content.imageUpload');const [src, setSrc] = useState('');const [alt, setAlt] = useState('');const [invalid, setInvalid] = useState(false);@@ -487,6 +489,17 @@ function ImageDialog({ editor, onClose }: { editor: Editor; onClose: () => void}}/>{invalid && <p className="text-xs text-destructive">{t('invalid')}</p>}+ {/* Or from their computer (00272): its address fills the field. */}+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">+ <ImageUploadButton+ className="h-7"+ onUploaded={(url) => {+ setSrc(url);+ setInvalid(false);+ }}+ />+ <span className="text-xs text-muted-foreground">{tUpload('hint')}</span>+ </div></div><div className="space-y-2"><Label htmlFor="content-image-alt">{t('altLabel')}</Label>diff --git a/web/src/components/content/image-upload-button.test.tsx b/web/src/components/content/image-upload-button.test.tsxnew file mode 100644index 000000000..dc6464ab2--- /dev/null+++ b/web/src/components/content/image-upload-button.test.tsx@@ -0,0 +1,80 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../messages/en.json';++const uploadContentImage = vi.fn();+vi.mock('@/lib/content/image-upload', async (importOriginal) => ({+ ...(await importOriginal()),+ uploadContentImage: (...args: unknown[]) => uploadContentImage(...args),+}));+const toast = vi.hoisted(() => Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn() }));+vi.mock('sonner', () => ({ toast }));++const { ImageUploadButton } = await import('./image-upload-button');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++/** Upload from your computer (00272): the image's address back for the field beside it. */++let container: HTMLDivElement;+let root: Root;+const onUploaded = vi.fn();++beforeEach(() => {+ uploadContentImage.mockReset();+ toast.error.mockReset();+ onUploaded.mockReset();+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});+afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++const render = () =>+ act(async () =>+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <ImageUploadButton onUploaded={onUploaded} />+ </NextIntlClientProvider>,+ ),+ );+const pick = (file: File) =>+ act(async () => {+ const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;+ Object.defineProperty(input, 'files', { value: [file], configurable: true });+ input.dispatchEvent(new Event('change', { bubbles: true }));+ });++describe('ImageUploadButton', () => {+ it('uploads the picked image and hands back its address', async () => {+ let done!: (value: unknown) => void;+ uploadContentImage.mockReturnValue(new Promise((resolve) => (done = resolve)));+ await render();+ const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;+ expect(input.accept).toBe('image/jpeg,image/png,image/webp,image/gif');+ expect(container.querySelector('button')!.textContent).toBe('Upload from your computer');+ const shot = new File(['x'], 'shot.png', { type: 'image/png' });+ await pick(shot);+ expect(uploadContentImage).toHaveBeenCalledWith(shot);+ // While it goes up: said, and not pressed again.+ expect(container.querySelector('button')!.textContent).toBe('Uploading…');+ expect(container.querySelector('button')!.disabled).toBe(true);+ await act(async () => done({ url: 'https://store.example/a.png' }));+ expect(onUploaded).toHaveBeenCalledWith('https://store.example/a.png');+ expect(container.querySelector('button')!.disabled).toBe(false);+ });++ it('says why an image didn’t go up', async () => {+ uploadContentImage.mockResolvedValue({ error: 'size' });+ await render();+ await pick(new File(['x'], 'big.png', { type: 'image/png' }));+ expect(toast.error).toHaveBeenCalledWith('That image is over 5 MB. Use a smaller one.');+ expect(onUploaded).not.toHaveBeenCalled();+ });+});diff --git a/web/src/components/content/image-upload-button.tsx b/web/src/components/content/image-upload-button.tsxnew file mode 100644index 000000000..74d63dd03--- /dev/null+++ b/web/src/components/content/image-upload-button.tsx@@ -0,0 +1,64 @@+'use client';++import { useRef, useState } from 'react';+import { useTranslations } from 'next-intl';+import { Upload } from 'lucide-react';+import { toast } from 'sonner';+import { Button } from '@/components/ui/button';+import { IMAGE_UPLOAD_ACCEPT, uploadContentImage } from '@/lib/content/image-upload';+import { cn } from '@/lib/utils';++/**+ * Upload from your computer (00272): picks an image, uploads it, and hands+ * back its public address for the field beside it. Says why a file can't+ * go up (its type, its size, the plan, the day's uploads made, or the+ * upload failing).+ */+export function ImageUploadButton({+ onUploaded,+ className,+}: {+ onUploaded: (url: string) => void;+ className?: string;+}) {+ const t = useTranslations('content.imageUpload');+ const input = useRef<HTMLInputElement>(null);+ const [uploading, setUploading] = useState(false);++ const upload = async (file: File | undefined) => {+ if (!file) return;+ setUploading(true);+ const result = await uploadContentImage(file);+ setUploading(false);+ // The same file can be picked again after a failure.+ if (input.current) input.current.value = '';+ if ('error' in result) {+ toast.error(t(`errors.${result.error}`));+ return;+ }+ onUploaded(result.url);+ };++ return (+ <>+ <input+ ref={input}+ type="file"+ accept={IMAGE_UPLOAD_ACCEPT}+ hidden+ onChange={(e) => void upload(e.target.files?.[0])}+ />+ <Button+ type="button"+ variant="outline"+ size="sm"+ className={cn('gap-1.5', className)}+ disabled={uploading}+ onClick={() => input.current?.click()}+ >+ <Upload aria-hidden className="h-3.5 w-3.5" />+ {uploading ? t('uploading') : t('button')}+ </Button>+ </>+ );+}diff --git a/web/src/components/settings/authors-section.tsx b/web/src/components/settings/authors-section.tsxindex 0058fd393..a992f4bfa 100644--- a/web/src/components/settings/authors-section.tsx+++ b/web/src/components/settings/authors-section.tsx@@ -6,6 +6,7 @@ import { toast } from 'sonner';import { Button } from '@/components/ui/button';import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';import { Checkbox } from '@/components/ui/checkbox';+import { ImageUploadButton } from '@/components/content/image-upload-button';import {Dialog,DialogClose,@@ -388,6 +389,7 @@ function AuthorDialog({onSaved: () => Promise<void>;}) {const t = useTranslations('settings.authors');+ const tUpload = useTranslations('content.imageUpload');const tCommon = useTranslations('common');const [form, setForm] = useState<{name: string;@@ -518,6 +520,14 @@ function AuthorDialog({aria-invalid={badPhoto}onChange={(e) => setForm({ ...form, photoUrl: e.target.value })}/>+ {/* Or the photo from their computer (00272): its address fills the field. */}+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">+ <ImageUploadButton+ className="h-7"+ onUploaded={(url) => setForm((prev) => ({ ...prev, photoUrl: url }))}+ />+ <span className="text-xs text-muted-foreground">{tUpload('hint')}</span>+ </div></div><div className="space-y-1"><label className="flex items-center gap-2 text-sm">diff --git a/web/src/lib/actions/content-images.test.ts b/web/src/lib/actions/content-images.test.tsnew file mode 100644index 000000000..03575e2cc--- /dev/null+++ b/web/src/lib/actions/content-images.test.ts@@ -0,0 +1,171 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** Who may upload an image and how much (00272): the app's gate, not the bucket's. */++let user: { id: string } | null;+let profile: { organization_id: string } | null;+let org: { subscription_status: string } | null;+vi.mock('@/lib/supabase/server', () => ({+ createClient: async () => ({+ auth: { getUser: async () => ({ data: { user } }) },+ from: (table: string) => {+ const chain = {+ select: () => chain,+ eq: () => chain,+ maybeSingle: async () => ({ data: table === 'profiles' ? profile : org, error: null }),+ };+ return chain;+ },+ }),+}));+/** content_image_uploads: the addresses given. */+type Given = { id: string; organization_id: string; path: string; created_at: string };+let given: Given[];+let noteFails: boolean;+const uploadsTable = {+ insert: (row: { organization_id: string; path: string }) => ({+ select: () => ({+ single: async () => {+ if (noteFails) return { data: null, error: { message: 'down' } };+ const kept = { id: `g${given.length + 1}`, created_at: new Date().toISOString(), ...row };+ given.push(kept);+ return { data: { id: kept.id }, error: null };+ },+ }),+ }),+ select: () => {+ let org = '';+ const chain = {+ eq: (_column: string, value: string) => ((org = value), chain),+ gt: async (_column: string, since: string) => ({+ count: given.filter((g) => g.organization_id === org && g.created_at > since).length,+ error: null,+ }),+ };+ return chain;+ },+ delete: () => ({+ eq: (column: 'id' | 'organization_id', value: string) => {+ const drop = (gone: (g: Given) => boolean) => {+ given = given.filter((g) => !gone(g));+ return { error: null };+ };+ return {+ lt: async (_column: string, before: string) =>+ drop((g) => g.organization_id === value && g.created_at < before),+ then: (resolve: (result: unknown) => void) => resolve(drop((g) => g[column] === value)),+ };+ },+ }),+};+const createSignedUploadUrl = vi.fn();+vi.mock('@/lib/supabase/admin', () => ({+ supabaseAdmin: {+ from: () => uploadsTable,+ storage: {+ from: (bucket: string) => ({+ createSignedUploadUrl: (...args: unknown[]) => createSignedUploadUrl(bucket, ...args),+ getPublicUrl: (path: string) => ({+ data: { publicUrl: `https://store.example/public/${bucket}/${path}` },+ }),+ }),+ },+ },+}));+let cloud: boolean;+vi.mock('@/config/plans', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/config/plans')>()),+ isCloud: () => cloud,+}));++const { prepareImageUpload } = await import('./content-images');+const { IMAGE_UPLOADS_PER_DAY } = await import('@/lib/content/image-upload-types');++/** Addresses given to org-1, `count` of them, each `hoursAgo` old. */+const givenBefore = (count: number, hoursAgo: number): Given[] =>+ Array.from({ length: count }, (_, i) => ({+ id: `old${hoursAgo}-${i}`,+ organization_id: 'org-1',+ path: `org-1/${i}.png`,+ created_at: new Date(Date.now() - hoursAgo * 3_600_000).toISOString(),+ }));++beforeEach(() => {+ user = { id: 'u1' };+ profile = { organization_id: 'org-1' };+ org = { subscription_status: 'active' };+ cloud = true;+ given = [];+ noteFails = false;+ createSignedUploadUrl.mockReset().mockImplementation(async (_bucket: string, path: string) => ({+ data: { path, token: 'tok', signedUrl: 'https://store.example/sign' },+ error: null,+ }));+});++describe('prepareImageUpload', () => {+ it("names the image in its organization's folder, and gives a one-time address for it", async () => {+ const ticket = await prepareImageUpload('image/webp');+ expect(ticket).toEqual({+ path: expect.stringMatching(/^org-1\/[0-9a-f-]{36}\.webp$/),+ token: 'tok',+ url: expect.stringMatching(/^https:\/\/store\.example\/public\/content-images\/org-1\//),+ });+ expect(createSignedUploadUrl).toHaveBeenCalledWith(+ 'content-images',+ (ticket as { path: string }).path,+ );+ });++ it('takes only the bucket’s types', async () => {+ expect(await prepareImageUpload('image/svg+xml')).toEqual({ error: 'type' });+ expect(await prepareImageUpload('constructor')).toEqual({ error: 'type' });+ expect(createSignedUploadUrl).not.toHaveBeenCalled();+ });++ it('needs an active or trialing subscription on the cloud', async () => {+ org = { subscription_status: 'canceled' };+ expect(await prepareImageUpload('image/png')).toEqual({ error: 'plan' });+ org = { subscription_status: 'trialing' };+ expect(await prepareImageUpload('image/png')).toMatchObject({ token: 'tok' });+ });++ it('counts each address given on the cloud, so asking in a loop stops at the day’s cap', async () => {+ given = givenBefore(IMAGE_UPLOADS_PER_DAY - 1, 1);+ expect(await prepareImageUpload('image/png')).toMatchObject({ token: 'tok' });+ expect(given).toHaveLength(IMAGE_UPLOADS_PER_DAY);+ // Not yet used, it counts: the next one is refused, and isn't kept.+ expect(await prepareImageUpload('image/png')).toEqual({ error: 'limit' });+ expect(given).toHaveLength(IMAGE_UPLOADS_PER_DAY);+ expect(createSignedUploadUrl).toHaveBeenCalledTimes(1);+ });++ it('leaves out, and clears, the addresses given more than a day ago', async () => {+ given = givenBefore(IMAGE_UPLOADS_PER_DAY, 25);+ expect(await prepareImageUpload('image/png')).toMatchObject({ token: 'tok' });+ expect(given).toHaveLength(1);+ });++ it('has no limits on a self-host', async () => {+ cloud = false;+ org = null;+ expect(await prepareImageUpload('image/png')).toMatchObject({ token: 'tok' });+ expect(given).toEqual([]);+ });++ it('fails with no session or organization, or when storage does', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ user = null;+ expect(await prepareImageUpload('image/png')).toEqual({ error: 'failed' });+ user = { id: 'u1' };+ profile = null;+ expect(await prepareImageUpload('image/png')).toEqual({ error: 'failed' });+ profile = { organization_id: 'org-1' };+ noteFails = true;+ expect(await prepareImageUpload('image/png')).toEqual({ error: 'failed' });+ noteFails = false;+ createSignedUploadUrl.mockResolvedValueOnce({ data: null, error: { message: 'down' } });+ expect(await prepareImageUpload('image/png')).toEqual({ error: 'failed' });+ error.mockRestore();+ });+});diff --git a/web/src/lib/actions/content-images.ts b/web/src/lib/actions/content-images.tsnew file mode 100644index 000000000..3f41263f9--- /dev/null+++ b/web/src/lib/actions/content-images.ts@@ -0,0 +1,96 @@+'use server';++import { randomUUID } from 'node:crypto';+import { isCloud, isSubscriptionActive } from '@/config/plans';+import { createClient } from '@/lib/supabase/server';+import {+ IMAGE_UPLOAD_BUCKET,+ IMAGE_UPLOADS_PER_DAY,+ imageUploadExtension,+} from '@/lib/content/image-upload-types';++/** Where one image goes up: its path, the one-time token for it, and its public address. */+export interface ImageUploadTicket {+ path: string;+ token: string;+ url: string;+}++const DAY_MS = 24 * 60 * 60 * 1000;++/**+ * Lets a member upload one image (00272). The app says who may and how+ * much, not the bucket's policies: only it knows a managed cloud from a+ * self-host. On the cloud, an organization with an active or trialing+ * subscription (the dashboard's gate), IMAGE_UPLOADS_PER_DAY addresses a+ * day (content_image_uploads); a self-host has no limits. The name is the+ * app's: the organization's folder, a new id and the type's extension. The+ * browser then sends the file itself to the one-time address (no server+ * action's body limit).+ */+export async function prepareImageUpload(+ type: string,+): Promise<ImageUploadTicket | { error: 'type' | 'plan' | 'limit' | 'failed' }> {+ const ext = typeof type === 'string' ? imageUploadExtension(type) : null;+ if (!ext) return { error: 'type' };+ const supabase = await createClient();+ const {+ data: { user },+ } = await supabase.auth.getUser();+ if (!user) return { error: 'failed' };+ const { data: profile } = await supabase+ .from('profiles')+ .select('organization_id')+ .eq('id', user.id)+ .maybeSingle();+ const orgId = profile?.organization_id;+ if (!orgId) return { error: 'failed' };+ // Imported here: the admin client is created at module load and needs the+ // service-role env, and the image dialogs import this module too.+ const { supabaseAdmin } = await import('@/lib/supabase/admin');+ const images = supabaseAdmin.storage.from(IMAGE_UPLOAD_BUCKET);++ const path = `${orgId}/${randomUUID()}.${ext}`;+ if (isCloud()) {+ const { data: org } = await supabase+ .from('organizations')+ .select('subscription_status')+ .eq('id', orgId)+ .maybeSingle();+ if (!isSubscriptionActive(org?.subscription_status)) return { error: 'plan' };+ // Each address given counts, kept before the count: addresses asked for+ // in a loop or at once can't pass the cap, used now or later.+ const uploads = () => supabaseAdmin.from('content_image_uploads');+ const since = new Date(Date.now() - DAY_MS).toISOString();+ const { data: given, error: givenError } = await uploads()+ .insert({ organization_id: orgId, path })+ .select('id')+ .single();+ if (givenError || !given) {+ console.error('Failed to note the image upload:', givenError?.message);+ return { error: 'failed' };+ }+ const { count, error: countError } = await uploads()+ .select('id', { count: 'exact', head: true })+ .eq('organization_id', orgId)+ .gt('created_at', since);+ if (countError || count === null) {+ console.error('Failed to count the day’s image uploads:', countError?.message);+ return { error: 'failed' };+ }+ if (count > IMAGE_UPLOADS_PER_DAY) {+ // Not given, so it doesn't count either.+ await uploads().delete().eq('id', given.id);+ return { error: 'limit' };+ }+ // The ones older than a day no longer count.+ await uploads().delete().eq('organization_id', orgId).lt('created_at', since);+ }++ const { data, error } = await images.createSignedUploadUrl(path);+ if (error || !data) {+ console.error('Failed to prepare the image upload:', error?.message);+ return { error: 'failed' };+ }+ return { path: data.path, token: data.token, url: images.getPublicUrl(path).data.publicUrl };+}diff --git a/web/src/lib/content/image-upload-types.ts b/web/src/lib/content/image-upload-types.tsnew file mode 100644index 000000000..029f0dbee--- /dev/null+++ b/web/src/lib/content/image-upload-types.ts@@ -0,0 +1,18 @@+/** Upload an image instead of pasting its address (00272): what goes up, and how much. */++export const IMAGE_UPLOAD_BUCKET = 'content-images';+/** The bucket's own limit: 5 MB a file. */+export const IMAGE_UPLOAD_MAX_BYTES = 5 * 1024 * 1024;+/** The types the bucket takes, with the extension each is saved under. */+export const IMAGE_UPLOAD_TYPES: Readonly<Record<string, string>> = {+ 'image/jpeg': 'jpg',+ 'image/png': 'png',+ 'image/webp': 'webp',+ 'image/gif': 'gif',+};+/** On the managed cloud, an organization's uploads a day (the bucket is public). */+export const IMAGE_UPLOADS_PER_DAY = 100;++/** The extension a type is saved under, or null for one the bucket doesn't take. */+export const imageUploadExtension = (type: string): string | null =>+ Object.hasOwn(IMAGE_UPLOAD_TYPES, type) ? IMAGE_UPLOAD_TYPES[type] : null;diff --git a/web/src/lib/content/image-upload.test.ts b/web/src/lib/content/image-upload.test.tsnew file mode 100644index 000000000..cdd6a2a5d--- /dev/null+++ b/web/src/lib/content/image-upload.test.ts@@ -0,0 +1,71 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** Upload an image instead of pasting its address (00272). */++const prepareImageUpload = vi.fn();+vi.mock('@/lib/actions/content-images', () => ({+ prepareImageUpload: (...args: unknown[]) => prepareImageUpload(...args),+}));+const uploadToSignedUrl = vi.fn();+vi.mock('@/lib/supabase/client', () => ({+ createClient: () => ({+ storage: {+ from: (bucket: string) => ({+ uploadToSignedUrl: (...args: unknown[]) => uploadToSignedUrl(bucket, ...args),+ }),+ },+ }),+}));++const { IMAGE_UPLOAD_MAX_BYTES, imageUploadProblem, uploadContentImage } =+ await import('./image-upload');++const file = (type: string, size = 1000) => new File([new Uint8Array(size)], 'shot', { type });+const TICKET = {+ path: 'org-1/0b5c2a1e-8f3d-4c7a-9e21-5d6f7a8b9c0d.png',+ token: 'tok',+ url: 'https://store.example/public/content-images/org-1/0b5c2a1e-8f3d-4c7a-9e21-5d6f7a8b9c0d.png',+};++beforeEach(() => {+ prepareImageUpload.mockReset().mockResolvedValue(TICKET);+ uploadToSignedUrl.mockReset().mockResolvedValue({ data: {}, error: null });+});++describe('uploadContentImage', () => {+ it('sends the image to the one-time address the app gives, and gives its address', async () => {+ const shot = file('image/png');+ const result = await uploadContentImage(shot);+ expect(prepareImageUpload).toHaveBeenCalledWith('image/png');+ expect(uploadToSignedUrl).toHaveBeenCalledWith('content-images', TICKET.path, 'tok', shot, {+ contentType: 'image/png',+ cacheControl: '31536000',+ });+ expect(result).toEqual({ url: TICKET.url });+ });++ it('refuses a file of another type or over 5 MB before asking', async () => {+ expect(imageUploadProblem(file('image/svg+xml'))).toBe('type');+ expect(imageUploadProblem(file('constructor'))).toBe('type');+ expect(imageUploadProblem(file('image/jpeg', IMAGE_UPLOAD_MAX_BYTES + 1))).toBe('size');+ expect(await uploadContentImage(file('application/pdf'))).toEqual({ error: 'type' });+ expect(prepareImageUpload).not.toHaveBeenCalled();+ });++ it('says why the app gave no address: the plan, or the day’s uploads made', async () => {+ prepareImageUpload.mockResolvedValueOnce({ error: 'plan' });+ expect(await uploadContentImage(file('image/jpeg'))).toEqual({ error: 'plan' });+ prepareImageUpload.mockResolvedValueOnce({ error: 'limit' });+ expect(await uploadContentImage(file('image/jpeg'))).toEqual({ error: 'limit' });+ expect(uploadToSignedUrl).not.toHaveBeenCalled();+ });++ it('says it failed when the upload or the ask does', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ uploadToSignedUrl.mockResolvedValueOnce({ data: null, error: { message: 'expired' } });+ expect(await uploadContentImage(file('image/jpeg'))).toEqual({ error: 'failed' });+ prepareImageUpload.mockRejectedValueOnce(new Error('offline'));+ expect(await uploadContentImage(file('image/jpeg'))).toEqual({ error: 'failed' });+ error.mockRestore();+ });+});diff --git a/web/src/lib/content/image-upload.ts b/web/src/lib/content/image-upload.tsnew file mode 100644index 000000000..5cd7094e2--- /dev/null+++ b/web/src/lib/content/image-upload.ts@@ -0,0 +1,61 @@+import { prepareImageUpload } from '@/lib/actions/content-images';+import { createClient } from '@/lib/supabase/client';+import {+ IMAGE_UPLOAD_BUCKET,+ IMAGE_UPLOAD_MAX_BYTES,+ IMAGE_UPLOAD_TYPES,+ imageUploadExtension,+} from './image-upload-types';++/**+ * Upload an image instead of pasting its address (00272): most people have+ * the screenshot or photo on their computer. The app gives a one-time+ * address under the member's organization's folder (prepareImageUpload,+ * which says who may and how much), the browser sends the file straight to+ * it (no server action's body limit), and the page and the CMS show it by+ * its public address.+ */++export { IMAGE_UPLOAD_BUCKET, IMAGE_UPLOAD_MAX_BYTES, IMAGE_UPLOAD_TYPES };+/** The file picker's filter. */+export const IMAGE_UPLOAD_ACCEPT = Object.keys(IMAGE_UPLOAD_TYPES).join(',');++/**+ * Why a file can't go up: its type, its size, the organization's plan (on+ * the cloud, an active one), the day's uploads made, or the upload failing.+ */+export type ImageUploadError = 'type' | 'size' | 'plan' | 'limit' | 'failed';++/** Why a file can't go up, before it is sent, or null. */+export function imageUploadProblem(file: File): ImageUploadError | null {+ if (!imageUploadExtension(file.type)) return 'type';+ if (file.size > IMAGE_UPLOAD_MAX_BYTES) return 'size';+ return null;+}++/** Uploads one image: its public address, or why it didn't go up. */+export async function uploadContentImage(+ file: File,+): Promise<{ url: string } | { error: ImageUploadError }> {+ const problem = imageUploadProblem(file);+ if (problem) return { error: problem };+ try {+ // A new name each time, the app's: nothing already up is overwritten.+ const ticket = await prepareImageUpload(file.type);+ if ('error' in ticket) return { error: ticket.error };+ const { error } = await createClient()+ .storage.from(IMAGE_UPLOAD_BUCKET)+ .uploadToSignedUrl(ticket.path, ticket.token, file, {+ contentType: file.type,+ cacheControl: '31536000',+ });+ if (error) {+ console.error('Failed to upload the image:', error.message);+ return { error: 'failed' };+ }+ return { url: ticket.url };+ } catch (err) {+ console.error('Failed to upload the image:', err);+ return { error: 'failed' };+ }+}