Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions .github/workflows/compile-draft.yml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ jobs:
setOutput('pdf_path', data.pdfPath);
setOutput('source_url', data.sourceUrl);
setOutput('upload_url', data.pdfUploadUrl);
const images = Array.isArray(data.images) ? data.images : [];
for (const image of images) console.log(`::add-mask::${image.url}`);
setOutput('images_json', JSON.stringify(images));
outputs.end();
NODE

Expand All @@ -93,6 +96,49 @@ jobs:
mkdir -p magazine/build
curl --fail --silent --show-error "$SOURCE_URL" --output magazine/build/edition.tex

- name: Download approved story illustrations
if: steps.prepare.outputs.ready == 'true'
env:
IMAGES_JSON: ${{ steps.prepare.outputs.images_json }}
SUPABASE_URL: ${{ secrets.NEXT_PUBLIC_SUPABASE_URL }}
run: |
node <<'NODE'
const fs = require('node:fs/promises');
const path = require('node:path');
(async () => {
const images = JSON.parse(process.env.IMAGES_JSON || '[]');
const expectedOrigin = new URL(process.env.SUPABASE_URL).origin;
const directory = path.join('magazine', 'build', 'images');
await fs.mkdir(directory, { recursive: true });
const seen = new Set();
for (const image of images) {
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(image.storyId)) {
throw new Error('An illustration has an invalid story ID.');
}
const url = new URL(image.url);
if (url.protocol !== 'https:' || url.origin !== expectedOrigin || !url.pathname.startsWith('/storage/v1/object/sign/drafts/')) {
throw new Error('An illustration link is outside private Supabase draft storage.');
}
if (seen.has(image.storyId)) continue;
seen.add(image.storyId);
const response = await fetch(url);
if (!response.ok || !response.headers.get('content-type')?.toLowerCase().startsWith('image/png')) {
throw new Error(`Illustration download returned HTTP ${response.status} or an unexpected type.`);
}
const bytes = Buffer.from(await response.arrayBuffer());
const pngSignature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
if (bytes.length < 32 || bytes.length > 8_000_000 || !bytes.subarray(0, 8).equals(pngSignature)) {
throw new Error('An illustration was invalid or exceeded the size limit.');
}
await fs.writeFile(path.join(directory, `${image.storyId}.png`), bytes, { flag: 'wx' });
}
console.log(`Downloaded ${seen.size} approved illustration(s).`);
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});
NODE

