Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d25db9367c | ||
|
|
1d29e50852 |
@@ -55,3 +55,17 @@ OFFSITE_RCLONE_REMOTE=
|
||||
# --- فقط برای docker-compose.prod.yml (حالت تولید با TLS) ---
|
||||
# DOMAIN=aramesh.example
|
||||
# ACME_EMAIL=admin@aramesh.example
|
||||
# دامنه دوم (در صورت وجود) — مسیرها و گواهی TLS برای هر دو صادر میشود
|
||||
# DOMAIN_ALIAS=aramesh.example.ir
|
||||
|
||||
# --- پیشنمایش خصوصی و انتشار (scripts/preview-mode.sh) ---
|
||||
# «on» یعنی سایت آنلاین است اما پشت گیت ورود و بدون ایندکس؛ «off» یعنی انتشار عمومی.
|
||||
# این مقادیر را دستی ویرایش نکنید — اسکریپت preview-mode.sh هماهنگشان میکند:
|
||||
# bash scripts/preview-mode.sh on|off|status → bash scripts/stack.sh deploy-prod
|
||||
# PREVIEW_MODE=on
|
||||
# هش htpasswd کاربر مشترک پیشنمایش — اولین «on» خودش میسازد
|
||||
# PREVIEW_AUTH_USERS=preview:$apr1$...
|
||||
# فهرست میانافزارهای فعال؛ «on» پرش میکند و «off» خالیش میکند
|
||||
# PREVIEW_MIDDLEWARES=preview-auth@docker,preview-noindex@docker
|
||||
# در انتشار، دامنه دوم را به اصلی ریدایرکت میکند تا محتوای تکراری ساخته نشود
|
||||
# ALIAS_REDIRECT_MIDDLEWARES=to-primary@docker
|
||||
|
||||
@@ -103,12 +103,47 @@ bash scripts/stack.sh deploy-prod
|
||||
`ssh -L 9001:127.0.0.1:9001 server`
|
||||
- همه روترهای websecure هدرهای امنیتی میگیرند (HSTS + nosniff)
|
||||
|
||||
### پیشنمایش خصوصی (کار روی سایت، قبل از انتشار عمومی)
|
||||
|
||||
سایت روی اینترنت بالا میآید و تیم با همان پنل مدیریت محتوا را ویرایش میکند
|
||||
(ویرایش درجای ایمیل/تلفن/متنها و نوشتن مقاله)، اما **نه عموم به آن دسترسی دارند و
|
||||
نه گوگل چیزی ایندکس میکند**. دو لایه محافظت:
|
||||
|
||||
1. **گیت ورود Traefik (Basic Auth)** — همه مسیرها (سایت، API، تصاویر و چت) پشت یک
|
||||
نام کاربری/رمز مشترکاند؛ بدون آن فقط ۴۰۱ برمیگردد
|
||||
2. **noindex** — هدر `X-Robots-Tag` روی همه پاسخها + `robots.txt` مسدودکننده +
|
||||
نقشه سایت خالی؛ حتی اگر گیت برداشته شود، گوگل چیزی ذخیره نمیکند
|
||||
|
||||
```bash
|
||||
bash scripts/preview-mode.sh on # فعالسازی (بار اول نام کاربری/رمز میسازد و چاپ میکند)
|
||||
bash scripts/stack.sh deploy-prod # اعمال
|
||||
bash scripts/preview-mode.sh status # وضعیت فعلی
|
||||
```
|
||||
|
||||
- دامنه اصلی (`DOMAIN`) و دامنه دوم (`DOMAIN_ALIAS`) هر دو سرو میشوند و هر دو گیت دارند
|
||||
- برای دادن دسترسی به کارفرما، همان نام کاربری/رمز مشترک را بدهید
|
||||
- رمز مشترک در `.env` (`PREVIEW_AUTH_USERS`) میماند — فقط یکبار چاپ میشود
|
||||
|
||||
### انتشار عمومی (برداشتن پیشنمایش)
|
||||
|
||||
```bash
|
||||
bash scripts/preview-mode.sh off # حذف گیت ورود + اجازه ایندکس
|
||||
bash scripts/stack.sh deploy-prod
|
||||
```
|
||||
|
||||
بعد از این مرحله:
|
||||
|
||||
1. دامنه دوم بهصورت ۳۰۱ دائمی به دامنه اصلی ریدایرکت میشود (جلوگیری از محتوای تکراری)
|
||||
2. در Search Console دامنه را تأیید و `https://DOMAIN/sitemap.xml` را ثبت کنید
|
||||
3. اگر پیشتر چیزی ایندکس شده بود، حذفش را از همان کنسول درخواست کنید
|
||||
|
||||
### چکلیست رفتن به تولید
|
||||
|
||||
1. `bash scripts/gen-env.sh` — رمزهای قوی جدید (رمزهای `.env` توسعه را کپی نکنید)
|
||||
2. DNS: رکوردهای دامنه و زیردامنهها + باز بودن پورتهای ۸۰/۴۴۳ در فایروال
|
||||
3. `DOMAIN`، `ACME_EMAIL`، `SITE_URL` را در `.env` تنظیم کنید
|
||||
4. اولین انتشار را روی یک زیردامنه آزمایشی انجام دهید (نقش staging) — `deploy-prod`
|
||||
3. `DOMAIN`، `DOMAIN_ALIAS` (دامنه دوم)، `ACME_EMAIL`، `SITE_URL` را در `.env` تنظیم کنید
|
||||
4. `bash scripts/preview-mode.sh on` — اولین انتشار بهصورت پیشنمایش خصوصی میرود؛
|
||||
محتوا را روی سایت آنلاین نهایی کنید و بعد `preview-mode.sh off` + deploy مجدد
|
||||
5. `python scripts/migrate-media.py` — انتقال یکباره تصاویر CDN خارجی به MinIO
|
||||
6. پشتیبانگیری خودکار: `docker compose --profile ops up -d db-backup` (پشتیبان ساعتی)
|
||||
+ `scripts/backup.sh` شبانه با cron/Task Scheduler
|
||||
|
||||
+121
-17
@@ -1,13 +1,19 @@
|
||||
"""انتهای پنل مدیریت — همه مسیرها نیازمند توکن JWT معتبر هستند."""
|
||||
|
||||
import csv
|
||||
import ipaddress
|
||||
import io
|
||||
import re
|
||||
import socket
|
||||
import urllib.request
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import boto3
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Request, Response, UploadFile, status
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, Response, UploadFile, status
|
||||
from PIL import Image, ImageOps
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -294,9 +300,41 @@ def _optimize_image(data: bytes, content_type: str) -> tuple[bytes, str, int, in
|
||||
return data, content_type, orig_w, orig_h
|
||||
|
||||
|
||||
def _readable_key(name: str, ext: str) -> str:
|
||||
"""کلید ذخیرهسازی خوانا از نام دلخواه/نام فایل — «۱۴۰۳/elahieh-tower-a1b2c3.jpg».
|
||||
|
||||
نامگذاریها ایمن میشوند: نویسههای ناامن و جداکننده مسیر حذف، فاصلهها خط تیره،
|
||||
طول محدود؛ خالی بودن نام → شناسه تصادفی مثل قبل. پسوند ۶ نویسهای تضمین یکتایی است.
|
||||
"""
|
||||
slug = re.sub(r"[^\w-ۿ\- ]+", "", name, flags=re.UNICODE).strip()
|
||||
slug = re.sub(r"[\s_]+", "-", slug).strip("-")[:80]
|
||||
unique = uuid.uuid4().hex[:6]
|
||||
base = f"{slug}-{unique}" if slug else uuid.uuid4().hex
|
||||
return f"{datetime.now(timezone.utc):%Y/%m}/{base}.{ext}"
|
||||
|
||||
|
||||
def _store_image(data: bytes, content_type: str, name: str) -> str:
|
||||
"""ذخیره تصویر در Object Storage با کلید خوانا — URL نسبی برمیگردد."""
|
||||
ext = ALLOWED_IMAGE_TYPES[content_type]
|
||||
key = _readable_key(name, ext)
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=settings.s3_endpoint,
|
||||
aws_access_key_id=settings.s3_access_key,
|
||||
aws_secret_access_key=settings.s3_secret_key,
|
||||
region_name="us-east-1",
|
||||
)
|
||||
try:
|
||||
s3.put_object(Bucket=settings.s3_bucket, Key=key, Body=data, ContentType=content_type)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=502, detail="ذخیره فایل در Object Storage ناموفق بود")
|
||||
return f"{settings.media_public_base}/{key}"
|
||||
|
||||
|
||||
@router.post("/upload")
|
||||
async def upload_media(
|
||||
file: UploadFile = File(...),
|
||||
name: str = Form(""),
|
||||
_admin: models.AdminUser = Depends(get_current_admin),
|
||||
):
|
||||
content_type = (file.content_type or "").lower()
|
||||
@@ -325,24 +363,90 @@ async def upload_media(
|
||||
# تصویر خراب/ناشناخته — همان داده اصلی ذخیره میشود
|
||||
pass
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
key = f"{now:%Y/%m}/{uuid.uuid4().hex}.{ext}"
|
||||
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=settings.s3_endpoint,
|
||||
aws_access_key_id=settings.s3_access_key,
|
||||
aws_secret_access_key=settings.s3_secret_key,
|
||||
region_name="us-east-1",
|
||||
)
|
||||
try:
|
||||
s3.put_object(Bucket=settings.s3_bucket, Key=key, Body=data, ContentType=content_type)
|
||||
except Exception:
|
||||
raise HTTPException(status_code=502, detail="ذخیره فایل در Object Storage ناموفق بود")
|
||||
# نام خوانا: نام ارسالی فرم، وگرنه نام اصلی فایل بدون پسوند
|
||||
display_name = (name or "").strip() or (file.filename or "").rsplit(".", 1)[0]
|
||||
url = _store_image(data, content_type, display_name)
|
||||
|
||||
return {
|
||||
"url": f"{settings.media_public_base}/{key}",
|
||||
"key": key,
|
||||
"url": url,
|
||||
"key": url.removeprefix(f"{settings.media_public_base}/"),
|
||||
"size": len(data),
|
||||
"content_type": content_type,
|
||||
"width": width,
|
||||
"height": height,
|
||||
}
|
||||
|
||||
|
||||
# ---------- درونریزی تصویر از نشانی خارجی (چسباندن از Outline و مانند آن) ----------
|
||||
|
||||
|
||||
class ImportImageIn(BaseModel):
|
||||
url: str
|
||||
|
||||
|
||||
def _assert_public_http(url: str) -> None:
|
||||
"""فقط http/https به مقاصد عمومی — جلوگیری از SSRF به شبکه داخلی."""
|
||||
parsed = urlparse(url)
|
||||
if parsed.scheme not in ("http", "https") or not parsed.hostname:
|
||||
raise HTTPException(status_code=400, detail="نشانی تصویر معتبر نیست")
|
||||
try:
|
||||
infos = socket.getaddrinfo(parsed.hostname, None)
|
||||
except socket.gaierror:
|
||||
raise HTTPException(status_code=400, detail="میزبان تصویر پیدا نشد")
|
||||
for info in infos:
|
||||
ip = ipaddress.ip_address(info[4][0])
|
||||
if not ip.is_global:
|
||||
raise HTTPException(status_code=400, detail="نشانی تصویر به میزبان داخلی اشاره میکند")
|
||||
|
||||
|
||||
@router.post("/import-image")
|
||||
async def import_image(
|
||||
payload: ImportImageIn,
|
||||
_admin: models.AdminUser = Depends(get_current_admin),
|
||||
):
|
||||
"""دانلود تصویر از نشانی خارجی، بهینهسازی و ذخیره در Object Storage خودِ سایت —
|
||||
تصاویر چسباندهشده از Outline/مستندات خارجی به میزبانی سایت منتقل میشوند."""
|
||||
_assert_public_http(payload.url)
|
||||
|
||||
max_bytes = settings.media_max_upload_mb * 1024 * 1024
|
||||
request = urllib.request.Request(
|
||||
payload.url, headers={"User-Agent": "ArameshSite/1.0 (+image import)"}
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=15) as response:
|
||||
content_type = (response.headers.get("Content-Type") or "").split(";")[0].strip().lower()
|
||||
if content_type not in ALLOWED_IMAGE_TYPES:
|
||||
raise HTTPException(
|
||||
status_code=415,
|
||||
detail="فرمت تصویر پشتیبانی نمیشود (مجاز: jpg، png، webp، gif، avif)",
|
||||
)
|
||||
data = response.read(max_bytes + 1)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
raise HTTPException(status_code=502, detail="دانلود تصویر از نشانی ناموفق بود")
|
||||
if len(data) == 0:
|
||||
raise HTTPException(status_code=400, detail="تصویر خالی است")
|
||||
if len(data) > max_bytes:
|
||||
raise HTTPException(
|
||||
status_code=413,
|
||||
detail=f"حجم تصویر بیش از {settings.media_max_upload_mb} مگابایت است",
|
||||
)
|
||||
|
||||
width = height = None
|
||||
if content_type in REENCODE_TYPES:
|
||||
try:
|
||||
data, content_type, width, height = _optimize_image(data, content_type)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# نام خوانا از مسیر نشانی — بدون پارامترهای کوئری
|
||||
url_name = urlparse(payload.url).path.rsplit("/", 1)[-1].rsplit(".", 1)[0]
|
||||
media_url = _store_image(data, content_type, url_name)
|
||||
|
||||
return {
|
||||
"url": media_url,
|
||||
"key": media_url.removeprefix(f"{settings.media_public_base}/"),
|
||||
"size": len(data),
|
||||
"content_type": content_type,
|
||||
"width": width,
|
||||
|
||||
@@ -32,6 +32,10 @@ class Settings(BaseSettings):
|
||||
site_url: str = ""
|
||||
# مسیر بیلد فرانتاند (شامل index.html) — برای سرو HTML با متای سئو در صفحات جزئیات
|
||||
frontend_dist: str = "../frontend/dist"
|
||||
# پیشنمایش خصوصی: سایت روی اینترنت است اما نه عمومی و نه ایندکسشدنی.
|
||||
# گیت اصلی ورود در Traefik است (Basic Auth)؛ این پرچم لایه دوم است:
|
||||
# هدر noindex روی همه پاسخها + robots.txt مسدودکننده.
|
||||
preview_mode: bool = False
|
||||
|
||||
|
||||
settings = Settings()
|
||||
|
||||
@@ -34,6 +34,17 @@ app.add_middleware(
|
||||
# پاسخهای JSON /api — فشردهسازی وقتی بدنه قابلتوجه است
|
||||
app.add_middleware(GZipMiddleware, minimum_size=1024)
|
||||
|
||||
|
||||
# پیشنمایش خصوصی — لایه دوم جلوگیری از ایندکس (لایه اول، گیت ورود Traefik است).
|
||||
# روی همه پاسخها هدر noindex مینشیند تا حتی در صورت حذف گیت، گوگل چیزی ذخیره نکند.
|
||||
# همیشه ثبت میشود و پرچم در زمان هر درخواست خوانده میشود (خاموشکردن انتشار = فقط تغییر .env).
|
||||
@app.middleware("http")
|
||||
async def _preview_noindex(request, call_next):
|
||||
response = await call_next(request)
|
||||
if settings.preview_mode:
|
||||
response.headers["X-Robots-Tag"] = "noindex, nofollow, noarchive"
|
||||
return response
|
||||
|
||||
app.include_router(public.router, prefix="/api", tags=["عمومی"])
|
||||
app.include_router(forms.router, prefix="/api", tags=["فرمها"])
|
||||
app.include_router(admin.auth_router, prefix="/api", tags=["احراز هویت"])
|
||||
|
||||
@@ -145,6 +145,17 @@ def run_ddl_migrations() -> None:
|
||||
conn.execute(
|
||||
text("ALTER TABLE articles ADD COLUMN IF NOT EXISTS seo_keyphrase VARCHAR(128) NOT NULL DEFAULT ''")
|
||||
)
|
||||
# متادیتای تصویر شاخص مقاله + پرسشوپاسخهای پایان مقاله (سئو)
|
||||
conn.execute(
|
||||
text("ALTER TABLE articles ADD COLUMN IF NOT EXISTS image_alt VARCHAR(256) NOT NULL DEFAULT ''")
|
||||
)
|
||||
conn.execute(
|
||||
text("ALTER TABLE articles ADD COLUMN IF NOT EXISTS image_title VARCHAR(256) NOT NULL DEFAULT ''")
|
||||
)
|
||||
conn.execute(text("ALTER TABLE articles ADD COLUMN IF NOT EXISTS faqs JSON"))
|
||||
conn.execute(text("ALTER TABLE articles ADD COLUMN IF NOT EXISTS faqs_en JSON"))
|
||||
# سطرهای موجود ستون تازه را NULL میگیرند — آرایه خالی یعنی «بدون پرسشوپاسخ»
|
||||
conn.execute(text("UPDATE articles SET faqs = '[]'::json WHERE faqs IS NULL"))
|
||||
# ستونهای انگلیسی — رشتهها با پیشفرض خالی، JSON بدون پیشفرض (NULL = بدون ترجمه)
|
||||
for table, column, col_type in EN_COLUMNS:
|
||||
if col_type == "JSON":
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import JSON, Boolean, DateTime, Integer, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
@@ -95,12 +96,18 @@ class Article(Base):
|
||||
category: Mapped[str] = mapped_column(String(64), default="")
|
||||
category_en: Mapped[str] = mapped_column(String(64), default="")
|
||||
image: Mapped[str] = mapped_column(Text, default="")
|
||||
# متن جایگزین و عنوان تصویر شاخص — سئو و دسترسپذیری
|
||||
image_alt: Mapped[str] = mapped_column(String(256), default="")
|
||||
image_title: Mapped[str] = mapped_column(String(256), default="")
|
||||
read: Mapped[str] = mapped_column(String(32), default="")
|
||||
read_en: Mapped[str] = mapped_column(String(32), default="")
|
||||
excerpt: Mapped[str] = mapped_column(Text, default="")
|
||||
excerpt_en: Mapped[str] = mapped_column(Text, default="")
|
||||
body: Mapped[list] = mapped_column(JSON, default=list) # سند TipTap (تاریخی: لیست پاراگراف)
|
||||
body_en: Mapped[dict] = mapped_column(JSON, default=dict) # سند TipTap انگلیسی
|
||||
# پرسش و پاسخهای پایان مقاله — [{question, answer}]؛ برای نتایج غنی سئو (FAQPage)
|
||||
faqs: Mapped[list] = mapped_column(JSON, default=list)
|
||||
faqs_en: Mapped[Optional[list]] = mapped_column(JSON) # NULL یعنی بدون ترجمه — برگشت به فارسی
|
||||
# draft | published — پیشنویس فقط برای ادمین دیده میشود
|
||||
status: Mapped[str] = mapped_column(String(16), default="published")
|
||||
# کلمه کلیدی هدف چکلیست سئو — راهنمای نوشتن، در سایت نمایش داده نمیشود
|
||||
|
||||
@@ -77,12 +77,17 @@ class ArticleOut(ORMModel):
|
||||
category: str
|
||||
category_en: str = ""
|
||||
image: str
|
||||
image_alt: str = ""
|
||||
image_title: str = ""
|
||||
read: str
|
||||
read_en: str = ""
|
||||
excerpt: str
|
||||
excerpt_en: str = ""
|
||||
body: dict
|
||||
body_en: Optional[dict] = None
|
||||
# پرسشوپاسخهای پایان مقاله — [{question, answer}]؛ سطرهای قدیمی ممکن است NULL باشند
|
||||
faqs: Optional[list[dict]] = None
|
||||
faqs_en: Optional[list[dict]] = None
|
||||
status: str
|
||||
seo_keyphrase: str
|
||||
|
||||
@@ -484,12 +489,16 @@ class ArticleIn(BaseModel):
|
||||
category: str = ""
|
||||
category_en: str = ""
|
||||
image: str = ""
|
||||
image_alt: str = ""
|
||||
image_title: str = ""
|
||||
read: str = ""
|
||||
read_en: str = ""
|
||||
excerpt: str = ""
|
||||
excerpt_en: str = ""
|
||||
body: dict = Field(default_factory=lambda: dict(EMPTY_DOC))
|
||||
body_en: dict = Field(default_factory=lambda: dict(EMPTY_DOC))
|
||||
faqs: list[dict] = []
|
||||
faqs_en: list[dict] = []
|
||||
status: Literal["draft", "published"] = "draft"
|
||||
seo_keyphrase: str = Field(default="", max_length=128)
|
||||
_validate_body = field_validator("body")(validate_doc_body)
|
||||
@@ -786,12 +795,16 @@ class ArticlePatch(BaseModel):
|
||||
category: Optional[str] = None
|
||||
category_en: Optional[str] = None
|
||||
image: Optional[str] = None
|
||||
image_alt: Optional[str] = None
|
||||
image_title: Optional[str] = None
|
||||
read: Optional[str] = None
|
||||
read_en: Optional[str] = None
|
||||
excerpt: Optional[str] = None
|
||||
excerpt_en: Optional[str] = None
|
||||
body: Optional[dict] = None
|
||||
body_en: Optional[dict] = None
|
||||
faqs: Optional[list[dict]] = None
|
||||
faqs_en: Optional[list[dict]] = None
|
||||
status: Optional[Literal["draft", "published"]] = None
|
||||
seo_keyphrase: Optional[str] = None
|
||||
_validate_body = field_validator("body")(validate_doc_body)
|
||||
|
||||
@@ -188,6 +188,12 @@ def _meta_for(db: Session, page_key: str, lang: str) -> tuple[str, str]:
|
||||
|
||||
@router.get("/robots.txt", response_class=Response)
|
||||
def robots(db: Session = Depends(get_db)):
|
||||
# پیشنمایش خصوصی — هیچ خزندهای نباید چیزی ذخیره کند
|
||||
if settings.preview_mode:
|
||||
return Response(
|
||||
content="User-agent: *\nDisallow: /\n",
|
||||
media_type="text/plain; charset=utf-8",
|
||||
)
|
||||
lines = ["User-agent: *", "Disallow: /admin", "Disallow: /api", ""]
|
||||
if settings.site_url:
|
||||
lines.append(f"Sitemap: {_absolute('/sitemap.xml')}")
|
||||
@@ -206,6 +212,13 @@ def _sitemap_entry(loc: str, fa: str, en: str) -> str:
|
||||
|
||||
@router.get("/sitemap.xml", response_class=Response)
|
||||
def sitemap(db: Session = Depends(get_db)):
|
||||
# پیشنمایش خصوصی — نقشه سایت خالی تا هیچ نشانیای اعلام نشود
|
||||
if settings.preview_mode:
|
||||
xml = (
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>\n'
|
||||
)
|
||||
return Response(content=xml, media_type="application/xml; charset=utf-8")
|
||||
fa_urls = list(STATIC_PATHS)
|
||||
fa_urls += [
|
||||
f"/blog/{a.slug}"
|
||||
@@ -262,7 +275,7 @@ def blog_detail(slug: str, db: Session = Depends(get_db)):
|
||||
brand = _brand_name(db)
|
||||
title, excerpt = _article_pair(article, "fa")
|
||||
first_text = _doc_text(article.body) if not isinstance(article.body, list) else " ".join(article.body[:2])
|
||||
jsonld = {
|
||||
jsonld: object = {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Article",
|
||||
"headline": title,
|
||||
@@ -273,6 +286,10 @@ def blog_detail(slug: str, db: Session = Depends(get_db)):
|
||||
"publisher": {"@type": "Organization", "name": brand},
|
||||
"mainEntityOfPage": _absolute(f"/blog/{article.slug}"),
|
||||
}
|
||||
# پرسشوپاسخ مقاله → اسکیمای FAQPage در همان بلوک (آرایهای از دو اسکیما)
|
||||
faq_schema = _faq_jsonld(article, "fa")
|
||||
if faq_schema:
|
||||
jsonld = [jsonld, faq_schema]
|
||||
noscript = f"<h1>{html.escape(title)}</h1><p>{html.escape(first_text)}</p>"
|
||||
return _shell(
|
||||
title=f"{title} | {brand}",
|
||||
@@ -325,12 +342,35 @@ def project_detail(slug: str, db: Session = Depends(get_db)):
|
||||
# ---------- صفحات انگلیسی (/en/...) ----------
|
||||
|
||||
|
||||
def _faq_jsonld(article: models.Article, lang: str) -> dict | None:
|
||||
"""اسکیمای FAQPage برای نتایج غنی گوگل — از پرسشوپاسخهای پایان مقاله.
|
||||
نسخه انگلیسی فقط وقتی ترجمه ثبت شده باشد جایگزین میشود."""
|
||||
faqs = article.faqs if isinstance(article.faqs, list) else []
|
||||
if lang == "en":
|
||||
faqs_en = article.faqs_en if isinstance(article.faqs_en, list) else None
|
||||
if faqs_en:
|
||||
faqs = faqs_en
|
||||
entities = [
|
||||
{"@type": "Question", "name": (f.get("question") or "").strip(),
|
||||
"acceptedAnswer": {"@type": "Answer", "text": (f.get("answer") or "").strip()}}
|
||||
for f in faqs
|
||||
if isinstance(f, dict) and (f.get("question") or "").strip()
|
||||
]
|
||||
if not entities:
|
||||
return None
|
||||
return {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "FAQPage",
|
||||
"mainEntity": entities,
|
||||
}
|
||||
|
||||
|
||||
def _en_blog_detail(article: models.Article, db: Session) -> HTMLResponse:
|
||||
brand = _brand_name(db, "en")
|
||||
title, excerpt = _article_pair(article, "en")
|
||||
body = article.body_en if isinstance(article.body_en, dict) else article.body
|
||||
first_text = _doc_text(body) if not isinstance(body, list) else " ".join(body[:2])
|
||||
jsonld = {
|
||||
jsonld: object = {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Article",
|
||||
"headline": title,
|
||||
@@ -341,6 +381,9 @@ def _en_blog_detail(article: models.Article, db: Session) -> HTMLResponse:
|
||||
"publisher": {"@type": "Organization", "name": brand},
|
||||
"mainEntityOfPage": _absolute(f"/en/blog/{article.slug}"),
|
||||
}
|
||||
faq_schema = _faq_jsonld(article, "en")
|
||||
if faq_schema:
|
||||
jsonld = [jsonld, faq_schema]
|
||||
noscript = f"<h1>{html.escape(title)}</h1><p>{html.escape(first_text)}</p>"
|
||||
return _shell(
|
||||
title=f"{title} | {brand}",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""تستهای API — مسیرهای عمومی، احراز هویت، CRUD مدیریت، پیشنویس مقاله و سئو."""
|
||||
|
||||
import re
|
||||
import socket
|
||||
|
||||
DOC = {"type": "doc", "content": [{"type": "paragraph"}]}
|
||||
|
||||
@@ -361,3 +362,218 @@ def test_article_body_url_sanitization(auth_client):
|
||||
body = res.json()["body"]
|
||||
marks = body["content"][0]["content"][0].get("marks", [])
|
||||
assert all("href" not in m.get("attrs", {}) for m in marks)
|
||||
|
||||
|
||||
# ---------- نامگذاری تصاویر، درونریزی و پرسشوپاسخ مقاله ----------
|
||||
|
||||
|
||||
class _FakeS3:
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.objects = {}
|
||||
|
||||
def put_object(self, **kwargs):
|
||||
self.objects[kwargs["Key"]] = kwargs["Body"]
|
||||
|
||||
|
||||
def _mock_storage(monkeypatch):
|
||||
"""MinIO در تست در دسترس نیست — کلاینت S3 و DNS عمومی جعل میشوند."""
|
||||
fake = _FakeS3()
|
||||
monkeypatch.setattr("app.api.admin.boto3.client", lambda *a, **k: fake)
|
||||
monkeypatch.setattr(
|
||||
"app.api.admin.socket.getaddrinfo",
|
||||
lambda host, port, *a, **k: [(socket.AF_INET, None, None, "", ("93.184.216.34", 0))],
|
||||
)
|
||||
return fake
|
||||
|
||||
|
||||
def _png_bytes() -> bytes:
|
||||
from PIL import Image
|
||||
import io
|
||||
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (8, 8), (200, 120, 60)).save(buf, "PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_upload_with_readable_name(auth_client, monkeypatch):
|
||||
_mock_storage(monkeypatch)
|
||||
res = auth_client.post(
|
||||
"/api/admin/upload",
|
||||
files={"file": ("raw name.png", _png_bytes(), "image/png")},
|
||||
data={"name": "برج الهیه tower!"},
|
||||
)
|
||||
assert res.status_code == 200, res.text
|
||||
key = res.json()["key"]
|
||||
# نام خوانا (فارسی/لاتین، بدون نویسه ناامن) + پسوند یکتا + پسوند تصویر
|
||||
assert "برج-الهیه-tower" in key
|
||||
assert key.endswith(".png")
|
||||
assert "!" not in key
|
||||
|
||||
|
||||
def test_upload_without_name_uses_filename(auth_client, monkeypatch):
|
||||
_mock_storage(monkeypatch)
|
||||
res = auth_client.post(
|
||||
"/api/admin/upload",
|
||||
files={"file": ("Elahieh Tower.jpg", _png_bytes(), "image/jpeg")},
|
||||
data={"name": ""},
|
||||
)
|
||||
assert res.status_code == 200
|
||||
assert "Elahieh-Tower" in res.json()["key"]
|
||||
|
||||
|
||||
def test_import_image_rejects_internal_host(auth_client):
|
||||
# SSRF — میزبان حلقهمحلی/خصوصی رد میشود پیش از هر درخواست شبکه
|
||||
res = auth_client.post("/api/admin/import-image", json={"url": "http://127.0.0.1:9000/x.png"})
|
||||
assert res.status_code == 400
|
||||
res = auth_client.post("/api/admin/import-image", json={"url": "http://192.168.1.5/x.png"})
|
||||
assert res.status_code == 400
|
||||
res = auth_client.post("/api/admin/import-image", json={"url": "file:///etc/passwd"})
|
||||
assert res.status_code == 400
|
||||
|
||||
|
||||
def test_import_image_rejects_bad_content_type(auth_client, monkeypatch):
|
||||
_mock_storage(monkeypatch)
|
||||
import io as _io
|
||||
|
||||
class FakeResponse:
|
||||
def __init__(self):
|
||||
self.headers = {"Content-Type": "text/html"}
|
||||
|
||||
def read(self, n):
|
||||
return b"<html></html>"
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
return False
|
||||
|
||||
def fake_urlopen(request, timeout):
|
||||
return FakeResponse()
|
||||
|
||||
monkeypatch.setattr("app.api.admin.urllib.request.urlopen", fake_urlopen)
|
||||
res = auth_client.post("/api/admin/import-image", json={"url": "https://example.com/page"})
|
||||
assert res.status_code == 415
|
||||
|
||||
|
||||
def test_import_image_happy_path(auth_client, monkeypatch):
|
||||
_mock_storage(monkeypatch)
|
||||
class FakeResponse:
|
||||
def __init__(self):
|
||||
self.headers = {"Content-Type": "image/png"}
|
||||
|
||||
def read(self, n):
|
||||
return _png_bytes()
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr("app.api.admin.urllib.request.urlopen", lambda request, timeout: FakeResponse())
|
||||
res = auth_client.post("/api/admin/import-image", json={"url": "https://wiki.example/Elahieh pic.png?token=1"})
|
||||
assert res.status_code == 200, res.text
|
||||
assert res.json()["url"].startswith("/media/")
|
||||
assert "Elahieh-pic" in res.json()["key"]
|
||||
|
||||
|
||||
def test_article_persists_image_meta_and_faqs(auth_client, client):
|
||||
created = auth_client.post(
|
||||
"/api/admin/articles",
|
||||
json={"slug": "meta-article", "title": "متادیتا", "body": DOC},
|
||||
)
|
||||
assert created.status_code == 201, created.text
|
||||
article_id = created.json()["id"]
|
||||
|
||||
faqs = [{"question": "هزینه چقدر است؟", "answer": "بستگی به پروژه دارد."}]
|
||||
res = auth_client.patch(
|
||||
f"/api/admin/articles/{article_id}",
|
||||
json={
|
||||
"image_alt": "نمای برج الهیه",
|
||||
"image_title": "برج آرامش",
|
||||
"faqs": faqs,
|
||||
"faqs_en": [{"question": "What is the cost?", "answer": "Depends on the project."}],
|
||||
},
|
||||
)
|
||||
assert res.status_code == 200, res.text
|
||||
assert res.json()["image_alt"] == "نمای برج الهیه"
|
||||
assert res.json()["image_title"] == "برج آرامش"
|
||||
assert res.json()["faqs"] == faqs
|
||||
|
||||
# انتشار و سپس خروجی عمومی — همین مقادیر برمیگردد
|
||||
assert auth_client.patch(f"/api/admin/articles/{article_id}", json={"status": "published"}).status_code == 200
|
||||
public = client.get("/api/articles/meta-article").json()
|
||||
assert public["image_alt"] == "نمای برج الهیه"
|
||||
assert public["faqs"] == faqs
|
||||
|
||||
assert auth_client.delete(f"/api/admin/articles/{article_id}").status_code == 204
|
||||
|
||||
|
||||
def test_blog_shell_includes_faqpage_jsonld(auth_client, client):
|
||||
created = auth_client.post(
|
||||
"/api/admin/articles",
|
||||
json={
|
||||
"slug": "faq-article",
|
||||
"title": "مقاله پرسشوپاسخ",
|
||||
"body": DOC,
|
||||
"status": "published",
|
||||
"faqs": [{"question": "زمان ساخت؟", "answer": "۳۰ ماه."}],
|
||||
},
|
||||
)
|
||||
assert created.status_code == 201, created.text
|
||||
|
||||
res = client.get("/blog/faq-article")
|
||||
assert res.status_code == 200
|
||||
assert "FAQPage" in res.text
|
||||
assert "زمان ساخت؟" in res.text
|
||||
|
||||
# نسخه انگلیسی بدون ترجمه → همان فارسی؛ با ترجمه → انگلیسی
|
||||
en = client.get("/en/blog/faq-article").text
|
||||
assert "FAQPage" in en
|
||||
article_id = created.json()["id"]
|
||||
auth_client.patch(
|
||||
f"/api/admin/articles/{article_id}",
|
||||
json={"faqs_en": [{"question": "How long?", "answer": "Thirty months."}]},
|
||||
)
|
||||
en = client.get("/en/blog/faq-article").text
|
||||
assert "How long?" in en
|
||||
assert "زمان ساخت؟" not in en
|
||||
|
||||
auth_client.delete(f"/api/admin/articles/{article_id}")
|
||||
|
||||
|
||||
def test_blog_shell_without_faqs_has_no_faqpage(client):
|
||||
res = client.get("/blog/published-post")
|
||||
assert res.status_code == 200
|
||||
assert "FAQPage" not in res.text
|
||||
|
||||
|
||||
# ---------- پیشنمایش خصوصی (برای انتشار عمومی خاموش میشود) ----------
|
||||
|
||||
|
||||
def test_preview_mode_blocks_robots_and_sitemap(client, monkeypatch):
|
||||
from app.config import settings
|
||||
|
||||
monkeypatch.setattr(settings, "preview_mode", True)
|
||||
try:
|
||||
robots = client.get("/robots.txt")
|
||||
assert robots.status_code == 200
|
||||
assert "Disallow: /" in robots.text
|
||||
assert "Sitemap:" not in robots.text
|
||||
|
||||
sitemap = client.get("/sitemap.xml")
|
||||
assert sitemap.status_code == 200
|
||||
assert "published-post" not in sitemap.text
|
||||
|
||||
# لایه دوم: هدر noindex روی همه پاسخها
|
||||
assert "noindex" in client.get("/api/health").headers.get("X-Robots-Tag", "")
|
||||
finally:
|
||||
monkeypatch.setattr(settings, "preview_mode", False)
|
||||
|
||||
|
||||
def test_public_mode_allows_indexing(client):
|
||||
robots = client.get("/robots.txt").text
|
||||
assert "Disallow: /admin" in robots
|
||||
assert "Sitemap:" in robots
|
||||
assert "noindex" not in client.get("/api/health").headers.get("X-Robots-Tag", "")
|
||||
|
||||
+33
-5
@@ -6,6 +6,16 @@
|
||||
#
|
||||
# همه درخواستهای HTTP به HTTPS هدایت میشوند و مسیریابیها فقط روی دامنه DOMAIN پاسخ میدهند.
|
||||
# برای داشبوردها: analytics.DOMAIN (آنالیتیکس) و grafana.DOMAIN (مانیتورینگ، با فایل monitoring).
|
||||
#
|
||||
# ---- پیشنمایش خصوصی و انتشار (scripts/preview-mode.sh) ----
|
||||
# در حالت پیشنمایش (PREVIEW_MODE=on) کل سایت پشت Basic Auth است و noindex میگیرد:
|
||||
# تیم با یک نام کاربری/رمز مشترک وارد میشود، محتوا را ویرایش میکند و هیچکس دیگری —
|
||||
# از جمله گوگل — به سایت دسترسی ندارد. برای انتشار عمومی:
|
||||
# bash scripts/preview-mode.sh off → deploy مجدد → ثبت sitemap در Search Console.
|
||||
#
|
||||
# DOMAIN دامنه اصلی است و DOMAIN_ALIAS دامنه دوم (هر دو مسیر و گواهی میگیرند).
|
||||
# در زمان انتشار، برای جلوگیری از محتوای تکراری، دامنه دوم را به اصلی ریدایرکت کنید:
|
||||
# ALIAS_REDIRECT=on (در .env) — ریدایرکت ۳۰۱ دائمی به دامنه اصلی.
|
||||
|
||||
services:
|
||||
traefik:
|
||||
@@ -43,7 +53,7 @@ services:
|
||||
- traefik.http.routers.media.entrypoints=websecure
|
||||
- traefik.http.routers.media.tls.certresolver=le
|
||||
- traefik.http.routers.media.priority=100
|
||||
- traefik.http.routers.media.middlewares=media-rewrite,sec-headers
|
||||
- traefik.http.routers.media.middlewares=${PREVIEW_MIDDLEWARES:+$PREVIEW_MIDDLEWARES,}media-rewrite,sec-headers
|
||||
- traefik.http.middlewares.media-rewrite.replacepathregex.regex=^/media/(.*)
|
||||
- traefik.http.middlewares.media-rewrite.replacepathregex.replacement=/aramesh-media/$$1
|
||||
- traefik.http.services.media.loadbalancer.server.port=9000
|
||||
@@ -53,16 +63,18 @@ services:
|
||||
# سایت هممبدأ است — CORS لازم نیست
|
||||
CORS_ORIGINS: '[]'
|
||||
SITE_URL: https://${DOMAIN:?DOMAIN را در .env تنظیم کنید}
|
||||
# پیشنمایش خصوصی — هدر noindex + robots مسدودکننده (لایه دوم؛ لایه اول گیت Traefik)
|
||||
PREVIEW_MODE: ${PREVIEW_MODE:-off}
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.http.routers.api.rule=Host(`${DOMAIN}`) && PathPrefix(`/api`)
|
||||
- traefik.http.routers.api.entrypoints=websecure
|
||||
- traefik.http.routers.api.tls.certresolver=le
|
||||
- traefik.http.routers.api.middlewares=api-flood,sec-headers
|
||||
- traefik.http.routers.api.middlewares=${PREVIEW_MIDDLEWARES:+$PREVIEW_MIDDLEWARES,}api-flood,sec-headers
|
||||
- traefik.http.routers.seo.rule=Host(`${DOMAIN}`) && (PathPrefix(`/blog/`) || Path(`/blog`) || PathPrefix(`/projects/`) || Path(`/projects`) || Path(`/en`) || PathPrefix(`/en/`) || PathPrefix(`/robots.txt`) || PathPrefix(`/sitemap.xml`))
|
||||
- traefik.http.routers.seo.entrypoints=websecure
|
||||
- traefik.http.routers.seo.tls.certresolver=le
|
||||
- traefik.http.routers.seo.middlewares=sec-headers
|
||||
- traefik.http.routers.seo.middlewares=${PREVIEW_MIDDLEWARES:+$PREVIEW_MIDDLEWARES,}sec-headers
|
||||
|
||||
frontend:
|
||||
labels:
|
||||
@@ -70,12 +82,28 @@ services:
|
||||
- traefik.http.routers.web.rule=Host(`${DOMAIN}`) && PathPrefix(`/`)
|
||||
- traefik.http.routers.web.entrypoints=websecure
|
||||
- traefik.http.routers.web.tls.certresolver=le
|
||||
- traefik.http.routers.web.middlewares=sec-headers
|
||||
- traefik.http.routers.web.middlewares=${PREVIEW_MIDDLEWARES:+$PREVIEW_MIDDLEWARES,}sec-headers
|
||||
# تعریف یکبارهٔ میانافزار هدرهای امنیتی — روی همهٔ روترهای websecure استفاده میشود
|
||||
- traefik.http.middlewares.sec-headers.headers.stsSeconds=31536000
|
||||
- traefik.http.middlewares.sec-headers.headers.stsIncludeSubdomains=true
|
||||
- traefik.http.middlewares.sec-headers.headers.stsPreload=true
|
||||
- traefik.http.middlewares.sec-headers.headers.contentTypeNosniff=true
|
||||
# ---- گیت پیشنمایش خصوصی ----
|
||||
# ورود با نام کاربری/رمز مشترک (htpasswd) — تا وقتی PREVIEW_MIDDLEWARES تنظیم است فعال میشود
|
||||
- traefik.http.middlewares.preview-auth.basicauth.users=${PREVIEW_AUTH_USERS:-disabled:nope}
|
||||
- traefik.http.middlewares.preview-auth.basicauth.realm=Aramesh private preview
|
||||
# لایه دوم جلوگیری از ایندکس — حتی اگر گیت حذف شد، گوگل چیزی ذخیره نکند
|
||||
- traefik.http.middlewares.preview-noindex.headers.customresponseheaders.X-Robots-Tag=noindex, nofollow, noarchive
|
||||
# ---- ریدایرکت دامنه دوم به اصلی (زمان انتشار: ALIAS_REDIRECT=on) ----
|
||||
- traefik.http.middlewares.to-primary.redirectregex.regex=^https?://[^/]+(.*)
|
||||
- traefik.http.middlewares.to-primary.redirectregex.replacement=https://${DOMAIN}$$1
|
||||
- traefik.http.middlewares.to-primary.redirectregex.permanent=true
|
||||
- traefik.http.routers.alias-redirect.rule=Host(`${DOMAIN_ALIAS:-invalid.invalid}`)
|
||||
- traefik.http.routers.alias-redirect.entrypoints=websecure
|
||||
- traefik.http.routers.alias-redirect.tls.certresolver=le
|
||||
- traefik.http.routers.alias-redirect.priority=1000
|
||||
- traefik.http.routers.alias-redirect.middlewares=${ALIAS_REDIRECT_MIDDLEWARES:-sec-headers}
|
||||
- traefik.http.routers.alias-redirect.service=web
|
||||
|
||||
chatbot:
|
||||
labels:
|
||||
@@ -84,7 +112,7 @@ services:
|
||||
- traefik.http.routers.chat.entrypoints=websecure
|
||||
- traefik.http.routers.chat.tls.certresolver=le
|
||||
- traefik.http.routers.chat.priority=100
|
||||
- traefik.http.routers.chat.middlewares=api-flood,sec-headers
|
||||
- traefik.http.routers.chat.middlewares=${PREVIEW_MIDDLEWARES:+$PREVIEW_MIDDLEWARES,}api-flood,sec-headers
|
||||
|
||||
umami:
|
||||
labels:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Controller, useController, useForm } from 'react-hook-form'
|
||||
import { Link, Navigate, useNavigate, useParams } from 'react-router-dom'
|
||||
import { ArrowRightIcon, CheckIcon, EyeIcon, Trash2Icon } from 'lucide-react'
|
||||
import { ArrowRightIcon, CheckIcon, EyeIcon, PlusIcon, Trash2Icon, XIcon } from 'lucide-react'
|
||||
import Swal from 'sweetalert2'
|
||||
import { useSiteData } from '../api'
|
||||
import { useAdmin } from './AdminContext'
|
||||
@@ -54,6 +54,75 @@ function normalizeTags(value: unknown): string[] {
|
||||
return []
|
||||
}
|
||||
|
||||
/** یک ردیف پرسشوپاسخ مقاله */
|
||||
type ArticleFaq = { question: string; answer: string }
|
||||
|
||||
/**
|
||||
* پنل پرسشوپاسخهای پایان مقاله — مثل بخش متا دیسکریپشن زیر ویرایشگر.
|
||||
* در زبان فارسی ستون faqs و در زبان انگلیسی faqs_en را ویرایش میکند؛
|
||||
* نسخه انگلیسیِ خالی در سایت به فارسی برمیگردد. ذخیرهسازی خودکار است.
|
||||
*/
|
||||
function FaqPanel({
|
||||
faqs,
|
||||
onChange,
|
||||
}: {
|
||||
faqs: ArticleFaq[]
|
||||
onChange: (next: ArticleFaq[]) => void
|
||||
}) {
|
||||
const update = (index: number, patch: Partial<ArticleFaq>) => {
|
||||
const next = faqs.map((f, i) => (i === index ? { ...f, ...patch } : f))
|
||||
onChange(next)
|
||||
}
|
||||
const remove = (index: number) => onChange(faqs.filter((_, i) => i !== index))
|
||||
const add = () => onChange([...faqs, { question: '', answer: '' }])
|
||||
|
||||
return (
|
||||
<div className="mt-4 grid gap-4">
|
||||
{faqs.map((faq, i) => (
|
||||
<div key={i} className="grid gap-3 border border-ivory/10 bg-ink/60 p-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-[11px] font-light text-copper">پرسش {i + 1}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => remove(i)}
|
||||
aria-label={`حذف پرسش ${i + 1}`}
|
||||
className="flex h-7 w-7 items-center justify-center border border-red-400/40 text-red-300 transition-colors hover:bg-red-500/10"
|
||||
>
|
||||
<XIcon className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
dir="auto"
|
||||
value={faq.question}
|
||||
onChange={(e) => update(i, { question: e.target.value })}
|
||||
placeholder="پرسش مخاطب…"
|
||||
aria-label={`متن پرسش ${i + 1}`}
|
||||
className="w-full border border-ivory/15 bg-char px-3 py-2 text-sm font-light text-ivory focus:border-copper focus:outline-none"
|
||||
/>
|
||||
<textarea
|
||||
rows={2}
|
||||
dir="auto"
|
||||
value={faq.answer}
|
||||
onChange={(e) => update(i, { answer: e.target.value })}
|
||||
placeholder="پاسخ کوتاه و روشن…"
|
||||
aria-label={`پاسخ پرسش ${i + 1}`}
|
||||
className="w-full resize-y border border-ivory/15 bg-char px-3 py-2 text-sm font-light leading-8 text-ivory focus:border-copper focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
onClick={add}
|
||||
className="flex w-fit items-center gap-2 border border-dashed border-ivory/25 px-4 py-2 text-xs font-light text-ivory/60 transition-colors hover:border-copper hover:text-copper"
|
||||
>
|
||||
<PlusIcon className="h-3.5 w-3.5" />
|
||||
افزودن پرسشوپاسخ
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const STATUS_TEXT: Record<string, string> = {
|
||||
idle: 'ذخیره شد',
|
||||
saving: 'در حال ذخیره…',
|
||||
@@ -458,6 +527,20 @@ export function ArticleWritePage() {
|
||||
/>
|
||||
</section>
|
||||
|
||||
{/* پرسشوپاسخهای پایان مقاله — سئوی FAQPage */}
|
||||
<section className="mt-8 border border-ivory/15 bg-char p-6">
|
||||
<h2 className="text-sm font-bold text-copper">پرسشهای متداول مقاله</h2>
|
||||
<p className="mt-1 text-xs font-light text-ivory/50">
|
||||
در پایان مقاله با ظاهر آکاردئونی سایت نمایش داده میشود و با اسکیمای FAQPage
|
||||
شانس نمایش در نتایج غنی گوگل را بالا میبرد.
|
||||
{editLang === 'en' && ' — ویرایش نسخه انگلیسی (خالی = نمایش متن فارسی)'}
|
||||
</p>
|
||||
<FaqPanel
|
||||
faqs={(editLang === 'en' ? draft.faqs_en : draft.faqs) ?? []}
|
||||
onChange={(next) => queueSave({ [suf('faqs')]: next })}
|
||||
/>
|
||||
</section>
|
||||
|
||||
{/* چکیده و متادیتا */}
|
||||
<SeoChecklist
|
||||
input={{
|
||||
|
||||
@@ -83,12 +83,17 @@ export const adminApi = {
|
||||
reorder: <T = unknown>(resource: string, ids: number[]) =>
|
||||
authFetch<T[]>(`/api/admin/${resource}/reorder`, { method: 'POST', body: JSON.stringify({ ids }) }),
|
||||
|
||||
upload: async (file: File): Promise<{ url: string; key: string }> => {
|
||||
upload: async (file: File, name?: string): Promise<{ url: string; key: string }> => {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file)
|
||||
if (name && name.trim()) fd.append('name', name.trim())
|
||||
return authFetch('/api/admin/upload', { method: 'POST', body: fd })
|
||||
},
|
||||
|
||||
/** درونریزی تصویر از نشانی خارجی — دانلود و ذخیره در Object Storage خود سایت */
|
||||
importImage: async (url: string): Promise<{ url: string; key: string }> =>
|
||||
authFetch('/api/admin/import-image', { method: 'POST', body: JSON.stringify({ url }) }),
|
||||
|
||||
changePassword: (currentPassword: string, newPassword: string) =>
|
||||
authFetch<{ ok: boolean }>('/api/auth/change-password', {
|
||||
method: 'POST',
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { useState } from 'react'
|
||||
import { AnimatePresence, motion } from 'framer-motion'
|
||||
import { PlusIcon } from 'lucide-react'
|
||||
|
||||
/** یک پرسشوپاسخ مقاله — همان شکل داده ستون faqs مقاله در دیتابیس */
|
||||
export type ArticleFaq = { question: string; answer: string }
|
||||
|
||||
/**
|
||||
* پرسشوپاسخهای پایان مقاله — همان رفتار آکاردئونی بخش FAQ سایت، بدون ویرایش مدیریتی.
|
||||
* در سرچ کنسول/نتایج غنی گوگل، اسکیمای FAQPage آن جداگانه تزریق میشود.
|
||||
*/
|
||||
export function ArticleFaq({ faqs }: { faqs: ArticleFaq[] }) {
|
||||
const [open, setOpen] = useState<number | null>(0)
|
||||
|
||||
if (!faqs.length) return null
|
||||
|
||||
return (
|
||||
<section className="mt-16" aria-label="پرسشهای متداول مقاله">
|
||||
<div className="mt-6 h-px w-24 bg-copper/70" />
|
||||
<ul className="mt-2">
|
||||
{faqs.map((faq, i) => {
|
||||
const isOpen = open === i
|
||||
return (
|
||||
<li key={i} className="border-b border-ivory/10">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(isOpen ? null : i)}
|
||||
aria-expanded={isOpen}
|
||||
className="flex w-full items-center justify-between gap-6 py-6 text-start transition-colors duration-200 ease-lux hover:text-copper"
|
||||
>
|
||||
<span
|
||||
className={`text-base font-bold md:text-lg ${
|
||||
isOpen ? 'text-copper' : 'text-ivory'
|
||||
}`}
|
||||
>
|
||||
{faq.question}
|
||||
</span>
|
||||
<PlusIcon
|
||||
className={`h-5 w-5 shrink-0 text-copper transition-transform duration-300 ease-lux ${
|
||||
isOpen ? 'rotate-45' : ''
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
<AnimatePresence initial={false}>
|
||||
{isOpen && (
|
||||
<motion.div
|
||||
initial={{ height: 0, opacity: 0 }}
|
||||
animate={{ height: 'auto', opacity: 1 }}
|
||||
exit={{ height: 0, opacity: 0 }}
|
||||
transition={{ duration: 0.28, ease: [0.23, 1, 0.32, 1] }}
|
||||
className="overflow-hidden"
|
||||
>
|
||||
<p className="pb-7 ps-2 text-sm font-light leading-9 text-ivory/60">
|
||||
{faq.answer}
|
||||
</p>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -203,7 +203,7 @@ export function ContactSection() {
|
||||
className="mt-8 font-light"
|
||||
onClick={() => {
|
||||
setSent(false)
|
||||
setForm({ name: '', phone: '', note: '' })
|
||||
setForm({ name: '', phone: '', note: '', website: '' })
|
||||
}}
|
||||
>
|
||||
<InlineEdit value={content.success_button_label} onSave={(v) => saveContent('success_button_label', v)} />
|
||||
|
||||
@@ -102,6 +102,42 @@ const CLOSED_LINK_MODAL: LinkModalState = {
|
||||
/** چند نویسه پیش از نشانگر برای تشخیص نشانیِ تایپشده بررسی میشود */
|
||||
const URL_LOOKBACK = 300
|
||||
|
||||
/** آیا src تصویر خارج از میزبانی سایت است (مثل چسباندهشده از Outline)؟ */
|
||||
function isExternalImageSrc(src: string): boolean {
|
||||
if (!src || src.startsWith('data:')) return false
|
||||
if (src.startsWith('/')) return false // مسیر نسبی/داخلی
|
||||
try {
|
||||
return new URL(src).origin !== window.location.origin
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* میزبانی مجدد تصاویر خارجی یک HTML — هر <img> با نشانی خارجی از سرور دانلود و در
|
||||
* Object Storage خود سایت ذخیره و src آن بازنویسی میشود (چسباندن از Outline و مانند آن).
|
||||
* تصویری که درونریزیاش شکست بخورد با src اصلی میماند.
|
||||
*/
|
||||
async function rehostExternalImages(html: string): Promise<string> {
|
||||
const parsed = new DOMParser().parseFromString(html, 'text/html')
|
||||
const imgs = Array.from(parsed.querySelectorAll('img[src]'))
|
||||
const externals = imgs.filter((img) => isExternalImageSrc(img.getAttribute('src') ?? ''))
|
||||
if (!externals.length) return html
|
||||
|
||||
await Promise.all(
|
||||
externals.map(async (img) => {
|
||||
const original = img.getAttribute('src') ?? ''
|
||||
try {
|
||||
const { url } = await adminApi.importImage(original)
|
||||
img.setAttribute('src', url)
|
||||
} catch {
|
||||
// نشانی خارجی میماند — شاید خودش کار کند
|
||||
}
|
||||
}),
|
||||
)
|
||||
return parsed.body.innerHTML
|
||||
}
|
||||
|
||||
function ToolButton({
|
||||
onClick,
|
||||
active = false,
|
||||
@@ -144,6 +180,8 @@ export function ArticleEditor({ doc, onChange, contentKey }: ArticleEditorProps)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const [direction, setDirection] = useState<TextDirection>('rtl')
|
||||
const [linkModal, setLinkModal] = useState<LinkModalState>(CLOSED_LINK_MODAL)
|
||||
// مرحله نامگذاری درج تصویر از نوار ابزار — پیشفرض از نام خود فایل
|
||||
const [pendingImage, setPendingImage] = useState<{ file: File; name: string } | null>(null)
|
||||
|
||||
const editor = useEditor({
|
||||
extensions: ARTICLE_EXTENSIONS,
|
||||
@@ -163,6 +201,22 @@ export function ArticleEditor({ doc, onChange, contentKey }: ArticleEditorProps)
|
||||
void uploadAndInsert(file)
|
||||
return true
|
||||
}
|
||||
// محتوای HTML با تصویر خارجی (Outline و مانند آن) — تصاویر به میزبانی سایت منتقل میشوند
|
||||
const html = event.clipboardData?.getData('text/html') ?? ''
|
||||
if (html.includes('<img')) {
|
||||
const parsed = new DOMParser().parseFromString(html, 'text/html')
|
||||
const hasExternal = Array.from(parsed.querySelectorAll('img[src]')).some((img) =>
|
||||
isExternalImageSrc(img.getAttribute('src') ?? ''),
|
||||
)
|
||||
if (hasExternal) {
|
||||
event.preventDefault()
|
||||
void (async () => {
|
||||
const transformed = await rehostExternalImages(html)
|
||||
editor?.chain().focus().insertContent(transformed).run()
|
||||
})()
|
||||
return true
|
||||
}
|
||||
}
|
||||
// چسباندن یک نشانی → مودال لینک بلافاصله باز میشود
|
||||
const text = event.clipboardData?.getData('text/plain')?.trim() ?? ''
|
||||
if (isUrlLike(text)) {
|
||||
@@ -186,6 +240,21 @@ export function ArticleEditor({ doc, onChange, contentKey }: ArticleEditorProps)
|
||||
void uploadAndInsert(file)
|
||||
return true
|
||||
}
|
||||
const html = event.dataTransfer?.getData('text/html') ?? ''
|
||||
if (html.includes('<img')) {
|
||||
const parsed = new DOMParser().parseFromString(html, 'text/html')
|
||||
const hasExternal = Array.from(parsed.querySelectorAll('img[src]')).some((img) =>
|
||||
isExternalImageSrc(img.getAttribute('src') ?? ''),
|
||||
)
|
||||
if (hasExternal) {
|
||||
event.preventDefault()
|
||||
void (async () => {
|
||||
const transformed = await rehostExternalImages(html)
|
||||
editor?.chain().focus().insertContent(transformed).run()
|
||||
})()
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
},
|
||||
// پایان تایپ یک نشانی (فاصله بعد از آن) → مودال لینک باز میشود
|
||||
@@ -237,11 +306,11 @@ export function ArticleEditor({ doc, onChange, contentKey }: ArticleEditorProps)
|
||||
editor.commands.setContent(incoming, { emitUpdate: false })
|
||||
}, [editor, contentKey, doc])
|
||||
|
||||
async function uploadAndInsert(file: File) {
|
||||
async function uploadAndInsert(file: File, name?: string) {
|
||||
if (!editor) return
|
||||
setUploading(true)
|
||||
await runSave(async () => {
|
||||
const { url } = await adminApi.upload(file)
|
||||
const { url } = await adminApi.upload(file, name)
|
||||
// نام پیشفرض از نام فایل ساخته میشود و در نبود آن، مقدار پیشفرض ثابت میماند
|
||||
const defaultAlt = file.name.replace(/\.[^.]+$/, '').replace(/[-_]+/g, ' ').trim()
|
||||
editor
|
||||
@@ -411,12 +480,72 @@ export function ArticleEditor({ doc, onChange, contentKey }: ArticleEditorProps)
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) void uploadAndInsert(file)
|
||||
if (file) {
|
||||
setPendingImage({ file, name: file.name.replace(/\.[^.]+$/, '') })
|
||||
}
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* مرحله نامگذاری تصویر — نام خوانای ذخیرهسازی با یک کلیک تایید میشود */}
|
||||
{pendingImage && (
|
||||
<div
|
||||
className="fixed inset-0 z-[90] flex items-center justify-center bg-black/60 p-6 backdrop-blur-sm"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="نام تصویر"
|
||||
onClick={() => setPendingImage(null)}
|
||||
>
|
||||
<div
|
||||
dir="rtl"
|
||||
className="w-full max-w-sm border border-ivory/15 bg-ink p-6 shadow-2xl"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<h2 className="text-sm font-bold text-copper">درج تصویر</h2>
|
||||
<label htmlFor="image-name-input" className="mt-4 block text-xs font-light text-ivory/60">
|
||||
نام فایل تصویر (برای نشانی ذخیرهسازی — اختیاری)
|
||||
</label>
|
||||
<input
|
||||
id="image-name-input"
|
||||
type="text"
|
||||
dir="auto"
|
||||
autoFocus
|
||||
value={pendingImage.name}
|
||||
onChange={(e) => setPendingImage({ ...pendingImage, name: e.target.value })}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
const { file, name } = pendingImage
|
||||
setPendingImage(null)
|
||||
void uploadAndInsert(file, name)
|
||||
}
|
||||
}}
|
||||
className="mt-2 w-full border border-ivory/15 bg-char px-3 py-2 text-sm font-light text-ivory focus:border-copper focus:outline-none"
|
||||
/>
|
||||
<div className="mt-5 flex items-center justify-end gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPendingImage(null)}
|
||||
className="border border-ivory/20 px-4 py-2 text-xs font-light text-ivory/70 transition-colors hover:border-copper hover:text-copper"
|
||||
>
|
||||
انصراف
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const { file, name } = pendingImage
|
||||
setPendingImage(null)
|
||||
void uploadAndInsert(file, name)
|
||||
}}
|
||||
className="bg-copper px-6 py-2 text-xs font-bold text-char transition-transform hover:scale-105"
|
||||
>
|
||||
درج تصویر
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* مودال لینک — انیمیشن ورود/خروج را خودش با کلاسهای Tailwind مدیریت میکند */}
|
||||
{linkModal.open && (
|
||||
<LinkModal
|
||||
|
||||
@@ -48,7 +48,10 @@ export function ImageField({
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const titleId = useId()
|
||||
const altId = useId()
|
||||
const nameId = useId()
|
||||
const [uploading, setUploading] = useState(false)
|
||||
/** نام دلخواه فایل برای ذخیرهسازی خوانا — پیشفرض از نام فایل انتخابی ساخته میشود */
|
||||
const [fileBaseName, setFileBaseName] = useState('')
|
||||
|
||||
const showTitle = title !== undefined || !!onSaveTitle
|
||||
const showAlt = alt !== undefined || !!onSaveAlt
|
||||
@@ -73,13 +76,16 @@ export function ImageField({
|
||||
setUploading(true)
|
||||
try {
|
||||
await runSave(async () => {
|
||||
const { url } = await adminApi.upload(file)
|
||||
// نام ذخیرهسازی: نام تایپشده کاربر، وگرنه نام خود فایل بدون پسوند
|
||||
const name = fileBaseName.trim() || file.name.replace(/\.[^.]+$/, '')
|
||||
const { url } = await adminApi.upload(file, name)
|
||||
const ok = await onSave(url)
|
||||
if (!ok) throw new Error('ذخیره نشد')
|
||||
// پیشفرضهای Alt/Title همان لحظه ثبت میشوند تا تصویر بدون متادیتا نماند
|
||||
if (showTitle) await titleField.commit()
|
||||
if (showAlt) await altField.commit()
|
||||
})
|
||||
setFileBaseName('')
|
||||
} finally {
|
||||
setUploading(false)
|
||||
}
|
||||
@@ -106,7 +112,7 @@ export function ImageField({
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-3">
|
||||
<div className="mt-3 flex flex-wrap items-end gap-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
@@ -120,6 +126,22 @@ export function ImageField({
|
||||
)}
|
||||
{uploading ? 'در حال آپلود…' : value ? 'تغییر تصویر' : 'انتخاب تصویر'}
|
||||
</button>
|
||||
|
||||
{/* نام ذخیرهسازی فایل — خالی یعنی از نام خود فایل استفاده شود */}
|
||||
<div className="w-56">
|
||||
<label htmlFor={nameId} className="text-[11px] font-light text-ivory/50">
|
||||
نام فایل تصویر (اختیاری)
|
||||
</label>
|
||||
<input
|
||||
id={nameId}
|
||||
type="text"
|
||||
dir="auto"
|
||||
value={fileBaseName}
|
||||
onChange={(event) => setFileBaseName(event.target.value)}
|
||||
placeholder="مثلاً: elahieh-tower"
|
||||
className={META_FIELD_CLASS.replace('mt-1.5 ', '')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{(showTitle || showAlt) && (
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { NodeViewWrapper } from '@tiptap/react'
|
||||
import type { NodeViewProps } from '@tiptap/react'
|
||||
import { PlusIcon, XIcon } from 'lucide-react'
|
||||
import { CloudUploadIcon, PlusIcon, XIcon } from 'lucide-react'
|
||||
import { adminApi } from '../../admin/adminClient'
|
||||
import { useAdmin } from '../../admin/AdminContext'
|
||||
|
||||
type ImageAttrs = {
|
||||
src: string
|
||||
@@ -19,25 +21,39 @@ const INLINE_FIELD_CLASS =
|
||||
const ADD_CAPTION_CLASS =
|
||||
'mt-1.5 inline-flex items-center gap-1.5 border border-dashed border-ivory/25 px-3 py-1 text-[11px] font-light text-ivory/50 transition-colors duration-150 hover:border-copper hover:text-copper'
|
||||
|
||||
/** تصاویر میزبان خارجی (مثل چسباندهشده از Outline) قابل میزبانی مجدد هستند */
|
||||
function isExternalImage(src: string): boolean {
|
||||
if (!src) return false
|
||||
if (src.startsWith('/media/') || src.startsWith('/')) return false
|
||||
try {
|
||||
return new URL(src, window.location.origin).origin !== window.location.origin
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* نمایش تصویر مقاله در ویرایشگر — دقیقاً با همان ساختار خروجی سایت:
|
||||
* <figure><img><figcaption>کپشن</figcaption></figure>
|
||||
*
|
||||
* ویرایش کاملاً درونخطی است (بدون پاپاور/مودال):
|
||||
* - هر تصویر یک «جعبه توضیح/کپشن» همراه خود دارد و متن آن در figcaption ذخیره میشود.
|
||||
* - دکمه X کپشن را کامل حذف میکند: صفت کپشن به مقدار پیشفرض برمیگردد و عنصر
|
||||
* figcaption با ورودیاش از DOM ویرایشگر (و از خروجی ذخیرهشده) حذف میشود؛
|
||||
* فقط تصویر میماند و «افزودن کپشن» دوباره جعبه را باز میکند.
|
||||
* - ویرایش Alt در ویرایشگر وجود ندارد؛ Alt هنگام درج از نام فایل ثبت میشود.
|
||||
* - دکمه X کپشن را کامل حذف میکند؛ «افزودن کپشن» دوباره جعبه را باز میکند.
|
||||
* - Alt و Title تصویر (نام تصویر برای سئو/دسترسپذیری) پس از درج هم قابل ویرایشاند.
|
||||
* - تصویر میزبان خارجی دکمه «میزبانی مجدد» دارد: تصویر دانلود و در Object Storage
|
||||
* خود سایت ذخیره میشود (ترمیم تصاویر چسباندهشده از Outline).
|
||||
* - دکمه X روی تصویر کل تصویر را حذف میکند.
|
||||
*/
|
||||
export function ImageNodeView({ node, updateAttributes, deleteNode, selected }: NodeViewProps) {
|
||||
const { src, alt, title, caption } = node.attrs as ImageAttrs
|
||||
const { runSave } = useAdmin()
|
||||
const hasCaption = Boolean((caption ?? '').trim())
|
||||
const [captionOpen, setCaptionOpen] = useState(true)
|
||||
const [rehosting, setRehosting] = useState(false)
|
||||
const captionInputRef = useRef<HTMLInputElement>(null)
|
||||
const focusOnOpen = useRef(false)
|
||||
const showCaption = captionOpen || hasCaption
|
||||
const external = isExternalImage(src)
|
||||
|
||||
// فقط وقتی کاربر «افزودن کپشن» را میزند ورودی فوکوس میگیرد (نه هنگام بارگذاری مقاله)
|
||||
useEffect(() => {
|
||||
@@ -57,6 +73,16 @@ export function ImageNodeView({ node, updateAttributes, deleteNode, selected }:
|
||||
setCaptionOpen(true)
|
||||
}
|
||||
|
||||
/** میزبانی مجدد تصویر خارجی — دانلود از منبع و ذخیره در Object Storage سایت */
|
||||
const rehost = () => {
|
||||
if (rehosting) return
|
||||
setRehosting(true)
|
||||
void runSave(async () => {
|
||||
const { url } = await adminApi.importImage(src)
|
||||
updateAttributes({ src: url })
|
||||
}).finally(() => setRehosting(false))
|
||||
}
|
||||
|
||||
return (
|
||||
<NodeViewWrapper
|
||||
className={`article-figure-node ${selected ? 'is-selected' : ''}`}
|
||||
@@ -77,6 +103,42 @@ export function ImageNodeView({ node, updateAttributes, deleteNode, selected }:
|
||||
<XIcon className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
|
||||
{/* تصویر خارجی (مثل Outline) — منتقل به میزبانی سایت */}
|
||||
{external && (
|
||||
<button
|
||||
type="button"
|
||||
contentEditable={false}
|
||||
onClick={rehost}
|
||||
disabled={rehosting}
|
||||
aria-label="میزبانی مجدد تصویر"
|
||||
title="تصویر از منبع خارجی دانلود و در سایت ذخیره میشود"
|
||||
className="absolute right-2 top-2 z-10 flex items-center gap-1.5 border border-copper/60 bg-ink/85 px-2.5 py-1 text-[11px] font-light text-copper backdrop-blur-sm transition-colors duration-150 hover:bg-copper hover:text-char disabled:opacity-60"
|
||||
>
|
||||
<CloudUploadIcon className={`h-3.5 w-3.5 ${rehosting ? 'animate-pulse' : ''}`} />
|
||||
{rehosting ? 'در حال انتقال…' : 'میزبانی مجدد'}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* نام تصویر — Alt و Title پس از درج هم قابل ویرایشاند */}
|
||||
<div contentEditable={false} className="mt-1.5 grid gap-1.5 sm:grid-cols-2">
|
||||
<input
|
||||
type="text"
|
||||
value={alt ?? ''}
|
||||
onChange={(event) => updateAttributes({ alt: event.target.value })}
|
||||
placeholder="نام تصویر / متن جایگزین (Alt)…"
|
||||
aria-label="متن جایگزین تصویر"
|
||||
className={INLINE_FIELD_CLASS}
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={title ?? ''}
|
||||
onChange={(event) => updateAttributes({ title: event.target.value })}
|
||||
placeholder="عنوان تصویر (Title)…"
|
||||
aria-label="عنوان تصویر"
|
||||
className={INLINE_FIELD_CLASS}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{showCaption ? (
|
||||
<figcaption className="article-figure__caption" contentEditable={false}>
|
||||
<input
|
||||
|
||||
@@ -46,7 +46,11 @@ export type ArticleStatus = 'draft' | 'published';
|
||||
export type Article = {
|
||||
id: number;
|
||||
slug: string; title: string; title_en?: string; date: string; date_en?: string; category: string; category_en?: string;
|
||||
image: string; read: string; read_en?: string; excerpt: string; excerpt_en?: string;
|
||||
image: string;
|
||||
read: string; read_en?: string; excerpt: string; excerpt_en?: string;
|
||||
/** پرسشوپاسخهای پایان مقاله — سئوی FAQPage (faqs_en خالی → برگشت به فارسی) */
|
||||
faqs?: { question: string; answer: string }[];
|
||||
faqs_en?: { question: string; answer: string }[] | null;
|
||||
/** سند TipTap — ردیفهای قدیمی ممکن است هنوز لیست پاراگراف باشند */
|
||||
body: ArticleBodyDoc | string[];
|
||||
/** بدنه انگلیسی — سند TipTap؛ null یعنی بدون ترجمه */
|
||||
|
||||
@@ -99,6 +99,7 @@ export function localizeSite(data: SiteData, lang: Lang): SiteData {
|
||||
read: s(a.read, a.read_en),
|
||||
excerpt: s(a.excerpt, a.excerpt_en),
|
||||
body: docHasText(a.body_en) ? a.body_en! : a.body,
|
||||
faqs: list(a.faqs ?? [], a.faqs_en),
|
||||
})),
|
||||
testimonials: data.testimonials.map((tm) => ({
|
||||
...tm,
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Reveal } from '../components/Reveal';
|
||||
import { ButtonLink } from '../components/Button';
|
||||
import { ArticleCard } from '../components/ArticleCard';
|
||||
import { ArticleMeta } from '../components/ArticleMeta';
|
||||
import { ArticleFaq } from '../components/ArticleFaq';
|
||||
import { TableOfContents, extractToc, type TocItem } from '../components/TableOfContents';
|
||||
import { Newsletter } from '../components/home/Newsletter';
|
||||
import { useSite } from '../api';
|
||||
@@ -47,6 +48,35 @@ export function ArticleDetail() {
|
||||
// عنوان تب، توضیح متا، OG و JSON-LD از خود مقاله
|
||||
useEffect(() => {
|
||||
if (!article) return;
|
||||
let jsonLd: Record<string, unknown> | Record<string, unknown>[] = {
|
||||
'@context': 'https://schema.org',
|
||||
'@type': 'Article',
|
||||
headline: article.title,
|
||||
description: article.meta_description || article.excerpt,
|
||||
image: article.image ? new URL(article.image, window.location.origin).href : undefined,
|
||||
inLanguage: lang,
|
||||
author: { '@type': 'Organization', name: article.author?.trim() || brand.name },
|
||||
publisher: { '@type': 'Organization', name: brand.name },
|
||||
mainEntityOfPage: new URL(href(`/blog/${article.slug}`), window.location.origin).href,
|
||||
};
|
||||
// پرسشوپاسخ مقاله → اسکیمای FAQPage در همان بلوک (آرایهای از دو اسکیما)
|
||||
const articleFaqs = article.faqs ?? [];
|
||||
if (articleFaqs.length) {
|
||||
jsonLd = [
|
||||
jsonLd,
|
||||
{
|
||||
'@context': 'https://schema.org',
|
||||
'@type': 'FAQPage',
|
||||
mainEntity: articleFaqs
|
||||
.filter((f) => f.question.trim())
|
||||
.map((f) => ({
|
||||
'@type': 'Question',
|
||||
name: f.question,
|
||||
acceptedAnswer: { '@type': 'Answer', text: f.answer },
|
||||
})),
|
||||
},
|
||||
];
|
||||
}
|
||||
applySeo({
|
||||
title: `${article.title} | ${brand.name}`,
|
||||
// توضیحات سئوی اختصاصی در اولویت است؛ در نبود آن، چکیده
|
||||
@@ -55,17 +85,7 @@ export function ArticleDetail() {
|
||||
image: article.image,
|
||||
type: 'article',
|
||||
lang,
|
||||
jsonLd: {
|
||||
'@context': 'https://schema.org',
|
||||
'@type': 'Article',
|
||||
headline: article.title,
|
||||
description: article.meta_description || article.excerpt,
|
||||
image: article.image ? new URL(article.image, window.location.origin).href : undefined,
|
||||
inLanguage: lang,
|
||||
author: { '@type': 'Organization', name: article.author?.trim() || brand.name },
|
||||
publisher: { '@type': 'Organization', name: brand },
|
||||
mainEntityOfPage: new URL(href(`/blog/${article.slug}`), window.location.origin).href,
|
||||
},
|
||||
jsonLd,
|
||||
});
|
||||
}, [article?.id, lang, href]);
|
||||
|
||||
@@ -171,6 +191,14 @@ export function ArticleDetail() {
|
||||
</div>
|
||||
</article>
|
||||
|
||||
{/* پرسشوپاسخهای پایان مقاله — همان ظاهر آکاردئونی FAQ سایت */}
|
||||
<div className="bg-ink pb-4">
|
||||
<div className="mx-auto max-w-5xl px-6 lg:px-10">
|
||||
<h2 className="text-section font-bold text-ivory">{t('fallbackFaqTitle')}</h2>
|
||||
<ArticleFaq faqs={article.faqs ?? []} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section className="bg-char py-20 lg:py-28" aria-label={t('relatedArticlesAria')}>
|
||||
<div className="mx-auto max-w-site px-6 lg:px-10">
|
||||
<h2 className="text-section font-bold text-ivory">{t('relatedArticles')}</h2>
|
||||
|
||||
+4
-3
@@ -72,10 +72,10 @@ function upsertAlternates(path: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
function setJsonLd(data: Record<string, unknown> | null): void {
|
||||
function setJsonLd(data: Record<string, unknown> | Record<string, unknown>[] | null): void {
|
||||
const id = 'seo-jsonld'
|
||||
let el = document.getElementById(id)
|
||||
if (!data) {
|
||||
if (!data || (Array.isArray(data) && data.length === 0)) {
|
||||
el?.remove()
|
||||
return
|
||||
}
|
||||
@@ -98,7 +98,8 @@ export type SeoInput = {
|
||||
type?: 'website' | 'article'
|
||||
/** زبان جاری — برای og:locale و لینکهای hreflang */
|
||||
lang?: Lang
|
||||
jsonLd?: Record<string, unknown> | null
|
||||
/** اسکیمای JSON-LD — یک شیء یا آرایهای از چند اسکیما (مثل Article + FAQPage) */
|
||||
jsonLd?: Record<string, unknown> | Record<string, unknown>[] | null
|
||||
}
|
||||
|
||||
/** تنظیم همه تگهای سئوی صفحه در یک فراخوانی */
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env bash
|
||||
# پیشنمایش خصوصی و انتشار عمومی سایت.
|
||||
#
|
||||
# bash scripts/preview-mode.sh status # وضعیت فعلی
|
||||
# bash scripts/preview-mode.sh on # سایت آنلاین ولی خصوصی (گیت ورود + noindex)
|
||||
# bash scripts/preview-mode.sh off # انتشار عمومی (حذف گیت + اجازه ایندکس)
|
||||
#
|
||||
# در حالت «on» کل سایت پشت Basic Auth است: تیم با نام کاربری/رمز مشترک وارد میشود،
|
||||
# محتوا را در همان سایت آنلاین ویرایش میکند (ویرایش درجای ایمیل/تلفن و بقیه محتوا)،
|
||||
# اما نه عموم به سایت دسترسی دارند و نه گوگل چیزی ایندکس میکند.
|
||||
#
|
||||
# پس از هر تغییر، استک را دوباره بالا بیاورید:
|
||||
# bash scripts/stack.sh deploy-prod
|
||||
#
|
||||
# با «فعال شدن» اولین بار، نام کاربری/رمز ساخته و در .env ذخیره میشود
|
||||
# (پیشفرض: preview / یک رمز تصادفی — در خروجی چاپ میشود).
|
||||
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
ENV_FILE=.env
|
||||
[ -f "$ENV_FILE" ] || { echo "فایل .env پیدا نشد — اول bash scripts/gen-env.sh" >&2; exit 1; }
|
||||
|
||||
# مقدار فعلی یک کلید در .env (یا خالی)
|
||||
env_get() {
|
||||
local key="$1"
|
||||
sed -n "s/^${key}=//p" "$ENV_FILE" | tail -1
|
||||
}
|
||||
|
||||
# تنظیم/جایگزینی یک کلید در .env (بدون آسیب به بقیه خطوط)
|
||||
env_set() {
|
||||
local key="$1" value="$2"
|
||||
if grep -q "^${key}=" "$ENV_FILE"; then
|
||||
# جداکننده | تا کاراکترهای ویژه مقدار (مثل / و $) مشکلی نسازند
|
||||
python - "$ENV_FILE" "$key" "$value" <<'PY'
|
||||
import io, sys
|
||||
path, key, value = sys.argv[1], sys.argv[2], sys.argv[3]
|
||||
lines = io.open(path, encoding="utf-8").read().split("\n")
|
||||
out = [f"{key}={value}" if line.startswith(f"{key}=") else line for line in lines]
|
||||
io.open(path, "w", encoding="utf-8", newline="\n").write("\n".join(out))
|
||||
PY
|
||||
else
|
||||
printf '\n%s=%s\n' "$key" "$value" >> "$ENV_FILE"
|
||||
fi
|
||||
}
|
||||
|
||||
# ساخت هش htpasswd — اول با openssl، در نبودش با ایمیج httpd (Docker لازم است)
|
||||
make_htpasswd() {
|
||||
local user="$1" pass="$2" hash
|
||||
if command -v openssl >/dev/null 2>&1; then
|
||||
hash=$(openssl passwd -apr1 "$pass")
|
||||
else
|
||||
hash=$(docker run --rm httpd:2.4-alpine htpasswd -nbB "$user" "$pass" | cut -d: -f2)
|
||||
fi
|
||||
printf '%s:%s' "$user" "$hash"
|
||||
}
|
||||
|
||||
# رمز تصادفی خوانا (بدون نویسههای گیجکننده)
|
||||
random_password() {
|
||||
python - <<'PY'
|
||||
import secrets, string
|
||||
alphabet = string.ascii_letters + string.digits
|
||||
print("".join(secrets.choice(alphabet) for _ in range(16)))
|
||||
PY
|
||||
}
|
||||
|
||||
PREVIEW_MIDDLEWARES_VALUE="preview-auth@docker,preview-noindex@docker"
|
||||
|
||||
case "${1:-status}" in
|
||||
on)
|
||||
users="$(env_get PREVIEW_AUTH_USERS)"
|
||||
if [ -z "$users" ]; then
|
||||
password="$(random_password)"
|
||||
users="$(make_htpasswd preview "$password")"
|
||||
env_set PREVIEW_AUTH_USERS "$users"
|
||||
echo "نام کاربری/رمز پیشنمایش ساخته شد:"
|
||||
echo " کاربر: preview"
|
||||
echo " رمز: $password"
|
||||
echo " (این رمز فقط همین یکبار چاپ میشود — در .env ذخیره شده است)"
|
||||
echo ""
|
||||
fi
|
||||
env_set PREVIEW_MODE on
|
||||
env_set PREVIEW_MIDDLEWARES "$PREVIEW_MIDDLEWARES_VALUE"
|
||||
# در پیشنمایش، دامنه دوم به اصلی ریدایرکت نمیشود تا هر دو قابل بررسی باشند
|
||||
env_set ALIAS_REDIRECT_MIDDLEWARES ""
|
||||
echo "پیشنمایش خصوصی فعال شد — سایت آنلاین است، ورود با نام کاربری/رمز، بدون ایندکس."
|
||||
echo "برای اعمال: bash scripts/stack.sh deploy-prod"
|
||||
;;
|
||||
|
||||
off)
|
||||
env_set PREVIEW_MODE off
|
||||
env_set PREVIEW_MIDDLEWARES ""
|
||||
# در انتشار، دامنه دوم به اصلی ریدایرکت میشود تا محتوای تکراری ایجاد نشود
|
||||
env_set ALIAS_REDIRECT_MIDDLEWARES "to-primary@docker"
|
||||
echo "حالت انتشار عمومی فعال شد — گیت ورود حذف و ایندکس مجاز میشود."
|
||||
echo "پس از deploy، نقشه سایت را در Search Console ثبت کنید:"
|
||||
echo " https://\$(grep '^DOMAIN=' .env | cut -d= -f2)/sitemap.xml"
|
||||
echo "برای اعمال: bash scripts/stack.sh deploy-prod"
|
||||
;;
|
||||
|
||||
status)
|
||||
mode="$(env_get PREVIEW_MODE)"
|
||||
mws="$(env_get PREVIEW_MIDDLEWARES)"
|
||||
alias_mws="$(env_get ALIAS_REDIRECT_MIDDLEWARES)"
|
||||
if [ "$mode" = "on" ]; then
|
||||
echo "وضعیت: پیشنمایش خصوصی (آنلاین، غیرعمومی، noindex)"
|
||||
elif [ "$mode" = "off" ]; then
|
||||
echo "وضعیت: انتشار عمومی"
|
||||
else
|
||||
echo "وضعیت: تعییننشده (PREVIEW_MODE=${mode:-خالی}) — پیشفرض compose: off"
|
||||
fi
|
||||
echo " PREVIEW_MIDDLEWARES=${mws:-(خالی — بدون گیت)}"
|
||||
echo " ALIAS_REDIRECT_MIDDLEWARES=${alias_mws:-(خالی — بدون ریدایرکت دامنه دوم)}"
|
||||
if [ -n "$(env_get PREVIEW_AUTH_USERS)" ]; then
|
||||
echo " کاربر پیشنمایش: $(env_get PREVIEW_AUTH_USERS | cut -d: -f1)"
|
||||
else
|
||||
echo " کاربر پیشنمایش: ساخته نشده (اولین «on» میسازد)"
|
||||
fi
|
||||
;;
|
||||
|
||||
*)
|
||||
echo "استفاده: bash scripts/preview-mode.sh [on|off|status]" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
Reference in New Issue
Block a user