diff --git a/next.config.mjs b/next.config.mjs index 29f964a..a6ce88f 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -7,6 +7,16 @@ const nextConfig = { reactStrictMode: false, poweredByHeader: false, turbopack: {}, + // Server Actions reject request bodies over 1 MB by default, which is smaller than + // any real photograph, so the admin image uploader needs a raised ceiling. Note that + // the file is re-sent to the PHP API as a fresh multipart request, so PHP's own + // `upload_max_filesize` and `post_max_size` have to allow at least this much too, + // otherwise PHP discards the upload before Laravel can validate it. + experimental: { + serverActions: { + bodySizeLimit: '8mb', + }, + }, images: { // The logo, the burger button and the social icons are SVGs. Without this // flag next/image refuses to optimise them and answers 400, so every SVG diff --git a/src/app/feed.xml/route.ts b/src/app/feed.xml/route.ts new file mode 100644 index 0000000..1f7010a --- /dev/null +++ b/src/app/feed.xml/route.ts @@ -0,0 +1,177 @@ +import type { PostType } from '../types/types'; + +export const dynamic = 'force-dynamic'; + +const FRONT_URL = (process.env.NEXT_PUBLIC_FRONT_URL || 'https://parsaaghayi.ir').replace(/\/+$/, ''); +const BLOG_API_URL = (process.env.NEXT_PUBLIC_BLOG_API_URL || 'https://backend.parsaaghayi.ir/api/blog').replace(/\/+$/, ''); + +// The blog API rejects `per_page` values above 50. +const PER_PAGE = 50; +// Upper bound on pagination to avoid looping forever. +const MAX_POST_PAGES = 20; + +type Paginated = { + data?: T[]; + meta?: { + total?: number; + current_page?: number; + last_page?: number; + }; +}; + +type FeedPost = Pick; + +function absoluteUrl(path: string): string { + return `${FRONT_URL}${path}`; +} + +function escapeXml(str: string | null | undefined): string { + if (typeof str !== 'string') { + return ''; + } + + const value = str.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); + return value; +} + +function formatRfc822(date: Date): string { + // RFC 822 format (GMT) + const utcDate = new Date(date.toUTCString()); + return utcDate.toUTCString().replace('GMT', '+0000'); +} + +function parseDate(...candidates: (string | null | undefined)[]): Date | undefined { + for (const candidate of candidates) { + if (typeof candidate !== 'string' || candidate.trim() === '') { + continue; + } + + const parsed = new Date(candidate.trim()); + + if (!Number.isNaN(parsed.getTime())) { + return parsed; + } + } + + return undefined; +} + +async function fetchJson(url: string): Promise { + try { + const response = await fetch(url, { cache: 'no-store' }); + + if (!response.ok) { + return null; + } + + return (await response.json()) as T; + } catch { + return null; + } +} + +async function fetchAllPosts(): Promise { + const items: FeedPost[] = []; + + for (let page = 1; page <= MAX_POST_PAGES; page += 1) { + const payload = await fetchJson>( + `${BLOG_API_URL}/posts?per_page=${PER_PAGE}&page=${page}`, + ); + + if (!payload || !Array.isArray(payload.data) || payload.data.length === 0) { + break; + } + + items.push(...payload.data); + + const lastPage = payload.meta?.last_page ?? 1; + const currentPage = payload.meta?.current_page ?? page; + + if (currentPage >= lastPage) { + break; + } + } + + return items; +} + +function extractDescription(post: FeedPost): string { + // Prefer excerpt; fall back to body (truncated to reasonable size) + if (typeof post.excerpt === 'string' && post.excerpt.trim() !== '') { + return post.excerpt; + } + if (typeof post.body === 'string' && post.body.trim() !== '') { + // Strip HTML tags if any, and truncate + const stripped = post.body.replace(/<[^>]*>/g, '').trim(); + return stripped.length > 500 ? stripped.slice(0, 497) + '...' : stripped; + } + return ''; +} + +function buildFeedItems(posts: FeedPost[]): string { + const items: string[] = []; + + for (const post of posts) { + if (typeof post?.slug !== 'string' || post.slug.trim() === '') { + continue; + } + + const pubDate = parseDate(post.published_at, post.updated_at); + const link = absoluteUrl(`/blog/posts/${post.slug}`); + const title = escapeXml(post.title); + const description = escapeXml(extractDescription(post)); + const guid = link; + + const pubDateXml = pubDate ? formatRfc822(pubDate) : ''; + + items.push(` + ${title} + ${link} + ${guid}${pubDateXml ? `\n ${pubDateXml}` : ''} + ${description} + `); + } + + return items.join('\n'); +} + +function buildValidFeed(posts: FeedPost[]): string { + const feedTitle = escapeXml('Parsa Aghayi Blog'); + const feedDescription = escapeXml('Persian-first blog by Parsa Aghayi covering web development, React, Next.js, TypeScript and software architecture.'); + const feedLink = absoluteUrl('/blog'); + const lastBuildDate = formatRfc822(new Date()); + + const itemsXml = buildFeedItems(posts); + + return ` + + + ${feedTitle} + ${feedLink} + ${feedDescription} + fa-ir + ${lastBuildDate} +${itemsXml} + +`; +} + +export async function GET(): Promise { + try { + const posts = await fetchAllPosts(); + const xml = buildValidFeed(posts); + return new Response(xml, { + headers: { + 'Content-Type': 'application/rss+xml; charset=utf-8', + }, + }); + } catch { + // If the API fails, return a valid, well-formed empty feed rather than throwing a 500. + const xml = buildValidFeed([]); + return new Response(xml, { + headers: { + 'Content-Type': 'application/rss+xml; charset=utf-8', + }, + }); + } +} diff --git a/src/app/lib/admin/api.ts b/src/app/lib/admin/api.ts index e0d420c..7e67f3b 100644 --- a/src/app/lib/admin/api.ts +++ b/src/app/lib/admin/api.ts @@ -109,6 +109,61 @@ function safeJson(text: string): unknown { } } +export type UploadedMedia = { + url: string; + path: string; + name: string; + size: number; + mime: string; +}; + +/** + * Multipart counterpart of `adminFetch`, which cannot be reused here: it always + * JSON-stringifies the body and pins `Content-Type: application/json`. + */ +export async function adminUpload(path: string, formData: FormData): Promise { + const token = await adminToken(); + + if (!token) throw new AdminApiError('نشست مدیریتی برقرار نیست.', 401); + + const response = await fetch(`${BACKEND}/api${path}`, { + method: 'POST', + // `Content-Type` is deliberately omitted. The boundary is generated by the + // runtime while it serialises the FormData; sending the header by hand (or + // reusing the JSON header of `adminFetch`) produces a body PHP cannot parse, + // so `$_FILES` stays empty and every upload fails with a 422. + headers: { Accept: 'application/json', Authorization: `Bearer ${token}` }, + body: formData, + cache: 'no-store', + }); + + const text = await response.text(); + const payload: unknown = text ? safeJson(text) : null; + + if (!response.ok) { + // The media endpoint throttles far harder than the rest of the admin API and + // its own "Too Many Attempts" text says nothing about what to do next. + if (response.status === 429) { + throw new AdminApiError( + 'تعداد درخواست‌های بارگذاری بیش از حد مجاز است. کمی صبر کنید و دوباره تلاش کنید.', + 429, + ); + } + + throw new AdminApiError( + messageFrom(payload, `بارگذاری فایل با خطا مواجه شد (${response.status}).`), + response.status, + ); + } + + // Uploads answer `{ data: { url, path, ... } }`; unwrap so callers get the file itself. + if (payload && typeof payload === 'object' && 'data' in payload) { + return (payload as { data: T }).data; + } + + return payload as T; +} + export async function listRows(path: string): Promise { const payload = await adminFetch<{ data?: T[] } | T[]>(path); return Array.isArray(payload) ? payload : (payload?.data ?? []); diff --git a/src/app/lib/admin/media.ts b/src/app/lib/admin/media.ts new file mode 100644 index 0000000..0e73dcb --- /dev/null +++ b/src/app/lib/admin/media.ts @@ -0,0 +1,82 @@ +'use server'; + +import { AdminApiError, adminFetch, adminUpload, type UploadedMedia } from './api'; + +/** + * The API rejects anything larger with 422, so the ceiling is checked here too. + * The client repeats this number for instant feedback; the server is the one that + * actually enforces it, because the client check is trivially bypassable. + */ +const MAX_UPLOAD_BYTES = 4 * 1024 * 1024; + +type UploadResult = { ok: true; url: string; path: string } | { ok: false; error: string }; +type DeleteResult = { ok: true; path: string } | { ok: false; error: string }; + +function message(error: unknown): string { + if (error instanceof AdminApiError) return error.message; + + return 'خطای پیش‌بینی‌نشده رخ داد.'; +} + +/** + * Only paths the media endpoint itself issued may be deleted, and no segment may + * walk out of `media/`, because the value is concatenated into an API URL. + */ +function mediaPath(value: unknown): string | null { + if (typeof value !== 'string') return null; + + const trimmed = value.trim(); + if (!trimmed.startsWith('media/')) return null; + + const segments = trimmed.split('/'); + if (segments.some((segment) => segment === '' || segment === '.' || segment === '..')) return null; + + return segments.join('/'); +} + +export async function uploadMediaAction(formData: FormData): Promise { + const entry = formData.get('file'); + + // A real multipart part arrives as a `File`, but a hand-built request can put a + // string — or nothing — under "file". Forwarding that would only earn a 422 the + // admin cannot act on, so the guard lives here. + if (!entry || typeof entry === 'string' || !(entry instanceof File) || entry.size === 0) { + return { ok: false, error: 'فایلی انتخاب نشده است.' }; + } + + if (entry.size > MAX_UPLOAD_BYTES) { + return { ok: false, error: 'حجم فایل بیش از ۴ مگابایت است.' }; + } + + try { + const media = await adminUpload('/admin/media', formData); + + if (!media?.url || !media.path) return { ok: false, error: 'پاسخ سرور برای فایل ارسالی معتبر نبود.' }; + + return { ok: true, url: media.url, path: media.path }; + } catch (error) { + return { ok: false, error: message(error) }; + } +} + +export async function deleteMediaAction(path: string): Promise { + const target = mediaPath(path); + + if (!target) return { ok: false, error: 'شناسه فایل نامعتبر است.' }; + + try { + await adminFetch(`/admin/media/${target.split('/').map(encodeURIComponent).join('/')}`, { + method: 'DELETE', + }); + } catch (error) { + // 404 means the file is already gone, which is exactly the state the caller + // asked for, so it is not surfaced as a failure. + if (error instanceof AdminApiError && error.status === 404) { + return { ok: true, path: target }; + } + + return { ok: false, error: message(error) }; + } + + return { ok: true, path: target }; +} diff --git a/src/app/lib/admin/resource-form.tsx b/src/app/lib/admin/resource-form.tsx index 6a11266..52672a5 100644 --- a/src/app/lib/admin/resource-form.tsx +++ b/src/app/lib/admin/resource-form.tsx @@ -1,8 +1,9 @@ 'use client'; -import { useActionState } from 'react'; +import { useActionState, useState, useTransition, type ChangeEvent } from 'react'; import { EMPTY_STATE, toDateTimeInput } from './format'; import { saveResourceAction } from './actions'; +import { uploadMediaAction } from './media'; import type { AdminRow, FieldDef, OptionRow, ResourceDef } from './resources'; import { Alert, Button, Field, inputClass } from './ui'; @@ -11,6 +12,10 @@ const LOCALE_TITLES: Record = { en: 'English version', }; +/** Mirrors the API ceiling so the file is refused before it is sent. */ +const MAX_UPLOAD_BYTES = 4 * 1024 * 1024; +const ACCEPTED_IMAGE_TYPES = 'image/jpeg,image/png,image/webp,image/gif'; + function initialValue(row: AdminRow | null, field: FieldDef): string | string[] { if (!row) return field.kind === 'multiselect' ? [] : ''; @@ -46,6 +51,114 @@ function initialValue(row: AdminRow | null, field: FieldDef): string | string[] return String(value); } +function ImageField({ field, initialUrl, id }: { field: FieldDef; initialUrl: string; id: string }) { + const [url, setUrl] = useState(initialUrl); + const [error, setError] = useState(null); + const [isUploading, startUpload] = useTransition(); + + const pick = (event: ChangeEvent) => { + const file = event.target.files?.[0]; + + // Cleared up front so choosing the very same file again still fires `change`. + event.target.value = ''; + + if (!file) return; + + if (file.size > MAX_UPLOAD_BYTES) { + setError('حجم فایل بیش از ۴ مگابایت است.'); + return; + } + + setError(null); + + const payload = new FormData(); + payload.set('file', file); + + startUpload(async () => { + const result = await uploadMediaAction(payload); + + if (result.ok) { + setUrl(result.url); + return; + } + + setError(result.error); + }); + }; + + return ( +
+
+ {url ? ( + <> + {/* A raw on purpose: the media host is not guaranteed to be listed in + `images.remotePatterns`, and the optimiser answers 400 for an unknown host — + the admin would never see the picture they just uploaded. */} + {field.label} + {/* Only clears the field. The stored file is left in place on purpose: the same + URL may already be referenced by another record, so removing it is a separate, + explicit action (`deleteMediaAction`) rather than a side effect of re-uploading. + A plain + + ) : ( +

+ تصویری انتخاب نشده است +

+ )} +
+ + {/* The real save is `saveResourceAction`, so the URL — uploaded or pasted — has to + travel in a named control. One input serves both paths: the uploader writes the + returned URL into the same state this input is bound to. */} + setUrl(event.target.value)} + placeholder={field.placeholder ?? 'https://example.com/image.jpg'} + required={field.required} + dir="ltr" + className={`${inputClass} text-left`} + /> + +
+ + {/* Intentionally unnamed: the file is already uploaded by the time the form can be + submitted, and a named file input would push its bytes into the save request. */} + +

+ {isUploading + ? 'در حال بارگذاری…' + : 'JPG، PNG، WEBP یا GIF — حداکثر ۴ مگابایت. فایل SVG پذیرفته نمی‌شود.'} +

+
+ + {error ? {error} : null} +
+ ); +} + export default function ResourceForm({ resource, row, @@ -102,6 +215,14 @@ export default function ResourceForm({ ); } + if (field.kind === 'image') { + return ( + + + + ); + } + if (field.kind === 'textarea') { return ( diff --git a/src/app/lib/admin/resources.ts b/src/app/lib/admin/resources.ts index 4ed16c4..53a4a1d 100644 --- a/src/app/lib/admin/resources.ts +++ b/src/app/lib/admin/resources.ts @@ -5,7 +5,8 @@ export type FieldKind = | 'url' | 'datetime' | 'select' - | 'multiselect'; + | 'multiselect' + | 'image'; export type FieldDef = { name: string; @@ -65,7 +66,7 @@ export const RESOURCES: ResourceDef[] = [ { name: 'tags', label: 'برچسب‌ها', kind: 'multiselect', optionsFrom: 'tags' }, { name: 'excerpt', label: 'خلاصه', kind: 'textarea', rows: 3, help: 'حداکثر ۵۰۰ کاراکتر. در فهرست نوشته‌ها نمایش داده می‌شود.' }, { name: 'body', label: 'متن نوشته', kind: 'textarea', rows: 18, required: true }, - { name: 'featured_image', label: 'تصویر شاخص', kind: 'url', placeholder: 'https://example.com/image.jpg' }, + { name: 'featured_image', label: 'تصویر شاخص', kind: 'image' }, { name: 'published_at', label: 'زمان انتشار', kind: 'datetime', help: 'خالی بگذارید تا پیش‌نویس بماند.' }, { name: 'views', label: 'بازدید', kind: 'number' }, { name: 'likes', label: 'پسند', kind: 'number' }, @@ -89,7 +90,7 @@ export const RESOURCES: ResourceDef[] = [ { name: 'slug', label: 'نشانی (slug)', kind: 'text', required: true }, { name: 'short_description', label: 'توضیح کوتاه', kind: 'textarea', rows: 3 }, { name: 'description', label: 'توضیح کامل', kind: 'textarea', rows: 8, required: true }, - { name: 'image', label: 'تصویر', kind: 'url', placeholder: 'https://example.com/image.jpg' }, + { name: 'image', label: 'تصویر', kind: 'image' }, ], }, { @@ -135,8 +136,8 @@ export const RESOURCES: ResourceDef[] = [ { name: 'description_fa', label: 'توضیح فارسی', kind: 'textarea', rows: 6, required: true, localeGroup: 'fa' }, { name: 'title_en', label: 'عنوان انگلیسی', kind: 'text', required: true, localeGroup: 'en' }, { name: 'description_en', label: 'توضیح انگلیسی', kind: 'textarea', rows: 6, required: true, localeGroup: 'en' }, - { name: 'image1', label: 'تصویر اول', kind: 'text', required: true, placeholder: '/images/projects/one.jpg' }, - { name: 'image2', label: 'تصویر دوم', kind: 'text', required: true, placeholder: '/images/projects/two.jpg' }, + { name: 'image1', label: 'تصویر اول', kind: 'image', required: true }, + { name: 'image2', label: 'تصویر دوم', kind: 'image', required: true }, ], }, { @@ -157,7 +158,7 @@ export const RESOURCES: ResourceDef[] = [ { name: 'description_fa', label: 'معرفی فارسی', kind: 'textarea', rows: 10, localeGroup: 'fa' }, { name: 'title_en', label: 'عنوان انگلیسی', kind: 'text', localeGroup: 'en' }, { name: 'description_en', label: 'معرفی انگلیسی', kind: 'textarea', rows: 10, localeGroup: 'en' }, - { name: 'image', label: 'تصویر پروفایل', kind: 'text', required: true, placeholder: '/images/profile.png' }, + { name: 'image', label: 'تصویر پروفایل', kind: 'image', required: true }, ], }, ];