- name: Compile the magazine PDF
id: latex
if: steps.prepare.outputs.ready == 'true'
Expand Down
42 changes: 41 additions & 1 deletion app/api/cron/compile/prepare/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export async function POST(request: Request) {
const admin = createSupabaseAdminClient();
let query = admin
.from("editions")
.select("id, status, tex_path, tex_hash")
.select("id, status, tex_path, tex_hash, window_start, created_at")
.eq("status", "draft");
if (input.editionId) query = query.eq("id", input.editionId);
const { data: edition, error } = await query.maybeSingle();
Expand Down Expand Up @@ -89,6 +89,45 @@ export async function POST(request: Request) {
throw new Error("Could not create a temporary PDF upload link.");
}

const { data: approvedStories, error: storiesError } = await admin
.from("stories")
.select("id")
.eq("status", "approved")
.eq("is_ai_related", true)
.gte("last_updated_at", edition.window_start ?? edition.created_at);
if (storiesError) throw new Error("Could not find approved issue stories.");

const storyIds = (approvedStories ?? []).map((story) => story.id);
const { data: images, error: imagesError } = storyIds.length
? await admin
.from("images")
.select("story_id, storage_path")
.in("story_id", storyIds)
.eq("license", "own")
.eq("approved", true)
.like("storage_path", "%.png")
: { data: [], error: null };
if (imagesError)
throw new Error("Could not find approved issue illustrations.");
const issueImages = await Promise.all(
(images ?? []).flatMap((image) => {
if (!image.story_id) return [];
return [
admin.storage
.from("drafts")
.createSignedUrl(image.storage_path, 3600)
.then(({ data, error }) => {
if (error || !data?.signedUrl) {
throw new Error(
"Could not create a temporary illustration link.",
);
}
return { storyId: image.story_id!, url: data.signedUrl };
}),
];
}),
);

return Response.json({
ok: true,
ready: true,
Expand All @@ -97,6 +136,7 @@ export async function POST(request: Request) {
sourceUrl: source.signedUrl,
pdfUploadUrl: upload.signedUrl,
pdfPath,
images: issueImages,
});
} catch (error) {
console.error("Could not prepare the draft PDF compile.", error);
Expand Down
50 changes: 50 additions & 0 deletions app/desk/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,56 @@ export async function saveStoryEdit(formData: FormData) {
revalidatePath("/desk");
}

export async function setImageApproval(formData: FormData) {
await requireEditor();
const id = storyIdSchema.safeParse(formData.get("imageId"));
const approvedValue = z
.enum(["true", "false"])
.safeParse(formData.get("approved"));
if (!id.success || !approvedValue.success) {
throw new Error("Invalid image review update.");
}

const admin = createSupabaseAdminClient();
const { data: image, error: lookupError } = await admin
.from("images")
.select("id, story_id, license")
.eq("id", id.data)
.maybeSingle();
if (lookupError || !image)
throw new Error("Could not find that illustration.");
if (image.license !== "own") {
throw new Error(
"Only publication-owned illustrations can be approved here.",
);
}

const approved = approvedValue.data === "true";
const { error } = await admin
.from("images")
.update({ approved })
.eq("id", image.id)
.eq("license", "own");
if (error) throw new Error("Could not save the illustration review.");

if (image.story_id) {
const { data: story, error: storyError } = await admin
.from("stories")
.select("status")
.eq("id", image.story_id)
.maybeSingle();
if (storyError) throw new Error("Could not load the illustration's story.");
if (story?.status === "approved") {
await invalidateCurrentDraftArtifacts();
await rebuildMagazineDraft();
}
}

revalidatePath("/desk/images");
revalidatePath("/desk/stories");
revalidatePath("/desk");
}

export async function saveDraftTemplateAction(formData: FormData) {
await requireEditor();
const admin = createSupabaseAdminClient();
Expand Down
147 changes: 132 additions & 15 deletions app/desk/images/page.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,144 @@
import { setImageApproval } from "@/app/desk/actions";
import Image from "next/image";
import { PageHeading } from "@/components/page-heading";
import { Button } from "@/components/ui/button";
import { EmptyState } from "@/components/ui/empty-state";
import { Section } from "@/components/ui/section";
import { requireEditor } from "@/lib/auth/require-editor";
import { createSupabaseAdminClient } from "@/lib/supabase/admin";
import { siteCopy } from "@/content/site";

export default function ImagesPage() {
export const dynamic = "force-dynamic";

export default async function ImagesPage() {
await requireEditor();
const admin = createSupabaseAdminClient();
const { data: rows, error } = await admin
.from("images")
.select("id, story_id, storage_path, credit, approved, created_at")
.eq("license", "own")
.order("created_at", { ascending: false })
.limit(100);
if (error) throw new Error("Could not load magazine illustrations.");

const storyIds = [
...new Set(
(rows ?? [])
.map((image) => image.story_id)
.filter((id): id is string => id !== null),
),
];
const { data: stories, error: storyError } = storyIds.length
? await admin
.from("stories")
.select("id, headline, status")
.in("id", storyIds)
: { data: [], error: null };
if (storyError) throw new Error("Could not load illustration story details.");
const storyById = new Map((stories ?? []).map((story) => [story.id, story]));

const { data: signedImages, error: signedImagesError } = rows?.length
? await admin.storage
.from("drafts")
.createSignedUrls(
rows.map((image) => image.storage_path),
3600,
)
: { data: [], error: null };
if (signedImagesError) throw new Error("Could not sign illustration previews.");
const imageByPath = new Map(
(rows ?? []).map((image) => [image.storage_path, image]),
);
const visible = (signedImages ?? []).flatMap((signed) => {
if (!signed.path || !signed.signedUrl || signed.error) return [];
const image = imageByPath.get(signed.path);
return image ? [{ ...image, url: signed.signedUrl }] : [];
});

return (
<Section>
<div className="flex flex-col gap-6 sm:flex-row sm:items-end sm:justify-between">
<PageHeading
eyebrow={siteCopy.desk.imagesTitle}
title={siteCopy.desk.imagesTitle}
description={siteCopy.desk.imagesIntro}
/>
<Button disabled title={siteCopy.desk.comingSoon}>
{siteCopy.desk.upload}
</Button>
</div>
<PageHeading
eyebrow={siteCopy.desk.imagesTitle}
title={siteCopy.desk.imagesTitle}
description="Gemini creates original editorial illustrations for AI stories. Review each one before it is placed in the magazine; unapproved images stay out of the PDF."
/>
<p className="text-muted mt-4 max-w-3xl text-sm leading-6">
The ingest job generates up to two illustrations per run for the
highest-priority AI stories that do not have one yet. Generated art is
an illustration, not a documentary photo. Publisher preview images are
not copied because a trusted news source does not automatically grant
reuse rights.
</p>
<div className="mt-10">
<EmptyState
title={siteCopy.desk.imageEmpty}
description={siteCopy.desk.imageRights}
/>
{!visible.length ? (
<EmptyState
title="No generated illustrations yet"
description="The next scheduled ingest run will create illustrations for eligible AI stories. They will appear here for editorial review."
/>
) : (
<div className="grid gap-6 md:grid-cols-2">
{visible.map((image) => {
const story = image.story_id
? storyById.get(image.story_id)
: null;
return (
<article
key={image.id}
className="border-line overflow-hidden rounded-xl border bg-white"
>
<Image
src={image.url}
alt={
story
? `AI-generated illustration for ${story.headline}`
: "AI-generated editorial illustration"
}
width={960}
height={540}
unoptimized
className="bg-paper aspect-video w-full object-cover"
/>
<div className="space-y-3 p-5">
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="text-xs font-semibold tracking-wide uppercase">
{image.approved ? "Approved for issue" : "Needs review"}
</span>
<span className="text-muted text-xs">
{new Date(image.created_at).toLocaleDateString()}
</span>
</div>
<h2 className="font-serif text-xl leading-tight">
{story?.headline ?? "Story no longer available"}
</h2>
<p className="text-muted text-xs">{image.credit}</p>
{story ? (
<p className="text-muted text-xs">
Story status: {story.status}
</p>
) : null}
<form action={setImageApproval}>
<input type="hidden" name="imageId" value={image.id} />
<input
type="hidden"
name="approved"
value={image.approved ? "false" : "true"}
/>
<Button
type="submit"
variant={image.approved ? "secondary" : "primary"}
className="min-h-10 px-4 text-xs"
>
{image.approved
? "Remove from issue"
: "Approve illustration"}
</Button>
</form>
</div>
</article>
);
})}
</div>
)}
</div>
</Section>
);
Expand Down
Loading
Loading