Files
KnowledgeBase/app/Http/Controllers/DocumentController.php
Knowledge Base System acf549c43c feat: 初始化知识库系统项目
- 实现基于 Laravel 11 和 Filament 3.X 的文档管理系统
- 添加用户认证和分组管理功能
- 实现文档上传、分类和权限控制
- 集成 Word 文档自动转换为 Markdown
- 集成 Meilisearch 全文搜索引擎
- 实现文档在线预览功能
- 添加安全日志和审计功能
- 完整的简体中文界面
- 包含完整的项目文档和部署指南

技术栈:
- Laravel 11.x
- Filament 3.X
- Meilisearch 1.5+
- Pandoc 文档转换
- Redis 队列系统
- Pest PHP 测试框架
2025-12-05 14:44:44 +08:00

99 lines
2.9 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Http\Controllers;
use App\Models\Document;
use App\Services\DocumentService;
use App\Services\MarkdownRenderService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Storage;
class DocumentController extends Controller
{
protected DocumentService $documentService;
protected MarkdownRenderService $markdownRenderService;
public function __construct(
DocumentService $documentService,
MarkdownRenderService $markdownRenderService
) {
$this->documentService = $documentService;
$this->markdownRenderService = $markdownRenderService;
}
/**
* 预览文档的 Markdown 内容(支持图片显示)
* 需求11.1, 11.3, 11.4
*
* @param Document $document
* @return \Illuminate\View\View|\Illuminate\Http\RedirectResponse
*/
public function preview(Document $document)
{
// 验证用户权限(使用 DocumentPolicy
// 需求11.3
if (!Gate::allows('view', $document)) {
abort(403, '您没有权限预览此文档');
}
// 检查文档是否已完成转换
if ($document->conversion_status !== 'completed') {
return view('documents.preview', [
'document' => $document,
'markdownHtml' => null,
]);
}
$markdownHtml = null;
try {
// 使用 DocumentPreviewService 的 Markdown 预览方法
// 这会修复图片路径并渲染 Markdown
// 需求11.1
$previewService = app(\App\Services\DocumentPreviewService::class);
$markdownHtml = $previewService->convertMarkdownToHtml($document);
} catch (\Exception $e) {
// 记录错误但不中断流程
\Log::error('Markdown 预览失败', [
'document_id' => $document->id,
'error' => $e->getMessage(),
]);
}
// 处理内容为空的情况
// 需求11.4
// 返回渲染后的 HTML 视图
return view('documents.preview', [
'document' => $document,
'markdownHtml' => $markdownHtml,
]);
}
/**
* 下载文档
*
* @param Document $document
* @return \Symfony\Component\HttpFoundation\StreamedResponse
*/
public function download(Document $document)
{
// 验证用户权限
if (!Gate::allows('download', $document)) {
abort(403, '您没有权限下载此文档');
}
$user = auth()->user();
try {
// 记录下载日志
$this->documentService->logDownload($document, $user);
// 返回文件下载响应
return $this->documentService->downloadDocument($document, $user);
} catch (\Exception $e) {
abort(500, '下载失败:' . $e->getMessage());
}
}
}