feat: post cover filter + admin AI cover action, restyle page-cache admin
Build and Deploy / verify (push) Successful in 10s
Build and Deploy / deploy (push) Successful in 17s

- 抽 CoverGenerator 服务(covers:generate 与后台共用),内部强制同步产出 card 转换
- 文章列表:新增封面状态图标列、「有/无封面/完全无图」筛选、行内「生成封面」AI 操作
- 页面缓存:统计改为原生 StatsOverviewWidget(缓存页数/总大小/命中率/时长),
  缓存明细表重排(表头、悬停、URL 截断、图标删除按钮、空状态)
This commit is contained in:
2026-10-14 23:48:57 +00:00
parent 58ebaf7f90
commit d041622531
6 changed files with 254 additions and 148 deletions
+94
View File
@@ -0,0 +1,94 @@
<?php
declare(strict_types=1);
namespace App\Blog\Services;
use App\Models\Post;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
/**
* AI 封面生成:复用「AI 设置」的 LLM 配置调 OpenAI 兼容 /image_generation 接口
* (如 MiniMax image-01),图片存入 media cover 集合(singleFile,重复生成自动替换)。
*/
class CoverGenerator
{
public function __construct(private LlmClient $llm) {}
public function isConfigured(): bool
{
return $this->llm->isConfigured();
}
public function model(?string $override = null): string
{
return $override ?: (string) blog_setting('llm_image_model', 'image-01');
}
public function generateFor(Post $post, ?string $model = null, ?string $style = null): void
{
if (! $this->llm->isConfigured()) {
throw new \RuntimeException('LLM 未配置:请先在后台「AI 设置」配置 Base URL / API Key');
}
// 站点无常驻 queue worker:同步产出 card 转换,避免缩略图永远卡在队列里。
config(['media-library.queue_conversions_by_default' => false]);
$response = Http::timeout(120)
->withToken($this->llm->apiKey())
->post($this->llm->baseUrl().'/image_generation', [
'model' => $this->model($model),
'prompt' => $this->buildPrompt($post, $style),
'aspect_ratio' => '16:9',
'response_format' => 'url',
'n' => 1,
'prompt_optimizer' => true,
]);
if ($response->failed()) {
throw new \RuntimeException('HTTP '.$response->status().':'.Str::limit($response->body(), 200));
}
$url = $response->json('data.image_urls.0');
if (! is_string($url) || $url === '') {
$reason = $response->json('base_resp.status_msg') ?: $response->body();
throw new \RuntimeException('接口未返回图片:'.Str::limit((string) $reason, 200));
}
$image = Http::timeout(60)->get($url)->throw();
$ext = match (strtolower(explode(';', (string) $image->header('Content-Type'))[0])) {
'image/png' => 'png',
'image/webp' => 'webp',
default => 'jpg',
};
$tmp = tempnam(sys_get_temp_dir(), 'cover_');
file_put_contents($tmp, $image->body());
try {
$post->addMedia($tmp)
->usingFileName('cover-'.$post->id.'.'.$ext)
->toMediaCollection('cover');
} finally {
@unlink($tmp);
}
}
public function buildPrompt(Post $post, ?string $style = null): string
{
$style = trim((string) ($style
?: blog_setting('cover_prompt_style', '扁平插画风格,色调柔和,构图简洁')));
$excerpt = Str::limit(trim(strip_tags((string) $post->excerpt)), 60, '');
$parts = ["为博客文章《{$post->title}》生成一张封面配图"];
if ($excerpt !== '') {
$parts[] = "内容大意:{$excerpt}";
}
$parts[] = $style;
$parts[] = '画面中不要出现任何文字';
return implode('。', $parts);
}
}
+7 -71
View File
@@ -4,16 +4,13 @@ declare(strict_types=1);
namespace App\Console\Commands;
use App\Blog\Services\LlmClient;
use App\Blog\Services\CoverGenerator;
use App\Models\Post;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
/**
* 用 AI 图像接口(OpenAI 兼容 /image_generation,如 MiniMax image-01)批量生成文章封面。
* 复用「AI 设置」里的 llm_base_url / llm_api_key,模型取 llm_image_model(默认 image-01)。
* 批量为文章生成 AI 封面(默认只补完全没有任何图片的文章)。
*/
class GenerateCovers extends Command
{
@@ -27,18 +24,16 @@ class GenerateCovers extends Command
protected $description = '用 AI 为文章批量生成封面图(存入 media cover 集合)';
public function handle(LlmClient $llm): int
public function handle(CoverGenerator $covers): int
{
if (! $llm->isConfigured()) {
if (! $covers->isConfigured()) {
$this->error('LLM 未配置:请先在后台「AI 设置」或 .env 配置 LLM_BASE_URL / LLM_API_KEY');
return self::FAILURE;
}
$model = (string) ($this->option('model') ?: blog_setting('llm_image_model', 'image-01'));
// 站点无常驻 queue worker:批量生成期间同步产出 card 转换,避免永远卡在队列里。
config(['media-library.queue_conversions_by_default' => false]);
$model = $covers->model($this->option('model') ?: null);
$style = $this->option('style') ?: null;
$query = Post::query()->published()->orderedForList();
@@ -75,7 +70,7 @@ class GenerateCovers extends Command
foreach ($todo as $post) {
try {
$this->generateFor($post, $llm, $model);
$covers->generateFor($post, $model, $style);
$ok++;
$this->info("✔ [{$post->id}] {$post->title}");
} catch (\Throwable $e) {
@@ -89,63 +84,4 @@ class GenerateCovers extends Command
return $ok === 0 && $fail > 0 ? self::FAILURE : self::SUCCESS;
}
private function generateFor(Post $post, LlmClient $llm, string $model): void
{
$response = Http::timeout(120)
->withToken($llm->apiKey())
->post($llm->baseUrl().'/image_generation', [
'model' => $model,
'prompt' => $this->buildPrompt($post),
'aspect_ratio' => '16:9',
'response_format' => 'url',
'n' => 1,
'prompt_optimizer' => true,
]);
if ($response->failed()) {
throw new \RuntimeException('HTTP '.$response->status().':'.Str::limit($response->body(), 200));
}
$url = $response->json('data.image_urls.0');
if (! is_string($url) || $url === '') {
$reason = $response->json('base_resp.status_msg') ?: $response->body();
throw new \RuntimeException('接口未返回图片:'.Str::limit((string) $reason, 200));
}
$image = Http::timeout(60)->get($url)->throw();
$ext = match (strtolower(explode(';', (string) $image->header('Content-Type'))[0])) {
'image/png' => 'png',
'image/webp' => 'webp',
default => 'jpg',
};
$tmp = tempnam(sys_get_temp_dir(), 'cover_');
file_put_contents($tmp, $image->body());
try {
$post->addMedia($tmp)
->usingFileName('cover-'.$post->id.'.'.$ext)
->toMediaCollection('cover');
} finally {
@unlink($tmp);
}
}
private function buildPrompt(Post $post): string
{
$style = trim((string) ($this->option('style')
?: blog_setting('cover_prompt_style', '扁平插画风格,色调柔和,构图简洁')));
$excerpt = Str::limit(trim(strip_tags((string) $post->excerpt)), 60, '');
$parts = ["为博客文章《{$post->title}》生成一张封面配图"];
if ($excerpt !== '') {
$parts[] = "内容大意:{$excerpt}";
}
$parts[] = $style;
$parts[] = '画面中不要出现任何文字';
return implode('。', $parts);
}
}
+9 -12
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Filament\Pages;
use App\Blog\Support\PageCacheMiddleware;
use App\Filament\Widgets\PageCacheStats;
use App\Models\Setting;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
@@ -28,18 +29,7 @@ class PageCache extends Page
protected string $view = 'filament.pages.page-cache';
/**
* @return array{hits: int, misses: int, count: int, rate: float, ttl: int}
*/
public function getStatsProperty(): array
{
return [
...PageCacheMiddleware::stats(),
'ttl' => (int) config('blog.page_cache_ttl', 300),
];
}
/**
* @return list<array{key: string, url: string, cached_at: string}>
* @return list<array{key: string, url: string, cached_at: string, size: int, expires_at: string}>
*/
public function getEntriesProperty(): array
{
@@ -72,6 +62,13 @@ class PageCache extends Page
Notification::make()->title('已删除这条缓存')->success()->send();
}
protected function getHeaderWidgets(): array
{
return [
PageCacheStats::class,
];
}
protected function getHeaderActions(): array
{
return [
@@ -4,17 +4,21 @@ declare(strict_types=1);
namespace App\Filament\Resources\Posts\Tables;
use App\Blog\Services\CoverGenerator;
use App\Models\Post;
use Filament\Actions\Action;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Actions\ViewAction;
use Filament\Notifications\Notification;
use Filament\Support\Enums\Width;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Enums\FiltersLayout;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
class PostsTable
{
@@ -46,6 +50,16 @@ class PostsTable
'draft' => 'warning',
default => 'gray',
}),
IconColumn::make('cover_state')
->label('封面')
->boolean()
->trueIcon('heroicon-o-photo')
->falseIcon('heroicon-o-x-mark')
->trueColor('success')
->falseColor('gray')
->state(fn (Post $record): bool => $record->coverImageUrl() !== null)
->tooltip(fn (Post $record): string => $record->coverImageUrl() !== null ? '已有封面' : '无封面,可用「生成封面」AI 补一张')
->toggleable(),
TextColumn::make('sticky_level')
->label('置顶')
->badge()
@@ -90,10 +104,50 @@ class PostsTable
SelectFilter::make('sticky_level')
->label('置顶')
->options(Post::stickyLevelOptions()),
SelectFilter::make('cover_status')
->label('封面')
->options([
'with' => '有封面',
'without' => '无封面',
'no_image' => '完全无图(正文/附件也没有)',
])
->query(fn (Builder $query, array $data): Builder => match ($data['value'] ?? null) {
'with' => $query->where(fn (Builder $q) => $q
->whereNotNull('cover_media_id')
->orWhereHas('media', fn (Builder $m) => $m->where('collection_name', 'cover'))),
'without' => $query
->whereNull('cover_media_id')
->whereDoesntHave('media', fn (Builder $m) => $m->where('collection_name', 'cover')),
'no_image' => $query
->whereNull('cover_media_id')
->whereDoesntHave('media', fn (Builder $m) => $m->where(fn (Builder $x) => $x
->where('collection_name', 'cover')
->orWhere(fn (Builder $y) => $y
->where('collection_name', 'attachments')
->where('mime_type', 'like', 'image/%'))))
->where('content', 'not like', '%<img%')
->where('content', 'not like', '%](http%'),
default => $query,
}),
], FiltersLayout::AboveContent)
->filtersFormColumns(3)
->filtersFormWidth(Width::ThreeExtraLarge)
->recordActions([
Action::make('generateCover')
->label('生成封面')
->icon('heroicon-o-photo')
->color('gray')
->requiresConfirmation()
->modalHeading('AI 生成封面')
->modalDescription(fn (Post $record): string => "根据《{$record->title}》的标题和摘要生成一张封面图,约需 20 秒,请耐心等待。")
->action(function (Post $record): void {
try {
app(CoverGenerator::class)->generateFor($record);
Notification::make()->title('封面已生成')->success()->send();
} catch (\Throwable $e) {
Notification::make()->title('生成失败')->body($e->getMessage())->danger()->send();
}
}),
Action::make('preview')
->label('预览')
->url(fn (Post $record): string => $record->url)
+36
View File
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Filament\Widgets;
use App\Blog\Support\PageCacheMiddleware;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
class PageCacheStats extends StatsOverviewWidget
{
protected function getStats(): array
{
$stats = PageCacheMiddleware::stats();
$size = (int) collect(PageCacheMiddleware::entries())->sum('size');
$sizeText = $size >= 1048576
? number_format($size / 1048576, 2).' MB'
: number_format($size / 1024, 1).' KB';
return [
Stat::make('缓存页面', $stats['count'].' 个')
->description('仅未登录访客的 GET 页面')
->icon('heroicon-m-document-text'),
Stat::make('总大小', $sizeText)
->description('全部缓存页合计')
->icon('heroicon-m-circle-stack'),
Stat::make('命中率', $stats['rate'].'%')
->description("命中 {$stats['hits']} · 未命中 {$stats['misses']}")
->icon('heroicon-m-chart-bar'),
Stat::make('缓存时长', ((int) config('blog.page_cache_ttl', 300)).' 秒')
->description('到期自动失效')
->icon('heroicon-m-clock'),
];
}
}
@@ -1,72 +1,61 @@
<x-filament-panels::page>
<div class="grid gap-4 md:grid-cols-4">
<x-filament::section>
<div class="text-sm text-gray-500 dark:text-gray-400">当前缓存页</div>
<div class="mt-1 text-2xl font-semibold">{{ $this->stats['count'] }} 条</div>
</x-filament::section>
<x-filament::section>
<div class="text-sm text-gray-500 dark:text-gray-400">命中率</div>
<div class="mt-1 text-2xl font-semibold">{{ $this->stats['rate'] }}%</div>
</x-filament::section>
<x-filament::section>
<div class="text-sm text-gray-500 dark:text-gray-400">命中 / 未命中</div>
<div class="mt-1 text-2xl font-semibold">{{ $this->stats['hits'] }} / {{ $this->stats['misses'] }}</div>
</x-filament::section>
<x-filament::section>
<div class="text-sm text-gray-500 dark:text-gray-400">过期时间</div>
<div class="mt-1 text-2xl font-semibold">{{ $this->stats['ttl'] }} 秒</div>
</x-filament::section>
</div>
<x-filament::section heading="已缓存的前台页面" class="mt-6">
<p class="mb-4 text-sm text-gray-500 dark:text-gray-400">
只缓存未登录访客打开的页面。登录后看前台不会进缓存,所以这里可能暂时是空的。
</p>
<x-filament::section>
<x-slot name="heading">已缓存的前台页面</x-slot>
<x-slot name="description">只缓存未登录访客打开的页面;登录后访问前台不会进缓存,所以这里可能暂时是空的。</x-slot>
@if(count($this->entries) === 0)
<p class="text-sm text-gray-500 dark:text-gray-400">当前没有前台页面缓存。</p>
@else
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="border-b border-gray-200 text-left dark:border-white/10">
<th class="py-2 pr-4 font-medium">地址</th>
<th class="py-2 pr-4 font-medium">大小</th>
<th class="py-2 pr-4 font-medium">缓存时间</th>
<th class="py-2 pr-4 font-medium">过期时间</th>
<th class="py-2 font-medium">操作</th>
</tr>
</thead>
<tbody>
@foreach($this->entries as $entry)
<tr class="border-b border-gray-100 dark:border-white/5" wire:key="cache-{{ $entry['key'] }}">
<td class="py-2 pr-4">
<a href="{{ $entry['url'] }}" target="_blank" rel="noopener noreferrer" class="text-primary-600 hover:underline">
{{ $entry['url'] }}
</a>
</td>
<td class="py-2 pr-4 whitespace-nowrap">{{ $entry['size'] ? number_format($entry['size'] / 1024, 1).' KB' : '—' }}</td>
<td class="py-2 pr-4 whitespace-nowrap">{{ $entry['cached_at'] ?: '—' }}</td>
<td class="py-2 pr-4 whitespace-nowrap">{{ $entry['expires_at'] ?: '—' }}</td>
<td class="py-2">
<x-filament::button
size="xs"
color="danger"
wire:click="forgetEntry('{{ $entry['key'] }}')"
wire:confirm="删除这条缓存?"
>
删除
</x-filament::button>
</td>
</tr>
@endforeach
</tbody>
</table>
<p class="mt-3 text-xs text-gray-500 dark:text-gray-400">
共 {{ count($this->entries) }} 条,合计 {{ number_format(collect($this->entries)->sum('size') / 1024 / 1024, 2) }} MB。
缓存说明:只缓存未登录访客 GET 的 200 页面;登录用户、评论提交等动态请求不缓存;浏览量统计不受影响。
</p>
<div class="flex flex-col items-center gap-3 py-10 text-gray-400 dark:text-gray-500">
<x-filament::icon icon="heroicon-o-inbox" class="h-10 w-10" />
<p class="text-sm">当前没有前台页面缓存</p>
</div>
@else
<div class="overflow-hidden rounded-xl ring-1 ring-gray-950/5 dark:ring-white/10">
<div class="overflow-x-auto">
<table class="w-full divide-y divide-gray-200 text-sm dark:divide-white/5">
<thead class="bg-gray-50 dark:bg-white/5">
<tr>
<th class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">地址</th>
<th class="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">大小</th>
<th class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">缓存时间</th>
<th class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">过期时间</th>
<th class="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-gray-400">操作</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-100 bg-white dark:divide-white/5 dark:bg-transparent">
@foreach($this->entries as $entry)
<tr class="transition hover:bg-gray-50 dark:hover:bg-white/5" wire:key="cache-{{ $entry['key'] }}">
<td class="max-w-0 px-4 py-3">
<a href="{{ $entry['url'] }}" target="_blank" rel="noopener noreferrer"
title="{{ $entry['url'] }}"
class="block w-64 truncate text-primary-600 hover:underline sm:w-80 lg:w-[32rem] dark:text-primary-400">
{{ $entry['url'] }}
</a>
</td>
<td class="whitespace-nowrap px-4 py-3 text-right tabular-nums text-gray-600 dark:text-gray-300">
{{ $entry['size'] ? number_format($entry['size'] / 1024, 1).' KB' : '—' }}
</td>
<td class="whitespace-nowrap px-4 py-3 text-gray-600 dark:text-gray-300">{{ $entry['cached_at'] ?: '—' }}</td>
<td class="whitespace-nowrap px-4 py-3 text-gray-600 dark:text-gray-300">{{ $entry['expires_at'] ?: '—' }}</td>
<td class="whitespace-nowrap px-4 py-3 text-right">
<x-filament::icon-button
icon="heroicon-m-trash"
color="danger"
size="sm"
label="删除这条缓存"
wire:click="forgetEntry('{{ $entry['key'] }}')"
wire:confirm="删除这条缓存?"
/>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
<p class="mt-4 text-xs text-gray-500 dark:text-gray-400">
共 {{ count($this->entries) }} 条 · 合计 {{ number_format(collect($this->entries)->sum('size') / 1024 / 1024, 2) }} MB
· 只缓存未登录访客 GET 的 200 页面,评论提交等动态请求不缓存,浏览量统计不受影响。
</p>
@endif
</x-filament::section>
</x-filament-panels::page>