Ajout dropdowns filter/sort/view dans toolbar, recherche inline, colonnes author/source masquables, remplacement emojis par SVG, amélioration styles hover/drag, modal move-to, menus contextuels enrichis.
479 lines
16 KiB
Python
479 lines
16 KiB
Python
"""FlowDeck — Library API: recents, favorites, shared, published, private, workspace."""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
|
|
from fastapi import APIRouter, Request, Query
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from app.db import get_conn
|
|
from app.auth.session import SessionManager
|
|
|
|
logger = logging.getLogger(__name__)
|
|
router = APIRouter(tags=["library"], prefix="/api/library")
|
|
|
|
SOURCE_TYPES = {"all", "local", "gitea", "github"}
|
|
|
|
|
|
def _get_user_id(request: Request) -> int:
|
|
user = SessionManager.decode_session(request.cookies.get("flowdeck_session", ""))
|
|
return user["id"] if user and user.get("id") else 1
|
|
|
|
|
|
def _detect_source_type(workspace: str) -> str:
|
|
ws = (workspace or "").strip()
|
|
if not ws:
|
|
return "local"
|
|
if ws.startswith("github:"):
|
|
return "github"
|
|
if "/" in ws:
|
|
return "gitea"
|
|
return "local"
|
|
|
|
|
|
def _source_label(source_type: str, workspace: str) -> str:
|
|
if source_type == "gitea":
|
|
return workspace
|
|
elif source_type == "github":
|
|
return workspace.replace("github:", "", 1)
|
|
return workspace or "Private"
|
|
|
|
|
|
def _build_item(db_row: dict, uid: int = 1) -> dict:
|
|
workspace = db_row.get("workspace", "") or ""
|
|
source_type = _detect_source_type(workspace)
|
|
page_id = db_row["id"]
|
|
title = db_row.get("title") or "Untitled"
|
|
|
|
# URL
|
|
if source_type in ("gitea", "github"):
|
|
ws = workspace.replace("github:", "", 1) if source_type == "github" else workspace
|
|
parts = ws.split("/", 1)
|
|
url = f"/gitea-workspace?owner={parts[0]}&repo={parts[1] if len(parts) > 1 else ''}"
|
|
else:
|
|
url = f"/pages/{page_id}"
|
|
|
|
# Icon
|
|
content_format = db_row.get("content_format", "blocks")
|
|
if db_row.get("is_folder"):
|
|
icon = "📁"
|
|
elif content_format == "file":
|
|
icon = "📄"
|
|
fn = title.lower()
|
|
if fn.endswith(".pdf"): icon = "📕"
|
|
elif any(fn.endswith(e) for e in [".png",".jpg",".jpeg",".gif",".webp",".svg"]): icon = "🖼️"
|
|
elif any(fn.endswith(e) for e in [".py",".js",".ts",".go",".rs"]): icon = "📜"
|
|
else:
|
|
icon = "📝"
|
|
|
|
return {
|
|
"id": page_id,
|
|
"title": title,
|
|
"icon": icon,
|
|
"is_folder": bool(db_row.get("is_folder", 0)),
|
|
"source_type": source_type,
|
|
"source_label": _source_label(source_type, workspace),
|
|
"workspace": workspace,
|
|
"workspace_name": _source_label(source_type, workspace),
|
|
"author": db_row.get("author") or "",
|
|
"author_initial": (db_row.get("author") or "?")[0].upper(),
|
|
"updated_at": db_row.get("updated_at", ""),
|
|
"visited_at": db_row.get("visited_at") or "",
|
|
"has_children": False,
|
|
"children": [],
|
|
"url": url,
|
|
"content_format": content_format,
|
|
"favorited": bool(db_row.get("favorited", 0)),
|
|
}
|
|
|
|
|
|
def _apply_source_filter(query: str, params: list, source_type: str) -> tuple[str, list]:
|
|
if source_type == "local":
|
|
query += " AND (p.workspace = '' OR (p.workspace NOT LIKE '%/%' AND p.workspace NOT LIKE 'github:%'))"
|
|
elif source_type == "gitea":
|
|
query += " AND p.workspace LIKE '%/%' AND p.workspace NOT LIKE 'github:%'"
|
|
elif source_type == "github":
|
|
query += " AND p.workspace LIKE 'github:%'"
|
|
return query, params
|
|
|
|
|
|
def _rows_to_items(rows, uid: int = 1) -> list:
|
|
return [_build_item(dict(r), uid) for r in rows]
|
|
|
|
|
|
def _enrich_children(items: list) -> list:
|
|
"""Add has_children info to items in a single batch query."""
|
|
if not items:
|
|
return items
|
|
ids = [it["id"] for it in items]
|
|
placeholders = ",".join(["?" for _ in ids])
|
|
with get_conn() as conn:
|
|
child_rows = conn.execute(
|
|
f"SELECT parent_id, COUNT(*) as cnt FROM pages "
|
|
f"WHERE parent_id IN ({placeholders}) AND deleted_at IS NULL "
|
|
f"GROUP BY parent_id",
|
|
ids,
|
|
).fetchall()
|
|
child_counts = {r["parent_id"]: r["cnt"] for r in child_rows}
|
|
for it in items:
|
|
it["has_children"] = bool(child_counts.get(it["id"], 0))
|
|
return items
|
|
|
|
|
|
# ═══════════ Tab endpoints ═══════════
|
|
|
|
BASE_SELECT = (
|
|
"SELECT p.id, p.title, p.workspace, p.updated_at, p.content_format, "
|
|
"p.parent_id, p.share_mode, p.parent_section"
|
|
)
|
|
|
|
|
|
@router.get("/recents")
|
|
async def library_recents(
|
|
request: Request,
|
|
source_type: str = Query(default="all"),
|
|
tree: int = Query(default=0),
|
|
workspace_id: int = Query(default=0),
|
|
):
|
|
if source_type not in SOURCE_TYPES:
|
|
source_type = "all"
|
|
|
|
uid = _get_user_id(request)
|
|
query = f"{BASE_SELECT} FROM pages p WHERE p.parent_section != 'Trash' AND p.deleted_at IS NULL"
|
|
params: list = []
|
|
|
|
# Hierarchical view: show only root-level pages at the top
|
|
if tree:
|
|
query += " AND p.parent_id IS NULL"
|
|
|
|
# Filter by active workspace
|
|
if workspace_id:
|
|
query += " AND p.workspace_id = ?"
|
|
params.append(workspace_id)
|
|
|
|
query, params = _apply_source_filter(query, params, source_type)
|
|
query += " ORDER BY p.updated_at DESC LIMIT 50"
|
|
|
|
with get_conn() as conn:
|
|
rows = conn.execute(query, params).fetchall()
|
|
|
|
items = _rows_to_items(rows, uid)
|
|
_enrich_children(items)
|
|
return {"items": items}
|
|
|
|
|
|
@router.get("/favorites")
|
|
async def library_favorites(
|
|
request: Request,
|
|
source_type: str = Query(default="all"),
|
|
tree: int = Query(default=0),
|
|
):
|
|
if source_type not in SOURCE_TYPES:
|
|
source_type = "all"
|
|
|
|
uid = _get_user_id(request)
|
|
query = (
|
|
f"SELECT p.id, p.title, p.workspace, p.updated_at, p.content_format, "
|
|
f"p.parent_id, p.share_mode, p.parent_section, 1 as favorited "
|
|
f"FROM favorites f JOIN pages p ON p.id = f.page_id "
|
|
f"WHERE f.user_id = ? AND p.parent_section != 'Trash' AND p.deleted_at IS NULL"
|
|
)
|
|
params: list = [uid]
|
|
if tree:
|
|
query += " AND p.parent_id IS NULL"
|
|
query, params = _apply_source_filter(query, params, source_type)
|
|
query += " ORDER BY f.position"
|
|
|
|
with get_conn() as conn:
|
|
rows = conn.execute(query, params).fetchall()
|
|
|
|
items = _rows_to_items(rows, uid)
|
|
_enrich_children(items)
|
|
return {"items": items}
|
|
|
|
|
|
@router.get("/shared")
|
|
async def library_shared(
|
|
request: Request,
|
|
source_type: str = Query(default="all"),
|
|
tree: int = Query(default=0),
|
|
):
|
|
if source_type not in SOURCE_TYPES:
|
|
source_type = "all"
|
|
|
|
uid = _get_user_id(request)
|
|
query = f"{BASE_SELECT} FROM pages p WHERE p.share_mode != 'private' AND p.parent_section != 'Trash' AND p.deleted_at IS NULL"
|
|
params: list = []
|
|
if tree:
|
|
query += " AND p.parent_id IS NULL"
|
|
query, params = _apply_source_filter(query, params, source_type)
|
|
query += " ORDER BY p.updated_at DESC LIMIT 50"
|
|
|
|
with get_conn() as conn:
|
|
rows = conn.execute(query, params).fetchall()
|
|
|
|
items = _rows_to_items(rows, uid)
|
|
_enrich_children(items)
|
|
return {"items": items}
|
|
|
|
|
|
@router.get("/published")
|
|
async def library_published(
|
|
request: Request,
|
|
source_type: str = Query(default="all"),
|
|
tree: int = Query(default=0),
|
|
):
|
|
if source_type not in SOURCE_TYPES:
|
|
source_type = "all"
|
|
|
|
uid = _get_user_id(request)
|
|
query = f"{BASE_SELECT} FROM pages p WHERE p.published = 1 AND p.parent_section != 'Trash' AND p.deleted_at IS NULL"
|
|
params: list = []
|
|
if tree:
|
|
query += " AND p.parent_id IS NULL"
|
|
query, params = _apply_source_filter(query, params, source_type)
|
|
query += " ORDER BY p.updated_at DESC LIMIT 50"
|
|
|
|
with get_conn() as conn:
|
|
rows = conn.execute(query, params).fetchall()
|
|
|
|
items = _rows_to_items(rows, uid)
|
|
_enrich_children(items)
|
|
return {"items": items}
|
|
|
|
|
|
@router.get("/private")
|
|
async def library_private(
|
|
request: Request,
|
|
source_type: str = Query(default="all"),
|
|
tree: int = Query(default=0),
|
|
):
|
|
if source_type not in SOURCE_TYPES:
|
|
source_type = "all"
|
|
|
|
uid = _get_user_id(request)
|
|
query = f"{BASE_SELECT} FROM pages p WHERE p.parent_section = 'Private' AND p.deleted_at IS NULL"
|
|
params: list = []
|
|
if tree:
|
|
query += " AND p.parent_id IS NULL"
|
|
query, params = _apply_source_filter(query, params, source_type)
|
|
query += " ORDER BY p.updated_at DESC LIMIT 50"
|
|
|
|
with get_conn() as conn:
|
|
rows = conn.execute(query, params).fetchall()
|
|
|
|
items = _rows_to_items(rows, uid)
|
|
_enrich_children(items)
|
|
return {"items": items}
|
|
|
|
|
|
@router.get("/local-workspace-children/{item_id:int}")
|
|
async def library_local_workspace_children(item_id: int, request: Request):
|
|
"""Return children of a local workspace item for tree expansion."""
|
|
uid = _get_user_id(request)
|
|
with get_conn() as conn:
|
|
# Get the item to find its workspace
|
|
item = conn.execute(
|
|
"SELECT workspace_id FROM local_workspace_items WHERE id=? AND deleted_at IS NULL",
|
|
[item_id],
|
|
).fetchone()
|
|
if not item:
|
|
return {"items": []}
|
|
|
|
rows = conn.execute(
|
|
"SELECT id, name, is_folder, parent_id, content_format, size, "
|
|
"COALESCE(updated_at, created_at) as updated_at "
|
|
"FROM local_workspace_items "
|
|
"WHERE parent_id = ? AND deleted_at IS NULL "
|
|
"ORDER BY is_folder DESC, name COLLATE NOCASE",
|
|
[item_id],
|
|
).fetchall()
|
|
|
|
items = []
|
|
for r in rows:
|
|
name = r["name"] or "Untitled"
|
|
is_folder = bool(r["is_folder"])
|
|
icon = "📁" if is_folder else "📄"
|
|
fn = name.lower()
|
|
if not is_folder:
|
|
if fn.endswith(".pdf"): icon = "📕"
|
|
elif any(fn.endswith(e) for e in [".png",".jpg",".jpeg",".gif",".webp",".svg"]): icon = "🖼️"
|
|
elif any(fn.endswith(e) for e in [".py",".js",".ts",".go",".rs"]): icon = "📜"
|
|
|
|
with get_conn() as conn:
|
|
child_count = conn.execute(
|
|
"SELECT COUNT(*) FROM local_workspace_items WHERE parent_id=? AND deleted_at IS NULL",
|
|
[r["id"]],
|
|
).fetchone()[0]
|
|
|
|
items.append({
|
|
"id": r["id"],
|
|
"title": name,
|
|
"icon": icon,
|
|
"is_folder": is_folder,
|
|
"source_type": "local-ws",
|
|
"source_label": "",
|
|
"workspace": "",
|
|
"workspace_name": "",
|
|
"author": "",
|
|
"author_initial": "?",
|
|
"updated_at": r["updated_at"] or "",
|
|
"visited_at": "",
|
|
"has_children": child_count > 0,
|
|
"children": [],
|
|
"url": f"/local-workspace?folder={r['id']}" if is_folder else f"/pages/{r['id']}",
|
|
"content_format": r["content_format"] or "file",
|
|
"favorited": False,
|
|
"size_display": _format_size(r["size"]) if r["size"] else "",
|
|
})
|
|
|
|
return {"items": items}
|
|
|
|
|
|
@router.get("/children/{page_id:int}")
|
|
async def library_children(page_id: int, request: Request):
|
|
"""Return child pages for a given parent page (for tree expansion in Library)."""
|
|
uid = _get_user_id(request)
|
|
with get_conn() as conn:
|
|
rows = conn.execute(
|
|
f"{BASE_SELECT}, (SELECT COUNT(*) FROM pages c WHERE c.parent_id = p.id AND c.deleted_at IS NULL) as child_count "
|
|
f"FROM pages p WHERE p.parent_id = ? AND p.deleted_at IS NULL "
|
|
f"ORDER BY p.title COLLATE NOCASE",
|
|
[page_id],
|
|
).fetchall()
|
|
items = _rows_to_items(rows, uid)
|
|
_enrich_children(items)
|
|
return {"items": items}
|
|
|
|
|
|
@router.get("/repository")
|
|
async def library_repository(
|
|
request: Request,
|
|
gitea_owner: str = Query(default=""),
|
|
gitea_repo: str = Query(default=""),
|
|
):
|
|
"""Return Gitea repository pages/files for the Library Repository tab."""
|
|
if not gitea_owner or not gitea_repo:
|
|
return {"items": []}
|
|
|
|
uid = _get_user_id(request)
|
|
ws_key = f"{gitea_owner}/{gitea_repo}"
|
|
query = f"{BASE_SELECT} FROM pages p WHERE p.workspace = ? AND p.deleted_at IS NULL"
|
|
params = [ws_key]
|
|
query += " ORDER BY p.updated_at DESC LIMIT 100"
|
|
|
|
with get_conn() as conn:
|
|
rows = conn.execute(query, params).fetchall()
|
|
|
|
items = _rows_to_items(rows, uid)
|
|
_enrich_children(items)
|
|
return {"items": items}
|
|
|
|
|
|
@router.get("/local-workspace")
|
|
async def library_local_workspace(
|
|
request: Request,
|
|
workspace_id: int = Query(default=0),
|
|
):
|
|
"""Return local workspace items (files/folders) formatted for Library display."""
|
|
from app.routers.dashboard import _get_active_workspace
|
|
uid = _get_user_id(request)
|
|
|
|
# Get the active workspace
|
|
ws = _get_active_workspace(request, user_id=uid)
|
|
if not ws:
|
|
return {"items": []}
|
|
|
|
ws_id = workspace_id or ws["id"]
|
|
|
|
# Query local workspace tree
|
|
with get_conn() as conn:
|
|
rows = conn.execute(
|
|
"SELECT id, name, is_folder, parent_id, content_format, size, "
|
|
"COALESCE(updated_at, created_at) as updated_at "
|
|
"FROM local_workspace_items "
|
|
"WHERE workspace_id = ? AND deleted_at IS NULL "
|
|
"ORDER BY is_folder DESC, name COLLATE NOCASE",
|
|
[ws_id],
|
|
).fetchall()
|
|
|
|
items = []
|
|
for r in rows:
|
|
name = r["name"] or "Untitled"
|
|
is_folder = bool(r["is_folder"])
|
|
icon = "📁" if is_folder else "📄"
|
|
fn = name.lower()
|
|
if not is_folder:
|
|
if fn.endswith(".pdf"): icon = "📕"
|
|
elif any(fn.endswith(e) for e in [".png",".jpg",".jpeg",".gif",".webp",".svg"]): icon = "🖼️"
|
|
elif any(fn.endswith(e) for e in [".py",".js",".ts",".go",".rs"]): icon = "📜"
|
|
|
|
# Check for children
|
|
child_count = conn.execute(
|
|
"SELECT COUNT(*) FROM local_workspace_items WHERE parent_id=? AND deleted_at IS NULL",
|
|
[r["id"]],
|
|
).fetchone()[0]
|
|
|
|
items.append({
|
|
"id": r["id"],
|
|
"title": name,
|
|
"icon": icon,
|
|
"is_folder": is_folder,
|
|
"source_type": "local-ws",
|
|
"source_label": ws.get("name", "Workspace"),
|
|
"workspace": ws.get("name", ""),
|
|
"workspace_name": ws.get("name", ""),
|
|
"author": "",
|
|
"author_initial": "?",
|
|
"updated_at": r["updated_at"] or "",
|
|
"visited_at": "",
|
|
"has_children": child_count > 0,
|
|
"children": [],
|
|
"url": f"/local-workspace?folder={r['id']}" if is_folder else f"/pages/{r['id']}",
|
|
"content_format": r["content_format"] or "file",
|
|
"favorited": False,
|
|
"size_display": _format_size(r["size"]) if r["size"] else "",
|
|
})
|
|
|
|
return {"items": items}
|
|
|
|
|
|
def _format_size(size_bytes):
|
|
if not size_bytes: return ""
|
|
if size_bytes < 1024: return f"{size_bytes} B"
|
|
if size_bytes < 1048576: return f"{size_bytes/1024:.1f} KB"
|
|
if size_bytes < 1073741824: return f"{size_bytes/1048576:.1f} MB"
|
|
return f"{size_bytes/1073741824:.1f} GB"
|
|
|
|
|
|
@router.get("/workspace")
|
|
async def library_workspace(
|
|
request: Request,
|
|
source_type: str = Query(default="all"),
|
|
tree: int = Query(default=0),
|
|
workspace_id: int = Query(default=0),
|
|
):
|
|
if source_type not in SOURCE_TYPES:
|
|
source_type = "all"
|
|
|
|
uid = _get_user_id(request)
|
|
query = f"{BASE_SELECT} FROM pages p WHERE (p.workspace != '' OR p.workspace_id IS NOT NULL) AND p.parent_section != 'Trash' AND p.deleted_at IS NULL"
|
|
params: list = []
|
|
|
|
if tree:
|
|
query += " AND p.parent_id IS NULL"
|
|
|
|
if workspace_id:
|
|
query += " AND p.workspace_id = ?"
|
|
params.append(workspace_id)
|
|
|
|
query, params = _apply_source_filter(query, params, source_type)
|
|
query += " ORDER BY p.updated_at DESC LIMIT 50"
|
|
|
|
with get_conn() as conn:
|
|
rows = conn.execute(query, params).fetchall()
|
|
|
|
items = _rows_to_items(rows, uid)
|
|
_enrich_children(items)
|
|
return {"items": items}
|