feat: use xpier media library for uploads and markdown embeds
Store media:ID in post bodies instead of CDN URLs, and keep sablog attach tokens as a fallback. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Blog\Services;
|
||||
|
||||
use App\Blog\Support\MarkdownMediaEmbed;
|
||||
use App\Models\Post;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use League\CommonMark\Environment\Environment;
|
||||
@@ -36,11 +37,15 @@ class PostContentRenderer
|
||||
*/
|
||||
public function render(Post $post): string
|
||||
{
|
||||
$embed = app(MarkdownMediaEmbed::class);
|
||||
$raw = (string) $post->content;
|
||||
|
||||
$content = $post->content_format === 'markdown'
|
||||
? $this->toHtml($post->content)
|
||||
: $post->content;
|
||||
? $this->toHtml($embed->expandMarkdown($raw))
|
||||
: $raw;
|
||||
|
||||
$html = $this->renderShortcodes($content, $post);
|
||||
$html = $embed->hydrateHtml($html);
|
||||
|
||||
// 插件钩子:付费内容过滤、AI 处理等
|
||||
$html = app(\App\Blog\Support\PluginManager::class)->applyFilters('post.rendered', $html, $post);
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Blog\Support;
|
||||
|
||||
use Xpier\FilamentMediaLibrary\Models\MediaLibrary;
|
||||
|
||||
/**
|
||||
* Markdown/HTML body must store library references, never CDN URLs.
|
||||
*
|
||||
* Markdown:  or [file.pdf](media:12)
|
||||
* HTML: [media=12]
|
||||
*/
|
||||
class MarkdownMediaEmbed
|
||||
{
|
||||
public const PROTOCOL = 'media:';
|
||||
|
||||
public function snippet(MediaLibrary $media, string $format = 'markdown'): string
|
||||
{
|
||||
$id = (int) $media->getKey();
|
||||
$isImage = $this->isImage($media);
|
||||
|
||||
if ($format === 'html') {
|
||||
return '[media='.$id.']';
|
||||
}
|
||||
|
||||
$label = $this->escapeMdLabel($this->label($media, $isImage));
|
||||
|
||||
return $isImage
|
||||
? ''
|
||||
: '['.$label.']('.self::PROTOCOL.$id.')';
|
||||
}
|
||||
|
||||
public function expandMarkdown(string $markdown): string
|
||||
{
|
||||
return preg_replace_callback(
|
||||
'/\]\(media:(\d+)\)/i',
|
||||
function (array $matches): string {
|
||||
$url = $this->publicUrl((int) $matches[1]);
|
||||
|
||||
return $url !== null ? ']('.$url.')' : $matches[0];
|
||||
},
|
||||
$markdown
|
||||
) ?? $markdown;
|
||||
}
|
||||
|
||||
public function hydrateHtml(string $html): string
|
||||
{
|
||||
$html = preg_replace_callback(
|
||||
'/\b(src|href)=([\'"])media:(\d+)\2/i',
|
||||
function (array $matches): string {
|
||||
$url = $this->publicUrl((int) $matches[3]);
|
||||
if ($url === null) {
|
||||
return $matches[0];
|
||||
}
|
||||
|
||||
return $matches[1].'='.$matches[2].$url.$matches[2];
|
||||
},
|
||||
$html
|
||||
) ?? $html;
|
||||
|
||||
return preg_replace_callback(
|
||||
'/\[media=(\d+)\]/i',
|
||||
function (array $matches): string {
|
||||
$id = (int) $matches[1];
|
||||
$media = $this->find($id);
|
||||
$url = $this->publicUrl($id);
|
||||
|
||||
if ($url === null) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($media && $this->isImage($media)) {
|
||||
return sprintf(
|
||||
'<img src="%s" alt="%s" loading="lazy" />',
|
||||
e($url),
|
||||
e($this->label($media, true))
|
||||
);
|
||||
}
|
||||
|
||||
$label = $media ? $this->label($media, false) : 'file-'.$id;
|
||||
|
||||
return sprintf('<a href="%s">%s</a>', e($url), e($label));
|
||||
},
|
||||
$html
|
||||
) ?? $html;
|
||||
}
|
||||
|
||||
public function find(int $id): ?MediaLibrary
|
||||
{
|
||||
try {
|
||||
return MediaLibrary::query()->find($id);
|
||||
} catch (\Throwable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public function publicUrl(int $id): ?string
|
||||
{
|
||||
$media = $this->find($id);
|
||||
$url = $media?->url;
|
||||
|
||||
return filled($url) ? (string) $url : null;
|
||||
}
|
||||
|
||||
public function isImage(MediaLibrary $media): bool
|
||||
{
|
||||
if ($media->type === MediaLibrary::TYPE_IMAGE) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return is_string($media->mime_type) && str_starts_with($media->mime_type, 'image/');
|
||||
}
|
||||
|
||||
protected function label(MediaLibrary $media, bool $isImage): string
|
||||
{
|
||||
if (filled($media->alt_text)) {
|
||||
return (string) $media->alt_text;
|
||||
}
|
||||
|
||||
$name = (string) ($media->original_name ?: basename((string) $media->path) ?: 'media-'.$media->getKey());
|
||||
|
||||
return $isImage ? (pathinfo($name, PATHINFO_FILENAME) ?: $name) : $name;
|
||||
}
|
||||
|
||||
protected function escapeMdLabel(string $label): string
|
||||
{
|
||||
return str_replace(['[', ']', '!'], ['\\[', '\\]', '\\!'], $label);
|
||||
}
|
||||
}
|
||||
@@ -4,12 +4,11 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Resources\Categories\Schemas;
|
||||
|
||||
use App\Support\MediaDisk;
|
||||
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
use Xpier\FilamentMediaLibrary\Components\MediaPicker;
|
||||
|
||||
class CategoryForm
|
||||
{
|
||||
@@ -43,12 +42,11 @@ class CategoryForm
|
||||
]),
|
||||
Section::make('封面')
|
||||
->schema([
|
||||
SpatieMediaLibraryFileUpload::make('cover')
|
||||
MediaPicker::make('cover_media_id')
|
||||
->label('封面图')
|
||||
->collection('cover')
|
||||
->image()
|
||||
->imageEditor()
|
||||
->disk(MediaDisk::name()),
|
||||
->module('articles')
|
||||
->mediaType('image')
|
||||
->relationship('coverMedia'),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -27,6 +27,11 @@ class MediaResource extends Resource
|
||||
|
||||
protected static ?string $pluralModelLabel = '媒体';
|
||||
|
||||
public static function shouldRegisterNavigation(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
protected static ?string $model = Media::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedRectangleStack;
|
||||
|
||||
@@ -2,18 +2,23 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
|
||||
namespace App\Filament\Resources\Posts\Schemas;
|
||||
|
||||
use App\Support\MediaDisk;
|
||||
use App\Blog\Support\MarkdownMediaEmbed;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\DateTimePicker;
|
||||
use Filament\Forms\Components\MarkdownEditor;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Schemas\Components\Actions;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Components\Utilities\Set;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
|
||||
use Xpier\FilamentMediaLibrary\Components\MediaPicker;
|
||||
use Xpier\FilamentMediaLibrary\Models\MediaLibrary;
|
||||
|
||||
class PostForm
|
||||
{
|
||||
@@ -39,7 +44,8 @@ class PostForm
|
||||
'markdown' => 'Markdown',
|
||||
'html' => 'HTML',
|
||||
])
|
||||
->default('markdown'),
|
||||
->default('markdown')
|
||||
->live(),
|
||||
Select::make('status')
|
||||
->label('状态')
|
||||
->options([
|
||||
@@ -51,17 +57,49 @@ class PostForm
|
||||
MarkdownEditor::make('content')
|
||||
->label('正文')
|
||||
->required()
|
||||
->helperText('Markdown 插入图片用 ,文件用 [文件名](media:ID)。不要把 CDN / 对象存储地址写进正文。')
|
||||
->fileAttachments(false)
|
||||
->columnSpanFull(),
|
||||
MediaPicker::make('insert_media_id')
|
||||
->label('从媒体库插入正文')
|
||||
->module('articles')
|
||||
->mediaType(null)
|
||||
->dehydrated(false)
|
||||
->helperText('选好媒体后点「插入到正文」。Markdown 写入 media:ID 引用,渲染时再换成真实地址。')
|
||||
->columnSpanFull(),
|
||||
Actions::make([
|
||||
Action::make('insertSelectedMedia')
|
||||
->label('插入到正文')
|
||||
->action(function (Get $get, Set $set): void {
|
||||
$mediaId = $get('insert_media_id');
|
||||
$media = is_numeric($mediaId)
|
||||
? MediaLibrary::query()->find((int) $mediaId)
|
||||
: null;
|
||||
|
||||
if (! $media instanceof MediaLibrary) {
|
||||
Notification::make()->title('请先从媒体库选择文件')->warning()->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$snippet = app(MarkdownMediaEmbed::class)->snippet(
|
||||
$media,
|
||||
(string) ($get('content_format') ?: 'markdown')
|
||||
);
|
||||
$set('content', rtrim((string) $get('content'))."\n\n".$snippet."\n");
|
||||
$set('insert_media_id', null);
|
||||
Notification::make()->title('已写入正文引用')->success()->send();
|
||||
}),
|
||||
])->columnSpanFull(),
|
||||
]),
|
||||
\Filament\Schemas\Components\Section::make('封面与摘要')
|
||||
->columns(2)
|
||||
->schema([
|
||||
SpatieMediaLibraryFileUpload::make('cover')
|
||||
MediaPicker::make('cover_media_id')
|
||||
->label('封面图')
|
||||
->collection('cover')
|
||||
->image()
|
||||
->imageEditor()
|
||||
->disk(MediaDisk::name())
|
||||
->module('articles')
|
||||
->mediaType('image')
|
||||
->relationship('coverMedia')
|
||||
->columnSpanFull(),
|
||||
Textarea::make('excerpt')
|
||||
->label('摘要(留空自动截取)')
|
||||
|
||||
@@ -6,8 +6,10 @@ namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Spatie\MediaLibrary\HasMedia;
|
||||
use Xpier\FilamentMediaLibrary\Models\MediaLibrary;
|
||||
use Spatie\MediaLibrary\InteractsWithMedia;
|
||||
|
||||
class Category extends Model implements HasMedia
|
||||
@@ -21,6 +23,7 @@ class Category extends Model implements HasMedia
|
||||
'display_order',
|
||||
'post_count',
|
||||
'description',
|
||||
'cover_media_id',
|
||||
];
|
||||
|
||||
public function posts(): HasMany
|
||||
@@ -28,6 +31,21 @@ class Category extends Model implements HasMedia
|
||||
return $this->hasMany(Post::class);
|
||||
}
|
||||
|
||||
public function coverMedia(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(MediaLibrary::class, 'cover_media_id');
|
||||
}
|
||||
|
||||
public function coverImageUrl(): ?string
|
||||
{
|
||||
$libraryUrl = $this->coverMedia?->url;
|
||||
if (filled($libraryUrl)) {
|
||||
return (string) $libraryUrl;
|
||||
}
|
||||
|
||||
return $this->getFirstMedia('cover')?->getUrl();
|
||||
}
|
||||
|
||||
public function getUrlAttribute(): string
|
||||
{
|
||||
return route('category.show', $this->slug ?? $this->id);
|
||||
|
||||
+26
-2
@@ -11,6 +11,7 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Spatie\MediaLibrary\HasMedia;
|
||||
use Xpier\FilamentMediaLibrary\Models\MediaLibrary;
|
||||
use Spatie\MediaLibrary\InteractsWithMedia;
|
||||
use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
||||
use Spatie\Tags\HasTags;
|
||||
@@ -30,6 +31,7 @@ class Post extends Model implements HasMedia
|
||||
'content',
|
||||
'content_format',
|
||||
'keywords',
|
||||
'cover_media_id',
|
||||
'status',
|
||||
'is_sticky',
|
||||
'close_comment',
|
||||
@@ -57,6 +59,26 @@ class Post extends Model implements HasMedia
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
|
||||
public function coverMedia(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(MediaLibrary::class, 'cover_media_id');
|
||||
}
|
||||
|
||||
public function coverImageUrl(?string $conversion = 'card'): ?string
|
||||
{
|
||||
$libraryUrl = $this->coverMedia?->url;
|
||||
if (filled($libraryUrl)) {
|
||||
return (string) $libraryUrl;
|
||||
}
|
||||
|
||||
$cover = $this->getFirstMedia('cover');
|
||||
if ($cover === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $cover->getUrl($conversion) ?: $cover->getUrl();
|
||||
}
|
||||
|
||||
public function comments(): HasMany
|
||||
{
|
||||
return $this->hasMany(Comment::class);
|
||||
@@ -133,8 +155,10 @@ class Post extends Model implements HasMedia
|
||||
|
||||
$text = strip_tags($this->content);
|
||||
// 付费块不进入摘要,避免付费内容泄漏到列表页/SEO meta
|
||||
$text = preg_replace('/\[paid\].*?\[\/paid\]/s', '', $text);
|
||||
$text = preg_replace('/\[[^\]]*\]/', '', $text);
|
||||
$text = preg_replace('/\[paid\].*?\[\/paid\]/s', '', $text) ?? $text;
|
||||
$text = preg_replace('/!\[([^\]]*)\]\((?:media|attach):\d+\)/i', '$1', $text) ?? $text;
|
||||
$text = preg_replace('/\[([^\]]*)\]\((?:media|attach):\d+\)/i', '$1', $text) ?? $text;
|
||||
$text = preg_replace('/\[[^\]]*\]/', '', $text) ?? $text;
|
||||
|
||||
return mb_substr($text, 0, 200);
|
||||
}
|
||||
|
||||
@@ -41,6 +41,10 @@ class AppServiceProvider extends ServiceProvider
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
config([
|
||||
'filament-media-library.navigation_group' => '内容',
|
||||
]);
|
||||
|
||||
// 自动加载所有插件的迁移(插件目录下 database/migrations)
|
||||
foreach (glob(base_path('plugins/*/database/migrations')) ?: [] as $path) {
|
||||
$this->loadMigrationsFrom($path);
|
||||
|
||||
@@ -28,6 +28,7 @@ use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;
|
||||
use Illuminate\Routing\Middleware\SubstituteBindings;
|
||||
use Illuminate\Session\Middleware\StartSession;
|
||||
use Illuminate\View\Middleware\ShareErrorsFromSession;
|
||||
use Xpier\FilamentMediaLibrary\Filament\MediaLibraryPlugin;
|
||||
|
||||
class AdminPanelProvider extends PanelProvider
|
||||
{
|
||||
@@ -98,6 +99,10 @@ class AdminPanelProvider extends PanelProvider
|
||||
->widgets([
|
||||
AccountWidget::class,
|
||||
])
|
||||
->plugins([
|
||||
MediaLibraryPlugin::make()
|
||||
->navigationGroup((string) config('filament-media-library.navigation_group', '内容')),
|
||||
])
|
||||
->middleware([
|
||||
EncryptCookies::class,
|
||||
AddQueuedCookiesToResponse::class,
|
||||
|
||||
Reference in New Issue
Block a user