297 lines
16 KiB
Python
297 lines
16 KiB
Python
"""Public share endpoints (ROADMAP #85, tranche 3).
|
|
|
|
Handlers déplacés depuis :mod:`backend.main` sans changement de
|
|
comportement : mêmes chemins (``/api/share/*``, ``/api/shares``,
|
|
``/s/{token}*``), mêmes modèles de réponse, mêmes dépendances
|
|
d'authentification (les pages ``/s/*`` restent publiques). La logique
|
|
métier vit déjà dans :mod:`backend.share`.
|
|
|
|
Adaptations strictement équivalentes (pas de changement de comportement) :
|
|
- ``_resolve_safe_path`` / ``_backup_file`` de ``main`` n'étaient que des
|
|
wrappers directs : appelés ici via :mod:`backend.services.paths` et
|
|
:mod:`backend.services.backups` (mêmes signatures, mêmes exceptions
|
|
``ServiceError`` toujours mappées par le handler global de ``main``).
|
|
- ``_render_markdown`` vient de :mod:`backend.render` (#85 T9, sans cycle
|
|
d'import).
|
|
"""
|
|
|
|
import html as html_mod
|
|
import json as _json
|
|
import logging
|
|
from pathlib import Path
|
|
|
|
import frontmatter
|
|
from fastapi import APIRouter, Body, Depends, HTTPException, Query
|
|
from fastapi.responses import FileResponse, HTMLResponse, Response
|
|
|
|
from backend.auth.middleware import check_vault_access, require_auth
|
|
from backend.indexer import get_vault_data, parse_markdown_file, update_single_file
|
|
from backend.render import _render_markdown
|
|
from backend.schemas import ShareModel, StatusResponse
|
|
from backend.secret_redactor import redact_file_content
|
|
from backend.services.backups import create_backup
|
|
from backend.services.paths import resolve_safe_path
|
|
from backend.share import (
|
|
create_share,
|
|
get_share_by_token,
|
|
list_shares,
|
|
record_access,
|
|
revoke_share,
|
|
)
|
|
|
|
logger = logging.getLogger("obsigate")
|
|
|
|
# Lazy import: WeasyPrint PDF export (requires GTK, may not be available everywhere)
|
|
try:
|
|
from backend.pdf_export import build_pdf_html, generate_pdf
|
|
except Exception: # pragma: no cover - WeasyPrint/GTK missing
|
|
generate_pdf = None # type: ignore[assignment]
|
|
build_pdf_html = None # type: ignore[assignment]
|
|
|
|
logging.getLogger("obsigate").warning("PDF export unavailable (WeasyPrint/GTK not found)")
|
|
|
|
router = APIRouter(tags=["sharing"])
|
|
|
|
|
|
@router.post("/api/share/{vault_name}", response_model=ShareModel)
|
|
async def api_share_create(
|
|
vault_name: str,
|
|
body: dict = Body(...),
|
|
current_user=Depends(require_auth),
|
|
):
|
|
"""Create a public share link for a document.
|
|
|
|
Also sets ``publish: true`` in the file's YAML frontmatter so the
|
|
frontend can visually indicate the file is publicly shared.
|
|
"""
|
|
if not check_vault_access(vault_name, current_user):
|
|
raise HTTPException(403, f"Accès refusé à la vault '{vault_name}'")
|
|
path = body.get("path", "")
|
|
expires = body.get("expires_in_hours")
|
|
share = create_share(vault_name, path, current_user["username"], expires)
|
|
share["url"] = f"/s/{share['token']}"
|
|
|
|
# Set publish: true in the file's frontmatter
|
|
vault_data = get_vault_data(vault_name)
|
|
if vault_data:
|
|
file_path = resolve_safe_path(Path(vault_data["path"]), path)
|
|
if file_path.exists() and file_path.suffix == ".md":
|
|
try:
|
|
raw = file_path.read_text(encoding="utf-8", errors="replace")
|
|
post = frontmatter.loads(raw)
|
|
if not post.metadata.get("publish"):
|
|
post.metadata["publish"] = True
|
|
new_raw = frontmatter.dumps(post)
|
|
create_backup(file_path, vault_name, path)
|
|
file_path.write_text(new_raw, encoding="utf-8")
|
|
await update_single_file(vault_name, str(file_path))
|
|
logger.info(f"Set publish:true on {vault_name}/{path}")
|
|
except Exception as e:
|
|
logger.warning(f"Failed to set publish metadata on {vault_name}/{path}: {e}")
|
|
|
|
return share
|
|
|
|
|
|
@router.get("/api/shares", response_model=list[ShareModel])
|
|
async def api_shares_list(vault: str | None = Query(None), current_user=Depends(require_auth)):
|
|
"""List all shares (optionally filtered by vault)."""
|
|
shares = list_shares(vault)
|
|
for s in shares:
|
|
s["url"] = f"/s/{s['token']}"
|
|
return shares
|
|
|
|
|
|
@router.delete("/api/share/{share_id}", response_model=StatusResponse)
|
|
async def api_share_revoke(share_id: str, current_user=Depends(require_auth)):
|
|
if not revoke_share(share_id):
|
|
raise HTTPException(404, "Share not found")
|
|
return {"status": "revoked"}
|
|
|
|
|
|
@router.get(
|
|
"/s/{token}/pdf",
|
|
response_class=Response,
|
|
responses={200: {"content": {"application/pdf": {}}, "description": "Shared document as PDF"}},
|
|
)
|
|
async def public_share_pdf_download(token: str):
|
|
"""Download shared document as real PDF via WeasyPrint."""
|
|
if generate_pdf is None:
|
|
raise HTTPException(501, "PDF export unavailable (WeasyPrint/GTK not available)")
|
|
share = get_share_by_token(token)
|
|
if not share:
|
|
raise HTTPException(404, "Share not found or expired")
|
|
vault_data = get_vault_data(share["vault"])
|
|
if not vault_data:
|
|
raise HTTPException(404, "Vault not found")
|
|
vault_root = Path(vault_data["path"])
|
|
file_path = resolve_safe_path(vault_root, share["path"])
|
|
if not file_path.exists():
|
|
raise HTTPException(404, "File not found")
|
|
try:
|
|
raw = file_path.read_text(encoding="utf-8", errors="replace")
|
|
except Exception:
|
|
raise HTTPException(500, "Cannot read file")
|
|
record_access(token)
|
|
raw = redact_file_content(raw, str(file_path))
|
|
post = parse_markdown_file(raw)
|
|
ext = file_path.suffix.lower()
|
|
if ext == ".md":
|
|
html = _render_markdown(post.content, share["vault"], file_path)
|
|
else:
|
|
html = f'<pre style="font-family:monospace;font-size:12px;line-height:1.6;white-space:pre-wrap">{html_mod.escape(raw)}</pre>'
|
|
title = post.metadata.get("title", file_path.stem)
|
|
pdf_html = build_pdf_html(html, str(title))
|
|
pdf_bytes = generate_pdf(pdf_html, str(title))
|
|
safe_name = "".join(c for c in str(title) if c.isascii() and (c.isalnum() or c in " _-.")).strip() or "document"
|
|
return Response(content=pdf_bytes, media_type="application/pdf", headers={"Content-Disposition": f'attachment; filename="{safe_name}.pdf"'})
|
|
|
|
|
|
@router.get("/s/{token}/raw", response_class=FileResponse)
|
|
async def public_share_raw(token: str):
|
|
"""Download the raw (original) shared document."""
|
|
share = get_share_by_token(token)
|
|
if not share:
|
|
raise HTTPException(404, "Share not found or expired")
|
|
vault_data = get_vault_data(share["vault"])
|
|
if not vault_data:
|
|
raise HTTPException(404, "Vault not found")
|
|
vault_root = Path(vault_data["path"])
|
|
file_path = resolve_safe_path(vault_root, share["path"])
|
|
if not file_path.exists():
|
|
raise HTTPException(404, "File not found")
|
|
record_access(token)
|
|
return FileResponse(path=str(file_path), filename=file_path.name, media_type="application/octet-stream")
|
|
|
|
|
|
@router.get("/s/{token}", response_class=HTMLResponse)
|
|
async def public_share_view(token: str):
|
|
"""Public share view — no authentication required."""
|
|
share = get_share_by_token(token)
|
|
if not share:
|
|
raise HTTPException(404, "Share not found or expired")
|
|
vault_data = get_vault_data(share["vault"])
|
|
if not vault_data:
|
|
raise HTTPException(404, "Vault not found")
|
|
vault_root = Path(vault_data["path"])
|
|
file_path = resolve_safe_path(vault_root, share["path"])
|
|
if not file_path.exists():
|
|
raise HTTPException(404, "File not found")
|
|
try:
|
|
raw = file_path.read_text(encoding="utf-8", errors="replace")
|
|
except Exception:
|
|
raise HTTPException(500, "Cannot read file")
|
|
record_access(token)
|
|
raw = redact_file_content(raw, str(file_path))
|
|
post = parse_markdown_file(raw)
|
|
ext = file_path.suffix.lower()
|
|
|
|
if ext == ".md":
|
|
html = _render_markdown(post.content, share["vault"], file_path)
|
|
else:
|
|
escaped = html_mod.escape(raw)
|
|
html = f'<pre style="background:var(--bg-card);border:1px solid var(--border);border-radius:8px;padding:16px;overflow-x:auto;font-size:0.85rem;line-height:1.6"><code>{escaped}</code></pre>'
|
|
|
|
title = post.metadata.get("title", file_path.stem)
|
|
|
|
# Escape everything user-controlled before embedding in HTML/JS (BUG-022).
|
|
title_esc = html_mod.escape(str(title))
|
|
# Neutralise ``</script>`` in the JS string literal too.
|
|
title_download_js = (
|
|
_json.dumps(f"{title}.md")
|
|
.replace("<", "\\u003c")
|
|
.replace(">", "\\u003e")
|
|
.replace("&", "\\u0026")
|
|
)
|
|
|
|
# JSON-escape raw content for embedding in HTML, and neutralise ``</script>``.
|
|
raw_json = (
|
|
_json.dumps(raw)
|
|
.replace("<", "\\u003c")
|
|
.replace(">", "\\u003e")
|
|
.replace("&", "\\u0026")
|
|
)
|
|
fm_html = ""
|
|
if post.metadata:
|
|
fm_items = []
|
|
skip_keys = {"title", "titre"}
|
|
for k, v in post.metadata.items():
|
|
if k in skip_keys:
|
|
continue
|
|
if isinstance(v, list):
|
|
v = ", ".join(str(x) for x in v)
|
|
elif isinstance(v, bool):
|
|
v = "✓" if v else "✗"
|
|
elif v is None:
|
|
v = "—"
|
|
fm_items.append(
|
|
f'<div class="fm-row"><span class="fm-key">{html_mod.escape(str(k))}</span>'
|
|
f'<span class="fm-val">{html_mod.escape(str(v))}</span></div>'
|
|
)
|
|
if fm_items:
|
|
fm_html = f'<div class="fm-section"><div class="fm-header">Frontmatter</div><div class="fm-body">{"".join(fm_items)}</div></div>'
|
|
|
|
return HTMLResponse(f"""<!DOCTYPE html><html lang="fr" data-theme="dark"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>{title_esc} — ObsiGate Share</title>
|
|
<style>
|
|
:root {{ --bg:#1a1a2e; --bg-card:#16213e; --text:#e0e0e0; --text-muted:#888; --accent:#6366f1; --border:#2a2a4a; --banner-bg:var(--accent); --banner-text:#fff; }}
|
|
[data-theme="light"] {{ --bg:#f8f9fa; --bg-card:#fff; --text:#1a1a2e; --text-muted:#666; --accent:#4f46e5; --border:#ddd; --banner-bg:#eef2ff; --banner-text:#4338ca; }}
|
|
*{{box-sizing:border-box;margin:0;padding:0}}
|
|
body{{font-family:system-ui,-apple-system,sans-serif;background:var(--bg);color:var(--text);line-height:1.7;min-height:100vh}}
|
|
.toolbar{{position:sticky;top:0;z-index:10;background:var(--bg-card);border-bottom:1px solid var(--border);padding:8px 16px;display:flex;align-items:center;gap:8px;flex-wrap:wrap}}
|
|
.toolbar-title{{font-weight:600;font-size:0.9rem;margin-right:auto;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}
|
|
.toolbar-btn{{padding:6px 12px;border:1px solid var(--border);border-radius:6px;background:var(--bg);color:var(--text);cursor:pointer;font-size:0.8rem;display:flex;align-items:center;gap:5px;transition:all .15s}}
|
|
.toolbar-btn:hover{{background:var(--accent);color:#fff;border-color:var(--accent)}}
|
|
.toolbar-btn svg{{width:15px;height:15px;flex-shrink:0}}
|
|
.toolbar-btn:hover svg{{stroke:#fff}}
|
|
.share-banner{{background:var(--banner-bg);color:var(--banner-text);padding:6px 16px;font-size:0.8rem;text-align:center;display:flex;align-items:center;justify-content:center;gap:6px}}
|
|
.share-banner svg{{width:14px;height:14px;flex-shrink:0}}
|
|
.content{{max-width:820px;margin:0 auto;padding:24px 20px 60px}}
|
|
.content h1{{font-size:1.8rem;margin-bottom:16px;border-bottom:2px solid var(--border);padding-bottom:8px}}
|
|
.content h2{{font-size:1.4rem;margin:24px 0 12px}}
|
|
.content h3{{font-size:1.15rem;margin:20px 0 8px}}
|
|
.content p{{margin:8px 0}}
|
|
.content pre{{background:var(--bg-card);border:1px solid var(--border);border-radius:8px;padding:12px 16px;overflow-x:auto;font-size:0.85rem}}
|
|
.content code{{font-size:0.9em;background:var(--bg-card);padding:1px 4px;border-radius:3px}}
|
|
.content pre code{{background:none;padding:0}}
|
|
.content a{{color:var(--accent)}}.content img{{max-width:100%;border-radius:6px}}
|
|
.fm-section{{background:var(--bg-card);border:1px solid var(--border);border-radius:8px;padding:12px 16px;margin-bottom:20px}}
|
|
.fm-header{{font-weight:600;font-size:0.8rem;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.5px;margin-bottom:8px}}
|
|
.fm-body{{display:grid;grid-template-columns:1fr 2fr;gap:4px 12px;font-size:0.85rem}}
|
|
.fm-row{{display:contents}}
|
|
.fm-key{{color:var(--accent);font-weight:500}}
|
|
.fm-val{{color:var(--text);word-break:break-word}}
|
|
.content blockquote{{border-left:3px solid var(--accent);padding-left:16px;color:var(--text-muted);margin:12px 0}}
|
|
.content table{{border-collapse:collapse;width:100%;margin:12px 0}}
|
|
.content th,.content td{{border:1px solid var(--border);padding:8px 12px;text-align:left}}
|
|
.content th{{background:var(--bg-card)}}
|
|
@media print{{.toolbar,.share-banner{{display:none}}body{{background:#fff;color:#000}}}}
|
|
@media(max-width:600px){{.content{{padding:16px 12px 40px}}.toolbar{{gap:4px}}.toolbar-btn{{padding:4px 8px;font-size:0.7rem}}}}
|
|
</style></head>
|
|
<body>
|
|
<div class="share-banner">
|
|
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>
|
|
Document partagé via ObsiGate
|
|
</div>
|
|
<div class="toolbar">
|
|
<span class="toolbar-title">{title_esc}</span>
|
|
<button class="toolbar-btn" onclick="toggleTheme()" title="Thème clair/sombre">
|
|
<svg id="theme-icon-dark" xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
|
|
<svg id="theme-icon-light" xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:none"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
|
|
</button>
|
|
<button class="toolbar-btn" onclick="exportMD()" title="Télécharger en Markdown">
|
|
<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
|
|
.md
|
|
</button>
|
|
<button class="toolbar-btn" onclick="location.href=location.pathname+'/pdf'" title="Télécharger en PDF">
|
|
<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
|
|
PDF
|
|
</button>
|
|
</div>
|
|
<div class="content" id="content">{fm_html}{html}</div>
|
|
<script id="raw-content" type="text/plain" style="display:none">{raw_json}</script>
|
|
<script>
|
|
function toggleTheme(){{var t=document.documentElement;var isDark=t.dataset.theme==="dark";t.dataset.theme=isDark?"light":"dark";document.getElementById("theme-icon-dark").style.display=isDark?"none":"";document.getElementById("theme-icon-light").style.display=isDark?"":"none";localStorage.setItem("obsigate-share-theme",t.dataset.theme)}}
|
|
(function(){{var s=localStorage.getItem("obsigate-share-theme");if(!s)s="dark";document.documentElement.dataset.theme=s;var isDark=s==="dark";document.getElementById("theme-icon-dark").style.display=isDark?"":"none";document.getElementById("theme-icon-light").style.display=isDark?"none":""}})();
|
|
function exportMD(){{var raw=JSON.parse(document.getElementById("raw-content").textContent);var b=new Blob([raw],{{type:"text/markdown"}});var a=document.createElement("a");a.href=URL.createObjectURL(b);a.download={title_download_js};a.click()}}
|
|
</script></body></html>""")
|