Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion api/routers/wiki.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import asyncio
import os
import re
from datetime import datetime
from typing import Optional, Literal
from urllib.parse import quote

from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import JSONResponse, Response, StreamingResponse
Expand Down Expand Up @@ -34,6 +36,20 @@
router = APIRouter(tags=["wiki"])


def _attachment_header(filename: str) -> str:
"""Build a Content-Disposition value that is safe for any file name.

Header values are encoded as latin-1, so a non-ASCII name (for example a
local repository in a Chinese directory) cannot go in ``filename=``. Send
an ASCII fallback there and the real name in ``filename*`` (RFC 6266).
"""
fallback = re.sub(r'[^A-Za-z0-9._-]', "_", filename)
return (
f'attachment; filename="{fallback}"; '
f"filename*=UTF-8''{quote(filename, safe='')}"
)


@router.post("/export/wiki")
async def post_export_wiki(request: WikiExportRequest):
"""
Expand Down Expand Up @@ -74,7 +90,7 @@ async def post_export_wiki(request: WikiExportRequest):
return Response(
content=content,
media_type=media_type,
headers={"Content-Disposition": f"attachment; filename={filename}"},
headers={"Content-Disposition": _attachment_header(filename)},
)


Expand Down
17 changes: 14 additions & 3 deletions src/app/[owner]/[repo]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -624,9 +624,20 @@ export default function RepoWikiPage() {
let filename = `${effectiveRepoInfo.repo}_wiki.${format === 'markdown' ? 'md' : 'json'}`;

if (contentDisposition) {
const filenameMatch = contentDisposition.match(/filename=(.+)/);
if (filenameMatch && filenameMatch[1]) {
filename = filenameMatch[1].replace(/"/g, '');
const encodedMatch = contentDisposition.match(/filename\*=UTF-8''([^;]+)/i);
const plainMatch = contentDisposition.match(/filename="?([^";]+)"?/i);
let decoded: string | null = null;
if (encodedMatch && encodedMatch[1]) {
try {
decoded = decodeURIComponent(encodedMatch[1].trim());
} catch {
decoded = null;
}
}
if (decoded) {
filename = decoded;
} else if (plainMatch && plainMatch[1]) {
filename = plainMatch[1].trim();
}
}

Expand Down
49 changes: 49 additions & 0 deletions tests/backend/routers/test_wiki_export.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from urllib.parse import unquote

import pytest
from fastapi.testclient import TestClient


def _export(repo_url: str):
from api.main import app

client = TestClient(app, raise_server_exceptions=False)
return client.post(
"/export/wiki",
json={
"repo_url": repo_url,
"type": "local",
"format": "markdown",
"pages": [
{
"id": "page-1",
"title": "P1",
"content": "body",
"filePaths": [],
"importance": "high",
"relatedPages": [],
}
],
},
)


@pytest.mark.parametrize(
"repo_url, repo_name",
[
("https://github.com/owner/repo", "repo"),
("/home/user/项目", "项目"),
("/home/user/my repo", "my repo"),
],
)
def test_export_wiki_content_disposition(repo_url, repo_name):
response = _export(repo_url)

assert response.status_code == 200
header = response.headers["content-disposition"]
header.encode("ascii")
assert header.startswith('attachment; filename="')
encoded = header.split("filename*=UTF-8''", 1)[1]
filename = unquote(encoded)
assert filename.startswith(f"{repo_name}_wiki_")
assert filename.endswith(".md")
Loading