refactor: 外链中转拆为内置插件 neatstudio.link-tracker

- 插件承载全部逻辑:redirects 迁移(hasTable 兼容旧库)、Redirect 模型、UrlRedirector、/go 路由+控制器、Filament 外链中转资源
- 核心只留 hook 接入点:
  - tracked_url() 助手走 link.redirect 过滤器(评论正文/作者网址/友链模板统一调用)
  - 正文外链改写移到插件的 post.rendered 过滤器(优先级 20,晚于会员付费过滤)
- 停用插件:链接恢复直连、内容不受影响;后台「管理 → 外链中转」查看点击量/启停
- 测试更新为插件上下文(含无过滤器降级断言);97 通过
This commit is contained in:
ak
2026-08-13 02:05:32 +08:00
parent 8f1ff6e3f9
commit f1b9d1e1c3
20 changed files with 118 additions and 62 deletions
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
// 兼容已由核心迁移建过表的旧库
if (Schema::hasTable('redirects')) {
return;
}
Schema::create('redirects', function (Blueprint $table) {
$table->id();
$table->string('hash', 16)->unique();
$table->text('target_url');
$table->unsignedBigInteger('clicks')->default(0);
$table->string('status', 20)->default('active'); // active / disabled
$table->timestamp('last_clicked_at')->nullable();
$table->timestamps();
$table->index('target_url');
});
}
public function down(): void
{
Schema::dropIfExists('redirects');
}
};
@@ -0,0 +1,12 @@
{
"title": "外链中转",
"version": "1.0.0",
"description": "站外链接改写为 /go/{hash}:302 跳转 + 点击统计 + 可停用拦截 + 隐藏真实链接,为广告位预留",
"usage": "启用后自动生效:\n1. 正文外链、评论正文 URL、评论作者网址、友链统一改写为 /go/{hash}\n2. 点击 /go/{hash} 302 跳转并计数;后台「管理 → 外链中转」查看点击量/启停\n3. 停用插件后链接恢复直连(不影响正文显示)",
"author": "LaraLog",
"type": "core",
"provider": "Plugins\\Neatstudio\\LinkTracker\\ServiceProvider",
"filament_resources": [
"Plugins\\Neatstudio\\LinkTracker\\Filament\\Resources\\RedirectResource"
]
}
@@ -0,0 +1,8 @@
<?php
declare(strict_types=1);
use Illuminate\Support\Facades\Route;
use Plugins\Neatstudio\LinkTracker\Http\GoController;
Route::get('/go/{hash}', [GoController::class, 'show'])->name('go.show');
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace Plugins\Neatstudio\LinkTracker\Filament\Resources\Pages;
use Filament\Resources\Pages\ListRecords;
use Plugins\Neatstudio\LinkTracker\Filament\Resources\RedirectResource;
class ListRedirects extends ListRecords
{
protected static string $resource = RedirectResource::class;
}
@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
namespace Plugins\Neatstudio\LinkTracker\Filament\Resources;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Plugins\Neatstudio\LinkTracker\Filament\Resources\Pages\ListRedirects;
use Plugins\Neatstudio\LinkTracker\Models\Redirect;
class RedirectResource extends Resource
{
protected static \UnitEnum|string|null $navigationGroup = '管理';
protected static ?string $model = Redirect::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedArrowUturnRight;
protected static ?string $navigationLabel = '外链中转';
protected static ?string $pluralModelLabel = '外链中转';
public static function form(Schema $schema): Schema
{
return $schema;
}
public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('hash')
->label('短码')
->badge()
->color('gray'),
TextColumn::make('target_url')
->label('目标地址')
->limit(50)
->copyable()
->searchable(),
TextColumn::make('clicks')
->label('点击量')
->numeric()
->sortable(),
TextColumn::make('status')
->label('状态')
->badge()
->formatStateUsing(fn ($state) => $state === 'active' ? '启用' : '停用')
->color(fn ($state) => $state === 'active' ? 'success' : 'danger'),
TextColumn::make('last_clicked_at')
->label('最后点击')
->dateTime('Y-m-d H:i')
->placeholder('—')
->sortable(),
TextColumn::make('created_at')
->label('创建时间')
->dateTime('Y-m-d H:i')
->toggleable(isToggledHiddenByDefault: true),
])
->filters([
\Filament\Tables\Filters\SelectFilter::make('status')
->label('状态')
->options(['active' => '启用', 'disabled' => '停用']),
], \Filament\Tables\Enums\FiltersLayout::AboveContent)
->recordActions([
Action::make('toggle')
->label(fn (Redirect $record) => $record->isActive() ? '停用' : '启用')
->color(fn (Redirect $record) => $record->isActive() ? 'danger' : 'success')
->action(fn (Redirect $record) => $record->update(['status' => $record->isActive() ? 'disabled' : 'active'])),
DeleteAction::make(),
])
->recordUrl(null)
->recordAction(null)
->defaultSort('clicks', 'desc');
}
public static function getPages(): array
{
return [
'index' => ListRedirects::route('/'),
];
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Plugins\Neatstudio\LinkTracker\Http;
use Plugins\Neatstudio\LinkTracker\Models\Redirect;
class GoController
{
/**
* 外链中转跳转:计数 + 302。停用的链接返回 410(可作二次拦截)。
*/
public function show(string $hash)
{
$redirect = Redirect::query()->where('hash', $hash)->firstOrFail();
if (! $redirect->isActive()) {
abort(410);
}
$redirect->hit();
return redirect()->away($redirect->target_url, 302);
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Plugins\Neatstudio\LinkTracker\Models;
use Illuminate\Database\Eloquent\Model;
class Redirect extends Model
{
protected $fillable = [
'hash', 'target_url', 'clicks', 'status', 'last_clicked_at',
];
protected $casts = [
'last_clicked_at' => 'datetime',
];
public function isActive(): bool
{
return $this->status === 'active';
}
public function hit(): void
{
$this->increment('clicks');
$this->update(['last_clicked_at' => now()]);
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Plugins\Neatstudio\LinkTracker;
use App\Blog\Support\PluginManager;
use App\Blog\Support\PluginServiceProvider;
use Plugins\Neatstudio\LinkTracker\Services\UrlRedirector;
class ServiceProvider extends PluginServiceProvider
{
protected function boot(PluginManager $manager): void
{
$this->loadRoutes(__DIR__.'/../routes/web.php');
// 核心视图(评论正文/作者网址/友链)通过 tracked_url() 走此过滤器改写
$manager->addFilter('link.redirect', function (string $url) {
return app(UrlRedirector::class)->goUrl($url);
}, 10);
// 正文外链改写:优先级 20,晚于会员付费内容过滤(10),保证 paywall 也覆盖
$manager->addFilter('post.rendered', function (string $html, \App\Models\Post $post) {
return app(UrlRedirector::class)->rewriteExternalLinks($html);
}, 20);
}
}
@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
namespace Plugins\Neatstudio\LinkTracker\Services;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\Cache;
use Plugins\Neatstudio\LinkTracker\Models\Redirect;
/**
* 外链中转:把站外链接改写为 /go/{hash},用于点击统计、二次拦截与未来广告位。
* 站内链接、相对路径、mailto/tel/锚点不中转。
*/
class UrlRedirector
{
public function goUrl(string $url): string
{
$url = trim((string) $url);
if (! $this->isExternal($url)) {
return $url;
}
return route('go.show', $this->hashFor($url));
}
public function isExternal(string $url): bool
{
if (! preg_match('#^https?://#i', $url)) {
return false;
}
$host = parse_url($url, PHP_URL_HOST);
if (! $host) {
return false;
}
$internalHost = parse_url((string) config('app.url'), PHP_URL_HOST);
return strcasecmp($host, (string) $internalHost) !== 0;
}
/**
* URL 对应的短 hash(确定性:同一 URL 复用同一条记录,并发安全)。
*/
public function hashFor(string $url): string
{
return Cache::remember('go.hash.'.md5($url), now()->addDay(), function () use ($url) {
$hash = substr(hash('sha256', $url), 0, 10);
for ($i = 0; $i < 3; $i++) {
try {
Redirect::create(['hash' => $hash, 'target_url' => $url]);
return $hash;
} catch (UniqueConstraintViolationException) {
$existing = Redirect::where('target_url', $url)->first();
if ($existing) {
return $existing->hash;
}
$hash = substr(hash('sha256', $url.$i), 0, 10);
}
}
return $hash;
});
}
/**
* HTML 里的站外 <a href> 改写为 /go 中转地址(站内/相对/锚点/mailto 不变)。
*/
public function rewriteExternalLinks(string $html): string
{
return preg_replace_callback(
'/<a\s+([^>]*?href=["\'])([^"\']+)(["\'][^>]*)>(.*?)<\/a>/is',
function (array $m): string {
$url = html_entity_decode(trim($m[2]));
$go = $this->goUrl($url);
if ($go === $url) {
return $m[0];
}
return '<a '.$m[1].e($go).$m[3].'>'.$m[4].'</a>';
},
$html
);
}
}