Compare commits

..
340 changed files with 554 additions and 15585 deletions

No files matched your search

-3
View File
@@ -63,6 +63,3 @@ AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"
# Approved illustration delivery (independent per environment)
ILLUSTRATION_DELIVERY_ENABLED=false
-1
View File
@@ -23,4 +23,3 @@ Thumbs.db
!/_env/*
./vite.config.js
/node_modules
/public/images/illustrations
+2 -57
View File
@@ -1,60 +1,5 @@
# FNA_V3 项目维护入口
# fnb 项目维护入口
项目工作先读 GemDocs AI版项目总览、维护协议及 `/Users/hellcat/Documents/GemDocs/AI版/10-项目/fna_v3.md`。线上事务优先经白色机 SSH;网页与订阅 HTTP 访问须符合 GemDocs 的反代规则。
项目工作先读 GemDocs AI版项目总览、维护协议及 `/Users/hellcat/Documents/GemDocs/AI版/10-项目/fnb.md`。线上事务优先经白色机 SSH;网页与订阅 HTTP 访问须符合 GemDocs 的反代规则。
订阅检测已独立为 SubCheck,入口见 [SubCheck](/Users/hellcat/Documents/GemCodes/subcheck/AGENTS.md);cfn来源适配与调查见 [CFN.md](/Users/hellcat/Documents/GemCodes/subcheck/docs/CFN.md)。fnb不再保存检测实现。代码、凭据、业务数据及并行修改按当前任务授权处理。
## FNA_V3 本地副本维护
CFN页头SVG猫和两行品牌文字的维护与回退见[品牌标志](docs/maintenance/BRANDING.md),已于2026-10-31发布,见[界面发布记录](docs/maintenance/UI_RELEASE_2026-10-31.md)。
本目录为独立 FNA_V3 副本,身份与环境以 GemDocs AI版 `10-项目/fna_v3.md` 为准;上述 FN_B 入口保留来源背景,不代表授权修改 FN_B。文章广告实现、配置与验收见 [广告维护说明](docs/maintenance/ADVERTISING.md)。统一机场推荐数据、正文替换和教程末尾展示见[机场推荐维护](docs/maintenance/AIRPORT_RECOMMENDATIONS.md),已于2026-10-31发布,见[界面发布记录](docs/maintenance/UI_RELEASE_2026-10-31.md)。免费节点详情页的只读结构化渲染、订阅保护与回退见[内容页重设计](docs/maintenance/FREENODE_ARTICLE_LAYOUT.md)。
SEO 的只读审计、优化顺序与逐项验收统一维护在 [SEO 优化建议与执行清单](docs/maintenance/SEO_PLAN.md),2026-10-22 建立。清单中的建议不代表已实施,后续按用户指定项目推进并更新本文件所链接的唯一正文。
## CFN系绘图接手
2026-10-23用户明确将此前由张天承担的绘图工作交给“画师【CFN系】”(personnel-position:cd029d9db8454ec68172b221ff35e6f6)。FNA_V3主程继续开发工作,后续绘图由该画师岗位承接,避免重复制作。本记录仅转交绘图范围,不改变开发或上线权限;未向原聊天发送消息。
风格已从原聊天最近作品及本地成图核实:现代主义剪纸拼贴、哑光色块、轻微丝网印刷颗粒、成熟动物比例、非对称构图和大块留白。参考文件在本项目output/imagegen/:freenode-dog-dalmatian-20261023.png、freenode-dog-dachshund-20261023.png、freenode-dogs-dance-20261023.png;同名txt保存完整提示词。延续视觉语言,每张更换主题或构图,不照搬布局。
接手首张试画及提示词:/Users/hellcat/Documents/Codex/2026-10-23/cfn/outputs/cfn-tuxedo-cat-20261023.png 和同名txt。用户已认可风格并继续扩充;2026-10-26按授权与后续猫狗作品一起归档到Resource V2,并接入本地FNA_V3,未发布到线上。归档和栏目配图的唯一维护入口见[本地插画资源与配图](docs/maintenance/ILLUSTRATIONS.md)。
教程栏目本地现为“新手教程”(/client,原入门教程)和“综合教程”(/advanced,原进阶教程)。栏目改名、首篇重写、DNS进阶文章及内容回退见[教程栏目维护](docs/maintenance/TUTORIALS.md)。原七篇旧教程均已处理:迁移文归进阶,其余按Android、iOS、Mac和Linux重写;另有Windows纯入门与DNS进阶文章。正文、图解和关联已本地验收,本地内容不代表线上发布。
## FNA 静态配图副本
2026-10-30起Resource保留原稿、图池和固定分配,FNA保存按内容去重的公开展示副本,由本站Nginx直接提供。同步、创建时校验、撤回、缓存与部署验收唯一正文见[静态配图副本](docs/maintenance/LOCAL_ILLUSTRATIONS.md)。用户访问图片不调用Resource、不执行PHP修复。2026-10-31明确源端删除/停用不影响FNA独立副本或已有文章关联,修复与恢复原图记录见[独立副本保留修复](docs/maintenance/INDEPENDENT_ILLUSTRATIONS_FIX_2026-10-31.md)。
2026-11-01本地新增八篇新手教程、置顶指引并将原七篇平台文章移入综合教程;免费节点页已接入指引。每篇新文独立设计主题封面并加网址水印。范围、回执与未上线边界见[新手教程调整](docs/maintenance/NEWCOMER_TUTORIALS_2026-11-01.md)。当前分类、文章与关系以写作索引为准,上述旧批次描述保留为历史。
## AI 文章写作(必读)
后续为 FNA_V3 选题、写作、重写、调整分类或撤下文章时,必须先读[AI写作与文章关联索引](docs/content/WRITING.md)。它是文章用途、稳定地址和正文关系的唯一登记入口。公开文章禁止出现“核对范围”“未实测”等内部核验/验收说明,具体禁止项与发布前检查按该写作规范执行;相关事实只留项目维护记录。写作时复用相关的下载、入门、进阶和排错内容,自然设置内链,并检查相关旧文是否需要补入口;完成后同步正文源、运行数据库和该索引,验收真实目标与锚点。未创建的文章不能编造链接,本地生效不能写成已上线;不自动开展全站重写或发布。
教程配图必须按[写作规范](docs/content/WRITING.md#教程双比例配图正式规则2026-11-01)交付3:2列表图和约2.4:1详情横幅:分别构图、统一纸艺质感、每篇不同场景、两图加网址水印;`cover`用于列表,`show_cover=false`,正文开头使用唯一`guide-figure tutorial-hero`。后续聊天及周期写作同样适用,发布前检查桌面和手机。
## 独立文章发布 API
用户已明确文章直接发布到 FNA_V3,不经过 ATOM。实现、调用契约、凭据边界及验收见[独立文章 API](docs/maintenance/EDITORIAL_API.md)。后续写稿使用本站草稿→签名预览→按hash发布→回执核对流程;相关旧文内链修改可同批提交。不要再用临时SQL脚本发布普通编辑文章。旧文首次接管必须显式指定原文章ID并保留URL;发布结果未知先查原请求UUID。代码已于2026-10-29随正式切换部署,生产临时编辑密钥在教程迁移后删除、接口默认关闭;后续按明确写作/发布任务临时启用并在完成后关闭,不扩大线上访问或发布范围。正式部署、备份、Git SHA及验收统一见[发布记录](docs/maintenance/RELEASE_PREFLIGHT_2026-10-28.md#正式切换2026-10-29)。
插画完成后按[自动交付](docs/maintenance/ILLUSTRATION_DELIVERY.md)提交批准批次;不要再手工上传发布/编辑图池或把保存草稿当作上线完成。
周期文章按[固定发布封装](docs/maintenance/EDITORIAL_RELEASE.md)执行:本机SSH必须经白色机到正式业务服务器,使用服务器进程内API,不临时开放公网接口。每周三篇、每天15:00检查、错过窗口回补及文章随机展示时间见[周期写作](docs/maintenance/WEEKLY_TUTORIALS.md);这一流程替代周期写作中的手动开关API步骤,不扩大其他实例或全站改版权限。
教程SEO、编辑API的IndexNow结果与重试、栏目sitemap的唯一维护说明见[教程SEO通知](docs/maintenance/EDITORIAL_INDEXNOW.md)。`sitemap: done`不代表搜索引擎已收到通知或已收录。
2026-11-01免费苹果ID详情页本地重设计:地区筛选、账号复制卡片、原始载荷保护、空记录与夜间模式见[苹果ID内容页维护](docs/maintenance/APPLE_ID_ARTICLE_LAYOUT.md)。仅本地,未部署;2026-11-02已补全82篇原始载荷复核,密码默认打码及显示/隐藏的维护和验收也见该文。
2026-11-01本地页头新增日间/夜间切换,默认跟随系统、手动选择持久化及窄屏验收见[主题切换维护](docs/maintenance/COLOR_SCHEME.md),未发布。
2026-11-02本地新增独立“看看资讯”栏目 `/news`,无文章、未发布;创建命令、分类备份及验收见[资讯栏目维护](docs/maintenance/NEWS.md)。
## SEO统一合同(2026-10-31)
首页、归档、教程、分页、索引、sitemap、内容更新时间和IndexNow统一按[SEO实施维护](docs/maintenance/SEO_IMPLEMENTATION_2026-10-31.md)。禁止恢复全query robots屏蔽、分页canonical第一页、按180天批量删正文、用点赞updated_at作为lastmod,或让源图删除影响本站独立副本。当前状态和未取得的搜索平台证据见该文档;实施不等于收录/排名已验证。
2026-10-31用户纠正:SEO只做内部优化,用户看到的布局、样式、可见标题/说明、图片呈现、导航和广告位置必须保持原界面;不因SEO增加说明块、分页条或改版。后续可见改动须用户另行明确要求。恢复基线与验证见[界面保留修复](docs/maintenance/SEO_UI_RESTORE_2026-10-31.md)。
2026-11-02用户授权全部待发布变更上线:暗色主题、苹果ID卡片与密码隐藏、新手教程与双比例图、七篇旧文归类、资讯栏目、点赞配置、品牌和最终HardNerd广告均已发布。当前正式范围、Git恢复点与服务器侧验收见[整批发布记录](docs/maintenance/FULL_RELEASE_2026-11-02.md),文章关系继续以写作索引为准;未做线上页面验收。
@@ -1,37 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Services\ShadowrocketNaming;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
final class AlignShadowrocketNaming extends Command
{
protected $signature = 'shadowrocket:align-naming {--apply}';
protected $description = 'Align resource category and article metadata without changing account payloads';
public function handle(): int
{
$count = DB::transaction(function () {
$category = DB::table('categories')->where('sSlug', 'shadowrocketids')->lockForUpdate()->sole();
$rows = DB::table('articles')->where('iCategoryId', $category->id)->lockForUpdate()->get(['id', 'sTitle', 'sTitleSub']);
$changes = $rows->filter(fn ($r) => ShadowrocketNaming::align($r->sTitle) !== $r->sTitle || ShadowrocketNaming::align($r->sTitleSub ?? '') !== ($r->sTitleSub ?? ''));
if (! $this->option('apply')) return $changes->count();
if ($changes->isEmpty() && $category->sName === '免费小火箭ID') return 0;
$directory = storage_path('app/private/category-backups');
if (! is_dir($directory)) mkdir($directory, 0700, true);
$backup = $directory.'/shadowrocket-naming-'.Str::uuid().'.json';
if (file_put_contents($backup, json_encode(['category' => $category, 'articles' => $rows], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)) === false) throw new \RuntimeException('Backup failed');
chmod($backup, 0600);
DB::table('categories')->where('id', $category->id)->update(['sName' => '免费小火箭ID', 'sDescription' => ShadowrocketNaming::align($category->sDescription ?? '')]);
foreach ($changes as $row) DB::table('articles')->where('id', $row->id)->update(['sTitle' => ShadowrocketNaming::align($row->sTitle), 'sTitleSub' => ShadowrocketNaming::align($row->sTitleSub ?? '')]);
return $changes->count();
});
if ($this->option('apply')) Cache::forget('global_nav_tree');
$this->info(json_encode(['apply' => (bool) $this->option('apply'), 'articles' => $count], JSON_UNESCAPED_UNICODE));
return self::SUCCESS;
}
}
@@ -1,52 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class BackfillEditorialLikes extends Command
{
protected $signature = 'article:backfill-editorial-likes {--apply : Apply missing settings; otherwise only list candidates}';
protected $description = '为已发布编辑文章补齐缺失点赞配置,保留已有参数和进度';
public function handle(): int
{
$ids = DB::table('editorial_documents')->whereNotNull('article_id')
->whereNotNull('published_revision')->orderBy('article_id')->pluck('article_id');
$result = [];
foreach ($ids as $id) {
$row = DB::transaction(function () use ($id) {
$a = DB::table('articles')->where('id', $id)->lockForUpdate()->first();
if (! $a || (int) $a->iStatus !== 1 || (int) $a->iYearLikeTarget !== 0
|| (int) $a->iYearLikeAdded !== 0 || $a->sYearLikeStartedAt !== null) {
return null;
}
$missingDefaults = (int) $a->i7like === 0 && (int) $a->i365like === 0;
$row = ['id' => $id, 'slug' => $a->sSlug, 'fill_defaults' => $missingDefaults,
'before' => ['seven_day' => (int) $a->i7like, 'yearly' => (int) $a->i365like],
'applied' => (bool) $this->option('apply')];
if ($this->option('apply')) {
$fields = ['iYearLikeTarget' => random_int(100, 500), 'sYearLikeStartedAt' => now()];
if ($missingDefaults) {
// Expired short-term campaigns are not restarted by changing article dates.
$fields['i7like'] = now()->lt(\Carbon\Carbon::parse($a->created_at)->addDays(7)) ? random_int(5, 35) : 0;
$fields['i365like'] = 50;
}
DB::table('articles')->where('id', $id)->update($fields);
$row['settings'] = $fields;
}
return $row;
}, 3);
if ($row) {
$result[] = $row;
}
}
$this->line(json_encode(['mode' => $this->option('apply') ? 'apply' : 'preview', 'count' => count($result),
'articles' => $result], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
return self::SUCCESS;
}
}
Regular → Executable
+13 -2
View File
@@ -25,9 +25,20 @@ public function handle(): void
private function article()
{
$this->info('正文按内容保留策略维护,不再按180天自动删除。');
}
$aCateId = Categories::whereIn("sSlug", ["freenode", "shadowrocketids"])->pluck("id")->toArray();
if (empty($aCateId)) {
$this->info("没有匹配的分类,跳过清理");
return;
}
$sDate = date('Y-m-d', strtotime('-180 days'));
$i = Articles::whereIn("iCategoryId", $aCateId)->whereDate("created_at", "<", $sDate)->delete();
$this->info("清理 {$i} 条数据");
}
private function articleLikes()
{
// 1. 确定 30 天前的时间点
-27
View File
@@ -1,27 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Services\Editorial\PublicationEffects;
use Illuminate\Console\Command;
final class EditorialReindex extends Command
{
protected $signature = 'editorial:reindex';
protected $description = 'Initialize the isolated FNA_V3 site search index';
public function handle(PublicationEffects $effects): int
{
try {
$result = $effects->index();
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE));
return $result['status'] === 'done' ? 0 : 1;
} catch (\Throwable) {
$this->error('Search index synchronization failed.');
return 1;
}
}
}
-40
View File
@@ -1,40 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Services\Editorial\ReleaseRunner;
use Illuminate\Console\Command;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
final class EditorialRelease extends Command
{
protected $signature = 'editorial:release';
protected $description = 'Run a resumable editorial API operation from JSON on stdin, on this application server';
public function handle(): int
{
try {
abort_unless(PHP_SAPI === 'cli', 403);
if (! app()->environment('testing')) {
abort_unless(app()->environment('production')
&& realpath(base_path()) === '/www/wwwroot/clashfreenode-new.com'
&& rtrim(config('editorial.base_url'), '/') === 'https://clashfreenode.com'
&& function_exists('posix_geteuid') && posix_getpwuid(posix_geteuid())['name'] === 'nginx', 403, 'Server binding mismatch');
}
$raw = stream_get_contents(STDIN, 48 * 1024 * 1024 + 1);
abort_unless(strlen($raw) <= 48 * 1024 * 1024, 413);
$input = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
abort_unless(is_array($input), 422);
$result = app(ReleaseRunner::class)->run($input);
$this->line(json_encode(['ok' => true, 'data' => $result], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
return ($result['phase'] ?? '') === 'published_pending' ? 2 : 0;
} catch (\Throwable $e) {
$status = $e instanceof HttpExceptionInterface ? $e->getStatusCode() : 500;
$this->line(json_encode(['ok' => false, 'status' => $status, 'error' => 'Release operation failed; use the same release_id to inspect or resume. No credential details are exposed.']));
return 1;
}
}
}
-61
View File
@@ -1,61 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
final class EditorialRequest extends Command
{
protected $signature = 'editorial:request {method} {path} {--payload=} {--image=}';
protected $description = 'Call this environment\'s editorial API without exposing the credential';
public function handle(): int
{
$path = $this->argument('path');
$method = strtoupper($this->argument('method'));
if (! preg_match('~\A[a-zA-Z0-9_/-]+\z~', $path) || str_contains($path, '..') || ! in_array($method, ['GET', 'POST'])) {
$this->error('Invalid API operation.');
return 1;
}
$file = config('editorial.credential_file');
$credential = is_file($file) ? json_decode(file_get_contents($file), true) : null;
if (! $credential || ($credential['environment'] ?? '') !== app()->environment() || ($credential['project'] ?? '') !== 'fna-v3'
|| ($credential['base_url'] ?? '') !== config('editorial.base_url')) {
$this->error('Credential binding mismatch.');
return 1;
}
$base = rtrim(config('editorial.base_url'), '/');
if (app()->environment('local') && ! in_array(parse_url($base, PHP_URL_HOST), ['fna-v3.loc', 'localhost', '127.0.0.1'])) {
$this->error('Local client refuses a nonlocal target.');
return 1;
}
try {
$request = Http::withOptions(['proxy' => '', 'allow_redirects' => false])->withToken($credential['fields']['api_key'])->acceptJson()->connectTimeout(3)->timeout(30);
if ($this->option('image')) {
$image = $this->option('image');
if (! is_file($image)) {
$this->error('Image not found.');
return 1;
}
$response = $request->attach('image', fopen($image, 'r'), basename($image))->post($base.'/api/editorial/v1/'.$path);
} else {
$payload = $this->option('payload') ? json_decode(file_get_contents($this->option('payload')), true, 512, JSON_THROW_ON_ERROR) : [];
$response = $request->send($method, $base.'/api/editorial/v1/'.$path, $method === 'GET' ? [] : ['json' => $payload]);
}
$data = $response->json();
$this->line(json_encode(['http_status' => $response->status(), 'data' => $data], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
return $response->successful() ? 0 : 1;
} catch (\Throwable) {
$this->error('Editorial request failed; credential and request headers were not displayed.');
return 1;
}
}
}
-46
View File
@@ -1,46 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
final class EditorialSetup extends Command
{
protected $signature = 'editorial:setup';
protected $description = 'Create a private credential for the local FNA_V3 editorial API';
public function handle(): int
{
$c = config('database.connections.mysql');
if (! app()->environment('local') || $c['database'] !== 'fna_v3' || ! in_array($c['host'], ['localhost', '127.0.0.1'])) {
$this->error('Local FNA_V3 only. Production credentials require separate provisioning.');
return 1;
}
$path = config('editorial.credential_file');
if (is_file($path)) {
$this->info('Credential already exists; not replaced.');
return 0;
}
if (! is_dir(dirname($path))) {
mkdir(dirname($path), 0700, true);
}
$data = ['project' => 'fna-v3', 'environment' => 'local', 'base_url' => config('editorial.base_url'), 'schema' => 'gemdocs.credential.v1', 'fields' => ['api_key' => 'fna_ed_'.bin2hex(random_bytes(32))]];
$old = umask(0077);
$file = fopen($path, 'x');
umask($old);
if (! $file) {
$this->error('Credential could not be created.');
return 1;
}
fwrite($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
fclose($file);
chmod($path, 0600);
$this->info('Local API credential created in private storage. Secret not displayed.');
return 0;
}
}
@@ -1,45 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/** Category and pin metadata only; article bodies/categories are published through the editorial API. */
final class OrganizeTutorials extends Command
{
protected $signature = 'tutorials:organize {--apply : Save the category name and pin the published guide}';
protected $description = 'Rename the beginner category and pin its verified guide, with a private metadata backup';
public function handle(): int
{
$category = DB::table('categories')->where('sSlug', config('tutorials.beginner_slug'))->where('iStatus', 1)->first();
$guide = DB::table('articles')->where('sSlug', config('tutorials.guide_slug'))->where('iStatus', 1)->first();
if (! $category || ! $guide || $guide->iCategoryId !== $category->id) {
$this->error('Publish the guide in the beginner category before applying metadata.');
return self::FAILURE;
}
$this->line(json_encode(['category' => $category->sSlug, 'name' => config('tutorials.beginner_name'), 'guide' => $guide->sSlug, 'pinned' => true], JSON_UNESCAPED_UNICODE));
if (! $this->option('apply')) return self::SUCCESS;
$backup = storage_path('app/private/editorial/tutorial-metadata-'.Str::uuid().'.json');
$snapshot = ['category_id' => $category->id, 'sName' => $category->sName, 'guide_id' => $guide->id, 'iIsTop' => $guide->iIsTop];
file_put_contents($backup, json_encode($snapshot, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
chmod($backup, 0600);
DB::transaction(function () use ($category, $guide) {
$currentCategory = DB::table('categories')->where('id', $category->id)->lockForUpdate()->first();
$currentGuide = DB::table('articles')->where('id', $guide->id)->lockForUpdate()->first();
if ($currentCategory->sName !== $category->sName || $currentGuide->iCategoryId !== $category->id || ! $currentGuide->iStatus) {
throw new \RuntimeException('Tutorial metadata changed; inspect before retrying.');
}
DB::table('categories')->where('id', $category->id)->update(['sName' => config('tutorials.beginner_name')]);
DB::table('articles')->where('id', $guide->id)->update(['iIsTop' => 1]);
});
Cache::forget('global_nav_tree');
\Spatie\ResponseCache\Facades\ResponseCache::clear();
$this->info('Category renamed and guide pinned. Private backup: '.$backup);
return self::SUCCESS;
}
}
@@ -1,40 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Services\Editorial\PublicationEffects;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
final class RetryEditorialIndexNow extends Command
{
protected $signature = 'editorial:indexnow-retry';
protected $description = 'Retry due editorial IndexNow notifications without republishing content';
public function handle(): int
{
if (! app()->environment(['production', 'testing']) || ! config('editorial.indexnow_enabled', app()->environment('production'))) {
$this->line('IndexNow retry disabled in this environment.');
return self::SUCCESS;
}
$ids = DB::table('editorial_publications')->where('effects->indexnow->status', 'pending')
->where(function ($q) {
$q->whereNull('effects->indexnow->next_attempt_at')
->orWhere('effects->indexnow->next_attempt_at', '<=', now()->timestamp);
})->orderBy('updated_at')->limit(10)->pluck('id');
$pending = 0;
foreach ($ids as $id) {
try {
$receipt = app(PublicationEffects::class)->synchronize($id);
$pending += ($receipt['effects']['indexnow']['status'] ?? '') === 'pending' ? 1 : 0;
} catch (\Throwable) {
$pending++;
}
}
$this->line(json_encode(['processed' => count($ids), 'pending' => $pending]));
return $pending ? self::FAILURE : self::SUCCESS;
}
}
@@ -1,13 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class RetrySeoNotifications extends Command
{
protected $signature = 'seo:indexnow-retry';
protected $description = 'Retry durable resource, collection and deletion notifications';
public function handle(): int
{
$this->line(json_encode(['processed'=>app(\App\Services\SeoNotifications::class)->retry()]));
return self::SUCCESS;
}
}
@@ -1,56 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
final class SetupNewsCategory extends Command
{
protected $signature = 'news:setup {--apply : Create the news category}';
protected $description = 'Create the 看看资讯 top-level category without changing existing content';
public function handle(): int
{
$existing = DB::table('categories')->where('sSlug', 'news')->orWhere('sName', '看看资讯')->get();
if ($existing->isNotEmpty()) {
if ($existing->count() !== 1 || $existing[0]->sSlug !== 'news'
|| $existing[0]->sName !== '看看资讯' || (int) $existing[0]->iParentId !== 0 || (int) $existing[0]->iStatus !== 1) {
$this->error('Conflicting news category; inspect before changing it.');
return self::FAILURE;
}
$this->info('看看资讯 already exists at /news (id '.$existing[0]->id.').');
return self::SUCCESS;
}
$this->line('Create 看看资讯 at /news, after existing top-level categories.');
if (! $this->option('apply')) return self::SUCCESS;
$directory = storage_path('app/private/category-backups');
if (! is_dir($directory)) mkdir($directory, 0700, true);
$backup = $directory.'/news-'.Str::uuid().'.json';
$before = DB::table('categories')->orderBy('id')->get();
if (file_put_contents($backup, json_encode($before, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) === false) {
throw new \RuntimeException('Category backup failed.');
}
chmod($backup, 0600);
$id = DB::transaction(function () {
$rows = DB::table('categories')->lockForUpdate()->get();
if ($rows->contains(fn ($row) => $row->sSlug === 'news' || $row->sName === '看看资讯')) {
throw new \RuntimeException('Category state changed; rerun after inspection.');
}
return DB::table('categories')->insertGetId([
'iParentId' => 0, 'sName' => '看看资讯', 'sSlug' => 'news',
'sDescription' => '最新资讯与动态。',
'iSort' => $rows->where('iParentId', 0)->max('iSort') + 1,
'iStatus' => 1, 'sHtmlClass' => 'fas fa-newspaper',
'iShowChildren' => 0, 'aBanner' => null, 'aOpt' => null,
]);
});
Cache::forget('global_nav_tree');
\Spatie\ResponseCache\Facades\ResponseCache::clear();
$this->info('Created 看看资讯 at /news (id '.$id.'). Backup: '.$backup);
return self::SUCCESS;
}
}
+2 -5
View File
@@ -6,15 +6,14 @@
use App\Models\Articles;
use Illuminate\Support\Facades\Cache;
use App\Services\CacheService;
use App\Services\OneYearArticleLikes;
class SyncArticleLikes extends Command
{
// 在 Kernel.php 中建议设置 ->everyFiveMinutes()
protected $signature = 'article:sync-likes';
protected $description = '文章点赞:短期额度、持续年度随机增长、一次性年度额度';
protected $description = '高标准点赞:7天自动碎化 + 全年天级随机';
public function handle(OneYearArticleLikes $oneYearLikes)
public function handle()
{
$iBurstCount = 0; // 记录本次执行爆发了多少文章
$iYearlyCount = 0; // 记录本次执行有多少文章中了全年奖
@@ -62,11 +61,9 @@ public function handle(OneYearArticleLikes $oneYearLikes)
Cache::put($sLockKey, 1, now()->addDay());
}
$oneYearAdded = $oneYearLikes->sync();
CacheService::updateOrderLikes();
$this->comment("本次任务结束:{$iBurstCount} 篇爆发增长,{$iYearlyCount} 篇全年喜提。");
$this->comment("一次性年度额度本次增加 {$oneYearAdded} 赞,额度用完后停止。");
}
/**
@@ -1,100 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Services\IllustrationPool;
use App\Services\LocalIllustrations;
use Illuminate\Console\Command;
final class SyncIllustrationDeliveries extends Command
{
protected $signature = 'illustrations:sync-deliveries';
protected $description = 'Synchronize pending illustration deliveries and acknowledge verified static copies';
public function handle(): int
{
if (! config('illustrations.delivery_enabled') || ! IllustrationPool::enabled() || ! LocalIllustrations::enabled()) {
$this->error('Illustration delivery is disabled');
return self::FAILURE;
}
$dir = dirname(config('illustrations.local_manifest'));
if (! is_dir($dir)) {
mkdir($dir, 0700, true);
}
$lock = fopen($dir.'/delivery.lock', 'c');
if (! $lock) {
return self::FAILURE;
}
if (! flock($lock, LOCK_EX | LOCK_NB)) {
fclose($lock);
return self::SUCCESS;
}
try {
$pending = array_slice(IllustrationPool::pendingDeliveries(), 0, 3); // Bound metadata calls below the consumer rate limit.
if (! $pending) {
$this->line('No pending illustration deliveries');
return self::SUCCESS;
}
$snapshots = [];
$images = [];
foreach ($pending as $batch) {
foreach ($batch['assets'] ?? [] as $asset) {
$pool = $asset['pool'] ?? '';
if (! in_array($pool, config('illustrations.categories'), true)) {
throw new \RuntimeException('invalid_pool');
}
if (! isset($snapshots[$pool])) {
$snapshots[$pool] = IllustrationPool::sourceSnapshot($pool);
}
$match = null;
foreach ($snapshots[$pool]['items'] as $image) {
if (($image['asset_id'] ?? '') === ($asset['asset_id'] ?? null)) {
$match = $image;
}
}
if (! $match) {
throw new \RuntimeException('delivery_asset_unavailable');
}
$images[$asset['asset_id']] = $match;
}
}
app(LocalIllustrations::class)->cacheDeliveryAssets(array_values($images));
$bytes = file_get_contents(config('illustrations.local_manifest'));
$manifest = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
foreach ($pending as $batch) {
if (($batch['state'] ?? '') !== 'awaiting_sync' || empty($batch['assets'])) {
throw new \RuntimeException('invalid_delivery');
}
foreach ($batch['assets'] as $asset) {
$local = $manifest['assets'][$asset['asset_id']] ?? null;
$sha = $asset['sha256'] ?? '';
if (! preg_match('/\A[a-f0-9]{64}\z/D', $sha) || ! $local || ($local['sha256'] ?? '') !== $sha || ($local['mime'] ?? '') !== 'image/webp') {
throw new \RuntimeException('missing_copy');
}
$path = rtrim(config('illustrations.local_directory'), '/').'/'.$sha.'.webp';
if (! is_file($path) || is_link($path) || hash_file('sha256', $path) !== $sha) {
throw new \RuntimeException('invalid_copy');
}
}
$ack = IllustrationPool::acknowledgeDelivery($batch['id'], ['fingerprint' => $batch['fingerprint'], 'manifest_sha256' => hash('sha256', $bytes)]);
if (($ack['state'] ?? '') !== 'completed') {
throw new \RuntimeException('ack_failed');
}
$this->line('Completed illustration delivery '.$batch['id']);
}
return self::SUCCESS;
} catch (\Throwable) {
$this->error('Illustration delivery sync incomplete; will retry without a completion ACK.');
return self::FAILURE;
} finally {
flock($lock, LOCK_UN);
fclose($lock);
}
}
}
@@ -1,53 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Models\Articles;
use App\Services\IllustrationPool;
use App\Services\LocalIllustrations;
use Illuminate\Console\Command;
use Spatie\ResponseCache\Facades\ResponseCache;
final class SyncLocalIllustrations extends Command
{
protected $signature = 'illustrations:sync-local {--assign-missing : Create missing Resource assignments for existing public articles}';
protected $description = 'Copy approved Resource images into deduplicated local static files and atomically reconcile article mappings';
public function handle(LocalIllustrations $local): int
{
if (! IllustrationPool::enabled()) {
$this->error('Resource binding is not enabled for this environment');
return self::FAILURE;
}
try {
$baseline = $local->selectionBaseline();
$snapshots = [];
$expected = [];
foreach (config('illustrations.categories') as $category => $pool) {
$keys = Articles::where('iCategoryId', $category)->where('iStatus', 1)->orderBy('created_at')->orderBy('id')->pluck('sSlug')->all();
IllustrationPool::forget($pool);
$snapshot = IllustrationPool::sourceSnapshot($pool);
$missing = array_values(array_diff($keys, array_keys($snapshot['selections']), array_keys($snapshot['unavailable'] ?? [])));
if ($missing && ! $this->option('assign-missing')) throw new \RuntimeException('Missing article assignments; rerun with --assign-missing using a write-scoped consumer');
foreach (array_chunk($missing, 200) as $chunk) IllustrationPool::assignSource($pool, $chunk);
if ($missing) $snapshot = IllustrationPool::sourceSnapshot($pool);
$snapshots[$pool] = $snapshot;
$expected[$pool] = $keys;
}
$result = $local->synchronize($snapshots, $baseline);
foreach ($expected as $pool => $keys) {
foreach ($keys as $key) {
if (! $local->thumbnail($pool, $key)) $result['pending'][$pool.':'.$key] ??= 'local_copy_unavailable';
}
}
ResponseCache::clear();
\Illuminate\Support\Facades\Cache::forget('article_order_likes');
$this->line(json_encode($result, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
return $result['pending'] ? self::FAILURE : self::SUCCESS;
} catch (\Throwable) {
// Never print request/credential exceptions or leave partial manifest writes.
$this->error('Local illustration sync failed; existing manifest retained if publication did not complete. Retry after checking Resource and filesystem access.');
return self::FAILURE;
}
}
}
@@ -1,152 +0,0 @@
<?php
namespace App\Http\Controllers\Api\Editorial;
use App\Http\Controllers\Controller;
use App\Models\Articles;
use App\Models\Categories;
use App\Services\Editorial\ContentRenderer;
use App\Services\Editorial\PublicationEffects;
use App\Services\Editorial\Publisher;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;
final class EditorialController extends Controller
{
public function catalog()
{
return response()->json(['categories' => DB::table('categories')->where('iStatus', 1)->whereNotIn('sSlug', ['freenode', 'shadowrocketids'])->get(['id', 'sName', 'sSlug', 'iParentId']),
'articles' => DB::table('articles')->leftJoin('editorial_documents', 'articles.id', '=', 'editorial_documents.article_id')
->whereNotIn('iCategoryId', DB::table('categories')->whereIn('sSlug', ['freenode', 'shadowrocketids'])->pluck('id'))
->get(['articles.id', 'sTitle', 'sSlug', 'iCategoryId', 'iStatus', 'content_key', 'revision', 'published_revision'])]);
}
public function source(int $article)
{
$a = DB::table('articles')->where('id', $article)->first();
abort_unless($a, 404);
$category = DB::table('categories')->where('id', $a->iCategoryId)->first();
abort_unless($category && ! in_array($category->sSlug, ['freenode', 'shadowrocketids']), 422, 'Not an editorial article');
return response()->json(['article_id' => $a->id, 'title' => $a->sTitle, 'summary' => $a->sTitleSub,
'slug' => $a->sSlug, 'body_html' => $a->sContent, 'category_slug' => $category->sSlug,
'tag_ids' => DB::table('article_tag')->where('iArticleId', $a->id)->pluck('iTagId'),
'created_at' => $a->created_at, 'display_published_at' => $a->sDisplayPublishedAt,
'cover' => $a->sThumb, 'show_cover' => (bool) $a->bPageThumb,
'like_growth' => ['seven_day_remaining' => (int) $a->i7like, 'yearly' => (int) $a->i365like,
'one_year_target' => (int) $a->iYearLikeTarget, 'one_year_added' => (int) $a->iYearLikeAdded,
'one_year_started_at' => $a->sYearLikeStartedAt],
'management' => DB::table('editorial_documents')->where('article_id', $a->id)->first()]);
}
public function store(Request $r, Publisher $p)
{
return response()->json($p->draft($r->all()), 201);
}
public function draft(string $draft, Publisher $p)
{
return response()->json($p->getDraft($draft));
}
public function publish(Request $r, string $draft, Publisher $p)
{
return response()->json($p->publish($draft, $r->all()));
}
public function article(string $key, Publisher $p)
{
return response()->json($p->article($key));
}
public function rollback(Request $r, string $key, Publisher $p)
{
return response()->json($p->rollback($key, $r->all()), 201);
}
public function receipt(string $publication, Publisher $p)
{
return response()->json($p->receipt($publication));
}
public function synchronize(string $publication, PublicationEffects $e)
{
return response()->json($e->synchronize($publication));
}
public function version(string $key, int $revision)
{
$v = DB::table('editorial_versions')->where('content_key', $key)->where('revision', $revision)->first();
abort_unless($v, 404);
return response()->json(['content_key' => $key, 'revision' => $revision, 'content' => json_decode($v->snapshot, true)]);
}
public function upload(Request $r, ContentRenderer $renderer)
{
$r->validate(['image' => 'required|file|max:8192|mimetypes:image/png,image/jpeg,image/webp,image/gif']);
$file = $r->file('image');
$info = @getimagesize($file->getRealPath());
abort_unless($info && $info[0] <= 12000 && $info[1] <= 12000 && $info[0] * $info[1] <= 40000000, 422, 'Image dimensions invalid');
$mime = $info['mime'];
$ext = ['image/png' => 'png', 'image/jpeg' => 'jpg', 'image/webp' => 'webp', 'image/gif' => 'gif'][$mime] ?? null;
abort_unless($ext && $file->getMimeType() === $mime, 422, 'Invalid image encoding');
$sha = hash_file('sha256', $file->getRealPath());
$dest = $renderer->privateImage($sha);
if (! is_dir(dirname($dest))) {
mkdir(dirname($dest), 0700, true);
}
if (! is_file($dest)) {
$temp = $dest.'.'.bin2hex(random_bytes(8));
if (! copy($file->getRealPath(), $temp) || ! rename($temp, $dest)) {
throw new \RuntimeException('Image storage failed');
}
chmod($dest, 0600);
}
DB::table('editorial_assets')->insertOrIgnore(['sha256' => $sha, 'extension' => $ext, 'mime' => $mime, 'bytes' => filesize($dest), 'created_at' => now()]);
return response()->json(['sha256' => $sha, 'reference' => 'asset:'.$sha, 'mime' => $mime, 'width' => $info[0], 'height' => $info[1]], 201);
}
public function asset(string $sha, ContentRenderer $renderer)
{
abort_unless(config('editorial.enabled'), 503);
$a = DB::table('editorial_assets')->where('sha256', $sha)->first();
abort_unless($a && is_file($renderer->privateImage($sha)), 404);
return response()->file($renderer->privateImage($sha), ['Content-Type' => $a->mime, 'Cache-Control' => 'private, no-store', 'X-Robots-Tag' => 'noindex, nofollow', 'X-Content-Type-Options' => 'nosniff']);
}
public function preview(string $draft, string $key, Publisher $p)
{
abort_unless(config('editorial.enabled'), 503);
$record = DB::table('editorial_drafts')->where('id', $draft)->first();
abort_unless($record, 404);
$items = json_decode($record->items, true);
$item = collect($items)->firstWhere('content_key', $key);
abort_unless($item, 404);
$expires = now()->addMinutes(config('editorial.preview_minutes'));
$base = rtrim(config('editorial.base_url'), '/');
$html = preg_replace_callback('/asset:([a-f0-9]{64})/', fn ($m) => $base.URL::temporarySignedRoute('editorial.preview-asset', $expires, ['sha' => $m[1]], absolute: false), $item['html']);
// Forward links between articles in this batch stay within the private preview.
foreach ($items as $target) {
$preview = $base.URL::temporarySignedRoute('editorial.preview', $expires, ['draft' => $draft, 'key' => $target['content_key']], absolute: false);
$pattern = '~href="/a/'.preg_quote($target['slug'], '~').'\.html(#[^"]*)?"~';
$html = preg_replace_callback($pattern, fn ($m) => 'href="'.htmlspecialchars($preview, ENT_QUOTES).($m[1] ?? '').'"', $html);
}
$cover = $item['cover'];
if ($cover && preg_match('/\Aasset:([a-f0-9]{64})\z/', $cover, $m)) {
$cover = $base.URL::temporarySignedRoute('editorial.preview-asset', $expires, ['sha' => $m[1]], absolute: false);
}
$a = new Articles;
$a->forceFill(['id' => 0, 'sTitle' => $item['title'], 'sTitleSub' => $item['summary'], 'sSlug' => $item['slug'], 'sContent' => $html,
'created_at' => now(), 'sDisplayPublishedAt' => now()->subSeconds($item['display_offset_seconds'] ?? 0), 'iLikeCount' => 0, 'bPageThumb' => $item['show_cover'] ?? false, 'sThumb' => $cover]);
$category = Categories::where('sSlug', $item['category_slug'])->with('oParent')->firstOrFail();
$a->setRelation('oCategory', $category);
$a->setRelation('oTags', collect());
return response()->view('pages.articles.default.show', ['oArticle' => $a, 'bEditorialPreview' => true, 'editorialRevision' => $item['revision'], 'editorialDraftStatus' => $record->status])
->withHeaders(['Cache-Control' => 'private, no-store', 'X-Robots-Tag' => 'noindex, nofollow', 'Referrer-Policy' => 'no-referrer']);
}
}
+61 -89
View File
@@ -58,25 +58,17 @@ public function receive(Request $oRequest)
$aPutField = [
"iCategoryId" => $oCategory->id,
"iLikeCount" => $aOpt["iLikeCount"] ?? "skip",
"i7like" => $aOpt["i7like"] ?? "skip",
"i365like" => $aOpt["i365like"] ?? "skip",
"iIsTop" => $aOpt["iIsTop"] ?? "skip",
"sThumb" => $aOpt["sThumb"] ?? "skip",
];
$oArticle = Articles::where("sSlug", $sSlug)->first();
if ($oArticle && \Illuminate\Support\Facades\DB::table('editorial_documents')->where('article_id',$oArticle->id)->exists()) {
abort(409, 'This article is managed by the editorial API');
}
if (!$oArticle) {
$oArticle = new Articles();
$oArticle->sSlug = $sSlug;
$overrides = [];
foreach (['i7like' => 'seven_day', 'i365like' => 'yearly'] as $field => $key) {
if (isset($aOpt[$field]) && $aOpt[$field] !== 'skip') $overrides[$key] = $aOpt[$field];
}
foreach (app(\App\Services\ArticleLikeDefaults::class)->newArticleFields('legacy_other', $overrides) as $field => $value) {
$oArticle->{$field} = $value;
}
}
foreach ($aPutField as $k => $v) {
@@ -88,10 +80,6 @@ public function receive(Request $oRequest)
$oArticle->sContent = $sSchema;
$oArticle->sTitle = $sTitle;
$oArticle->sTitleSub = mb_substr(strip_tags($sSchema), 0, 150, 'utf-8');
if (\App\Services\IllustrationPool::enabled()) {
$pool = config('illustrations.categories.'.$oCategory->id);
if ($pool) $oArticle->sThumb = \App\Services\IllustrationPool::forArticle($pool, $sSlug);
}
$oArticle->save();
@@ -114,38 +102,32 @@ public function receiveShadowrocketids(Request $oRequest)
$sArticle = $aData["content"] ?? '';
$sTitle = $aData["title"] ?? '';
$sTitleSub = $aData["title_sub"] ?? '';
$sTitle = \App\Services\ShadowrocketNaming::align($sTitle);
$sTitleSub = \App\Services\ShadowrocketNaming::align($sTitleSub);
$aArticleTags = $aData["tags"] ?? [];
$sSlug = 'ssi'.date("Ymd");
// $sImgAuthor = "tg_xiuren_a";
$sSubKey = $_ENV['site_code_short'].'::ssi';
$i7like = $aData["7like"] ?? 0;
$oThumbNum = ArticleThumbNum::firstOrCreate(["author_code" => $sSubKey, "type" => "shadowrocketids"]);
$iThumbNum = $oThumbNum->num;
if (\App\Services\IllustrationPool::enabled()) {
$sThumbPath = \App\Services\IllustrationPool::forArticle('shadowrocketids', $sSlug);
$sThumbNumTrue = $iThumbNum + 1;
} else {
$sImagesApi = "https://".config("path.url_resource_base")."/api/images/get/url-by-subkey";
$aApiArg = [
"sSubKey" => $sSubKey,
"iNum" => $iThumbNum+1,
];
$sApiResult = HttpV2::make($sImagesApi, "post")->withToken()->setDataA($aApiArg)->send();
$aApiResult = json_decode($sApiResult, true);
if (!isset($aApiResult["isDone"]) || !$aApiResult["isDone"]) {
echo $sApiResult;
return response()->json($oFlow->fail("{$sObjName}的图片api调用失败"));
}
$sThumbPath = $aApiResult["aData"]["sFileUrl"];
$sThumbNumTrue = $aApiResult["aData"]["iTrueNum"];
$sImagesApi = "https://".config("path.url_resource_base")."/api/images/get/url-by-subkey";
$aApiArg = [
"sSubKey" => $sSubKey,
"iNum" => $iThumbNum+1,
];
$sApiResult = HttpV2::make($sImagesApi, "post")->withToken()->setDataA($aApiArg)->send();
$aApiResult = json_decode($sApiResult, true);
if (!isset($aApiResult["isDone"]) || !$aApiResult["isDone"]) {
echo $sApiResult;
return response()->json($oFlow->fail("{$sObjName}的图片api调用失败"));
}
$sThumbPath = $aApiResult["aData"]["sFileUrl"];
$sThumbNumTrue = $aApiResult["aData"]["iTrueNum"];
$oCategories = Categories::where("sSlug", "shadowrocketids")->first();
$oArticle = Articles::where('sSlug', $sSlug)->first();
@@ -162,8 +144,7 @@ public function receiveShadowrocketids(Request $oRequest)
// 只有新创建时才写入初始点赞数
if (!$oArticle) {
$overrides = isset($aData['7like']) ? ['seven_day' => $aData['7like']] : [];
$aAttributes += app(\App\Services\ArticleLikeDefaults::class)->newArticleFields('shadowrocketids', $overrides);
$aAttributes['i7like'] = $i7like;
}
$oArticle = Articles::updateOrCreate(
@@ -177,7 +158,8 @@ public function receiveShadowrocketids(Request $oRequest)
$sArticleUrl = config("app.url")."/a/".$sSlug;
$bIndexR = '待服务器队列处理';
$oIndexNow = new IndexNowService();
$bIndexR = $oIndexNow->pushUrls([$sArticleUrl.".html"]);
TeleSlave::notify()->send($sArticleUrl." 发布成功 | "."indexNow推送:".$bIndexR);
@@ -191,7 +173,6 @@ public function receiveFreenode(Request $oRequest)
$aData = $oRequest->all();
$aArticle = $aData["article"];
$resourceState = \App\Services\ResourcePublication::validate($aArticle);
$sArticleTitle = $aArticle["title"];
$sArticleTitleSub = $aArticle["title_sub"];
$sArticleContent = $aArticle["content"];
@@ -199,32 +180,28 @@ public function receiveFreenode(Request $oRequest)
$sSlug = 'fn'.date("Ymd");
// $sImgAuthor = "tg_xiuren_a";
$sSubKey = $_ENV['site_code_short'].'::fn';
$i7like = $aArticle["7like"];
$oThumbNum = ArticleFreenodeThumbNum::firstOrCreate(["author_code" => $sSubKey]);
$iThumbNum = $oThumbNum->num;
if (\App\Services\IllustrationPool::enabled()) {
$sThumbPath = \App\Services\IllustrationPool::forArticle('freenode', $sSlug);
$sThumbNumTrue = $iThumbNum + 1;
} else {
$sImagesApi = "https://".config("path.url_resource_base")."/api/images/get/url-by-subkey";
$aApiArg = [
"sSubKey" => $sSubKey,
"iNum" => $iThumbNum+1,
];
$sApiResult = HttpV2::make($sImagesApi, "post")->withToken()->setDataA($aApiArg)->send();
$aApiResult = json_decode($sApiResult, true);
if (!isset($aApiResult["isDone"]) || !$aApiResult["isDone"]) {
echo $sApiResult;
return response()->json($oFlow->fail("{$sObjName}的图片api调用失败"));
}
$sThumbPath = $aApiResult["aData"]["sFileUrl"];
$sThumbNumTrue = $aApiResult["aData"]["iTrueNum"];
$sImagesApi = "https://".config("path.url_resource_base")."/api/images/get/url-by-subkey";
$aApiArg = [
"sSubKey" => $sSubKey,
"iNum" => $iThumbNum+1,
];
$sApiResult = HttpV2::make($sImagesApi, "post")->withToken()->setDataA($aApiArg)->send();
$aApiResult = json_decode($sApiResult, true);
if (!isset($aApiResult["isDone"]) || !$aApiResult["isDone"]) {
echo $sApiResult;
return response()->json($oFlow->fail("{$sObjName}的图片api调用失败"));
}
$sThumbPath = $aApiResult["aData"]["sFileUrl"];
$sThumbNumTrue = $aApiResult["aData"]["iTrueNum"];
$oCategories = Categories::where("sSlug", "freenode")->first();
$oArticle = Articles::where('sSlug', $sSlug)->first();
@@ -241,13 +218,12 @@ public function receiveFreenode(Request $oRequest)
// 只有新创建时才写入初始点赞数
if (!$oArticle) {
$overrides = isset($aArticle['7like']) ? ['seven_day' => $aArticle['7like']] : [];
$aAttributes += app(\App\Services\ArticleLikeDefaults::class)->newArticleFields('freenode', $overrides);
$aAttributes['i7like'] = $i7like;
}
$oArticle = Articles::updateOrCreate(
['sSlug' => $sSlug],
$aAttributes + $resourceState
$aAttributes
);
(new TagService())->syncArticleTagsByName($oArticle, $aArticleTags);
@@ -256,9 +232,10 @@ public function receiveFreenode(Request $oRequest)
$sArticleUrl = config("app.url")."/a/".$sSlug;
$bIndexR = '待服务器队列处理';
$oIndexNow = new IndexNowService();
$bIndexR = $oIndexNow->pushUrls([$sArticleUrl.".html"]);
TeleSlave::notify()->send($sArticleUrl.".html"." 发布成功 | "."indexNow推送:".$bIndexR); // indexR是true或false,发送到tg什么都没有?
TeleSlave::notify()->send($sArticleUrl." 发布成功 | "."indexNow推送:".$bIndexR); // indexR是true或false,发送到tg什么都没有?
return response()->json($oFlow->done());
}
@@ -276,33 +253,28 @@ public function receiveFreenode_laji(Request $oRequest)
$aArticleTags = $aArticle["tags"];
$sSlug = 'fn'.date("Ymd");
$sImgAuthor = "tg_xiuren_a";
$i7like = $aArticle["7like"] ?? 0;
$i7like = $aArticle["7like"];
$oThumbNum = ArticleFreenodeThumbNum::firstOrCreate(["author_code" => $sImgAuthor]);
$iThumbNum = $oThumbNum->num;
if (\App\Services\IllustrationPool::enabled()) {
$sThumbPath = \App\Services\IllustrationPool::forArticle('freenode', $sSlug);
$sThumbNumTrue = $iThumbNum + 1;
} else {
$sImagesApi = "https://".config("path.url_resource_base")."/api/images/get/url-by-num";
$aApiArg = [
"sAuthorCode" => $sImgAuthor,
"iNum" => $iThumbNum+1,
];
$sApiResult = HttpV2::make($sImagesApi, "post")->withToken()->setDataA($aApiArg)->send();
$aApiResult = json_decode($sApiResult, true);
if (!isset($aApiResult["isDone"]) || !$aApiResult["isDone"]) {
echo $sApiResult;
return response()->json($oFlow->fail("{$sObjName}的图片api调用失败"));
}
$sThumbPath = $aApiResult["aData"]["sFileUrl"];
$sThumbNumTrue = $aApiResult["aData"]["iTrueNum"];
$sImagesApi = "https://".config("path.url_resource_base")."/api/images/get/url-by-num";
$aApiArg = [
"sAuthorCode" => $sImgAuthor,
"iNum" => $iThumbNum+1,
];
$sApiResult = HttpV2::make($sImagesApi, "post")->withToken()->setDataA($aApiArg)->send();
$aApiResult = json_decode($sApiResult, true);
if (!isset($aApiResult["isDone"]) || !$aApiResult["isDone"]) {
echo $sApiResult;
return response()->json($oFlow->fail("{$sObjName}的图片api调用失败"));
}
$sThumbPath = $aApiResult["aData"]["sFileUrl"];
$sThumbNumTrue = $aApiResult["aData"]["iTrueNum"];
$oCategories = Categories::where("sSlug", "freenode")->first();
$oArticle = Articles::updateOrCreate(
+2 -2
View File
@@ -12,10 +12,10 @@ public function index(): Response
$sContent .= "Allow: /\n";
$sContent .= "Disallow: /admin/\n";
$sContent .= "Disallow: /api/\n";
$sContent .= "\n";
$sContent .= "Disallow: /storage/\n";
$sContent .= "Disallow: /vendor/\n";
$sContent .= "Disallow: /test/\n";
$sContent .= "Disallow: /like/\n\n";
$sContent .= "Disallow: /*?*\n\n";
$sContent .= "Sitemap: " . config('app.url') . "/sitemap.xml\n";
// 核心修复:强制指定 text/plain 响应头
+23 -14
View File
@@ -1,24 +1,33 @@
<?php
namespace App\Http\Controllers;
use App\Models\Articles;
use App\Models\Categories;
use App\Services\Seo;
use App\Services\ArticlesService;
use Illuminate\Http\Response;
class SitemapController extends Controller
{
public function index(): Response
{
$articles = Articles::publicVisible()->with('oCategory.oParent')->orderByDesc('created_at')->orderByDesc('id')->get();
$latest = app(ArticlesService::class)->getLatestFreeNodeSlug();
$home = $latest ? $articles->firstWhere('sSlug',$latest) : null;
$entries = $home ? [['url'=>Seo::url(),'modified'=>Seo::modified($home)]] : [];
foreach (Categories::where('iStatus',1)->with('oParent')->orderBy('id')->get() as $category) {
if ($category->iParentId && (!$category->oParent || !$category->oParent->iStatus)) continue;
$members = $articles->filter(fn($a)=>$a->iCategoryId === $category->id || ($category->iShowChildren && $a->oCategory->iParentId === $category->id));
if ($members->isNotEmpty()) $entries[] = ['url'=>Seo::url(Seo::categoryPath($category)),'modified'=>null];
}
foreach ($articles->filter(fn($a)=>Seo::indexable($a)) as $a) $entries[] = ['url'=>Seo::articleUrl($a),'modified'=>Seo::modified($a)];
return response()->view('sitemap',['entries'=>$entries])->header('Content-Type','application/xml; charset=UTF-8');
// 连表查询分类:按 aOpt['noindexday'] 动态过滤过期文章
$cArticles = Articles::where('iStatus', 1)
->whereHas('oCategory', function ($q) {
$q->where(function ($query) {
// 1. 没有配置 noindexday,或者 noindexday = 0 的文章,一直保留
$query->whereNull('aOpt')
->orWhereRaw("JSON_UNQUOTE(JSON_EXTRACT(aOpt, '$.noindexday')) IS NULL")
->orWhereRaw("JSON_UNQUOTE(JSON_EXTRACT(aOpt, '$.noindexday')) = '0'")
// 2. 配置了天数的,只取 N 天内创建的新文章
->orWhereRaw("articles.created_at >= NOW() - INTERVAL CAST(JSON_UNQUOTE(JSON_EXTRACT(aOpt, '$.noindexday')) AS UNSIGNED) DAY");
});
})
->orderBy('created_at', 'desc')
->get();
$sXmlContent = view('sitemap', [
'cArticles' => $cArticles
])->render();
return response($sXmlContent, 200)->header('Content-Type', 'text/xml');
}
}
+26 -50
View File
@@ -19,12 +19,10 @@ public function __construct(ArticlesService $oService)
public function search(Request $oRequest, string $sKeyword)
{
$page = \App\Services\Seo::page($oRequest);
$data = $this->oArticlesService->search($sKeyword, 'view');
$data['seo'] = \App\Services\Seo::listMeta('搜索:'.$data['sKeywords'], '本站文章搜索结果', '/search/'.rawurlencode($data['sKeywords']), $page, false);
return $this->listing($oRequest, $data);
$xData = $this->oArticlesService->search($sKeyword, 'view');
return view('pages.articles.default.index', $xData);
}
public function like(int $iArticleId, Request $oRequest)
{
// 1. 获取/生成指纹
@@ -45,55 +43,33 @@ public function like(int $iArticleId, Request $oRequest)
public function listByTag(Request $oRequest, string $sSlug)
{
$page = \App\Services\Seo::page($oRequest);
$data = $this->oArticlesService->getTagArticles($sSlug, 'view');
$data['seo'] = \App\Services\Seo::listMeta($data['oTag']->sName.'相关文章', '按标签浏览本站内容', '/tag/'.$sSlug, $page, false);
return $this->listing($oRequest, $data);
$xData = $this->oArticlesService->getTagArticles($sSlug, 'view');
return view('pages.articles.default.index', $xData);
}
public function home(Request $oRequest)
public function list(Request $oRequest, string $sSlug1, string $sSlug2 = null)
{
if ($oRequest->filled('s')) {
abort_unless(is_string($oRequest->query('s')),404);
return redirect(\App\Services\Seo::url('/search/'.rawurlencode(trim($oRequest->query('s')))),301);
}
$page = \App\Services\Seo::page($oRequest);
if ($oRequest->has('page')) return redirect(\App\Services\Seo::url($page>1?'/freenode':'/', $page),301);
$slug = $this->oArticlesService->getLatestFreeNodeSlug();
if (!$slug) return response()->view('pages.articles.default.unavailable', [], 503)->header('Retry-After','3600');
$data = $this->articleData($slug, $oRequest);
$data['bIsHome'] = true;
$data['seo'] = \App\Services\Seo::articleMeta($data['oArticle'], true);
return view('pages.articles.default.show', $data);
}
public function list(Request $oRequest, string $sSlug1, ?string $sSlug2 = null)
{
$page = \App\Services\Seo::page($oRequest);
$data = $this->oArticlesService->getCategoryArticles($sSlug2 ?? $sSlug1, 'view');
$category = $data['oCategory'];
$path = \App\Services\Seo::categoryPath($category);
if ($sSlug2) abort_unless($path === '/'.$sSlug1.'/'.$sSlug2, 404);
$heading = $category->sSlug === 'freenode' ? '免费节点更新记录' : \App\Services\Seo::categoryName($category);
$desc = $category->sSlug === 'freenode' ? '按发布时间查看免费节点历史记录;获取当前订阅请访问首页。' : ($category->sDescription ?: $heading.'相关文章与使用说明');
$data['seo'] = \App\Services\Seo::listMeta($heading, $desc, $path, $page, $data['oArticles']->total()>0);
if ('/'.$sSlug1 !== $path && !$sSlug2) return redirect(\App\Services\Seo::url($path,$page),301);
return $this->listing($oRequest, $data);
}
private function listing(Request $request, array $data)
{
$page = \App\Services\Seo::page($request);
abort_if($page > $data['oArticles']->lastPage(),404);
if ($request->has('page') && $page === 1) return redirect($data['seo']['canonical'],301);
$data['oArticles']->withPath(strtok($data['seo']['canonical'],'?'));
return view('pages.articles.default.index', $data);
}
private function articleData(string $slug, Request $request): array
{
return $this->oArticlesService->getArticle($slug, $request->ip(), $request->cookie('visitor_token') ?? md5($request->ip().$request->userAgent()));
$sSlug = $sSlug2 ?? $sSlug1;
$xData = $this->oArticlesService->getCategoryArticles($sSlug, 'view');
return view('pages.articles.default.index', $xData);
}
public function show(string $sArticleSlug, Request $oRequest)
{
$data = $this->articleData($sArticleSlug,$oRequest);
$data['seo'] = \App\Services\Seo::articleMeta($data['oArticle']);
return view('pages.articles.default.show',$data);
$sFingerprint = $oRequest->cookie('visitor_token')
?? md5($oRequest->ip() . $oRequest->userAgent());
$xData = $this->oArticlesService->getArticle($sArticleSlug, $oRequest->ip(), $sFingerprint);
// $xData["siteUrl"] = config("app.url");
$sViewPath = 'pages.articles.default.show';
//
// if ($xData["oArticle"]->oCategory->sSlug == "freenode") {
// $sViewPath = 'pages.articles.freenode.show';
// }
return view($sViewPath, $xData);
}
}
@@ -1,45 +0,0 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
final class EditorialAuthentication
{
public function handle(Request $request, Closure $next)
{
abort_unless(config('editorial.enabled'), 503, 'Editorial API disabled');
if (app()->environment('local')) {
$db = config('database.connections.'.config('database.default'));
abort_unless(($db['database'] ?? '') === 'fna_v3' && in_array($db['host'] ?? '', ['localhost', '127.0.0.1']) && empty($db['url']), 503, 'Local editorial database binding mismatch');
}
$path = config('editorial.credential_file');
$process = PHP_SAPI === 'cli' ? config('editorial.process_credential') : null;
$credential = $process ?? (is_file($path) ? json_decode(file_get_contents($path), true) : null);
abort_if($process && (! is_int($process['expires_at'] ?? null) || $process['expires_at'] <= time()), 401, 'Process session expired');
abort_unless(is_array($credential)
&& ($credential['environment'] ?? null) === app()->environment()
&& ($credential['project'] ?? null) === 'fna-v3'
&& ($credential['schema'] ?? null) === 'gemdocs.credential.v1'
&& ($credential['base_url'] ?? null) === config('editorial.base_url')
&& preg_match('/\Afna_ed_[a-f0-9]{64}\z/', $credential['fields']['api_key'] ?? ''), 503, 'Editorial credential unavailable');
abort_unless(hash_equals($credential['fields']['api_key'], $request->bearerToken() ?? ''), 401, 'Invalid editorial credential');
try {
$response = $next($request);
} catch (\Illuminate\Database\QueryException $e) {
return response()->json(['message' => 'Concurrent or incompatible database write; query current status before retry'], 409);
} catch (\Throwable $e) {
if ($e instanceof \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface || $e instanceof \Illuminate\Validation\ValidationException) {
throw $e;
}
\Illuminate\Support\Facades\Log::error('Editorial operation failed', ['exception_type' => get_class($e)]);
return response()->json(['message' => 'Editorial operation failed; query the request ID before retrying'], 500);
}
$response->headers->set('Cache-Control', 'private, no-store');
$response->headers->set('X-Robots-Tag', 'noindex, nofollow');
return $response;
}
}
-13
View File
@@ -1,13 +0,0 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
final class SeoHeaders
{
public function handle(Request $request, Closure $next)
{
$response = $next($request);
if ($response->getStatusCode() >= 400 || $request->is('api/*','like/*','up','test/*')) $response->headers->set('X-Robots-Tag','noindex, nofollow');
return $response;
}
}
Regular → Executable
+24 -40
View File
@@ -14,22 +14,6 @@
class Articles extends Model
{
protected $guarded = [];
public function getSThumbAttribute($value)
{
return \App\Services\IllustrationPool::thumbnail($this->attributes, $value);
}
public function attributesToArray(): array
{
$attributes = parent::attributesToArray();
// Laravel's snake-case mutator discovery misses the legacy camelCase column.
if (array_key_exists('sThumb', $attributes)) {
$attributes['sThumb'] = $this->getAttribute('sThumb');
}
return $attributes;
}
protected $appends = ['s_created_at_diff'];
use Searchable;
@@ -38,7 +22,7 @@ protected function sCreatedAtDiff(): Attribute
{
return Attribute::get(function () {
// 1. 别直接用 $this->created_at,防止它还没被实例化成 Carbon 对象
$oDate = \Carbon\Carbon::parse($this->attributes['sDisplayPublishedAt'] ?? $this->created_at);
$oDate = \Carbon\Carbon::parse($this->created_at);
$oNow = \Carbon\Carbon::now();
// 2. 计算小时差(强制转整数)
@@ -67,12 +51,12 @@ protected function sCreatedAtDiff(): Attribute
public function shouldBeSearchable(): bool
{
return \App\Services\Seo::public($this);
return (int)$this->iStatus === 1;
}
public function searchableAs(): string
{
return config('editorial.search_index') ?: 'articles';
return 'articles';
}
public function toSearchableArray(): array
@@ -97,34 +81,34 @@ public function toSearchableArray(): array
* 判断当前文章是否超过分类设置的 SEO 暴露天数
* @return bool
*/
public function bIsSeoExpired(): bool { return !\App\Services\Seo::indexable($this); }
public function scopePublicVisible($query)
public function bIsSeoExpired(): bool
{
return $query->where('articles.iStatus', 1)->where('articles.created_at', '<=', now())
->whereHas('oCategory', fn($c) => $c->where('iStatus', 1)->where(fn($p) => $p
->where('iParentId', 0)->orWhereHas('oParent', fn($parent) => $parent->where('iStatus', 1))));
}
$oCategory = $this->oCategory;
// 未关联分类,或分类下的 aOpt 没设置,默认不处理(不过期)
if (!$oCategory || empty($oCategory->aOpt) || !isset($oCategory->aOpt['noindexday'])) {
return false;
}
$iNoindexDay = (int) $oCategory->aOpt['noindexday'];
// 0 或负数代表不限制,一直暴露给搜索引擎
if ($iNoindexDay <= 0) {
return false;
}
// 判断文章创建时间是否早于 N 天前
$oCreateDate = \Carbon\Carbon::parse($this->created_at);
return $oCreateDate->lt(\Carbon\Carbon::now()->subDays($iNoindexDay));
}
protected static function booted()
{
static::saving(function ($article) {
// Historical test fixtures and migration tooling may use the pre-SEO schema.
if (!\Illuminate\Support\Facades\Schema::hasColumn('articles', 'sContentUpdatedAt')) return;
if (!$article->exists || $article->isDirty(['sTitle','sTitleSub','sContent','sThumb','iCategoryId','iStatus','bPageThumb'])) {
$article->sContentUpdatedAt = now();
}
if (!$article->exists && $article->oCategory?->sSlug === 'freenode') $article->sSeoPolicy = 'archive';
});
static::saved(function ($article) {
if ($article->wasRecentlyCreated || $article->wasChanged(['sTitle','sTitleSub','sContent','sThumb','iCategoryId','iStatus'])) {
app(\App\Services\SeoNotifications::class)->changed($article);
}
static::saved(function () {
ResponseCache::forget('/'); // 要改成具体文章
});
static::deleted(function ($article) {
app(\App\Services\SeoNotifications::class)->changed($article,true);
static::deleted(function () {
ResponseCache::forget('/'); // 要改成具体文章
});
}
+1 -1
View File
@@ -12,7 +12,7 @@ class AppServiceProvider extends ServiceProvider
*/
public function register(): void
{
$this->app->scoped(\App\Services\LocalIllustrations::class);
//
}
/**
+1 -3
View File
@@ -21,9 +21,7 @@ public function boot(): void
$aHotArticles = CacheService::updateOrderLikes();
}
$ids = collect($aHotArticles)->pluck('oArticle.id');
$visible = \App\Models\Articles::publicVisible()->whereIn('id',$ids)->pluck('id')->all();
$oView->with('oOrderLikes', array_values(array_filter($aHotArticles, fn($item)=>in_array($item['oArticle']['id'],$visible))));
$oView->with('oOrderLikes', $aHotArticles);
});
}
-79
View File
@@ -1,79 +0,0 @@
<?php
namespace App\Services;
use DOMDocument;
use DOMElement;
use DOMXPath;
/** Presentation-only adaptation: keep every original account/password pair intact. */
final class AppleIdArticleLayout
{
public static function prepare(string $html): ?array
{
if (!preg_match('/免费苹果(?:账号|ID)/u', $html)) return null;
$dom = new DOMDocument('1.0', 'UTF-8');
$before = libxml_use_internal_errors(true);
try {
$dom->loadHTML('<?xml encoding="UTF-8"><html><body><div id="aid-root">'.str_replace(ArticleRecommendations::SLOT, '', $html).'</div></body></html>', LIBXML_NONET);
$root = $dom->getElementById('aid-root');
if (!$root) return null;
$xpath = new DOMXPath($dom);
$copies = $xpath->query('.//*[@data-clipboard-text]', $root);
if (!$copies || $copies->length % 2) return null;
// Empty historical updates are valid, but plaintext account rows must not disappear.
if (!$copies->length && (preg_match('/账号[::]|密码[::]/u', $root->textContent)
|| !$xpath->query('.//*[self::h1 or self::h2 or self::h3 or self::h4 or self::h5 or self::h6][starts-with(normalize-space(.), "免费苹果")]', $root)->length)) return null;
$result = ['accounts' => [], 'regions' => [], 'warnings' => [], 'intro' => '', 'outro' => ''];
$containers = [];
for ($i = 0; $i < $copies->length; $i += 2) {
$account = $copies->item($i);
$password = $copies->item($i + 1);
$container = $account->parentNode;
while ($container && $container !== $root && $container->parentNode !== $root) $container = $container->parentNode;
// Unknown nesting, labels or additional copy controls retain the legacy rendering.
if (!$container instanceof DOMElement || $container->parentNode !== $root || $container->tagName !== 'p') return null;
$fields = $xpath->query('.//*[@data-clipboard-text]', $container);
if ($fields->length !== 2 || !$fields->item(0)->isSameNode($account) || !$fields->item(1)->isSameNode($password)) return null;
$text = self::text($container->textContent);
if (!preg_match('/^账号[::]\s*.+[,,]\s*密码[::]\s*.+[,,]\s*地区[::]\s*(.*?)[,,]\s*检测时间[::]\s*(.*?)\s*$/u', $text, $match)) return null;
$username = $account->getAttribute('data-clipboard-text');
$secret = $password->getAttribute('data-clipboard-text');
if ($username === '' || $secret === '') return null;
$region = trim($match[1]);
if ($region === '') $region = '未注明';
$result['accounts'][] = ['account' => $username, 'password' => $secret, 'region' => $region, 'checked_at' => trim($match[2])];
$result['regions'][$region] = ($result['regions'][$region] ?? 0) + 1;
$containers[] = $container;
}
$seenAccount = false;
foreach (iterator_to_array($root->childNodes) as $node) {
$isAccount = false;
foreach ($containers as $container) if ($node->isSameNode($container)) { $isAccount = true; break; }
if ($isAccount) { $seenAccount = true; continue; }
$text = self::text($node->textContent);
if ($text === '') continue;
if ($node instanceof DOMElement && preg_match('/^免费苹果(?:账号|ID)/u', $text) && preg_match('/^h[1-6]$/', $node->tagName)) continue;
if (str_contains($text, '必须从App Store登录') && str_contains($text, 'iCloud')) {
$warning = preg_replace('/^[\x{26A0}\x{FE0F}\s]+/u', '', $text);
if (!in_array($warning, $result['warnings'], true)) $result['warnings'][] = $warning;
continue;
}
$result[$seenAccount ? 'outro' : 'intro'] .= $dom->saveHTML($node);
}
return $result;
} catch (\Throwable) {
return null;
} finally {
libxml_clear_errors();
libxml_use_internal_errors($before);
}
}
private static function text(string $text): string
{
return trim(preg_replace('/\s+/u', ' ', $text));
}
}
-61
View File
@@ -1,61 +0,0 @@
<?php
namespace App\Services;
use InvalidArgumentException;
final class ArticleLikeDefaults
{
public function editorialCategory(string $slug): string
{
if ($slug === 'advanced') {
return 'comprehensive';
}
return in_array($slug, ['client', 'windows', 'andorid', 'ios', 'linux', 'mac'], true)
? 'beginner' : 'editorial_other';
}
/** @return array{seven_day:int, yearly:int, one_year:int} */
public function resolve(string $type, array $overrides = []): array
{
$limits = ['seven_day' => 1000000, 'yearly' => 365, 'one_year' => 1000000];
$settings = config('article_likes.'.$type);
if (! is_array($settings)) {
throw new InvalidArgumentException('Missing article like defaults: '.$type);
}
$result = [];
foreach ($limits as $key => $max) {
// Site settings are authoritative, including zero. Incoming values
// remain accepted for API compatibility but cannot change the policy.
$value = $settings[$key] ?? null;
if (is_array($value)) {
if (count($value) !== 2 || ! array_is_list($value) || ! is_int($value[0]) || ! is_int($value[1])
|| $value[0] < 0 || $value[1] > $max || $value[0] > $value[1]) {
throw new InvalidArgumentException('Invalid article like range: '.$type.'.'.$key);
}
$value = random_int($value[0], $value[1]);
}
// Legacy callers historically submit numeric strings.
if (is_string($value) && ctype_digit($value)) {
$value = (int) $value;
}
if (! is_int($value) || $value < 0 || $value > $max) {
throw new InvalidArgumentException('Invalid article like value: '.$type.'.'.$key);
}
$result[$key] = $value;
}
return $result;
}
public function newArticleFields(string $type, array $overrides = []): array
{
$values = $this->resolve($type, $overrides);
return ['i7like' => $values['seven_day'], 'i365like' => $values['yearly'],
'iYearLikeTarget' => $values['one_year'], 'iYearLikeAdded' => 0,
'sYearLikeStartedAt' => $values['one_year'] > 0 ? now() : null];
}
}
-66
View File
@@ -1,66 +0,0 @@
<?php
namespace App\Services;
use App\Models\Articles;
final class ArticleRecommendations
{
public const SLOT = '<!-- fna-airport-recommendations -->';
public static function providers(): array
{
if (! config('airport_recommendations.enabled')) return [];
$providers = array_filter(config('airport_recommendations.providers', []), fn ($p) =>
($p['enabled'] ?? false) && filter_var($p['url'] ?? '', FILTER_VALIDATE_URL)
&& in_array(parse_url($p['url'], PHP_URL_SCHEME), ['https', 'http'], true));
uasort($providers, fn ($a, $b) => ($a['order'] ?? 0) <=> ($b['order'] ?? 0));
return $providers;
}
/** Presentation only: article storage, API receipts and subscription bytes stay intact. */
public static function prepare(Articles $article): array
{
$html = $article->sContent ?? '';
$category = $article->oCategory;
$slug = $category?->sSlug;
$scope = in_array($slug, ['freenode', 'shadowrocketids', 'advanced', 'client'], true)
|| $category?->oParent?->sSlug === 'client';
$enabled = $scope && self::providers() !== [];
if (! $enabled) return ['body' => $html, 'enabled' => false, 'inline' => false];
$inline = false;
if (in_array($slug, ['freenode', 'shadowrocketids'], true)) {
// Match the known legacy heading and its own Fuyun link, bounded by the next heading.
if (preg_match('~(?:<p\b[^>]*>\s*)?<h[2-6]\b[^>]*>\s*机场推荐\s*[-—-::]*\s*福云\s*[::]?\s*</h[2-6]>~u', $html, $head, PREG_OFFSET_CAPTURE)) {
$start = $head[0][1];$from = $start + strlen($head[0][0]);
$tail = substr($html, $from);
if (preg_match('~<h[1-6]\b~i', $tail, $next, PREG_OFFSET_CAPTURE)) $tail = substr($tail, 0, $next[0][1]);
preg_match_all('~<a\b[^>]*>.*?</a>~si', $tail, $links, PREG_OFFSET_CAPTURE);
foreach ($links[0] as [$link, $offset]) {
$text = html_entity_decode(strip_tags($link), ENT_QUOTES | ENT_HTML5, 'UTF-8');
if (! str_contains($text, '机场官网') || ! str_contains($text, '福云')) continue;
$end = $from + $offset + strlen($link);
if (preg_match('~\A(?:\s|</(?:b|strong|p)>)*~i', substr($html, $end), $closing)) $end += strlen($closing[0]);
$html = substr($html, 0, $start).self::SLOT.substr($html, $end);
$inline = true;
break;
}
}
}
if ($slug === 'advanced') {
$anchor = '#'.config('airport_recommendations.anchor');
if (! str_contains($html, $anchor)) {
$jump = '<p class="airport-recommendation-jump">如果需要更稳定的线路,可以从文末的<a href="'.e($anchor).'">机场推荐</a>中选择。</p>';
$inserted = false;
$html = preg_replace_callback('~<p\b[^>]*>.*?</p>~si', function ($m) use (&$inserted, $jump) {
if ($inserted || ! preg_match('/免费节点|订阅|稳定|机场|线路/u', strip_tags($m[0]))) return $m[0];
$inserted = true;
return $m[0].$jump;
}, $html);
if (! $inserted) $html .= $jump;
}
}
return ['body' => $html, 'enabled' => true, 'inline' => $inline];
}
}
@@ -1,15 +0,0 @@
<?php
namespace App\Services;
use Illuminate\Http\Request;
use Spatie\ResponseCache\CacheProfiles\CacheAllSuccessfulGetRequests;
class ArticleResponseCacheProfile extends CacheAllSuccessfulGetRequests
{
public function enabled(Request $request): bool
{
// 首页跟随最新免费节点文章,不能沿用整页的七天缓存。
return false; // Public HTML contains session/like state and time-dependent visibility; static assets remain cacheable.
}
}
Regular → Executable
+129 -35
View File
@@ -143,46 +143,140 @@ public function like(int $iArticleId, string $sIp, string $sFingerprint): array
}
}
public function search(string $keywords, string $resultType = 'view')
public function search(string $sKeywords, string $sResultType)
{
$term = trim(strip_tags($keywords));
abort_if($term === '' || mb_strlen($term) > 100, 404);
// Live DB authorization avoids stale external-index documents and cross-site results.
$literal = '%'.str_replace(['!','%','_'], ['!!','!%','!_'], $term).'%';
$articles = Articles::publicVisible()->with('oCategory.oParent')
->where(fn($q) => $q->whereRaw("sTitle LIKE ? ESCAPE '!'", [$literal])->orWhereRaw("sContent LIKE ? ESCAPE '!'", [$literal]))
->orderByDesc('iIsTop')->orderByDesc('created_at')->orderByDesc('id')->paginate(config('seo.page_size'));
return ['oArticles'=>$articles, 'sKeywords'=>$term];
}
public function getTagArticles(string $slug, string $resultType = 'view')
{
$tag = Tags::where('sSlug', $slug)->firstOrFail();
return ['oTag'=>$tag, 'oArticles'=>$tag->oArticles()->publicVisible()->with('oCategory.oParent')
->orderByDesc('iIsTop')->orderByDesc('created_at')->orderByDesc('id')->paginate(config('seo.page_size'))];
}
public function getLatestFreeNodeSlug(): ?string
{
foreach (Articles::publicVisible()->whereHas('oCategory', fn($q)=>$q->where('sSlug','freenode'))
->orderByDesc('created_at')->orderByDesc('id')->cursor() as $article) {
if (ResourcePublication::usable($article)) return $article->sSlug;
if (empty($sKeywords)) {
return [];
}
return null;
$sKeywords = strip_tags(trim($sKeywords));
$oArticles = Articles::search($sKeywords)
->options([
'attributesToHighlight' => ['sTitle', 'sContent', 'sCategoryName'],
// 1. 把 attributesToSnippet 改成 attributesToCrop
'attributesToCrop' => ['sContent'],
// 2. 设置裁剪后的长度(单位是字符,按需调整)
'cropLength' => 100,
'highlightPreTag' => '<mark class="highlight">',
'highlightPostTag' => '</mark>',
])
->orderByDesc('iIsTop')
->paginate(config('app.page_limit'));
$oArticles->getCollection()->transform(function ($oArticle) {
$aMeta = $oArticle->scoutMetadata();
$aFormatted = $aMeta['_formatted'] ?? [];
if (!empty($aFormatted)) {
$oArticle->sTitle = $aFormatted['sTitle'] ?? $oArticle->sTitle;
$oArticle->sContent = $aFormatted['sContent'] ?? $oArticle->sContent;
if (isset($aFormatted['sCategoryName'])) {
$oArticle->sCategoryName = $aFormatted['sCategoryName'];
$oArticle->setRelation('oCategory', (object)[
'sName' => $aFormatted['sCategoryName'],
'sSlug' => $oArticle->sCategorySlug ?? ''
]);
}
}
return $oArticle;
});
if ($sResultType === "ajax") {
$sHtml = '';
foreach ($oArticles as $oArticle) {
$sHtml .= view('components.article-item', ['oArticle' => $oArticle])->render();
}
$xResult = $sHtml;
} else {
$xResult = [
'oArticles' => $oArticles,
];
}
return $xResult;
}
public function getCategoryArticles(string $slug, string $resultType = 'view')
public function getTagArticles(string $sSlug, string $sResultType)
{
$category = Categories::where('sSlug', $slug)->where('iStatus',1)->with('oParent')->firstOrFail();
abort_if($category->iParentId && (!$category->oParent || !$category->oParent->iStatus),404);
$ids = [$category->id];
if ($category->iShowChildren) $ids = array_merge($ids, Categories::where('iParentId',$category->id)->where('iStatus',1)->pluck('id')->all());
$articles = Articles::publicVisible()->whereIn('iCategoryId',$ids)->with('oCategory.oParent')
->orderByDesc('iIsTop')->orderByDesc('created_at')->orderByDesc('id')->paginate(config('seo.page_size'));
return ['oCategory'=>$category,'oArticles'=>$articles,'iArticleCount'=>$articles->total()];
$oTags = Tags::where('sSlug', $sSlug)->firstOrFail();
$oArticles = $oTags->oArticles()
->where('iStatus', 1) // 只拿已发布的
->with(['oCategory']) // 预加载关联,拒绝 N+1
->orderByDesc('iIsTop') // 置顶优先
->orderByDesc('created_at') // 最新优先
->paginate(config('app.page_limit')); // 必须分页,否则数据多了会爆内存
if ($sResultType === "ajax") {
$sHtml = '';
foreach ($oArticles as $oArticle) {
$sHtml .= view('components.article-item', ['oArticle' => $oArticle])->render();
}
$xResult = $sHtml;
} else {
$xResult = [
'oArticles' => $oArticles,
];
}
return $xResult;
}
public function getArticle(string $slug, string $ip, string $fingerprint)
public function getCategoryArticles(string $sSlug, string $sResultType)
{
$article = Articles::publicVisible()->where('sSlug',$slug)->with(['oCategory.oParent','oTags'])->firstOrFail();
$article->bIsLiked = ArticleLikes::where('iArticleId',$article->id)
->where(fn($q)=>$q->where('sIp',$ip)->orWhere('sFingerprint',$fingerprint))->exists();
return ['oArticle'=>$article];
$oCategory = Categories::where('sSlug', $sSlug)->firstOrFail();
if ($oCategory->iShowChildren) {
$aCategoryIds = Categories::where('iParentId', $oCategory->id)
->pluck('id')
->push($oCategory->id)
->toArray();
} else {
$aCategoryIds = [$oCategory->id];
}
$oArticles = Articles::whereIn('iCategoryId', $aCategoryIds)
->with(['oUser', 'oCategory'])
->orderBy('iIsTop', 'desc')
->orderBy('created_at', 'desc')
->simplePaginate(config('app.page_limit'));
if ($sResultType === "ajax") {
$sHtml = '';
foreach ($oArticles as $oArticle) {
$sHtml .= view('components.article-item', ['oArticle' => $oArticle])->render();
}
$aResult = $sHtml;
} else {
$aResult = [
'oCategory' => $oCategory,
'oArticles' => $oArticles,
];
}
return $aResult;
}
public function getArticle(string $sArticleSlug, string $sIp, string $sFingerprint)
{
$oArticle = Articles::where('sSlug', $sArticleSlug)
->where('iStatus', 1)
->with(['oCategory.oParent', 'oTags'])
->firstOrFail();
$oArticle->bIsLiked = ArticleLikes::where('iArticleId', $oArticle->id)
->where(function($q) use ($sIp, $sFingerprint) {
$q->where('sIp', $sIp)
->orWhere('sFingerprint', $sFingerprint);
})->exists();
// return $oArticle;
return [
'oArticle' => $oArticle
];
}
}
Regular → Executable
+1 -1
View File
@@ -68,7 +68,7 @@ class CacheService
public static function updateOrderLikes(): array
{
// 1. 基于 Articles 表按最后点赞时间倒序,涵盖真实赞与算法注入赞
$cArticles = Articles::publicVisible()
$cArticles = Articles::where('iStatus', 1)
->whereNotNull('sLastLikedAt')
->orderBy('sLastLikedAt', 'desc')
->limit(5)
-102
View File
@@ -1,102 +0,0 @@
<?php
namespace App\Services\Editorial;
use DOMDocument;
use Illuminate\Support\Facades\DB;
use League\CommonMark\GithubFlavoredMarkdownConverter;
final class ContentRenderer
{
public function render(array $item): string
{
$html = $item['format'] === 'html' ? $item['body'] : (string) (new GithubFlavoredMarkdownConverter([
'html_input' => 'allow', 'allow_unsafe_links' => false,
]))->convert($item['body']);
$dom = $this->document($html);
$allowed = explode(' ', 'html body p div span h1 h2 h3 h4 h5 h6 strong b em i u s del small blockquote pre code ul ol li hr br a img figure figcaption table thead tbody tfoot tr th td nav section details summary link');
$attrs = explode(' ', 'href src alt title class id width height loading decoding rel target colspan rowspan aria-label aria-hidden');
foreach ($dom->getElementsByTagName('*') as $node) {
abort_unless(in_array($node->nodeName, $allowed), 422, 'Unsupported HTML element: '.$node->nodeName);
foreach ($node->attributes as $a) {
abort_unless(in_array($a->name, $attrs), 422, 'Unsupported HTML attribute: '.$a->name);
}
if ($node->hasAttribute('href')) {
$href = $node->getAttribute('href');
abort_unless(preg_match('~\A(?:https://[^\s]+|/(?!/)[^\s]*|\#[^\s]*)\z~u', $href), 422, 'Unsupported link URL');
if (str_starts_with($href, 'https://') && parse_url($href, PHP_URL_HOST) === parse_url(config('editorial.base_url'), PHP_URL_HOST)) {
abort(422, 'Use a root-relative path for internal links');
}
if (str_starts_with($href, '/images/')) {
abort_unless(! str_contains($href, '..') && is_file(public_path(ltrim($href, '/'))), 422, 'Image link unavailable');
}
}
if ($node->nodeName === 'link') {
abort_unless($node->getAttribute('rel') === 'stylesheet' && $node->getAttribute('href') === '/css/tutorials.css', 422, 'Unsupported stylesheet');
}
if ($node->hasAttribute('src')) {
$src = $node->getAttribute('src');
if (preg_match('/\Aasset:([a-f0-9]{64})\z/', $src, $m)) {
abort_unless(DB::table('editorial_assets')->where('sha256', $m[1])->exists(), 422, 'Unknown uploaded image');
} else {
abort_unless(preg_match('~\A/images/(?!.*\.\.)([a-zA-Z0-9_./-]+)\.(png|jpg|jpeg|webp|gif|svg)\z~', $src)
&& is_file(public_path(ltrim($src, '/'))), 422, 'Images must be uploaded or existing local assets');
}
}
if ($node->getAttribute('target') === '_blank') {
$node->setAttribute('rel', 'noopener noreferrer');
}
}
$body = $dom->getElementsByTagName('body')->item(0);
$html = '';
foreach ($body->childNodes as $child) {
$html .= $dom->saveHTML($child);
}
if (! str_contains($html, 'class="tutorial-body"')) {
$html = '<link rel="stylesheet" href="/css/tutorials.css"><div class="tutorial-body">'.$html.'</div>';
}
// Existing article Blade calls nl2br. Preserve code newlines as entities.
$html = preg_replace_callback('/<pre\b[^>]*>.*?<\/pre>/s', fn ($m) => str_replace("\n", '&#10;', $m[0]), $html);
return str_replace(["\r", "\n"], '', $html);
}
public function document(string $html): DOMDocument
{
$dom = new DOMDocument('1.0', 'UTF-8');
$previous = libxml_use_internal_errors(true);
$dom->loadHTML('<?xml encoding="UTF-8"><html><body>'.$html.'</body></html>', LIBXML_NONET);
libxml_clear_errors();
libxml_use_internal_errors($previous);
return $dom;
}
public function publicImages(string $html): string
{
return preg_replace_callback('/asset:([a-f0-9]{64})/', function ($m) {
$asset = DB::table('editorial_assets')->where('sha256', $m[1])->first();
abort_unless($asset && is_file($this->privateImage($asset->sha256)), 422, 'Uploaded image unavailable');
$url = '/images/editorial/'.$asset->sha256.'.'.$asset->extension;
$destination = public_path(ltrim($url, '/'));
if (! is_dir(dirname($destination))) {
mkdir(dirname($destination), 0755, true);
}
if (! is_file($destination)) {
$tmp = $destination.'.'.bin2hex(random_bytes(6)).'.tmp';
if (! copy($this->privateImage($asset->sha256), $tmp) || ! rename($tmp, $destination)) {
throw new \RuntimeException('Image publication failed');
}
chmod($destination, 0644);
}
abort_unless(hash_file('sha256', $destination) === $asset->sha256, 422, 'Image checksum mismatch');
return $url;
}, $html);
}
public function privateImage(string $sha): string
{
return storage_path('app/private/editorial/assets/'.$sha);
}
}
@@ -1,108 +0,0 @@
<?php
namespace App\Services\Editorial;
use App\Models\Articles;
use Illuminate\Support\Facades\Http;
/** Durable notification state lives in the publication receipt, alongside cache/search effects. */
final class IndexNowNotification
{
public function initial(array $articles): array
{
if (! $this->enabled()) {
return ['status' => 'skipped', 'reason' => 'disabled-environment'];
}
if (! collect($articles)->contains(fn ($a) => $a['content_changed'] ?? false)) {
return ['status' => 'skipped', 'reason' => 'no-content-change'];
}
return ['status' => 'pending', 'attempts' => 0];
}
public function synchronize(array $state, array $published): array
{
if (($state['status'] ?? '') !== 'pending' || ! $this->enabled()
|| ($state['next_attempt_at'] ?? 0) > now()->timestamp) {
return $state;
}
$base = rtrim((string) config('editorial.base_url'), '/');
$urls = [];
foreach ($published as $item) {
if (! ($item['content_changed'] ?? false)) {
continue;
}
$article = Articles::with('oCategory')->find($item['article_id']);
if (! $article || !\App\Services\Seo::indexable($article)) {
continue;
}
$url = $base.'/a/'.$article->sSlug.'.html';
if ($url === $item['url'] && preg_match('/\A[a-z0-9_-]+\z/', $article->sSlug)) {
$urls[] = $url;
$urls[] = \App\Services\Seo::url(\App\Services\Seo::categoryPath($article->oCategory));
if ($article->oCategory->oParent) $urls[] = \App\Services\Seo::url(\App\Services\Seo::categoryPath($article->oCategory->oParent));
}
}
$urls = array_values(array_unique($urls));
if (! $urls) {
return array_replace($state, ['status' => 'skipped', 'reason' => 'no-current-indexable-url']);
}
return $this->submit($state, $urls);
}
public function submit(array $state, array $urls): array
{
if (!$this->enabled() || ($state['next_attempt_at'] ?? 0) > now()->timestamp) return $state;
$base = rtrim((string) config('editorial.base_url'), '/');
$host = parse_url($base, PHP_URL_HOST);
// No per-article target, redirect, or credentials in URLs. Never probe public pages from local.
if (! $host || ! preg_match('~\Ahttps://[a-z0-9.-]+\z~i', $base)
|| $base !== rtrim((string) config('app.url'), '/')
|| $host !== config('app.site_code')) {
return $this->pending($state, 'site-binding-mismatch');
}
$key = config('key.indexnow');
if (! is_string($key) || ! preg_match('/\A[a-zA-Z0-9-]{8,128}\z/', $key)) {
return $this->pending($state, 'key-missing-or-invalid');
}
foreach ($urls as $url) {
if (!str_starts_with($url, $base.'/') || parse_url($url, PHP_URL_HOST) !== $host || parse_url($url, PHP_URL_QUERY) || parse_url($url, PHP_URL_FRAGMENT)) return $this->pending($state,'invalid-target');
}
if (!$urls) return ['status'=>'skipped','reason'=>'no-current-indexable-url'];
try {
$response = Http::connectTimeout(5)->timeout(15)->withoutRedirecting()->acceptJson()
->post('https://api.indexnow.org/indexnow', [
'host' => $host, 'key' => $key, 'keyLocation' => $base.'/'.$key.'.txt', 'urlList' => $urls,
]);
$code = $response->status();
if (in_array($code, [200, 202], true)) {
return ['status' => 'done', 'attempts' => ($state['attempts'] ?? 0) + 1,
'http_status' => $code, 'urls' => $urls, 'submitted_at' => now()->toIso8601String(),
'result' => $code === 202 ? 'received-key-validation-pending' : 'received'];
}
return $this->pending($state, 'http-error', $code);
} catch (\Throwable) {
// Response bodies and exception messages may contain the key. Persist only safe diagnostics.
return $this->pending($state, 'transport-error');
}
}
private function enabled(): bool
{
return app()->environment(['production', 'testing'])
&& (bool) config('editorial.indexnow_enabled', app()->environment('production'));
}
private function pending(array $state, string $reason, ?int $code = null): array
{
$attempts = ($state['attempts'] ?? 0) + 1;
return ['status' => 'pending', 'attempts' => $attempts, 'reason' => $reason, 'http_status' => $code,
'last_attempt_at' => now()->toIso8601String(),
'next_attempt_at' => now()->timestamp + min(86400, 300 * 2 ** min(9, $attempts - 1))];
}
}
-66
View File
@@ -1,66 +0,0 @@
<?php
namespace App\Services\Editorial;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
/** Calls the existing HTTP routes on the application server, without opening its public API. */
final class ProcessApi
{
private array $credential;
public function __construct()
{
abort_unless(PHP_SAPI === 'cli', 403);
$this->credential = ['schema' => 'gemdocs.credential.v1', 'project' => 'fna-v3',
'environment' => app()->environment(), 'base_url' => config('editorial.base_url'),
'expires_at' => time() + 600, 'fields' => ['api_key' => 'fna_ed_'.bin2hex(random_bytes(32))]];
}
public function call(string $method, string $path, array $data = [], ?UploadedFile $image = null): array
{
abort_unless(in_array($method, ['GET', 'POST']) && preg_match('~\A[a-zA-Z0-9_/-]+\z~', $path), 422);
$response = $this->dispatch($method, '/api/editorial/v1/'.$path, $data, $image);
$body = json_decode($response->getContent(), true);
abort_unless($response->isSuccessful(), $response->getStatusCode(), 'Editorial API rejected operation; inspect state before retry');
abort_unless(is_array($body), 502, 'Unexpected API response');
return $body;
}
public function preview(string $url): string
{
$base = rtrim(config('editorial.base_url'), '/');
abort_unless(str_starts_with($url, $base.'/api/editorial/v1/preview/'), 422, 'Preview origin mismatch');
$response = $this->dispatch('GET', substr($url, strlen($base)));
abort_unless($response->isSuccessful() && str_contains($response->headers->get('Content-Type', ''), 'text/html')
&& str_contains($response->headers->get('X-Robots-Tag', ''), 'noindex'), 502, 'Preview render failed');
return $response->getContent();
}
private function dispatch(string $method, string $path, array $data = [], ?UploadedFile $image = null)
{
abort_unless(time() < $this->credential['expires_at'], 401, 'Process session expired');
$before = ['editorial.enabled' => config('editorial.enabled'),
'editorial.process_credential' => config('editorial.process_credential')];
$originalRequest = app('request');
config(['editorial.enabled' => true, 'editorial.process_credential' => $this->credential]);
try {
$server = ['HTTP_ACCEPT' => 'application/json', 'HTTP_AUTHORIZATION' => 'Bearer '.$this->credential['fields']['api_key'],
'CONTENT_TYPE' => 'application/json', 'REMOTE_ADDR' => '127.0.0.1'];
$request = Request::create(rtrim(config('editorial.base_url'), '/').$path, $method, [], [],
$image ? ['image' => $image] : [], $server, $image ? null : json_encode($data));
$kernel = app(Kernel::class);
$response = $kernel->handle($request);
$kernel->terminate($request, $response);
return $response;
} finally {
config($before);
app()->instance('request', $originalRequest);
}
}
}
@@ -1,86 +0,0 @@
<?php
namespace App\Services\Editorial;
use App\Models\Articles;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Meilisearch\Client;
use Spatie\ResponseCache\Facades\ResponseCache;
final class PublicationEffects
{
public function synchronize(string $id): array
{
DB::transaction(function () use ($id) {
$row = DB::table('editorial_publications')->where('id', $id)->lockForUpdate()->first();
abort_unless($row, 404);
$receipt = json_decode($row->receipt, true);
$effects = json_decode($row->effects ?? '{}', true) ?: [];
if (($effects['cache']['status'] ?? '') !== 'done') {
try {
ResponseCache::clear();
Cache::forget('article_order_likes');
$effects['cache'] = ['status' => 'done'];
} catch (\Throwable) {
$effects['cache'] = ['status' => 'pending', 'reason' => 'Cache refresh failed; retry synchronization'];
}
}
if (($effects['search']['status'] ?? '') !== 'done') {
try {
$ids = array_column($receipt['articles'], 'article_id');
$effects['search'] = $this->index($ids);
} catch (\Throwable) {
$effects['search'] = ['status' => 'pending', 'reason' => 'Search synchronization failed; retry synchronization'];
}
}
// Sitemap is generated from current DB rows, no external submission is performed.
$effects['sitemap'] = ['status' => ($effects['cache']['status'] ?? '') === 'done' ? 'done' : 'pending', 'method' => 'database-driven'];
// Legacy receipts were not queued for notification; never backfill them implicitly.
$notification = $effects['indexnow'] ?? ['status' => 'skipped', 'reason' => 'legacy-publication'];
if (($effects['cache']['status'] ?? '') === 'done') {
$notification = app(IndexNowNotification::class)->synchronize($notification, $receipt['articles']);
}
$effects['indexnow'] = $notification;
DB::table('editorial_publications')->where('id', $id)->update(['effects' => json_encode($effects), 'updated_at' => now()]);
});
return app(Publisher::class)->receipt($id);
}
public function index(?array $ids = null): array
{
$driver = config('scout.driver');
if (in_array($driver, ['collection', 'database'])) {
return ['status' => 'done', 'method' => 'live-database'];
}
if ($driver !== 'meilisearch') {
return ['status' => 'pending', 'reason' => 'Configure a supported site search driver'];
}
$name = config('editorial.search_index');
$host = config('scout.meilisearch.host');
if (! $name || (app()->environment('local') && (! in_array(parse_url($host, PHP_URL_HOST), ['localhost', '127.0.0.1', '::1']) || ! str_starts_with($name, 'fna_v3_')))) {
return ['status' => 'pending', 'reason' => 'An isolated search index is required'];
}
$client = new Client($host, config('scout.meilisearch.key'));
$index = $client->index($name);
$wait = function ($task) use ($client) {
$result = $client->waitForTask($task['taskUid'], 10000, 50);
if (($result['status'] ?? '') !== 'succeeded') {
throw new \RuntimeException('Index task failed');
}
};
$wait($index->updateSortableAttributes(['iIsTop', 'created_at']));
$wait($index->updateFilterableAttributes(['iStatus', 'iCategoryId']));
$query = Articles::query()->where('iStatus', 1);
if ($ids !== null) {
$query->whereIn('id', $ids);
}
$documents = $query->get()->map(fn ($a) => $a->toSearchableArray() + ['created_at' => $a->created_at?->timestamp])->all();
if ($documents) {
$wait($index->addDocuments($documents, 'id'));
}
return ['status' => 'done', 'method' => 'meilisearch', 'index' => $name, 'documents' => count($documents)];
}
}
-325
View File
@@ -1,325 +0,0 @@
<?php
namespace App\Services\Editorial;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Validator;
final class Publisher
{
public function __construct(private ContentRenderer $renderer) {}
public function draft(array $input): array
{
$data = Validator::make($input, [
'request_id' => 'required|uuid', 'articles' => 'required|array|min:1|max:'.config('editorial.max_batch'),
'articles.*.content_key' => ['required', 'string', 'max:100', 'regex:/\A[a-z0-9][a-z0-9_-]*\z/'],
'articles.*.expected_revision' => 'required|integer|min:0',
'articles.*.slug' => ['required', 'string', 'max:180', 'regex:/\A[a-z0-9][a-z0-9_-]*\z/'],
'articles.*.title' => 'required|string|max:200', 'articles.*.summary' => 'required|string|max:255',
'articles.*.category_slug' => 'required|string|max:50',
'articles.*.format' => 'sometimes|in:markdown,html', 'articles.*.body' => 'required|string|max:500000',
'articles.*.tag_ids' => 'sometimes|array|max:20', 'articles.*.tag_ids.*' => 'integer|min:1',
'articles.*.cover' => 'sometimes|nullable|string|max:255',
'articles.*.show_cover' => 'sometimes|boolean',
'articles.*.display_time_randomize' => 'sometimes|boolean',
'articles.*.adopt_article_id' => 'sometimes|integer|min:1',
'articles.*.like_settings' => 'sometimes|array:seven_day,yearly,one_year',
'articles.*.like_settings.seven_day' => 'sometimes|integer|min:0|max:1000000',
'articles.*.like_settings.yearly' => 'sometimes|integer|min:0|max:365',
'articles.*.like_settings.one_year' => 'sometimes|integer|min:0|max:1000000',
])->validate();
$data['operation'] = $input['_operation'] ?? 'draft';
$hash = $this->hash($data);
DB::transaction(function () use ($data, $hash) {
$inserted = DB::table('editorial_drafts')->insertOrIgnore([
'id' => $data['request_id'], 'payload_hash' => $hash, 'items' => '[]',
'status' => 'draft', 'created_at' => now(), 'updated_at' => now(),
]);
$draft = DB::table('editorial_drafts')->where('id', $data['request_id'])->lockForUpdate()->first();
abort_unless($draft && hash_equals($draft->payload_hash, $hash), 409, 'Request ID reused with different content');
if (! $inserted) {
return;
}
$rows = $data['articles'];
usort($rows, fn ($a, $b) => strcmp($a['content_key'], $b['content_key']));
abort_unless(count(array_unique(array_column($rows, 'content_key'))) === count($rows)
&& count(array_unique(array_column($rows, 'slug'))) === count($rows), 422, 'Duplicate article in batch');
$items = [];
foreach ($rows as $row) {
$key = $row['content_key'];
DB::table('editorial_documents')->insertOrIgnore(['content_key' => $key, 'revision' => 0, 'created_at' => now(), 'updated_at' => now()]);
$doc = DB::table('editorial_documents')->where('content_key', $key)->lockForUpdate()->first();
abort_unless((int) $doc->revision === (int) $row['expected_revision'], 409, 'Revision changed: '.$key);
$article = $doc->article_id ? DB::table('articles')->where('id', $doc->article_id)->lockForUpdate()->first() : null;
if (isset($row['adopt_article_id'])) {
abort_unless(! $doc->article_id || (int) $doc->article_id === (int) $row['adopt_article_id'], 409, 'Content key already bound');
$article = DB::table('articles')->where('id', $row['adopt_article_id'])->lockForUpdate()->first();
abort_unless($article && ! DB::table('editorial_documents')->where('article_id', $article->id)->where('content_key', '!=', $key)->exists(), 409, 'Article missing or already managed');
if (! $doc->article_id) {
DB::table('editorial_documents')->where('content_key', $key)->update(['article_id' => $article->id, 'published_revision' => 0]);
DB::table('editorial_versions')->insert(['content_key' => $key, 'revision' => 0, 'snapshot' => json_encode($this->baseline($key, $article)), 'created_at' => now()]);
}
}
abort_if($doc->article_id && ! $article, 409, 'Managed article was removed');
if ($article) {
abort_if(array_key_exists('like_settings', $row), 422, 'Like settings are only accepted for new articles');
abort_if(array_key_exists('display_time_randomize', $row), 422, 'Display time settings are only accepted for new articles');
abort_unless($article->sSlug === $row['slug'], 409, 'Stable article URL cannot change');
$sourceCategory = DB::table('categories')->where('id', $article->iCategoryId)->value('sSlug');
abort_if(in_array($sourceCategory, ['freenode', 'shadowrocketids']), 422, 'Resource articles cannot be adopted by the editorial API');
}
$collision = DB::table('articles')->where('sSlug', $row['slug'])->first();
abort_if($collision && (! $article || $collision->id !== $article->id), 409, 'URL belongs to another article; explicit adoption required');
$category = $this->category($row['category_slug']);
$tags = $row['tag_ids'] ?? ($article ? $this->tags($article->id) : []);
$tags = array_values(array_unique(array_map('intval', $tags)));
sort($tags);
abort_unless(DB::table('tags')->whereIn('id', $tags)->count() === count($tags), 422, 'Unknown tag ID');
$item = [
'content_key' => $key, 'revision' => $doc->revision + 1, 'slug' => $row['slug'],
'title' => $row['title'], 'summary' => $row['summary'], 'category_slug' => $category->sSlug,
'format' => $row['format'] ?? 'markdown', 'body' => $row['body'], 'tag_ids' => $tags,
'cover' => array_key_exists('cover', $row) ? $row['cover'] : ($article->sThumb ?? null),
'show_cover' => (bool) ($row['show_cover'] ?? ($article->bPageThumb ?? false)),
'base_article_hash' => $article ? $this->articleHash($article) : null,
];
if (! $article) {
// Freeze display offset and like defaults once; retries cannot redraw them.
$item['display_offset_seconds'] = ($row['display_time_randomize'] ?? true) ? random_int(0, 21600) : 0;
$defaults = app(\App\Services\ArticleLikeDefaults::class);
$item['like_settings'] = $defaults->resolve($defaults->editorialCategory($category->sSlug), $row['like_settings'] ?? []);
}
$item['html'] = $this->renderer->render($item);
if ($item['cover']) {
$this->renderer->render(['format' => 'html', 'body' => '<img src="'.htmlspecialchars($item['cover'], ENT_QUOTES).'">']);
}
DB::table('editorial_documents')->where('content_key', $key)->update(['revision' => $item['revision'], 'updated_at' => now()]);
$items[] = $item;
}
$this->validateLinks($items);
DB::table('editorial_drafts')->where('id', $data['request_id'])->update(['items' => json_encode($items, JSON_UNESCAPED_UNICODE), 'updated_at' => now()]);
}, 3);
return $this->getDraft($data['request_id']);
}
public function getDraft(string $id): array
{
$d = DB::table('editorial_drafts')->where('id', $id)->first();
abort_unless($d, 404);
$items = json_decode($d->items, true);
$base = rtrim(config('editorial.base_url'), '/');
return ['draft_id' => $id, 'hash' => $d->payload_hash, 'status' => $d->status, 'publication_id' => $d->publication_id,
'articles' => array_map(fn ($i) => ['content_key' => $i['content_key'], 'revision' => $i['revision'], 'title' => $i['title'],
'path' => '/a/'.$i['slug'].'.html', 'display_offset_seconds' => $i['display_offset_seconds'] ?? 0, 'like_settings' => $i['like_settings'] ?? null,
'preview_url' => $base.URL::temporarySignedRoute('editorial.preview', now()->addMinutes(config('editorial.preview_minutes')), ['draft' => $id, 'key' => $i['content_key']], absolute: false)], $items)];
}
public function article(string $key): array
{
$doc = DB::table('editorial_documents')->where('content_key', $key)->first();
abort_unless($doc, 404);
$article = $doc->article_id ? DB::table('articles')->where('id', $doc->article_id)->first() : null;
return ['content_key' => $key, 'latest_revision' => $doc->revision, 'published_revision' => $doc->published_revision,
'article_id' => $doc->article_id, 'path' => $article ? '/a/'.$article->sSlug.'.html' : null,
'versions' => DB::table('editorial_versions')->where('content_key', $key)->orderByDesc('revision')->get(['revision', 'created_at'])->toArray()];
}
public function rollback(string $key, array $input): array
{
$data = Validator::make($input, ['request_id' => 'required|uuid', 'expected_revision' => 'required|integer|min:0', 'target_revision' => 'required|integer|min:0'])->validate();
$v = DB::table('editorial_versions')->where('content_key', $key)->where('revision', $data['target_revision'])->first();
abort_unless($v, 404, 'Published version unavailable');
$item = json_decode($v->snapshot, true);
$item = array_intersect_key($item, array_flip(['content_key', 'slug', 'title', 'summary', 'category_slug', 'format', 'body', 'tag_ids', 'cover', 'show_cover']));
$item['expected_revision'] = $data['expected_revision'];
return $this->draft(['request_id' => $data['request_id'], 'articles' => [$item], '_operation' => 'rollback:'.$key.':'.$data['target_revision']]);
}
public function publish(string $id, array $input): array
{
$data = Validator::make($input, ['request_id' => 'required|uuid', 'expected_hash' => 'required|string|size:64'])->validate();
$opHash = $this->hash(['draft_id' => $id, 'expected_hash' => $data['expected_hash']]);
$publication = DB::transaction(function () use ($id, $data, $opHash) {
$existing = DB::table('editorial_publications')->where('id', $data['request_id'])->lockForUpdate()->first();
if ($existing) {
abort_unless(hash_equals($existing->payload_hash, $opHash), 409, 'Publish request ID reused');
return $existing->id;
}
$draft = DB::table('editorial_drafts')->where('id', $id)->lockForUpdate()->first();
abort_unless($draft, 404);
abort_unless(hash_equals($draft->payload_hash, $data['expected_hash']), 409, 'Previewed draft hash changed');
if ($draft->status === 'published') {
return $draft->publication_id;
}
$items = json_decode($draft->items, true);
$documents = [];
foreach ($items as $item) {
$doc = DB::table('editorial_documents')->where('content_key', $item['content_key'])->lockForUpdate()->first();
abort_unless($doc && (int) $doc->revision === $item['revision'], 409, 'Draft superseded: '.$item['content_key']);
$current = $doc->article_id ? DB::table('articles')->where('id', $doc->article_id)->lockForUpdate()->first() : null;
abort_unless(($current ? $this->articleHash($current) : null) === $item['base_article_hash'], 409, 'Article edited outside this draft');
abort_if(! $current && DB::table('articles')->where('sSlug', $item['slug'])->exists(), 409, 'URL now belongs to another article');
$this->category($item['category_slug']);
abort_unless(DB::table('tags')->whereIn('id', $item['tag_ids'])->count() === count($item['tag_ids']), 422, 'Tag removed since preview');
$documents[$item['content_key']] = $doc;
}
$this->validateLinks($items, true);
$published = [];
foreach ($items as $item) {
$doc = $documents[$item['content_key']];
$html = $this->renderer->publicImages($item['html']);
$cover = $item['cover'] ? $this->renderer->publicImages($item['cover']) : null;
$fields = ['sTitle' => $item['title'], 'sTitleSub' => $item['summary'], 'sSlug' => $item['slug'],
'sContent' => $html, 'sThumb' => $cover, 'iCategoryId' => $this->category($item['category_slug'])->id,
'iStatus' => 1, 'bPageThumb' => $item['show_cover'], 'updated_at' => now()];
if ($doc->article_id) {
$articleId = $doc->article_id;
DB::table('articles')->where('id', $articleId)->update($fields);
} else {
// Older frozen drafts retain their original zero defaults.
$likes = $item['like_settings'] ?? ['seven_day' => 0, 'yearly' => 0, 'one_year' => 0];
$articleId = DB::table('articles')->insertGetId($fields + ['iUserId' => 1, 'iViews' => 0, 'iLikeCount' => 0,
'i7like' => $likes['seven_day'], 'i365like' => $likes['yearly'],
'iYearLikeTarget' => $likes['one_year'], 'iYearLikeAdded' => 0,
'sYearLikeStartedAt' => $likes['one_year'] > 0 ? now() : null,
'iIsTop' => 0, 'created_at' => now(),
'sDisplayPublishedAt' => now()->subSeconds($item['display_offset_seconds'] ?? 0)]);
}
$oldTags = $this->tags($articleId);
DB::table('article_tag')->where('iArticleId', $articleId)->delete();
foreach ($item['tag_ids'] as $tag) {
DB::table('article_tag')->insert(['iArticleId' => $articleId, 'iTagId' => $tag]);
}
foreach (array_unique(array_merge($oldTags, $item['tag_ids'])) as $tag) {
DB::table('tags')->where('id', $tag)->update(['iArticleCount' => DB::table('article_tag')->where('iTagId', $tag)->count()]);
}
$contentChanged = $item['base_article_hash'] !== $this->articleHash(DB::table('articles')->where('id', $articleId)->first());
if ($contentChanged && \Illuminate\Support\Facades\Schema::hasColumn('articles','sContentUpdatedAt')) {
DB::table('articles')->where('id',$articleId)->update(['sContentUpdatedAt'=>now()]);
}
DB::table('editorial_documents')->where('content_key', $item['content_key'])->update(['article_id' => $articleId, 'published_revision' => $item['revision'], 'updated_at' => now()]);
DB::table('editorial_versions')->insert(['content_key' => $item['content_key'], 'revision' => $item['revision'], 'snapshot' => json_encode($item, JSON_UNESCAPED_UNICODE), 'created_at' => now()]);
$published[] = ['content_key' => $item['content_key'], 'article_id' => $articleId, 'revision' => $item['revision'],
'content_changed' => $item['base_article_hash'] !== $this->articleHash(DB::table('articles')->where('id', $articleId)->first()),
'url' => rtrim(config('editorial.base_url'), '/').'/a/'.$item['slug'].'.html'];
}
DB::table('editorial_publications')->insert(['id' => $data['request_id'], 'draft_id' => $id, 'payload_hash' => $opHash,
'receipt' => json_encode(['publication_id' => $data['request_id'], 'status' => 'published', 'articles' => $published], JSON_UNESCAPED_UNICODE),
'effects' => json_encode(['indexnow' => app(IndexNowNotification::class)->initial($published)]),
'created_at' => now(), 'updated_at' => now()]);
DB::table('editorial_drafts')->where('id', $id)->update(['status' => 'published', 'publication_id' => $data['request_id'], 'updated_at' => now()]);
return $data['request_id'];
}, 3);
return app(PublicationEffects::class)->synchronize($publication);
}
public function receipt(string $id): array
{
$row = DB::table('editorial_publications')->where('id', $id)->first();
abort_unless($row, 404);
return json_decode($row->receipt, true) + ['effects' => json_decode($row->effects ?? 'null', true)];
}
public function category(string $slug): object
{
$c = DB::table('categories')->where('sSlug', $slug)->where('iStatus', 1)->first();
abort_unless($c && ! in_array($slug, ['freenode', 'shadowrocketids']), 422, 'Unknown or non-editorial category');
return $c;
}
public function articleHash(object $a): string
{
return $this->hash(['fields' => array_intersect_key((array) $a, array_flip(['sTitle', 'sTitleSub', 'sSlug', 'sContent', 'sThumb', 'iCategoryId', 'iStatus', 'bPageThumb'])), 'tag_ids' => $this->tags($a->id)]);
}
private function tags(int $id): array
{
return DB::table('article_tag')->where('iArticleId', $id)->orderBy('iTagId')->pluck('iTagId')->map(fn ($v) => (int) $v)->toArray();
}
private function baseline(string $key, object $a): array
{
$category = DB::table('categories')->where('id', $a->iCategoryId)->value('sSlug');
return ['content_key' => $key, 'slug' => $a->sSlug, 'title' => $a->sTitle, 'summary' => $a->sTitleSub ?? '',
'category_slug' => $category, 'format' => 'html', 'body' => $a->sContent, 'tag_ids' => $this->tags($a->id), 'cover' => $a->sThumb, 'show_cover' => (bool) $a->bPageThumb];
}
public function hash(array $data): string
{
$sort = function (&$value) use (&$sort) {
if (! is_array($value)) {
return;
}
if (! array_is_list($value)) {
ksort($value);
}
foreach ($value as &$child) {
$sort($child);
}
};
$sort($data);
return hash('sha256', json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
}
private function validateLinks(array $items, bool $includeIncoming = false): void
{
$targets = [];
foreach ($items as $i) {
$targets[$i['slug']] = $i['html'];
}
$sources = array_column($items, 'html');
if ($includeIncoming) {
// Only inspect incoming links affected by this batch, not unrelated legacy problems.
foreach (DB::table('articles')->where('iStatus', 1)->whereNotIn('sSlug', array_keys($targets))->get(['sContent']) as $a) {
$dom = $this->renderer->document($a->sContent ?? '');
foreach ($dom->getElementsByTagName('a') as $link) {
$href = $link->getAttribute('href');
if (preg_match('~\A/a/([a-z0-9_-]+)\.html(?:#.*)?\z~', $href, $m) && isset($targets[$m[1]])) {
$sources[] = '<a href="'.htmlspecialchars($href, ENT_QUOTES).'">incoming</a>';
}
}
}
}
foreach ($sources as $source) {
$dom = $this->renderer->document($source);
foreach ($dom->getElementsByTagName('a') as $link) {
$href = $link->getAttribute('href');
if (str_starts_with($href, '#') && strlen($href) > 1) {
abort_unless($dom->getElementById(rawurldecode(substr($href, 1))), 422, 'Missing local anchor: '.$href);
} elseif (str_starts_with($href, '/a/')) {
abort_unless(preg_match('~\A/a/([a-z0-9_-]+)\.html(?:#([^?]*))?\z~', $href, $m), 422, 'Invalid article path');
$target = $targets[$m[1]] ?? DB::table('articles')->where('sSlug', $m[1])->where('iStatus', 1)->value('sContent');
abort_unless(is_string($target), 422, 'Unpublished article target: '.$href);
if (! empty($m[2])) {
abort_unless($this->renderer->document($target)->getElementById(rawurldecode($m[2])), 422, 'Missing target anchor: '.$href);
}
} elseif (str_starts_with($href, '/') && ! str_starts_with($href, '/images/') && $href !== '/css/tutorials.css' && $href !== '/') {
$segments = explode('/', trim($href, '/'));
if ($segments[0] === 'tag' && count($segments) === 2) {
abort_unless(DB::table('tags')->where('sSlug', $segments[1])->exists(), 422, 'Unknown tag link');
} else {
abort_unless(count($segments) <= 2, 422, 'Invalid category link');
$c = DB::table('categories')->where('sSlug', end($segments))->where('iStatus', 1)->first();
abort_unless($c, 422, 'Unknown category link');
if (count($segments) === 2) {
abort_unless(DB::table('categories')->where('id', $c->iParentId)->value('sSlug') === $segments[0], 422, 'Wrong category parent');
}
}
}
}
}
}
}
-205
View File
@@ -1,205 +0,0 @@
<?php
namespace App\Services\Editorial;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;
final class ReleaseRunner
{
public function __construct(private ProcessApi $api) {}
public function run(array $input): array
{
$op = $input['operation'] ?? '';
abort_unless(in_array($op, ['catalog', 'source', 'prepare', 'review', 'publish', 'status']), 422, 'Unknown operation');
if ($op === 'catalog') {
return $this->api->call('GET', 'catalog');
}
if ($op === 'source') {
abort_unless(is_int($input['article_id'] ?? null) && $input['article_id'] > 0, 422);
return $this->api->call('GET', 'source-articles/'.$input['article_id']);
}
$id = $input['release_id'] ?? '';
abort_unless(is_string($id) && Str::isUuid($id), 422, 'release_id must be a UUID');
$root = config('editorial.release_directory', storage_path('app/private/editorial-releases'));
if (! is_dir($root)) {
mkdir($root, 0700, true);
}
$lock = fopen($root.'/runner.lock', 'c');
abort_unless($lock && flock($lock, LOCK_EX | LOCK_NB), 409, 'Another release operation is running');
try {
$file = $root.'/'.$id.'.json';
$state = is_file($file) ? json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR) : null;
if ($op === 'prepare') {
$bundle = ['articles' => $input['articles'] ?? [], 'assets' => $input['assets'] ?? []];
$bundleHash = app(Publisher::class)->hash($bundle);
abort_if($state && $state['bundle_hash'] !== $bundleHash, 409, 'Release ID reused with changed bundle');
if (! $state) {
$state = ['release_id' => $id, 'bundle_hash' => $bundleHash, 'draft_id' => $id,
'publication_request_id' => (string) Str::uuid(), 'phase' => 'preparing'];
$this->save($file, $state); // Persist IDs before any API mutation.
}
$articles = $this->assets($bundle);
$draft = $this->api->call('POST', 'drafts', ['request_id' => $id, 'articles' => $articles]);
$state['draft'] = $draft;
if ($state['phase'] === 'preparing') {
$state['phase'] = 'prepared';
}
$this->save($file, $state);
return $state;
}
abort_unless($state, 404, 'Release not found; retry prepare using the original bundle');
if ($op === 'status') {
return $this->receipt($file, $state);
}
$draft = $this->api->call('GET', 'drafts/'.$state['draft_id']);
if ($op === 'review') {
$previews = [];
foreach ($draft['articles'] as $article) {
$previews[$article['content_key']] = $this->api->preview($article['preview_url']);
}
$state['review'] = ['hash' => $draft['hash'], 'digest' => app(Publisher::class)->hash($previews), 'rendered_at' => gmdate('c')];
$state['phase'] = $draft['status'] === 'published' ? 'published' : 'reviewed';
$this->save($file, $state);
return $state + ['previews' => $previews];
}
abort_unless(isset($state['review'])
&& hash_equals($state['review']['hash'], $input['expected_hash'] ?? '')
&& hash_equals($state['review']['digest'], $input['review_digest'] ?? '')
&& hash_equals($draft['hash'], $state['review']['hash']), 409, 'Review the frozen draft before publishing');
// Query first even after a lost response or interrupted local state update.
$state = $this->receipt($file, $state);
if (! isset($state['receipt'])) {
$state['phase'] = 'publishing';
$this->save($file, $state);
$state['receipt'] = $this->api->call('POST', 'drafts/'.$state['draft_id'].'/publish',
['request_id' => $state['publication_request_id'], 'expected_hash' => $state['review']['hash']]);
$this->save($file, $state);
}
$receiptId = $state['receipt']['publication_id'];
$state['receipt'] = $this->api->call('POST', 'publications/'.$receiptId.'/synchronize');
return $this->verify($file, $state);
} finally {
flock($lock, LOCK_UN);
fclose($lock);
}
}
private function receipt(string $file, array $state): array
{
try {
$state['receipt'] = $this->api->call('GET', 'publications/'.$state['publication_request_id']);
} catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
if ($e->getStatusCode() !== 404) {
throw $e;
}
// Another publisher may have completed this same draft with its own UUID.
$draft = $this->api->call('GET', 'drafts/'.$state['draft_id']);
if ($draft['publication_id']) {
$state['receipt'] = $this->api->call('GET', 'publications/'.$draft['publication_id']);
} else {
return $state;
}
}
return $this->verify($file, $state);
}
private function verify(string $file, array $state): array
{
$timestamp = \Illuminate\Support\Facades\DB::table('editorial_publications')->where('id', $state['receipt']['publication_id'])->value('created_at');
$state['published_at'] = \Carbon\CarbonImmutable::parse($timestamp, config('app.timezone'))->toIso8601String();
$readback = [];
foreach ($state['receipt']['articles'] as $article) {
$source = $this->api->call('GET', 'source-articles/'.$article['article_id']);
$version = $this->api->call('GET', 'articles/'.$article['content_key'].'/versions/'.$article['revision'])['content'];
$imagesValid = true;
$resolve = function (string $html) use (&$imagesValid) {
return preg_replace_callback('/asset:([a-f0-9]{64})/', function ($m) use (&$imagesValid) {
$extension = \Illuminate\Support\Facades\DB::table('editorial_assets')->where('sha256', $m[1])->value('extension');
$url = '/images/editorial/'.$m[1].'.'.$extension;
$path = public_path(ltrim($url, '/'));
$imagesValid = $imagesValid && is_file($path) && hash_file('sha256', $path) === $m[1];
return $url;
}, $html);
};
$expectedHtml = $resolve($version['html']);
$expectedCover = $version['cover'] ? $resolve($version['cover']) : $version['cover'];
$matches = $source['body_html'] === $expectedHtml && $source['title'] === $version['title']
&& $source['summary'] === $version['summary'] && $source['slug'] === $version['slug']
&& $source['category_slug'] === $version['category_slug'] && $source['cover'] === $expectedCover
&& $source['show_cover'] === $version['show_cover'] && $imagesValid;
$readback[] = ['content_key' => $article['content_key'], 'article_id' => $article['article_id'],
'revision_matches' => (int) $source['management']['published_revision'] === (int) $article['revision'],
'content_matches' => $matches,
'body_sha256' => hash('sha256', $source['body_html']), 'like_growth' => $source['like_growth']];
}
$state['readback'] = $readback;
$done = collect($state['receipt']['effects'])->every(fn ($e, $name) => ($e['status'] ?? '') === 'done'
|| ($name === 'indexnow' && ($e['status'] ?? '') === 'skipped'));
$state['phase'] = $done && collect($readback)->every(fn ($r) => $r['revision_matches'] && $r['content_matches']) ? 'complete' : 'published_pending';
$this->save($file, $state);
return $state;
}
private function assets(array $bundle): array
{
abort_unless(is_array($bundle['assets']) && count($bundle['assets']) <= 10, 422);
$replacements = [];
foreach ($bundle['assets'] as $asset) {
abort_unless(preg_match('/\A[a-z0-9_-]{1,80}\z/', $asset['name'] ?? '') && ! isset($replacements['file:'.$asset['name']]), 422, 'Invalid or duplicate asset name');
$bytes = base64_decode($asset['base64'] ?? '', true);
abort_unless($bytes !== false && strlen($bytes) <= 8 * 1024 * 1024, 422, 'Invalid asset');
$temp = tempnam(sys_get_temp_dir(), 'editorial-upload-');
try {
file_put_contents($temp, $bytes);
chmod($temp, 0600);
$result = $this->api->call('POST', 'assets', [], new UploadedFile($temp, $asset['name'], null, null, true));
$replacements['file:'.$asset['name']] = $result['reference'];
} finally {
@unlink($temp);
}
}
$articles = $bundle['articles'];
abort_unless(is_array($articles) && count($articles) >= 1 && count($articles) <= 10, 422);
foreach ($articles as &$article) {
foreach (['body', 'cover'] as $field) {
if (isset($article[$field])) {
$article[$field] = preg_replace_callback('/file:([a-z0-9_-]+)/', function ($m) use ($replacements) {
abort_unless(isset($replacements[$m[0]]), 422, 'Missing bundled asset');
return $replacements[$m[0]];
}, $article[$field]);
}
}
}
return $articles;
}
private function save(string $file, array $state): void
{
$temp = $file.'.'.bin2hex(random_bytes(8));
try {
$handle = fopen($temp, 'x');
chmod($temp, 0600);
$bytes = json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
if (fwrite($handle, $bytes) !== strlen($bytes) || ! fflush($handle) || ! fsync($handle)) {
throw new \RuntimeException('Release state write failed');
}
fclose($handle);
if (! rename($temp, $file)) {
throw new \RuntimeException('Release state replacement failed');
}
} finally {
@unlink($temp);
}
}
}
-93
View File
@@ -1,93 +0,0 @@
<?php
namespace App\Services;
use DOMDocument;
use DOMElement;
/** Read-only adaptation of the legacy daily-node article into a task-oriented layout. */
final class FreeNodeArticleLayout
{
public static function prepare(string $html): ?array
{
if (!preg_match('~(?:<p\b[^>]*>\s*)?<h[2-6]\b[^>]*>\s*免费节点订阅链接\s*[::]?\s*</h[2-6]>(?:\s*</p>)?~u', $html, $heading, PREG_OFFSET_CAPTURE)) return null;
if (!preg_match('~<p\b[^>]*>\s*温馨提示\s*[::]?\s*</p>~u', $html, $help, PREG_OFFSET_CAPTURE, $heading[0][1])) return null;
$start = $heading[0][1];$from = $start + strlen($heading[0][0]);$end = $help[0][1];
$intro = self::fragment(str_replace(ArticleRecommendations::SLOT, '', substr($html, 0, $start)));
$subscriptions = self::fragment(substr($html, $from, $end - $from));
if (!$intro || !$subscriptions) return null;
$result = ['count' => null, 'speed' => null, 'regions' => [], 'community' => [], 'intro' => '', 'notes' => '', 'subscriptions' => [], 'usage' => substr($html, $end + strlen($help[0][0]))];
foreach (iterator_to_array($intro->childNodes) as $node) {
$text = self::text($node->textContent);
if ($text === '') continue;
if (preg_match('/^本次更新共\s*(\d+)\s*个可用节点[,,]\s*最高速度\s*([^。]+)[。]?$/u', $text, $m)) {
$result['count'] = (int)$m[1];$result['speed'] = trim($m[2]);continue;
}
if (preg_match('/^覆盖(.+?)等多个区域[。]?$/u', $text, $m)) {
$result['regions'] = array_values(array_unique(array_filter(array_map('trim', preg_split('/[、,,]/u', $m[1])))));continue;
}
if (str_starts_with($text, '复制下方订阅链接')) continue;
if ($node instanceof DOMElement && preg_match('/点击加入我们的tg频道|点击关注我们的github仓库/u', $text)) {
$recognized = false;
foreach ($node->getElementsByTagName('a') as $a) {
$url = $a->getAttribute('href');$host = strtolower(parse_url($url, PHP_URL_HOST) ?? '');
if (parse_url($url, PHP_URL_SCHEME) !== 'https' || !in_array($host, ['t.me', 'github.com'], true)) continue;
$result['community'][] = ['url' => $url, 'label' => $host === 't.me' ? 'Telegram 更新频道' : 'GitHub 项目仓库'];$recognized = true;
}
if ($recognized) continue;
}
$result['intro'] .= $intro->ownerDocument->saveHTML($node);
}
$urls = [];
foreach (iterator_to_array($subscriptions->getElementsByTagName('a')) as $a) {
if (!$a->hasAttribute('data-clipboard-text')) continue;
$url = $a->getAttribute('data-clipboard-text');
if (!filter_var($url, FILTER_VALIDATE_URL) || !in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https'], true)) return null;
$path = parse_url($url, PHP_URL_PATH) ?? '';
$type = match (true) {
(bool)preg_match('/-clash\.(yaml|yml)$/i', $path) => ['key'=>'clash', 'title'=>'Clash / Mihomo', 'format'=>'YAML', 'clients'=>'Clash Verge Rev、Mihomo 等客户端', 'symbol'=>'C'],
(bool)preg_match('/-singbox\.(txt|json)$/i', $path) => ['key'=>'singbox', 'title'=>'Sing-box / Hiddify', 'format'=>'SING-BOX', 'clients'=>'Sing-box、Hiddify 等客户端', 'symbol'=>'S'],
(bool)preg_match('/-v2ray\.txt$/i', $path) => ['key'=>'v2ray', 'title'=>'V2ray / Shadowrocket', 'format'=>'通用订阅', 'clients'=>'v2rayNG、Shadowrocket 等客户端', 'symbol'=>'V'],
default => null,
};
// Unknown formats keep the original article rather than dropping a subscription.
if (!$type || isset($result['subscriptions'][$type['key']])) return null;
$result['subscriptions'][$type['key']] = $type + ['url'=>$url];$urls[] = $url;
}
if ($result['subscriptions'] === []) return null;
// Keep every supplementary note while removing only labels/URLs now shown in cards.
foreach (iterator_to_array($subscriptions->childNodes) as $node) {
$text = self::text($node->textContent);
if ($text === '' || in_array($text, $urls, true) || preg_match('/订阅链接\s*[::]$/u', $text)) continue;
if ($node instanceof DOMElement && ($node->hasAttribute('data-clipboard-text') || $node->getElementsByTagName('a')->length)) {
foreach (iterator_to_array($node->getElementsByTagName('a')) as $link) {
if ($link->hasAttribute('data-clipboard-text')) $link->parentNode->removeChild($link);
}
if (self::text($node->textContent) === '' || in_array(self::text($node->textContent), $urls, true)) continue;
}
$result['notes'] .= $subscriptions->ownerDocument->saveHTML($node);
}
$order = ['clash'=>0, 'v2ray'=>1, 'singbox'=>2];
uasort($result['subscriptions'], fn ($a, $b) => $order[$a['key']] <=> $order[$b['key']]);
$result['subscriptions'] = array_values($result['subscriptions']);
return $result;
}
private static function text(string $text): string
{
return trim(preg_replace('/\s+/u', ' ', $text));
}
private static function fragment(string $html): ?DOMElement
{
$dom = new DOMDocument('1.0', 'UTF-8');$before = libxml_use_internal_errors(true);
try {
$dom->loadHTML('<?xml encoding="UTF-8"><html><body><div id="fn-root">'.$html.'</div></body></html>', LIBXML_NONET);
return $dom->getElementById('fn-root');
} catch (\Throwable) {
return null;
} finally {
libxml_clear_errors();libxml_use_internal_errors($before);
}
}
}
-147
View File
@@ -1,147 +0,0 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
final class IllustrationPool
{
public static function enabled(): bool
{
$base = match (app()->environment()) {
'local' => 'http://resource.loc:8612',
'production' => 'https://resource-v2.gemcook.net',
'staging' => 'https://test.clashfreenode.com/resource-v2',
default => null,
};
return $base !== null && config('illustrations.enabled')
&& config('illustrations.base_url') === $base;
}
private static function request(string $method, string $path, array $body = []): array
{
if (!self::enabled()) throw new \RuntimeException('Illustration service is disabled or not bound to this environment');
$file = config('illustrations.credential_file');
if (!$file || !is_file($file)) throw new \RuntimeException('Illustration credential unavailable');
$credential = json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
if (($credential['project'] ?? '') !== 'fna-v3' || ($credential['base_url'] ?? '') !== config('illustrations.base_url')
|| !preg_match('/\Arsv2_[a-f0-9]{64}\z/D', $credential['token'] ?? '')) {
throw new \RuntimeException('Invalid illustration credential configuration');
}
try {
$response = Http::withOptions(['proxy' => '', 'allow_redirects' => false])
->withToken($credential['token'])->acceptJson()->withUserAgent('FNA-V3/ResourceV2')
->connectTimeout(2)->timeout(8)->send($method, config('illustrations.base_url').'/api/v2/'.$path, ['json' => $body]);
if (!$response->successful() || !is_array($response->json('data'))) throw new \RuntimeException();
return $response->json('data');
} catch (\Throwable $e) {
// Never include request headers, credential bytes or response bodies in exceptions.
throw new \RuntimeException('Resource V2 illustration request failed');
}
}
public static function pendingDeliveries(): array
{
return self::request('GET', 'illustration-deliveries');
}
public static function acknowledgeDelivery(string $id, array $receipt): array
{
if (! preg_match('/\A[a-f0-9-]{36}\z/D', $id)) throw new \RuntimeException('Invalid delivery');
return self::request('POST', 'illustration-deliveries/'.$id.'/ack', $receipt);
}
public static function snapshot(string $pool): array
{
return Cache::store('file')->remember('illustrations.v2.'.$pool, 60, function () use ($pool) {
try {
$data = self::sourceSnapshot($pool);
Cache::store('file')->forever('illustrations.v2.last-good.'.$pool, $data);
return $data;
} catch (\Throwable $e) {
$saved = Cache::store('file')->get('illustrations.v2.last-good.'.$pool);
if (is_array($saved)) return $saved;
throw $e;
}
});
}
public static function forget(string $pool): void
{
Cache::store('file')->forget('illustrations.v2.'.$pool);
}
public static function sourceSnapshot(string $pool): array
{
$data = self::request('GET', 'pools/'.$pool);
$seen = [];
while (! empty($data['next'])) {
$after = $data['next'];
if (isset($seen[$after])) throw new \RuntimeException('Resource pagination did not advance');
$seen[$after] = true;
$page = self::request('GET', 'pools/'.$pool.'?after='.rawurlencode($after));
$data['selections'] = array_replace($data['selections'], $page['selections']);
$data['unavailable'] = array_replace($data['unavailable'] ?? [], $page['unavailable'] ?? []);
$data['next'] = $page['next'];
}
return $data;
}
public static function assign(string $pool, array $keys): array
{
$selections = self::assignSource($pool, $keys);
if (LocalIllustrations::enabled()) {
foreach ($selections as $key => &$image) {
$image['url'] = url(app(LocalIllustrations::class)->storeSelection($pool, $key, $image));
}
unset($image);
}
return $selections;
}
public static function assetMetadata(string $id): array
{
if (! preg_match('/\A[a-f0-9-]{36}\z/D', $id)) throw new \RuntimeException('Invalid illustration asset');
return self::request('GET', 'assets/'.$id);
}
public static function assignSource(string $pool, array $keys): array
{
$data = self::request('POST', 'pools/'.$pool.'/selections', ['keys' => $keys]);
self::forget($pool);
return $data['selections'];
}
public static function forArticle(string $pool, string $slug): string
{
return self::assign($pool, [$slug])[$slug]['url'];
}
public static function thumbnail(array $article, ?string $original): ?string
{
$pool = config('illustrations.categories.'.($article['iCategoryId'] ?? ''));
if (!$pool || empty($article['sSlug'])) return $original;
if (LocalIllustrations::enabled()) {
$url = app(LocalIllustrations::class)->thumbnail($pool, $article['sSlug']);
return $url ? url($url) : null;
}
if (!self::enabled()) return $original;
try {
$snapshot = self::snapshot($pool);
$reason = $snapshot['unavailable'][$article['sSlug']] ?? null;
if ($reason) {
// Repair accidental physical loss, never override deliberate publication/access withdrawal.
if (in_array($reason, ['file_missing', 'file_corrupt', 'file_symlink'], true)) {
try { return self::forArticle($pool, $article['sSlug']); }
catch (\Throwable $e) { return null; }
}
return null;
}
return $snapshot['selections'][$article['sSlug']]['url'] ?? $original;
} catch (\Throwable $e) {
// A failed resource service must not invent or reassign an article's image.
return $original;
}
}
}
-198
View File
@@ -1,198 +0,0 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
/** Public, content-addressed display copies. Network and hash work only runs on writes/sync. */
final class LocalIllustrations
{
private ?array $manifest = null;
public static function enabled(): bool
{
return (bool) config('illustrations.local_enabled');
}
private function read(): array
{
if ($this->manifest !== null) return $this->manifest;
$path = config('illustrations.local_manifest');
try {
$value = is_file($path) && ! is_link($path) ? json_decode(file_get_contents($path), true, 512, JSON_THROW_ON_ERROR) : [];
return $this->manifest = ($value['version'] ?? null) === 1 ? $value : ['version' => 1, 'assets' => [], 'selections' => []];
} catch (\Throwable) {
// Public requests never fetch Resource, hash files or repair a missing manifest.
return $this->manifest = ['version' => 1, 'assets' => [], 'selections' => []];
}
}
public function thumbnail(string $pool, string $slug): ?string
{
$state = $this->read();
$id = $state['selections'][$pool][$slug] ?? null;
$url = $id ? ($state['assets'][$id]['url'] ?? null) : null;
return is_string($url) && preg_match('~\A'.preg_quote(config('illustrations.local_url_prefix'), '~').'/[a-f0-9]{64}\.(?:webp|png|jpg|gif)\z~D', $url) ? $url : null;
}
private function locked(callable $callback): mixed
{
$dir = dirname(config('illustrations.local_manifest'));
if (! is_dir($dir) && ! mkdir($dir, 0700, true) && ! is_dir($dir)) throw new \RuntimeException('Local illustration state directory unavailable');
if (is_link($dir)) throw new \RuntimeException('Local illustration state must not be a symlink');
$lock = fopen($dir.'/state.lock', 'c');
if (! $lock || ! flock($lock, LOCK_EX)) throw new \RuntimeException('Local illustration lock unavailable');
try {
$this->manifest = null;
return $callback();
} finally {
flock($lock, LOCK_UN);
fclose($lock);
}
}
private function save(array $state): void
{
$state['version'] = 1;
$state['updated_at'] = gmdate('c');
$path = config('illustrations.local_manifest');
$tmp = tempnam(dirname($path), '.manifest-');
try {
chmod($tmp, 0600);
$bytes = json_encode($state, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
if (file_put_contents($tmp, $bytes) !== strlen($bytes) || ! rename($tmp, $path)) throw new \RuntimeException('Local illustration manifest update failed');
$this->manifest = $state;
} finally {
if (is_file($tmp)) unlink($tmp);
}
}
private function copy(array $image, array $assets): array
{
$id = $image['asset_id'] ?? '';
$source = $image['url'] ?? '';
$base = rtrim(config('illustrations.base_url'), '/');
if (! preg_match('/\A[a-f0-9-]{36}\z/D', $id) || ! preg_match('~\A'.preg_quote($base, '~').'/media/[a-f0-9-]{36}\z~D', $source)) throw new \RuntimeException('Unregistered illustration source');
$meta = $assets[$id] ?? IllustrationPool::assetMetadata($id);
$sha = $meta['sha256'] ?? '';
$mime = $meta['mime'] ?? '';
$ext = ['image/webp' => 'webp', 'image/png' => 'png', 'image/jpeg' => 'jpg', 'image/gif' => 'gif'][$mime] ?? null;
$size = (int) ($meta['bytes'] ?? 0);
if (! $ext || ! preg_match('/\A[a-f0-9]{64}\z/D', $sha) || $size < 1 || $size > 20971520) throw new \RuntimeException('Invalid illustration metadata');
$dir = config('illustrations.local_directory');
if (is_link($dir) || (! is_dir($dir) && ! mkdir($dir, 0755, true) && ! is_dir($dir))) throw new \RuntimeException('Local illustration directory unavailable');
$path = $dir.'/'.$sha.'.'.$ext;
if (is_link($path)) throw new \RuntimeException('Local illustration file must not be a symlink');
if (! is_file($path) || filesize($path) !== $size || ! hash_equals($sha, hash_file('sha256', $path))) {
$tmp = tempnam(dirname(config('illustrations.local_manifest')), '.image-');
$out = null;
$stream = null;
try {
$response = Http::withOptions(['proxy' => '', 'allow_redirects' => false, 'stream' => true])->withUserAgent('FNA-V3/LocalIllustrations')->connectTimeout(3)->timeout(30)->get($source);
if (! $response->successful()) throw new \RuntimeException('Illustration download failed');
$stream = $response->toPsrResponse()->getBody();
$out = fopen($tmp, 'wb');
$bytes = 0;
$hash = hash_init('sha256');
while (! $stream->eof()) {
$chunk = $stream->read(65536);
$bytes += strlen($chunk);
if ($bytes > 20971520 || fwrite($out, $chunk) !== strlen($chunk)) throw new \RuntimeException('Invalid illustration download size');
hash_update($hash, $chunk);
}
fclose($out);$out = null;
$info = @getimagesize($tmp);
if ($bytes !== $size || ! hash_equals($sha, hash_final($hash)) || ! $info || ($info['mime'] ?? '') !== $mime || $info[0] * $info[1] > 10000000) throw new \RuntimeException('Illustration download integrity failed');
chmod($tmp, 0644);
if (! rename($tmp, $path)) throw new \RuntimeException('Local illustration publication failed');
} finally {
if (is_resource($out)) fclose($out);
if ($stream) $stream->close();
if (is_file($tmp)) unlink($tmp);
}
}
return ['asset_id' => $id, 'sha256' => $sha, 'mime' => $mime, 'bytes' => $size,
'url' => config('illustrations.local_url_prefix').'/'.$sha.'.'.$ext, 'source_url' => $source];
}
/** Delivery intake copies only approved batch assets; it does not reconcile existing articles. */
public function cacheDeliveryAssets(array $images): void
{
$this->locked(function () use ($images) {
$state = $this->read();
foreach ($images as $image) {
$state['assets'][$image['asset_id']] = $this->copy($image, $state['assets']);
}
$this->save($state);
});
}
public function storeSelection(string $pool, string $slug, array $image): string
{
return $this->locked(function () use ($pool, $slug, $image) {
$state = $this->read();
$asset = $this->copy($image, $state['assets']);
$state['assets'][$image['asset_id']] = $asset;
$state['selections'][$pool][$slug] = $image['asset_id'];
$this->save($state);
return $asset['url'];
});
}
/** One atomic manifest switch after all downloadable files pass verification. */
public function selectionBaseline(): array
{
$this->manifest = null;
return $this->read()['selections'];
}
public function synchronize(array $snapshots, ?array $baseline = null): array
{
$baseline ??= $this->selectionBaseline();
return $this->locked(function () use ($snapshots, $baseline) {
$state = $this->read();
$pending = [];
foreach ($snapshots as $pool => $snapshot) {
$available = [];
foreach (array_merge($snapshot['items'], array_values($snapshot['selections'])) as $image) {
$id = $image['asset_id'];
if (isset($available[$id])) continue;
$state['assets'][$id] = $this->copy($image, $state['assets']);
$available[$id] = true;
}
// Published FNA copies are independent of the source lifecycle.
// A deleted source reference must not silently remove a local assignment.
$selections = $state['selections'][$pool] ?? [];
foreach ($snapshot['selections'] as $slug => $image) $selections[$slug] = $image['asset_id'];
foreach ($snapshot['unavailable'] ?? [] as $slug => $reason) {
$id = $state['selections'][$pool][$slug] ?? null;
$old = $id ? ($state['assets'][$id] ?? null) : null;
$local = $old ? config('illustrations.local_directory').'/'.basename($old['url']) : null;
// Source deletion, disabling or withdrawal never revokes an FNA copy.
if ($local && is_file($local) && ! is_link($local) && hash_equals($old['sha256'], hash_file('sha256', $local))) {
$selections[$slug] = $id;
} else {
// Report missing/corrupt local bytes without destroying recovery metadata.
$selections[$slug] = $id;
$pending[$pool.':'.$slug] = $reason;
}
}
// Receivers may publish new mappings while the remote snapshot is in flight.
// Never replace a local change made after this sync's baseline was captured.
$current = $state['selections'][$pool] ?? [];
$before = $baseline[$pool] ?? [];
foreach (array_unique(array_merge(array_keys($before), array_keys($current))) as $slug) {
$exists = array_key_exists($slug, $current);
if ($exists !== array_key_exists($slug, $before) || ($current[$slug] ?? null) !== ($before[$slug] ?? null)) {
if ($exists) $selections[$slug] = $current[$slug];
else unset($selections[$slug]);
unset($pending[$pool.':'.$slug]);
}
}
$state['selections'][$pool] = $selections;
}
$this->save($state);
return ['assets' => count($state['assets']), 'selections' => array_map('count', $state['selections']), 'pending' => $pending];
});
}
}
-59
View File
@@ -1,59 +0,0 @@
<?php
namespace App\Services;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
final class OneYearArticleLikes
{
/** Each article owns its progress; retries and overlapping workers cannot pay twice. */
public function sync(): int
{
$total = 0;
DB::table('articles')->where('iStatus', 1)
->whereColumn('iYearLikeTarget', '>', 'iYearLikeAdded')
->select('id')->chunkById(100, function ($articles) use (&$total) {
foreach ($articles as $article) {
$total += $this->syncArticle($article->id);
}
});
return $total;
}
public function syncArticle(int $id): int
{
return DB::transaction(function () use ($id) {
$article = DB::table('articles')->where('id', $id)->lockForUpdate()->first();
if (! $article || (int) $article->iStatus !== 1
|| $article->iYearLikeTarget <= $article->iYearLikeAdded) {
return 0;
}
$now = CarbonImmutable::now();
if (! $article->sYearLikeStartedAt) {
DB::table('articles')->where('id', $id)->update(['sYearLikeStartedAt' => $now]);
return 0;
}
$start = CarbonImmutable::parse($article->sYearLikeStartedAt);
$end = $start->addYearNoOverflow();
$duration = $end->getTimestamp() - $start->getTimestamp();
$elapsed = max(0, min($duration, $now->getTimestamp() - $start->getTimestamp()));
$due = intdiv((int) $article->iYearLikeTarget * $elapsed, $duration);
$add = max(0, $due - (int) $article->iYearLikeAdded);
if ($add > 0) {
// Query-builder arithmetic preserves real/other automatic likes and content timestamps.
DB::table('articles')->where('id', $id)->update([
'iLikeCount' => DB::raw('iLikeCount + '.$add),
'iYearLikeAdded' => DB::raw('iYearLikeAdded + '.$add),
'sLastLikedAt' => $now,
]);
}
return $add;
}, 3);
}
}
@@ -1,19 +0,0 @@
<?php
namespace App\Services;
final class ResourceArticlePresentation
{
/** Remove legacy follow prompts only from the two daily resource columns. */
public static function body(string $html, ?string $category): string
{
if (! in_array($category, ['freenode', 'shadowrocketids'], true)) return $html;
return preg_replace_callback('~<p\b[^>]*>.*?</p>(?:\s*<p\b[^>]*>\s*</p>)*~si', static function (array $match): string {
$text = html_entity_decode(strip_tags($match[0]), ENT_QUOTES | ENT_HTML5, 'UTF-8');
$text = preg_replace('/\s+/u', '', $text);
if (preg_match('/点击加入我们的(?:tg|telegram)频道|点击关注我们的github仓库/iu', $text)) return '';
return $match[0];
}, $html);
}
}
-24
View File
@@ -1,24 +0,0 @@
<?php
namespace App\Services;
use App\Models\Articles;
final class ResourcePublication
{
public static function usable(Articles $article): bool
{
if (in_array($article->sResourceStatus, ['failed','empty'], true)) return false;
// Legacy explicit zero is evidence of no result, not a successful refresh.
return !preg_match('/(?:共|更新)\s*0\s*个可用节点/u', Seo::text($article->sTitleSub));
}
public static function validate(array $article): array
{
validator($article, ['title'=>'required|string|max:250','title_sub'=>'present|string|max:4000',
'content'=>'required|string|max:2000000','tags'=>'present|array','7like'=>'nullable|integer|min:0',
'check_status'=>'nullable|in:success,failed,unknown','valid_count'=>'nullable|integer|min:0'])->validate();
$count = isset($article['valid_count']) ? (int)$article['valid_count'] : null;
$state = $article['check_status'] ?? 'unknown';
// Compatibility for the current upstream; a reported count is not a new live check.
if ($count === null && preg_match('/(?:共|更新)\s*(\d+)\s*个可用节点/u', Seo::text($article['title_sub']), $m)) $count = (int)$m[1];
abort_if($state === 'failed' || $count === 0 || trim(Seo::text($article['content'])) === '', 422, 'Resource update has no usable result; previous publication retained');
return ['sResourceStatus'=>$state === 'success' && $count > 0 ? 'success' : 'unknown','iResourceCount'=>$count];
}
}
-110
View File
@@ -1,110 +0,0 @@
<?php
namespace App\Services;
use App\Models\Articles;
use App\Models\Categories;
use Carbon\Carbon;
use Illuminate\Http\Request;
/** One URL, visibility and indexing contract for HTML, sitemap and notifications. */
final class Seo
{
public static function url(string $path = '/', int $page = 1): string
{
return rtrim(config('app.url'), '/').'/'.ltrim($path, '/').($page > 1 ? '?page='.$page : '');
}
public static function articleUrl(Articles $article): string { return self::url('/a/'.$article->sSlug.'.html'); }
public static function categoryPath(Categories $category): string
{
return ($category->oParent ? '/'.$category->oParent->sSlug : '').'/'.$category->sSlug;
}
public static function categoryName(Categories $category): string
{
return match ($category->sSlug) { 'andorid' => 'Android', 'ios' => 'iOS', default => $category->sName };
}
public static function text(?string $html, int $limit = 200): string
{
$text = html_entity_decode(strip_tags($html ?? ''), ENT_QUOTES | ENT_HTML5, 'UTF-8');
return mb_substr(trim(preg_replace('/\s+/u', ' ', $text)), 0, $limit);
}
public static function imageSize(?string $url): array
{
$path = parse_url($url ?? '', PHP_URL_PATH);
if (!$path || str_contains($path,'..') || !str_starts_with($path,'/')) return [];
if (parse_url($url,PHP_URL_HOST) && parse_url($url,PHP_URL_HOST) !== parse_url(config('app.url'),PHP_URL_HOST)) return [];
$file = public_path(ltrim($path,'/'));
if (!is_file($file)) return [];
$size = @getimagesize($file);
return $size ? ['width'=>$size[0],'height'=>$size[1]] : [];
}
public static function body(string $html): string
{
// Preserve editorial HTML byte-for-byte except confirmed commercial links.
return preg_replace_callback('~<a\b[^>]*>~i', function($match) {
$tag = $match[0];
if (!preg_match('~\bhref\s*=\s*([\x22\x27])(.*?)\1~i',$tag,$href)) return $tag;
$host = parse_url(html_entity_decode($href[2],ENT_QUOTES),PHP_URL_HOST);
if (!in_array($host,['fuuu.cloud','xn--123-9i9dj97q.com','hardnerd.net'],true)) return $tag;
$tokens = ['sponsored','noopener'];
if (preg_match('~\brel\s*=\s*([\x22\x27])(.*?)\1~i',$tag,$rel)) {
$tokens = array_unique(array_merge(preg_split('/\s+/',trim($rel[2])),$tokens));
return str_replace($rel[0],'rel="'.implode(' ',$tokens).'"',$tag);
}
return substr($tag,0,-1).' rel="'.implode(' ',$tokens).'">';
}, $html);
}
public static function public(Articles $a): bool
{
return (int)$a->iStatus === 1 && $a->created_at && !$a->created_at->isFuture()
&& $a->oCategory && (int)$a->oCategory->iStatus === 1
&& (!$a->oCategory->iParentId || ($a->oCategory->oParent && (int)$a->oCategory->oParent->iStatus === 1));
}
public static function indexable(Articles $a): bool
{
if (!self::public($a) || in_array($a->sSeoPolicy, ['archive','noindex'], true)) return false;
if ($a->sSeoPolicy === 'index') return true;
// Legacy records retain their existing age policy; tutorials never inherit it.
if (!in_array($a->oCategory->sSlug, ['freenode','shadowrocketids'])) return true;
$days = (int)($a->oCategory->aOpt['noindexday'] ?? 0);
return $days <= 0 || !$a->created_at->copy()->addDays($days)->isPast();
}
public static function modified(Articles $a): ?string
{
return $a->sContentUpdatedAt ? Carbon::parse($a->sContentUpdatedAt)->toAtomString() : null;
}
public static function page(Request $r): int
{
$raw = $r->query('page', '1');
$keys = array_filter(explode('&', $r->server('QUERY_STRING', '')), fn($p) => urldecode(explode('=', $p, 2)[0]) === 'page');
abort_if(count($keys) > 1 || !is_scalar($raw) || !preg_match('/\A[1-9][0-9]{0,5}\z/', (string)$raw), 404);
return (int)$raw;
}
public static function articleMeta(Articles $a, bool $home = false): array
{
$canonical = $home ? self::url() : self::articleUrl($a);
$title = $home ? config('seo.home_title') : self::text($a->sTitle, 250);
$description = $home ? config('seo.home_description') : self::text($a->sTitleSub ?: $a->sContent);
$schema = [['@context'=>'https://schema.org', '@type'=>$home ? 'WebSite' : 'Article',
'name'=>$home ? config('seo.brand') : $title, 'url'=>$canonical]];
if (!$home) {
$schema[0] += ['headline'=>$title,'mainEntityOfPage'=>$canonical,'datePublished'=>$a->created_at->toAtomString(),
'author'=>['@type'=>'Organization','name'=>config('seo.brand'),'url'=>self::url()]];
if ($modified = self::modified($a)) $schema[0]['dateModified'] = $modified;
if ($a->sThumb) $schema[0]['image'] = str_starts_with($a->sThumb, '/') ? self::url($a->sThumb) : $a->sThumb;
$crumbs = [['name'=>'首页','item'=>self::url()]];
if ($a->oCategory->oParent) $crumbs[] = ['name'=>self::categoryName($a->oCategory->oParent),'item'=>self::url(self::categoryPath($a->oCategory->oParent))];
$crumbs[] = ['name'=>self::categoryName($a->oCategory),'item'=>self::url(self::categoryPath($a->oCategory))];
$crumbs[] = ['name'=>$title,'item'=>$canonical];
$schema[] = ['@context'=>'https://schema.org','@type'=>'BreadcrumbList','itemListElement'=>array_map(fn($c,$i)=>['@type'=>'ListItem','position'=>$i+1]+$c,$crumbs,array_keys($crumbs))];
}
return ['title'=>$title.' - '.config('seo.brand'),'heading'=>$title,'description'=>$description,'canonical'=>$canonical,
'robots'=>$home || self::indexable($a) ? 'index, follow' : 'noindex, follow','type'=>$home ? 'website' : 'article','schema'=>$schema];
}
public static function listMeta(string $heading, string $description, string $path, int $page, bool $index = true): array
{
$url = self::url($path, $page);
return ['heading'=>$heading, 'title'=>$heading.($page>1?' · 第'.$page.'页':'').' - '.config('seo.brand'),
'description'=>self::text($description), 'canonical'=>$url, 'robots'=>$index?'index, follow':'noindex, follow',
'schema'=>[['@context'=>'https://schema.org','@type'=>'CollectionPage','name'=>$heading,'url'=>$url]]];
}
}
-54
View File
@@ -1,54 +0,0 @@
<?php
namespace App\Services;
use App\Models\Articles;
use App\Services\Editorial\IndexNowNotification;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
final class SeoNotifications
{
public function changed(Articles $a, bool $deleted = false): void
{
if (!Schema::hasTable('seo_notifications')) return;
$urls = [];
if ($deleted || !Seo::public($a)) $urls[] = Seo::articleUrl($a);
elseif (Seo::indexable($a)) $urls[] = Seo::articleUrl($a);
if ($a->oCategory?->sSlug === 'freenode') $urls[] = Seo::url();
if ($a->oCategory) $urls[] = Seo::url(Seo::categoryPath($a->oCategory));
$event = $deleted || !Seo::public($a) ? 'delete' : 'update';
$key = hash('sha256',json_encode([$a->id,$event,$a->sContentUpdatedAt,$a->sTitle,$a->sContent,$a->sThumb,$a->iStatus]));
$this->enqueue($key,$urls,$event);
}
public function enqueue(string $key, array $urls, string $event = 'update'): void
{
if (!app()->environment(['production','testing']) || !config('editorial.indexnow_enabled',app()->environment('production'))) return;
DB::table('seo_notifications')->insertOrIgnore(['event_key'=>$key,'urls'=>json_encode(array_values(array_unique($urls))),
'event'=>$event,'state'=>json_encode(['status'=>'pending','attempts'=>0]),'created_at'=>now(),'updated_at'=>now()]);
}
public function retry(int $limit = 10): int
{
$processed = 0;
foreach (DB::table('seo_notifications')->orderBy('id')->cursor() as $candidate) {
$s = json_decode($candidate->state,true);
if (($s['status'] ?? '') !== 'pending' || ($s['next_attempt_at'] ?? 0) > now()->timestamp) continue;
DB::transaction(function () use ($candidate,&$processed) {
$row = DB::table('seo_notifications')->where('id',$candidate->id)->lockForUpdate()->first();
$state = json_decode($row->state,true);
if (($state['status'] ?? '') !== 'pending' || ($state['next_attempt_at'] ?? 0) > now()->timestamp) return;
$urls = json_decode($row->urls,true);
if ($row->event !== 'delete') $urls = array_values(array_filter($urls,function($url) {
$path = parse_url($url,PHP_URL_PATH);
if (preg_match('~^/a/([a-zA-Z0-9_-]+)\.html$~',$path,$m)) {
$a = Articles::where('sSlug',$m[1])->first(); return $a && Seo::indexable($a);
}
if ($path === '/') return app(ArticlesService::class)->getLatestFreeNodeSlug() !== null;
return true;
}));
$state = app(IndexNowNotification::class)->submit($state,$urls);
DB::table('seo_notifications')->where('id',$row->id)->update(['state'=>json_encode($state),'updated_at'=>now()]);
$processed++;
});
if ($processed >= $limit) break;
}
return $processed;
}
}
-12
View File
@@ -1,12 +0,0 @@
<?php
namespace App\Services;
final class ShadowrocketNaming
{
public static function align(string $text): string
{
$text = str_replace(['免费苹果账号', '免费苹果ID', '免费苹果id', '(小火箭账号、shadowrocket id)'], ['免费小火箭ID', '免费小火箭ID', '免费小火箭ID', ''], $text);
return str_replace('免费小火箭ID,可用于使用小火箭(shadowrocket)', '免费Appale ID,已购买小火箭(shadowrocket)', $text);
}
}
+22 -44
View File
@@ -107,7 +107,7 @@ public static function fail(string $sChatCode = 'admin'): self
// new
public static function notify(string $sChatCode = 'admin'): self
{
return self::start("fail", $sChatCode);
return self::start("notification", $sChatCode);
}
@@ -275,51 +275,29 @@ private function _send_master(): Flow
$aData = $this->buildDataTom();
if ($this->enableSlaveQueue) {
$oFlow = ServiceHttpQueue::start("telegram_master")->arg($aData)->save();
} else {
$oFlow = Flow::start("_send_master");
$sUrlMaSterBase = $_ENV["url_master_base"] ?? "";
if (!$sUrlMaSterBase) {
throw new \Exception("未设置env的url_master_base");
}
$sUrlMasterPost = "https://".$sUrlMaSterBase."/api/telegram/post";
try {
$oHttpV2 = HttpV2::make($sUrlMasterPost);
if ($this->enableAsync) {
$oHttpV2 = $oHttpV2->enableAsync();
}
$r = $oHttpV2->enableJsonAs()->setData($aData)->send();
if ($this->enableAsync) {
return $oFlow->sData("async")->done("async");
} else {
$a = json_decode($r, true);
$isDone = $a["isDone"] ?? false;
if ($isDone) {
return $oFlow->done();
} else {
return $oFlow->fail($r);
}
}
} catch (\Throwable $e) {
$oFlow = $oFlow->fail($e->getMessage());
}
return ServiceHttpQueue::start("telegram_master")->arg($aData)->save();
}
$flow = Flow::start("operations notification");
try {
$root = dirname(__DIR__, 4);
require_once $root . '/ops/AdminNotice.php';
$this->operationsEventKey ??= bin2hex(random_bytes(16));
$receipts = \LegacyOperations\AdminNotice::submit($root, $aData, $this->operationsEventKey);
return $flow->done('TeleHub accepted ' . implode(',', $receipts));
} catch (\Throwable $error) {
return $flow->fail($error->getMessage());
}
return $oFlow;
}
// 直接从本地发到tg,几乎用不上,都走master了
private ?string $operationsEventKey = null;
public function forOperationsQueueRow(int $id): self
{
$this->operationsEventKey = 'queue.' . $id;
return $this;
}
private function _send_local(): Flow
{
if ($this->enableSlaveQueue) {
Regular → Executable
-1
View File
@@ -12,7 +12,6 @@
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->append(\App\Http\Middleware\SeoHeaders::class);
$middleware->prepend(\Spatie\ResponseCache\Middlewares\CacheResponse::class);
$middleware->alias([
'doCache' => \Spatie\ResponseCache\Middlewares\CacheResponse::class,
-16
View File
@@ -1,16 +0,0 @@
<?php
return [
'dpl' => [
'enabled' => env('DPL_AD_ENABLED', true),
'url' => 'https://dp-link.net/',
],
'hn' => [
'enabled' => env('HN_AD_ENABLED', true),
'url' => env('HN_AD_URL', env('APP_ENV', 'production') === 'local' ? 'http://hn.loc/' : 'https://hardnerd.net/'),
],
'fuc' => [
'enabled' => env('FUC_AD_ENABLED', true),
'url' => env('FUC_AD_URL', 'https://xn--123-9i9dj97q.com/'),
],
];
-33
View File
@@ -1,33 +0,0 @@
<?php
return [
'enabled' => env('AIRPORT_RECOMMENDATIONS_ENABLED', true),
'anchor' => 'airport-recommendations',
// User-supplied commercial copy. Edit here once, then clear config/response caches.
'providers' => [
'fuc' => [
'enabled' => true, 'order' => 10, 'name' => '福云', 'tagline' => '日常之选',
'url' => env('AIRPORT_FUC_URL', 'https://xn--123-9i9dj97q.com/'),
'price' => '18', 'period' => '元 / 月',
'features' => ['流媒体解锁', 'AI 解锁'],
'description' => '老牌机场,套餐性价比高,适合日常娱乐办公',
'coupon' => 'clashfreenode.com', 'discount' => '9 折',
],
'dpl' => [
'enabled' => true, 'order' => 20, 'name' => 'DP-LINK.NET', 'tagline' => '专线服务',
'url' => env('AIRPORT_DPL_URL', 'https://dp-link.net/'),
'price' => '26', 'period' => '元 / 月',
'features' => ['流媒体解锁', 'AI 解锁'],
'description' => '专线机场,适合对网络质量有要求的用户',
'coupon' => 'clashfreenode.com', 'discount' => '9 折',
],
'hn' => [
'enabled' => true, 'order' => 30, 'name' => 'hardnerd', 'tagline' => '灵活套餐',
'url' => env('AIRPORT_HN_URL', 'https://hardnerd.net/'),
'price' => '28', 'period' => '元 / 月',
'features' => ['流媒体解锁', 'AI 解锁'],
'description' => '专线机场,适合对网络质量有要求的用户,有一次性套餐',
'coupon' => 'clashfreenode.com', 'discount' => '9 折',
],
],
];
-25
View File
@@ -1,25 +0,0 @@
<?php
// 新文章自动点赞默认值。整数表示固定值,[最小值, 最大值]表示随机整数(含两端);0表示关闭。
// seven_day:前7天的增长额度;yearly:持续年度概率参数;one_year:一年内一次性额外额度。
// 修改只影响之后新建的文章;编辑旧文章、重试草稿不会重置。本文件覆盖上游/API传值,0也优先。
return [
'beginner' => [ // 新手教程及其平台子栏目
'seven_day' => [1, 18], 'yearly' => 50, 'one_year' => [50, 150],
],
'comprehensive' => [ // 综合教程
'seven_day' => [1, 15], 'yearly' => 30, 'one_year' => [20, 80],
],
'editorial_other' => [ // 文章API创建的其他栏目
'seven_day' => [1, 15], 'yearly' => 30, 'one_year' => [20, 80],
],
'freenode' => [ // 免费节点;忽略上游自动点赞值
'seven_day' => [3, 32], 'yearly' => 0, 'one_year' => 0,
],
'shadowrocketids' => [ // 小火箭ID;忽略上游自动点赞值
'seven_day' => [1, 12], 'yearly' => 0, 'one_year' => 0,
],
'legacy_other' => [ // 旧通用接收接口;同样由本站配置决定
'seven_day' => 0, 'yearly' => 0, 'one_year' => 0,
],
];
-5
View File
@@ -1,5 +0,0 @@
<?php
return [
'telegram_url' => env('COMMUNITY_TELEGRAM_URL', 'https://t.me/clashfreenode'),
];
-11
View File
@@ -1,11 +0,0 @@
<?php
return [
'enabled' => env('EDITORIAL_API_ENABLED', env('APP_ENV') === 'local'),
'base_url' => env('EDITORIAL_BASE_URL', env('APP_ENV') === 'local' ? 'http://fna-v3.loc' : env('APP_URL')),
'credential_file' => storage_path('app/private/editorial/credential.json'),
'preview_minutes' => 30,
'max_batch' => 10,
'search_index' => env('EDITORIAL_SEARCH_INDEX', env('APP_ENV') === 'local' ? 'fna_v3_articles' : null),
'indexnow_enabled' => env('EDITORIAL_INDEXNOW_ENABLED', env('APP_ENV') === 'production'),
];
-13
View File
@@ -1,13 +0,0 @@
<?php
return [
'delivery_enabled' => (bool) env('ILLUSTRATION_DELIVERY_ENABLED', false),
'enabled' => (bool) env('RESOURCE_V2_ILLUSTRATIONS_ENABLED', env('LOCAL_ILLUSTRATIONS_ENABLED', env('APP_ENV') === 'local')),
'base_url' => env('RESOURCE_V2_URL', 'http://resource.loc:8612'),
'credential_file' => env('RESOURCE_V2_CREDENTIAL_FILE'),
'local_enabled' => (bool) env('LOCAL_ILLUSTRATIONS_MIRROR_ENABLED', false),
'local_directory' => public_path('images/illustrations'),
'local_manifest' => storage_path('app/private/illustrations/manifest.json'),
'local_url_prefix' => '/images/illustrations',
'categories' => [1 => 'freenode', 9 => 'shadowrocketids'],
];
+1 -1
View File
@@ -13,7 +13,7 @@
* You can provide your own class given that it implements the
* CacheProfile interface.
*/
'cache_profile' => App\Services\ArticleResponseCacheProfile::class,
'cache_profile' => Spatie\ResponseCache\CacheProfiles\CacheAllSuccessfulGetRequests::class,
// 'cache_profile' => Spatie\ResponseCache\CacheProfiles\CacheAllRequests::class,
// 'cache_profile' => \App\Support\CustomCacheProfile::class,
//'cache_profile' => \App\Support\BrutalCacheProfile::class,
-7
View File
@@ -1,7 +0,0 @@
<?php
return [
'brand' => env('SEO_BRAND', env('site_code_short') === 'cfn' ? 'ClashFreeNode' : env('APP_NAME', '网站')),
'home_title' => env('SEO_HOME_TITLE', '免费节点与订阅使用指南'),
'home_description' => '获取最近更新的免费节点与订阅,查看 Clash、V2ray 客户端新手教程和连接排错指南。资源状态随时间和网络环境变化。',
'page_size' => env('page_limit', 10),
];
-15
View File
@@ -1,15 +0,0 @@
<?php
return [
'guide_slug' => 'getting-started',
'beginner_slug' => 'client',
'beginner_name' => '新手教程',
// Dedicated platform mastheads; the /client overview intentionally has none.
'category_banners' => [
'windows' => ['image' => '/images/tutorial-categories/windows-paper-banner.jpg', 'title' => 'Windows'],
'mac' => ['image' => '/images/tutorial-categories/mac-paper-banner.jpg', 'title' => 'Mac'],
'andorid' => ['image' => '/images/tutorial-categories/android-paper-banner.jpg', 'title' => 'Android'],
'ios' => ['image' => '/images/tutorial-categories/ios-paper-banner.jpg', 'title' => 'iPhone / iPad'],
'linux' => ['image' => '/images/tutorial-categories/linux-paper-banner.jpg', 'title' => 'Linux'],
],
];
@@ -1,57 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('editorial_documents', function (Blueprint $t) {
$t->string('content_key', 100)->primary();
$t->unsignedBigInteger('article_id')->nullable()->unique();
$t->unsignedInteger('revision')->default(0);
$t->unsignedInteger('published_revision')->nullable();
$t->timestamps();
});
Schema::create('editorial_drafts', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->string('payload_hash', 64);
$t->longText('items');
$t->string('status', 20)->default('draft');
$t->uuid('publication_id')->nullable();
$t->timestamps();
});
Schema::create('editorial_versions', function (Blueprint $t) {
$t->id();
$t->string('content_key', 100);
$t->unsignedInteger('revision');
$t->longText('snapshot');
$t->timestamp('created_at');
$t->unique(['content_key', 'revision']);
});
Schema::create('editorial_publications', function (Blueprint $t) {
$t->uuid('id')->primary();
$t->uuid('draft_id')->unique();
$t->string('payload_hash', 64);
$t->longText('receipt');
$t->longText('effects')->nullable();
$t->timestamps();
});
Schema::create('editorial_assets', function (Blueprint $t) {
$t->string('sha256', 64)->primary();
$t->string('extension', 5);
$t->string('mime', 40);
$t->unsignedInteger('bytes');
$t->timestamp('created_at');
});
}
public function down(): void
{
foreach (['editorial_assets', 'editorial_publications', 'editorial_versions', 'editorial_drafts', 'editorial_documents'] as $table) {
Schema::dropIfExists($table);
}
}
};
@@ -1,24 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('articles', function (Blueprint $table) {
$table->unsignedInteger('iYearLikeTarget')->default(0);
$table->unsignedInteger('iYearLikeAdded')->default(0);
$table->timestamp('sYearLikeStartedAt')->nullable();
});
}
public function down(): void
{
Schema::table('articles', fn (Blueprint $table) => $table->dropColumn([
'iYearLikeTarget', 'iYearLikeAdded', 'sYearLikeStartedAt',
]));
}
};
@@ -1,18 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('articles', fn (Blueprint $table) => $table->timestamp('sDisplayPublishedAt')->nullable());
}
public function down(): void
{
Schema::table('articles', fn (Blueprint $table) => $table->dropColumn('sDisplayPublishedAt'));
}
};
@@ -1,22 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void {
Schema::table('articles', function (Blueprint $t) {
$t->timestamp('sContentUpdatedAt')->nullable();
$t->string('sSeoPolicy', 24)->nullable();
$t->string('sResourceStatus', 24)->nullable();
$t->unsignedInteger('iResourceCount')->nullable();
});
Schema::create('seo_notifications', function (Blueprint $t) {
$t->id(); $t->string('event_key', 64)->unique(); $t->text('urls');
$t->string('event', 16); $t->text('state'); $t->timestamps();
});
}
public function down(): void {
Schema::dropIfExists('seo_notifications');
Schema::table('articles', fn (Blueprint $t) => $t->dropColumn(['sContentUpdatedAt','sSeoPolicy','sResourceStatus','iResourceCount']));
}
};
-13
View File
@@ -1,13 +0,0 @@
[Unit]
Description=Process approved illustration deliveries (fna)
After=network-online.target
[Service]
Type=oneshot
User=nginx
Group=nginx
WorkingDirectory=/www/wwwroot/clashfreenode-new.com
ExecStart=/usr/bin/php -d memory_limit=512M artisan illustrations:sync-deliveries --no-interaction
TimeoutStartSec=300
UMask=0022
NoNewPrivileges=true
PrivateTmp=true
-8
View File
@@ -1,8 +0,0 @@
[Unit]
Description=Poll approved illustration deliveries (fna)
[Timer]
OnBootSec=60
OnUnitInactiveSec=60
Persistent=true
[Install]
WantedBy=timers.target
@@ -1,5 +0,0 @@
# 2026-10-31矮版广告素材
李响制作、用户确认的三张最终素材及完整提示词。正式展示只使用assets.json登记的最终PNG;本地中间迭代图不作为生产候选。
固定广告位3.675:1、cover取景,福云center 40%。每次打开随机选一张,候选在template中,活动DOM只加载选中的一张;没有新增接口或轮播。原旧图保留用于恢复,不在同页叠加。
@@ -1,20 +0,0 @@
{
"dpl": {
"path": "public/images/ads/dpl-ad-compact-wordmark-20261031.png",
"width": 2169,
"height": 725,
"sha256": "c0742c8f7102ea2ebb70feea5caa9113ef032df54e2ab9d9097d797a5a12e92b"
},
"hn": {
"path": "public/images/ads/hn-ad-compact-HardNerd-20261031.png",
"width": 2020,
"height": 778,
"sha256": "54372d16b924fa8e99dbae96e9f7fd8ef3d17f11879505024d897df8d57ffb7b"
},
"fuc": {
"path": "public/images/ads/fuc-ad-compact-five-years-20261031.png",
"width": 2141,
"height": 734,
"sha256": "48e26721e3d05f9e7ebedf8e08d182aad2b0f5f8e656f2d8a09122053692f045"
}
}
@@ -1 +0,0 @@
Use case: ads-marketing, identity-preserving redesign. Reference image: existing approved DPL advertisement, brand identity/style reference only. Create a NEW COMPOSITION for an EXTRA WIDE SHORT horizontal banner, exact target 1962x534 pixels, aspect ratio 3.674:1. This is NOT a smaller copy of the tall original and NOT original art centered with empty side gutters. Design natively to fill every edge of this short wide canvas. Preserve exact blue rounded DPL mark with white layered signal lines and DPL letters, dark navy blue grid background, blue/purple cyan gradient headline, subtle orbital network globe. Redesign layout: small DPL brand upper left, readable medium large headline below and a restrained short supporting line, compact blue CTA integrated lower left. Right half: simplified three slim floating network region cards with tiny flags and bars, arranged laterally in a shallow diagonal, not vertically stacked tall. Text EXACT: "DPL", "畅连全球网络", "日常访问 · 远程办公 · 在线娱乐", "查看套餐", and on cards "美国 · US", "日本 · JP", "香港 · HK". Tiny gray "广告" upper right. No numeric promises or extra text. Refined visual hierarchy: main headline about66px at1962wide; secondary32px; CTA32px. Strong whitespace without huge logo or giant headline. All elements comfortably within534pxheight, no cropping, no stretching, no mockup frame. Full-bleed native wide banner with well-balanced optical composition.
@@ -1 +0,0 @@
Use case: text-localization. Edit the provided existing DPL compact horizontal advertisement. Change ONLY the small white brand wordmark beside the blue logo in the upper left from "DPL" to EXACT uppercase "DP-LINK.NET". Keep its height and clean sans serif font weight similar to the existing DPL text; extend the wordmark naturally to the right with refined tight optical kerning and balanced icon-to-text gap. Preserve the blue logo icon EXACTLY. Preserve every other pixel/compositional element as closely as possible: wide aspect ratio, dark navy grid, globe, region cards, gradients, headline "畅连全球网络", subtitle "日常访问 · 远程办公 · 在线娱乐", button "查看套餐", tiny 广告. No other wording changes. Do not redesign, enlarge, move or crop anything else. The replacement wordmark must read D P hyphen L I N K dot N E T: "DP-LINK.NET".
@@ -1 +0,0 @@
Use case: text-localization. Edit the supplied existing FUC purple rocket advertisement. Replace ONLY the large white headline "全球网络中继服务" with EXACT "全球网络加速". Replace ONLY the smaller lavender subtitle "随时随处,尽情使用" with EXACT "五年稳定运营". Keep headline and subtitle left aligned with the same existing left edge, approximately same font size and weight as their respective old lines, retaining natural refined character spacing instead of stretching the shorter phrases to fill the previous width. Preserve existing logo and 福云 wordmark EXACTLY, deep purple starry background, rocket, planets, orbital curves, white 开始使用 button with arrow, tiny 广告 top-right, all positions and original wide canvas. No other wording or visual changes. Exact Chinese text is mandatory: 全球网络加速 / 五年稳定运营.
@@ -1 +0,0 @@
Use case: ads-marketing. Input1: CURRENT FUC homepage screenshot, visual-style reference ONLY, not a composition to crop or reuse. Input2: current official FUC continuous-cloud purple logo, brand mark reference, reproduce its distinctive exact loop/cloud shape; no giant 福 character. Design a NEW polished short extra-wide FUC display advertisement, target1962x534px, aspect3.674:1. Full-bleed deep royal purple #3e269d background, restrained violet/magenta orbital curves and sparse tiny stars, inspired by CURRENT homepage. Left quarter: tasteful official purple cloud mark paired with WHITE Chinese wordmark "福云" at restrained size, enough contrast. Middle-left/main area: readable bold WHITE exact headline "全球网络中继服务"; below smaller muted lavender exact subtitle "随时随处,尽情使用". Lower-left small refined white rounded pill CTA with purple exact text "开始使用" and a small right arrow. Right third: sophisticated minimal purple rocket/orbital illustration with soft magenta planet glow and flowing curved paths, not childish clipart, modest supporting scale. Allow strong clean negative space. Tiny light lavender "广告" upper right. Do NOT use old huge 福 glyph, white/lilac background, Netflix/video stills, platform trademarks, UI navbar or page chrome. No pricing, speed claims, numbers or extra text. Careful typography and compact horizontal hierarchy that belongs to a534px tall canvas. Not a scaled down tall ad, no side padding gutters or outer borders. Native full-width short banner.
@@ -1 +0,0 @@
Use case: text-localization. Edit the supplied existing HN advertisement. Replace ONLY lowercase brand wordmark "hardnerd" with EXACT case-sensitive "HardNerd": uppercase H, lowercase ard, uppercase N, lowercase erd. Spell H a r d N e r d. Keep the same gradient colors, clean bold font, approximate wordmark size, icon-to-wordmark gap, baseline, centered composition and generous brand-to-tagline spacing. Keep the H/lime-glasses icon EXACTLY unchanged. Keep white Chinese tagline EXACTLY "硬核架构,品质专线,全球网络畅通无阻", same small size and placement. Preserve background charcoal, teal/purple glow, wide dimensions, tiny 广告 and all other details. No additional changes.
@@ -1 +0,0 @@
Use case: text-localization and typography refinement. Edit this existing compact HN advertisement. Preserve exact H/lime-glasses icon, dark charcoal background, teal and violet glows, wide canvas and all Chinese wording. Change brand wordmark to EXACT all lowercase "hardnerd" (lowercase h, not capital H). Enlarge this gradient brand WORDMARK by about18 percent compared with current, keeping icon roughly current size and optically aligned beside wordmark; brand group centered. Shrink lower white Chinese tagline by about20 percent: exact "硬核架构,品质专线,全球网络畅通无阻". Increase clear vertical gap between brand row and tagline from current roughly50px to about95px at original2021px width. Put brand row around y300, tagline around y475; center the overall two-row composition. Refined restrained natural letter spacing, tagline on one line, no exaggerated tracking. Preserve plenty of safe space within central2021x550 visible banner crop; all main content stays within y180..570. Keep tiny gray 广告 upper right, no other text or graphics. Do not change the icon design. No CTA. Main requested changes only: brand larger and lowercase, tagline smaller, more space between rows.
@@ -1 +0,0 @@
Use case: ads-marketing, identity-preserving redesign. Reference image: current Hardnerd advertisement, brand style/logo/text reference only. Create a NEW native extra-wide short banner 1962x534px, aspect ratio3.674:1. Do not scale down the tall old advertisement or letterbox it. Fill full canvas edge-to-edge with charcoal black, restrained teal glow left and violet glow right. Preserve EXACT H lime-glasses icon and gradient wordmark "Hardnerd" with capital H, original brand forms. Recompose using generous horizontal room: cohesive brand group centered around x981 y210, width about650px, icon balanced approximately95pxheight, wordmark about88px high. Below at y350 put the exact white tagline on one line "硬核架构,品质专线,全球网络畅通无阻", around42px font with subtle restrained natural tracking, not exaggerated wide character spacing. Tiny understated gray "广告" upper right. Keep whole group visually centered with balanced top/bottom margins, enough gap between brand and tagline. Only these texts. No green footer, no button or CTA, no shine or overly dramatic effects, no frame. Mature premium quiet typography designed for this exact short wide canvas, crisp legible Chinese and consistent brand proportions.
-229
View File
@@ -1,229 +0,0 @@
# AI 写作与文章关联索引
适用项目:FNA_V3。用户于2026-10-27指定本聊天持续为该项目写文章,并要求各 AI 写作时形成相关内容之间的跳转。**每次选题、撰写、重写、改名、移动、合并或撤下文章前,先读本文。** 本规则适用于项目中的后续 AI,不依赖某一聊天的上下文;不表示后台自动写作或自动发布。
发布已采用本站[独立文章 API](../maintenance/EDITORIAL_API.md),不经过ATOM。AI保留项目正文源,通过API保存冻结草稿、取得签名预览、发布确认的hash并核对回执;本索引仍由写作AI同任务维护,API不会自动改写它。
2026-10-31用户另行授权综合教程每周随机三篇的周期写作与发布,Codex任务已建立,自2026-11-02当周开始。随机计划、额度、幂等台账与执行状态唯一见[周期写作](../maintenance/WEEKLY_TUTORIALS.md);这一授权不扩大为全站重写或其他实例发布。
本文是写作流程、文章用途及文章关系的唯一维护入口。文章正文保存在各自源文件,数据库是页面实际读取的内容;栏目实现、渲染与备份方法见[教程维护](../maintenance/TUTORIALS.md),SEO项目状态见[SEO清单](../maintenance/SEO_PLAN.md)。不要在这些文档中再复制一份持续更新的文章关系表。
2026-10-31新增[统一机场推荐模块](../maintenance/AIRPORT_RECOMMENDATIONS.md):入门/综合教程自动在末尾展示,综合教程由展示层补入文内跳转;不要在正文源重复维护机场价格、地址和优惠码,也不要创建同名airport-recommendations锚点。已随[界面发布](../maintenance/UI_RELEASE_2026-10-31.md)上线。
## 1 写作前先确定读者要完成的任务
- 新手教程(原“入门教程”,URL仍为`/client`):以第一次使用为前提,讲准备、下载、安装、配置、使用和基本排错。不要把客户端迁移作为普通入门教程的主线。
- 下载与选型:讲适用平台、版本/架构、官方来源和选哪个安装包;引用官方发布入口,不把未经验证的第三方包当官方下载。
- 综合教程(栏目原名“进阶教程”,URL仍为`/advanced`):讲具体机制、配置取舍、迁移或专项排错,并链接读者需要的基础操作。
- 看看资讯(`/news`):独立资讯栏目,2026-11-02本地与正式建立,当前无文章;具体栏目维护见[资讯栏目](../maintenance/NEWS.md)。创建栏目不表示已授权自动采集或写作。
- 资源与时效内容:区分长期说明和当天资源状态。长期教程优先链接稳定说明/栏目,不依赖会过期的某一天资源页。
先查询下表和当前数据库,再决定重写已有文章还是新增。主题相同优先完善唯一正文;不同平台可以分别写,但需要实际的平台差异。标题、开头、步骤和关联链接都应服务于同一个任务。
本站是公开分享免费节点的站点。入门教程优先按“从本站获取适用格式的免费订阅→导入→选择节点→验证”的实际过程组织;公开分享的订阅与私人账户订阅需要区分,不把私人账户保密提醒套进免费资源步骤。相关说明和内链自然放在读者需要的位置,避免堆叠与场景无关的提示框。
正文直接进入引言,不再添加“入门教程 · Android · 更新于……”这类顶部信息行;分类、平台和日期不要在正文开头重复网站信息栏。必要的官方参考链接可保留在文末,内部核验过程另存维护记录。
**禁止在公开文章中写内部核验与验收说明。** 用户于2026-10-27明确要求:以后文章里不再出现“本文的核对范围”“已核对官方文档”“未实测”“未进行真机联网测试”“未修改本机网络”等内容,也不换成同义的提示框、脚注或免责声明。核验范围、设备测试情况、开发验收过程及本地/上线状态只写入项目维护记录,不进入正文、摘要、图注或封面。
公开内容保留对读者有用的操作步骤、版本兼容条件、配置限制和参考来源;不得编造实测结论。发布前检查全文,发现上述内部说明必须删除或移入维护记录,不能指望上线流程自动去掉。“本页旧文”“沿用原地址更新内容”“核对本文时”等编辑历史和核验口吻同样移入维护记录;版本信息直接写适用版本、系统要求或示例版本。参考链接优先选读者实际需要的下载、配置与使用文档,不堆放仅用于编辑取证的界面实现源码。
自然、准确地表达;必要时用真实操作图、流程图、配置示例。软件版本、下载入口与兼容要求使用当次核对的官方来源;来源核验、页面检查和设备实测分别记录,未做实测不写“实测”。
### 文章封面与水印(2026-11-01)
每次新写的每篇文章都须独立设计并生成主题图片;不复用同一底图换标题,不沿用单调的标题横线卡片。根据文章的设备、操作或机制构思不同场景、构图和配色,为文章生成与具体主题相符的封面图,并加上本站网址 **clashfreenode.com** 水印。用户提供的参考图以画面表达主题,角落有低调的站点署名;借鉴这种主题视觉与水印的关系,不照搬其他网站的名称、标志或固定版式。封面应适合本站缩略图裁切,在小尺寸下仍能看清主体和水印;文字优先使用中文,应用名称及品牌名保留原名,水印不遮挡关键信息。生成后检查实际渲染的品牌拼写、可读性和裁切效果,必要时调整;按文章API的图片上传与发布流程交付。
**统一画风,不统一模板(2026-11-01用户确认)**:教程封面采用“纸艺拼贴+微缩立体场景”(tactile papercraft / miniature diorama editorial illustration),保留纸张纤维与折叠、层叠色块、可信的物件体积、柔和定向光和自然投影。认可参考为[客户端下载图](tutorials/assets/newcomer/clients-cover.png)的设备陈列,以及[新手指引图](tutorials/assets/newcomer/start-paper-cover.png)的路线与关卡;二者质感相通,但场景与构图明显不同。每篇按主题重新设计视觉比喻、主体、镜头角度、构图与配色,不固定为设备托盘,不反复使用笔记本、山景屏幕、盆栽或同样的台座布局,不只换设备/标题/颜色。可以使用地图、建筑、机械、航行、城市网络等不同表现;这是举例,不是每篇必须套用的固定清单。既要表达文章主题,也要确保成组浏览时不重复。此规则只适用于教程封面,不改免费节点插画池。
封面图与正文里的操作截图、流程图用途不同,正文需要解释操作或机制时仍应提供对应图解。此要求自后续新文起执行,不自动更换已发布文章的封面。文章专题封面通过文章资产流程处理,不因此改动免费节点插画图池;CFN系独立插画仍遵循项目既有画师分工及交付流程。
### 教程双比例配图(正式规则,2026-11-01)
用户已确认试样并要求其他文章遵循此方式。**后续每篇新手/综合教程必须同时交付两张同主题、分别构图的图片**,不是仅适用于当前聊天或新手指引的临时试验:
- **列表缩略图:3:2。** 上传后写入文章 `cover`,主体和标题在列表小图中清晰;不要把列表图误认为正方形。
- **详情头图:约2.4:1。** 为低矮宽画幅重新安排主体、文字和留白,完整展现主题;不可通过硬裁、拉伸或上下补空白把3:2图凑成横幅。两张图保持同一文章的主题与画风,不必复制物件位置。
- 两图均按上一节的纸艺拼贴+微缩场景风格独立设计,带准确的 `clashfreenode.com` 水印;不同文章的视觉比喻、场景、配色和视角应有变化。正文操作截图及图解另按解释需要提供。
**发布实现必须一致:** `cover` 指向3:2缩略图,`show_cover=false`,详情横幅放在正文 `.tutorial-body` 开头,以唯一的 `figure.guide-figure.tutorial-hero` 包住图片。上传两张图片后使用API返回的实际 `asset:SHA256`,并填写实际宽高和说明性alt;不要把示例占位符直接发布:
```html
<figure class="guide-figure tutorial-hero"><img src="asset:实际横幅SHA256" width="实际宽度" height="实际高度" alt="主题说明" decoding="async"></figure>
```
现有 `tutorials.css` 使横幅占满正文宽度并等比显示。不得再打开默认头图造成重复,也不得给横幅设置固定高度裁切。改旧文时保留原 `cover`、日期、正文和点赞进度,只更新已获授权的图片内容;同步Markdown源、HTML渲染稿和文章版本索引。原图、交付JPG及完整提示词保存在文章资产目录,不依赖聊天临时文件。
发布前逐篇检查:列表仍使用3:2图;详情仅一张约2.4:1头图;桌面和手机无横向溢出;标题、水印、主体完整可读;图片加载成功;实际正文与缩略图分别使用正确资源。缺少任一配图或未完成检查时不能把文章标成全部完成。普通改稿不自动批量重画历史文章;本次已获授权推广的是2026-11-01这批8篇新手教程,回执与回退见[新手教程维护记录](../maintenance/NEWCOMER_TUTORIALS_2026-11-01.md)。
栏目banner与文章配图是不同资产:`/client` 总列表不显示大图;五个平台子栏目显示各自主题banner及动态名称/文章数量。栏目图不替代文章的两张配图,修改入口见[新手教程维护记录](../maintenance/NEWCOMER_TUTORIALS_2026-11-01.md)。
### 周期文章的展示时间(2026-10-31)
用户要求每天北京时间15:00检查周期计划,新文章展示日期从实际发布时间随机向前偏移0~21600秒(含端点)。API在新文草稿中冻结`display_offset_seconds`,首次发布计算独立的`sDisplayPublishedAt`;列表和详情沿原有日期显示样式使用该字段,未设置时使用真实创建时间。实际`created_at`、发布回执及点赞起点不改;重试、旧文编辑和回退不重抽、不改旧文展示时间。`display_time_randomize`只允许新建时设置,默认true,显式false为零偏移。不要把随机时间或内部执行过程写进公开正文。
### AI 新文章的点赞参数(2026-10-29)
后续AI通过本站独立文章API**新建文章**时由API在保存草稿时为每篇独立取默认值并冻结;相同请求重试、查询预览及发布不重新抽取。统一设置入口为[文章自动点赞配置](../../config/article_likes.php),配置文件覆盖上游/API传入的自动点赞数值,0也优先;分类与优先级见[自动点赞维护](../maintenance/ARTICLE_LIKES.md#新文章统一设置2026-11-01本地)。下表是现有默认值的说明,后续以配置文件的实际值为准;本次统一配置已于2026-11-02随Git发布上线。重写、接管、回退已有文章不重置原参数、点赞数或已完成进度,不自动给现有文章批量补额度。
| 设置 | 默认值 | 含义 |
| --- | --- | --- |
| `i7like`,API `like_settings.seven_day` | 新手1~18;综合/其他编辑1~15(含端点) | 原有短期待增加额度,随原任务逐次扣减 |
| `i365like`,API `like_settings.yearly` | 新手50;综合/其他编辑30 | 保留原持续年度随机机制:每天以50/365概率加1,长期平均每年约50赞,并非每年保证恰好50,不随一年结束停止 |
| `iYearLikeTarget`,API `like_settings.one_year` | 新手50~150;综合/其他编辑20~80(含端点) | 新增一次性年度额度;设200表示独立累计自动增加200赞,不是总点赞数封顶200 |
一次性年度额度从正式发布时开始,按实际经过时间在一个日历年内分散增加,`iYearLikeAdded`记录已增加数量,`sYearLikeStartedAt`记录开始时间;满额后该项停止,`i365like`持续增长和真实点赞继续独立计算。任务停机造成的欠额在恢复后补至应有进度;满一年后首次恢复会补完余额,不能在调度停机时凭空执行。
新文章省略`like_settings`,由配置文件决定三个值;为兼容旧调用,接口仍校验该对象,但传入值不会覆盖本地配置。要关闭某项,在配置文件中设为0。保存后检查草稿响应的`like_settings`,发布后从鉴权的`source-articles/{id}`响应`like_growth`回读确认。旧文章编辑不传此对象;API拒绝通过普通改稿重置额度。设置与进度只属于内部发布数据,不写进公开正文、摘要、图注或封面。
具体字段、迁移、任务、测试与回退见[文章自动点赞维护](../maintenance/ARTICLE_LIKES.md)。2026-10-29当时的默认值已部署正式cfn(不是2026-11-01本地的新范围和优先级),原每5分钟点赞任务已接入新增年度额度;本机仍未启动调度。按用户本次明确授权,正式10篇教程已补齐缺项:3篇全0新文补全部默认值,另外7篇仅补一次性年度额度并保留原参数。后续不自动重置已有文章,补配结果见上述维护记录。
## 2 当前文章登记
本地登记更新:2026-11-01。新手栏目现有8篇新文,原7篇平台教程移至综合教程,URL、正文、日期和点赞进度保留。分类与新稿已于2026-11-02通过正式API发布;正式ID、版本及验收见[整批发布记录](../maintenance/FULL_RELEASE_2026-11-02.md)。具体批次与回退见[新手教程调整](../maintenance/NEWCOMER_TUTORIALS_2026-11-01.md)。
ID用于核对本地行,站内链接使用已确认路径。跨环境迁移后重新核对ID,不能假定生产ID相同。
| 内容键 | 本地ID / 栏目 | 标题 | 实际路径 | 正文源 / 编辑状态 | 用途与引用边界 |
| --- | --- | --- | --- | --- | --- |
| verge-windows-start | 362 / 综合教程 | Clash Verge Rev 使用教程:从安装到第一次连接(Windows) | `/a/clash-verge-rev-windows.html` | [windows.md](tutorials/windows.md);本地API版本5 | Windows新用户操作入口;下载段落锚点为 `#install` |
| cfw-to-verge | 212 / 综合教程 | 从 Clash for Windows 迁移到 Clash Verge Rev | `/a/m167.html` | [migration.md](tutorials/migration.md);本地API版本5 | 保留旧配置并更换客户端;不作为纯入门入口 |
| mihomo-dns | 361 / 综合教程 | Clash 进阶:DNS 防泄漏配置与验证 | `/a/mihomo-dns-leak.html` | [dns.md](tutorials/dns.md);本地API版本6 | Mihomo桌面DNS专题,含配置片段与验证方法 |
| cfa-android-legacy | 206 / 综合教程 | Clash Meta for Android 使用教程:导入订阅、选择节点与连接 | `/a/m169.html` | [clash-meta-android.md](tutorials/clash-meta-android.md);本地API版本7 | Android Clash配置入门;`#install` 安装、`#import` 导入;按MetaCubeX v2.11.36核对,保留原键和URL |
| quantumult-ios-legacy | 207 / 综合教程 | Quantumult X 使用教程:iOS 安装、订阅导入与连接 | `/a/m170.html` | [quantumult-x-ios.md](tutorials/quantumult-x-ios.md);本地API版本6 | iPhone/iPad入门;区分原生资源与本站通用订阅,#parser 解释第三方资源解析器,#import 导入;无真机实测 |
| v2rayng-android-legacy | 208 / 综合教程 | v2rayNG 使用教程:Android 安装、导入订阅与连接 | `/a/m171.html` | [v2rayng-android.md](tutorials/v2rayng-android.md);本地API版本8 | Android入门;`#install` 下载、`#import` 订阅导入;保留既有内容键和URL |
| clashx-mac-legacy | 209 / 综合教程 | Mac 代理客户端下载指南:ClashX 与 Clash Verge Rev 怎么选 | `/a/m172.html` | [mac-client-guide.md](tutorials/mac-client-guide.md);本地API版本6 | Mac选型与官方下载;#download 核对系统与芯片,链接实际安装教程;旧ClashX原入口不可核验不等于所有分支失效 |
| cfw-mac-legacy | 210 / 综合教程 | Clash Verge Rev 使用教程:Mac 安装、订阅与系统代理 | `/a/m173.html` | [verge-mac.md](tutorials/verge-mac.md);本地API版本3 | Mac操作入口;#install DMG安装,#import 订阅,系统代理与退出排错;无设备联网实测 |
| cfw-linux-legacy | 211 / 综合教程 | Clash Verge Rev 使用教程:Linux 安装、订阅与代理设置 | `/a/m174.html` | [verge-linux.md](tutorials/verge-linux.md);本地API版本6 | Linux桌面入门;#install 包格式与架构,#import 订阅,#terminal 单条curl代理验证;不适用于无桌面的服务器 |
| system-proxy-vs-tun | 365 / 综合教程 | 系统代理和 TUN 有什么区别?接管范围、使用选择与排错 | `/a/system-proxy-vs-tun.html` | [system-proxy-tun.md](tutorials/system-proxy-tun.md);本地API版本1 | 桌面代理接管与出口选择;`#choose` 场景选择、`#switch` 切换检查、`#troubleshoot` 排错;三张流程图 |
| clash-routing-modes | 366 / 综合教程 | Clash 规则、全局和直连怎么选?代理组与分流排错教程 | `/a/clash-rule-global-direct.html` | [clash-routing-modes.md](tutorials/clash-routing-modes.md);2026-10-31本地ID366/版本1,正式ID382/版本1已发布 | 模式选择与代理组分流;`#groups` 组内选择、`#custom` 添加规则、`#verify` 验证新连接 |
| newcomer-start | 373 / 新手教程(client) | 新手指引:从免费订阅到第一次连接 | `/a/getting-started.html` | [start.md](tutorials/newcomer/start.md);本地API版本3(双比例配图);2026-11-02正式ID393/版本1已发布 | 先选设备,再下载安装、导入对应格式的免费订阅并连接。Windows、Mac、安卓、iPhone、Linux和路由器的入口都在这里。 |
| newcomer-windows | 374 / 新手教程(windows) | Windows 新手教程:用 Clash Verge Rev 连接免费节点 | `/a/windows-free-nodes.html` | [windows.md](tutorials/newcomer/windows.md);本地API版本3(双比例配图);2026-11-02正式ID394/版本1已发布 | 从选择 Windows 安装包开始,复制本站 Clash 订阅、选中配置与节点,再开启系统代理完成第一次连接。 |
| newcomer-mac | 371 / 新手教程(mac) | Mac 新手教程:安装 Clash Verge Rev 并导入免费订阅 | `/a/mac-free-nodes.html` | [mac.md](tutorials/newcomer/mac.md);本地API版本3(双比例配图);2026-11-02正式ID391/版本1已发布 | 区分 Apple 芯片和 Intel 安装包,将应用放入应用程序,导入 Clash 订阅并开启系统代理。 |
| newcomer-android | 367 / 新手教程(andorid) | Android 新手教程:用 FlClash 导入免费订阅 | `/a/android-flclash.html` | [android.md](tutorials/newcomer/android.md);本地API版本3(双比例配图);2026-11-02正式ID387/版本1已发布 | 在安卓手机安装 FlClash,导入 Clash 格式订阅、选择节点并允许 VPN 连接,附后台断连排查。 |
| newcomer-ios | 369 / 新手教程(ios) | iPhone / iPad 新手教程:用 Hiddify 连接免费节点 | `/a/ios-hiddify.html` | [ios.md](tutorials/newcomer/ios.md);本地API版本3(双比例配图);2026-11-02正式ID389/版本1已发布 | 从 App Store 安装 Hiddify,添加本站订阅、允许 VPN 配置并检查连接,说明订阅更新与节点切换。 |
| newcomer-linux | 370 / 新手教程(linux) | Linux 新手教程:在桌面环境使用 Clash Verge Rev | `/a/linux-free-nodes.html` | [linux.md](tutorials/newcomer/linux.md);本地API版本3(双比例配图);2026-11-02正式ID390/版本1已发布 | 按发行版和 CPU 架构选择安装包,导入免费订阅、开启系统代理,并区分浏览器与终端的连接方式。 |
| newcomer-router | 372 / 新手教程(client) | 路由器新手教程:用 OpenClash 导入免费订阅 | `/a/router-openclash.html` | [router.md](tutorials/newcomer/router.md);本地API版本3(双比例配图);2026-11-02正式ID392/版本1已发布 | 在兼容的 OpenWrt 路由器上安装插件与内核、添加 Clash 订阅、启用配置,再检查设备是否经过这台路由器。 |
| newcomer-clients | 368 / 新手教程(client) | 客户端下载与选择:按设备找到适合的软件 | `/a/proxy-clients.html` | [clients.md](tutorials/newcomer/clients.md);本地API版本2(双比例配图);2026-11-02正式ID388/版本1已发布 | 汇总常用代理客户端的官方入口,说明系统、架构和订阅格式如何匹配,并连接到各平台的新手教程。 |
2026-10-31新教程正式ID382/版本1、本地ID366/版本1已发表;系统代理/TUN正文补入口后两环境均为API版本2(正式ID376、本地ID365)。正式发布时间14:58:28北京时间,IndexNow由VPS-003提交返回200,服务器HTTP与图哈希/锚点验收通过。唯一状态与恢复记录见[规则模式教程发布记录](../maintenance/ROUTING_MODES_2026-10-31.md)。
这里只登记长期编辑内容及值得复用的稳定资源说明,不逐条收录日更节点或账号文章。稳定入口为 `/`(当前免费节点)、`/freenode`(历史分享归档)、`/client`(新手教程)、`/advanced`(综合教程);平台入口和名称修改另按项目路由核对,不从名称自行拼接。
2026-10-29部署边界更新:上表10篇已通过本站API迁移到独立test并经用户确认后切到正式cfn,旧URL保留;生产发布以预览实际正文冻结再发布,未用test整库覆盖。test和生产的临时编辑密钥均在迁移后删除,接口默认关闭;后续本地写作继续使用本地API,正式编辑按明确任务与生产绑定启用。实际部署及验收统一见[发布记录](../maintenance/RELEASE_PREFLIGHT_2026-10-28.md#正式切换2026-10-29),上表ID仍为本地ID。
2026-10-31 SEO发布后,新稿获取当前免费资源优先链接 `/`;需要历史记录时链接 `/freenode`。下表保留旧文实际内链事实,旧栏目仍正常可用,不因入口规则变化虚报旧文正文已改;后续相关编辑时按内容用途维护。
## 3 已有文章关系
以下为2026-10-28从本地数据库正文提取并核对源文件的**实际内链**,不是建议列表。箭头表示正文中有从来源到目标的链接;入向关系从本表反查,不另存一份容易失步的反向清单。
| 来源内容键 | 目标内容键 | 读者为什么跳转 / 放置位置 | 状态 |
| --- | --- | --- | --- |
| verge-windows-start | 栏目 `/freenode` | 导入前获取Clash订阅,以及节点失效后查看较新的分享 | 已在本地正文实现 |
| verge-windows-start | mihomo-dns | 入门完成后学习DNS路径;文末“下一步” | 已在本地正文实现 |
| mihomo-dns | verge-windows-start | 尚未安装客户端的读者回到Windows入门;文末说明 | 已在本地正文实现 |
| cfw-to-verge | 栏目 `/freenode` | 迁移时获取Clash/Mihomo免费订阅;保留旧订阅重新导入的选项 | 已在本地正文实现 |
| cfw-to-verge | mihomo-dns | 完成迁移后检查DNS路径;文末“下一步” | 已在本地正文实现 |
| v2rayng-android-legacy | 栏目 `/freenode` | 获取v2ray订阅、整批失效后寻找较新分享 | 已在本地正文实现 |
| v2rayng-android-legacy | verge-windows-start `#install` | 日常使用段落后,供同时需要Windows客户端的读者继续 | 已在本地正文实现 |
| v2rayng-android-legacy | cfa-android-legacy `#import` | 获取订阅段落说明Clash格式的Android导入入口 | 已在本地正文实现 |
| cfa-android-legacy | v2rayng-android-legacy `#import` | 导入前说明v2ray订阅和单节点分享链接的另一客户端用法 | 已在本地正文实现 |
| cfa-android-legacy | 栏目 `/freenode` | 获取Clash订阅,旧批次失效后寻找较新分享 | 已在本地正文实现 |
| cfa-android-legacy | verge-windows-start `#install` | 日常使用末尾提供Windows客户端安装入口 | 已在本地正文实现 |
| quantumult-ios-legacy | 栏目 `/freenode` | 选择较新的免费订阅;明确本站通用订阅需要格式适配 | 已在本地正文实现 |
| quantumult-ios-legacy | clashx-mac-legacy `#download` | 日常使用后提供Mac客户端选择入口,说明配置不可直接通用 | 已在本地正文实现 |
| clashx-mac-legacy | cfw-mac-legacy `#install` / `#import` | 选好客户端下载后进入Mac安装和连接步骤 | 已在本地正文实现 |
| clashx-mac-legacy | 栏目 `/freenode` | 选定客户端后获取Clash/Mihomo订阅 | 已在本地正文实现 |
| clashx-mac-legacy | verge-windows-start | 同时使用Windows时转到对应平台教程 | 已在本地正文实现 |
| clashx-mac-legacy | cfw-linux-legacy | 同时使用Linux桌面时转到对应平台教程 | 已在本地正文实现 |
| cfw-mac-legacy | clashx-mac-legacy `#download` | 安装前核对Mac系统和CPU架构 | 已在本地正文实现 |
| cfw-mac-legacy | 栏目 `/freenode` | 导入前选择Clash/Mihomo免费订阅 | 已在本地正文实现 |
| cfw-mac-legacy | mihomo-dns | 基本连接完成后深入检查DNS路径 | 已在本地正文实现 |
| cfw-linux-legacy | 栏目 `/freenode` | 导入Clash/Mihomo订阅和更新失效批次 | 已在本地正文实现 |
| cfw-linux-legacy | mihomo-dns | Linux基本连接后继续学习DNS与TUN验证 | 已在本地正文实现 |
| cfw-linux-legacy | clashx-mac-legacy `#download` | 需要Mac客户端时进入对应下载指南 | 已在本地正文实现 |
| verge-windows-start | system-proxy-vs-tun `#choose` | “需要一开始就开 TUN 吗”后提供接管方式选择入口 | 已在本地正文实现 |
| mihomo-dns | system-proxy-vs-tun `#tun` | TUN/DNS 配置片段前解释接管机制 | 已在本地正文实现 |
| system-proxy-vs-tun | verge-windows-start `#enable` | 切换前完成 Windows 基本连接 | 已在本地正文实现 |
| system-proxy-vs-tun | cfw-mac-legacy `#enable` | 切换前完成 Mac 基本连接 | 已在本地正文实现 |
| system-proxy-vs-tun | cfw-linux-legacy `#connect` / `#terminal` | Linux 基础连接及单条命令显式代理 | 已在本地正文实现 |
| system-proxy-vs-tun | mihomo-dns `#dns-2` | 继续检查 DNS 接管、加密和出口 | 已在本地正文实现 |
| system-proxy-vs-tun | clash-routing-modes `#groups` | 已接管但走错出口时检查规则和代理组;放在场景选择之前 | 2026-10-31本地与正式已发布 |
| clash-routing-modes | verge-windows-start `#enable` / cfw-mac-legacy `#enable` | 尚未完成基本连接时返回对应平台操作 | 2026-10-31本地与正式已发布 |
| clash-routing-modes | system-proxy-vs-tun `#routing` / `#troubleshoot` | 解释接管和分流的区别,以及看不到连接时排错 | 2026-10-31本地与正式已发布 |
| clash-routing-modes | mihomo-dns `#dns-2` | 出口正确但域名解析仍异常时继续查DNS | 2026-10-31本地与正式已发布 |
两篇Android教程通过订阅格式段落互链;Mac下载指南与操作教程互链,Linux从下载指南和真实Linux栏目获得入口,iOS沿用真实iOS栏目入口。系统代理与TUN专题由Windows和DNS正文提供入口,并指向三平台的基础操作及DNS专题。目录、标签、导航和热门榜不算正文关联;正文内链及锚点已经本地HTTP验证。
### 新手教程新增关系(2026-11-01建立,2026-11-02正式发布)
| 来源内容键 | 实际目标 | 用途 / 位置 |
| --- | --- | --- |
| newcomer-start | `/a/windows-free-nodes.html`、`/a/mac-free-nodes.html`、`/a/android-flclash.html`、`/a/ios-hiddify.html`、`/a/linux-free-nodes.html`、`/a/router-openclash.html`、`/a/proxy-clients.html`、`/`、`/a/system-proxy-vs-tun.html#choose`、`/a/clash-rule-global-direct.html`、`/advanced` | 正文中的获取订阅、设备操作、下载、专题与返回指引入口 |
| newcomer-windows | `/a/proxy-clients.html#verge`、`/`、`/a/system-proxy-vs-tun.html#choose`、`/a/clash-verge-rev-windows.html`、`/a/getting-started.html#devices` | 正文中的获取订阅、设备操作、下载、专题与返回指引入口 |
| newcomer-mac | `/a/proxy-clients.html#verge`、`/`、`/a/clash-rule-global-direct.html#groups`、`/a/system-proxy-vs-tun.html#choose`、`/a/m173.html`、`/a/getting-started.html#devices` | 正文中的获取订阅、设备操作、下载、专题与返回指引入口 |
| newcomer-android | `/a/proxy-clients.html#flclash`、`/`、`/a/m171.html#import`、`/a/getting-started.html#devices`、`/a/clash-rule-global-direct.html` | 正文中的获取订阅、设备操作、下载、专题与返回指引入口 |
| newcomer-ios | `/a/proxy-clients.html#ios`、`/`、`/a/getting-started.html#devices`、`/a/m170.html` | 正文中的获取订阅、设备操作、下载、专题与返回指引入口 |
| newcomer-linux | `/a/proxy-clients.html#verge`、`/`、`/a/m174.html#terminal`、`/a/system-proxy-vs-tun.html#choose`、`/a/getting-started.html#devices` | 正文中的获取订阅、设备操作、下载、专题与返回指引入口 |
| newcomer-router | `/a/getting-started.html#devices`、`/`、`/a/getting-started.html`、`/a/clash-rule-global-direct.html` | 正文中的获取订阅、设备操作、下载、专题与返回指引入口 |
| newcomer-clients | `/a/windows-free-nodes.html`、`/a/mac-free-nodes.html`、`/a/android-flclash.html`、`/a/ios-hiddify.html`、`/a/linux-free-nodes.html`、`/a/router-openclash.html`、`/a/m167.html`、`/a/m170.html#import`、`/a/m171.html`、`/a/m169.html`、`/a/getting-started.html#subscription` | 正文中的获取订阅、设备操作、下载、专题与返回指引入口 |
| 免费节点页面展示层 | `/a/getting-started.html` | 获取免费订阅标题下;旧版正文回退页在正文前;仅目标公开可用时显示 |
新手指引置顶于`/client`,六个设备入口与下载总览均为真实已保存页面;原七篇移栏不改正文内链。
## 4 怎样安排链接
| 关系 | 典型写法与放置位置 | 目标选择 |
| --- | --- | --- |
| 前置准备 | “尚未安装客户端,先完成……”放在需要操作之前 | 对应平台的安装/下载/入门文章 |
| 具体操作 | “订阅导入步骤见……”放在提到该操作的位置 | 对应教程的具体段落锚点 |
| 解释概念 | “关于系统代理与TUN的区别……”放在需要解释处 | 已完成、平台适用的专题文章 |
| 解决故障 | 在具体错误或现象后提供排查入口 | 对应问题的排错文章 |
| 继续学习 | 完成当前任务后的下一步,放在文末 | 与当前任务相邻的进阶内容 |
| 返回基础 | 进阶内容给尚未具备前置条件的读者一个入口 | 基础教程;不强迫已经会用的读者重复阅读 |
### 下载文章的具体例子
**跨平台下载入口已建立**:`/a/proxy-clients.html`,汇总六类设备的官方来源和对应新手操作入口;新文章优先引用这一下载入口或设备教程的下载段落。
**Mac另有独立选型与下载指南**,可链接 `/a/m172.html#download`,其中也提供Mac安装与导入教程的入口。Windows当前可用目标仍是入门教程中的下载段落:
```html
<a href="/a/clash-verge-rev-windows.html#install">Clash Verge Rev Windows 下载与安装步骤</a>
```
例如,后续撰写某篇进阶配置教程,读者需要先安装该客户端,就可在前置准备处使用这个入口。如果以后建立其他平台的独立下载文章:先创建并验证真实URL,登记用途与状态,再把适用教程中的下载链接改到新文;同时在下载文章中提供“下载后如何使用”的入门链接。不要提前创造一个不存在的下载URL,也不要把本段示例当作当前正文已经增加的链接。
### 链接质量约束
- 按读者需要建立方向,不要求任意两篇都互链。新增文章应检查“从哪里能找到它”,在确有相关性的旧文中补入口;若没有合适旧文,明确使用真实栏目入口并记录原因,不硬塞链接。
- 使用描述目标任务的锚文本,例如“Windows 订阅导入步骤”;少用无意义的“点击这里”,不重复堆砌关键词,不设固定链接数量指标。
- 站内文章使用根相对路径 `/a/实际slug.html`,不要写本机 `.loc` 或未经确认的生产域名。锚点必须真实存在;平台不适用时说清范围,不把Windows教程当作所有平台通用操作。
- 正文相关位置优先,文末“下一步”只保留有用内容,不把每篇文章都变成全站链接目录。
- 待写、撤下、未核验或已过时的文章不能包装成可靠的当前操作入口。需要引用历史内容时,明确历史用途和限制。
- 改名或移动分类优先保留原slug。确需改URL/合并/撤下时,先查本表入向关系及源文件/数据库中的实际链接,再处理所有受影响正文和已授权范围内的重定向;只改索引不算修复完成。
- 不把“未来关联”记为“已实现”。对公开文章,不发布指向仅本地存在页面的内链;上线时核对目标与来源是否一同部署。
## 5 每次写作的固定流程
1. **查现状。** 读AGENTS和本文,按主题/平台搜索登记表,再查当前数据库标题、slug、栏目、发布状态和正文。阅读拟链接文章,不能只凭标题判断合适。
2. **确定位置。** 明确本文解决什么、读者需要什么前置知识、完成后下一步是什么。挑选现有有效目标;缺少的内容登记为待办,不自动扩大成一批新文章。
3. **写正文。** 遵守第1节公开内容要求,禁止写核对范围、未实测等内部说明;发布前检查正文、摘要、图注和封面。在合适段落放入自然的站内链接,并保留必要官方来源。新文确定slug前查重。首次重写仅在数据库中的旧文时,先备份,再建立项目正文源。
4. **补相关旧文。** 在本次获准写作范围内,同步维护直接相关的少量链接,保留无关正文和并行修改;不借机全站重写、修改资源数据或上线。新文只有草稿时先登记计划,等目标可用后再启用链接。
5. **保存与同步。** 按[独立文章API](../maintenance/EDITORIAL_API.md)提交完整草稿批次,预览确认后发布指定hash并查询回执;不手工绕过版本控制更新文章表。首次接管旧文显式绑定准确ID。项目正文源与本文的文章行、实际关系行同任务维护;草稿、公开正文、搜索同步和生产部署分别确认,避免源文件有链接而网页没有。
6. **验收链接。** 检查来源正文是否实际含链接、目标标题/栏目/平台是否匹配、HTTP是否成功及锚点是否存在;不能只看200(项目路由可能接受错误前缀)。检查移动排版和配图;访问线上仍按项目授权边界,不能以验链接为由越界。
7. **收尾说明。** 报告改了哪些文章、增加/修复了哪些关联、哪些仅在本地生效、是否同步搜索及是否发布。未完成的关系保留明确原因与下一步。备份和操作过程留维护记录,不向本索引堆聊天流水。
## 6 登记规则与待补内容
新增登记项使用稳定内容键,字段沿用第2节:本地ID、栏目、准确标题、真实路径、正文源、编辑/环境状态、读者任务与适用限制。标题变化不必更换内容键。关系沿用第3节:来源键、目标键、理由/位置、实际状态;有段落链接时同时记录锚点。填写核对日期和证据范围,禁止把“已有记录”写成“刚刚实测”。
当前待补(选题储备,**尚未创建文章,也不自动授权逐篇执行**):
| 主题 | 当前可用替代入口 | 处理条件 |
| --- | --- | --- |
| 更细的客户端选型专题 | 已有 `/a/proxy-clients.html` 跨平台下载入口 | 存在独立读者任务时再拆分,避免重复总览 |
| 订阅导入失败排查 | Windows入门的导入与常见问题段落 | 积累明确错误场景后再拆专题,避免重复原文 |
本次建立的是AI协作约定和已核实的关联索引,不是自动推荐程序、链接注入脚本或定时任务。正文关系变动时由执行写作的AI同任务更新本文。
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 MiB

@@ -1 +0,0 @@
Create a polished website category masthead illustration. EXTRA-WIDE 21:9 composition, ideally 2100x900. Tactile papercraft collage and miniature three-dimensional diorama, clearly visible thick paper fibers and cut edges, layered construction, natural directional light and gentle shadows, editorial quality, rich but harmonious color. A friendly green Android-shaped folded paper robot carrying a small download parcel through a lively layered botanical paper garden, oversized leaves, terracotta paths, moss green and warm cream, playful but sophisticated. Distinctive complete scene composed for wide banner. Main recognizable platform subject in center and right, bottom-left 22 percent kept quiet for website's live category title. No written headings, no English slogan, no fake interface text. Only exact small watermark 'clashfreenode.com' in upper-right with safe margin, readable and understated. No border, no stock watermark, no repeated template, no photography.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 MiB

@@ -1 +0,0 @@
Create a polished website category masthead illustration. EXTRA-WIDE 21:9 composition, ideally 2100x900. Tactile papercraft collage and miniature three-dimensional diorama, clearly visible thick paper fibers and cut edges, layered construction, natural directional light and gentle shadows, editorial quality, rich but harmonious color. A paper-crafted phone and tablet standing like clean archways in a sculptural lavender and peach courtyard, translucent vellum panels and small folded data ribbons connecting the two, soft lilac deep plum cream, axonometric. Distinctive complete scene composed for wide banner. Main recognizable platform subject in center and right, bottom-left 22 percent kept quiet for website's live category title. No written headings, no English slogan, no fake interface text. Only exact small watermark 'clashfreenode.com' in upper-right with safe margin, readable and understated. No border, no stock watermark, no repeated template, no photography.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 MiB

@@ -1 +0,0 @@
Create a polished website category masthead illustration. EXTRA-WIDE 21:9 composition, ideally 2100x900. Tactile papercraft collage and miniature three-dimensional diorama, clearly visible thick paper fibers and cut edges, layered construction, natural directional light and gentle shadows, editorial quality, rich but harmonious color. A distinctive black-white-yellow paper penguin in a tiny crafted open-source workshop, cream paper terminal scroll, brass card gears and green tool drawers, long orderly workbench, forest green mustard black cream, intimate oblique view. Distinctive complete scene composed for wide banner. Main recognizable platform subject in center and right, bottom-left 22 percent kept quiet for website's live category title. No written headings, no English slogan, no fake interface text. Only exact small watermark 'clashfreenode.com' in upper-right with safe margin, readable and understated. No border, no stock watermark, no repeated template, no photography.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 MiB

@@ -1 +0,0 @@
Create a polished website category masthead illustration. EXTRA-WIDE 21:9 composition, ideally 2100x900. Tactile papercraft collage and miniature three-dimensional diorama, clearly visible thick paper fibers and cut edges, layered construction, natural directional light and gentle shadows, editorial quality, rich but harmonious color. An elegant silver paper laptop on an organic terraced teal island, a delicate cream bridge carrying a red download package, ivory folded sails behind, restrained teal coral cream palette, low side angle. Distinctive complete scene composed for wide banner. Main recognizable platform subject in center and right, bottom-left 22 percent kept quiet for website's live category title. No written headings, no English slogan, no fake interface text. Only exact small watermark 'clashfreenode.com' in upper-right with safe margin, readable and understated. No border, no stock watermark, no repeated template, no photography.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 MiB

@@ -1 +0,0 @@
Create a polished website category masthead illustration. EXTRA-WIDE 21:9 composition, ideally 2100x900. Tactile papercraft collage and miniature three-dimensional diorama, clearly visible thick paper fibers and cut edges, layered construction, natural directional light and gentle shadows, editorial quality, rich but harmonious color. A blue four-pane window-shaped paper portal, an inviting tiny desk and desktop monitor, keyboard keys becoming stepping stones towards a configuration gear, blue cream and warm amber, architectural perspective. Distinctive complete scene composed for wide banner. Main recognizable platform subject in center and right, bottom-left 22 percent kept quiet for website's live category title. No written headings, no English slogan, no fake interface text. Only exact small watermark 'clashfreenode.com' in upper-right with safe margin, readable and understated. No border, no stock watermark, no repeated template, no photography.
@@ -1,9 +0,0 @@
# 规则、全局与直连配图
原生 SVG 为可编辑源,PNG 为文章 API 上传用图;未使用外部截图。封面沿用 system-proxy-tun-cover.svg 的现有样式;正文两图分别表达路由模式与代理组选择路径。
- `cover.svg` / `cover.png`:960×540。
- `modes.svg` / `modes.png`:1000×670。
- `groups.svg` / `groups.png`:1000×610。
正文源:../../clash-routing-modes.md。技术图使用本机 Chrome 在禁网页面渲染,正式展示副本通过文章资产 API 发布。制作/发布记录见 ../../../../maintenance/ROUTING_MODES_2026-10-31.md。
Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="960" height="540" viewBox="0 0 960 540"><rect width="960" height="540" fill="#eaf2f7"/><rect x="55" y="62" width="6" height="412" fill="#347c99"/><g font-family="Arial, PingFang SC, Microsoft YaHei, sans-serif"><text x="97" y="130" font-size="24" fill="#47748a" letter-spacing="3">代理设置 · 综合教程</text><text x="97" y="265" font-size="51" fill="#18394d" font-weight="700">规则、全局与直连</text><text x="100" y="327" font-size="30" fill="#547084">分流模式 · 代理组 · 连接验证</text><path d="M100 403H725" stroke="#92b6c9" stroke-width="3"/><circle cx="100" cy="403" r="9" fill="#347c99"/><circle cx="410" cy="403" r="9" fill="#347c99"/><circle cx="725" cy="403" r="9" fill="#347c99"/></g></svg>

Before

Width:  |  Height:  |  Size: 775 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 84 KiB

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="610" viewBox="0 0 1000 610"><rect width="1000" height="610" rx="20" fill="#f0f5f7"/><g font-family="PingFang SC, Microsoft YaHei, sans-serif"><text x="45" y="64" font-size="34" fill="#264658" font-weight="600">同一条影音规则,两种不同的组内选择</text><text x="45" y="115" font-size="29" fill="#264658" font-weight="600">情况一:影音组直接选择节点甲</text><rect x="45" y="145" width="275" height="95" rx="14" fill="#fff" stroke="#bed0d9"/><text x="69" y="204" font-size="30" fill="#264658" font-weight="600">影音规则</text><text x="326" y="204" font-size="29" fill="#264658" font-weight="400">→</text><rect x="363" y="145" width="275" height="95" rx="14" fill="#fff" stroke="#bed0d9"/><text x="387" y="204" font-size="30" fill="#264658" font-weight="600">影音组</text><text x="644" y="204" font-size="29" fill="#264658" font-weight="400">→</text><rect x="681" y="145" width="275" height="95" rx="14" fill="#e3edf3" stroke="#bed0d9"/><text x="705" y="204" font-size="30" fill="#264658" font-weight="600">节点甲</text><text x="45" y="285" font-size="26" fill="#5d7380" font-weight="400">调整“节点选择”不会改变上面这条选择路径。</text><text x="45" y="345" font-size="29" fill="#264658" font-weight="600">情况二:影音组选择另一个代理组</text><rect x="45" y="375" width="195" height="95" rx="14" fill="#fff" stroke="#bed0d9"/><text x="69" y="434" font-size="30" fill="#264658" font-weight="600">影音规则</text><text x="246" y="434" font-size="29" fill="#264658" font-weight="400">→</text><rect x="283" y="375" width="195" height="95" rx="14" fill="#fff" stroke="#bed0d9"/><text x="307" y="434" font-size="30" fill="#264658" font-weight="600">影音组</text><text x="484" y="434" font-size="29" fill="#264658" font-weight="400">→</text><rect x="521" y="375" width="195" height="95" rx="14" fill="#fff" stroke="#bed0d9"/><text x="545" y="434" font-size="30" fill="#264658" font-weight="600">节点选择</text><text x="722" y="434" font-size="29" fill="#264658" font-weight="400">→</text><rect x="759" y="375" width="195" height="95" rx="14" fill="#e3edf3" stroke="#bed0d9"/><text x="783" y="434" font-size="30" fill="#264658" font-weight="600">节点乙</text><text x="45" y="515" font-size="26" fill="#5d7380" font-weight="400">此时调整“节点选择”,才会影响影音连接的后续出口。</text><text x="45" y="571" font-size="26" fill="#5d7380" font-weight="400">示意组名:请以自己的配置与新连接详情为准。</text></g></svg>

Before

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 KiB

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1000" height="670" viewBox="0 0 1000 670"><rect width="1000" height="670" rx="20" fill="#f0f5f7"/><g font-family="PingFang SC, Microsoft YaHei, sans-serif"><text x="45" y="64" font-size="34" fill="#264658" font-weight="600">模式决定:已进入客户端的连接怎样出去</text><rect x="45" y="105" width="910" height="86" rx="14" fill="#fff" stroke="#bed0d9"/><text x="75" y="159" font-size="32" fill="#264658" font-weight="600">请求已进入 Mihomo</text><rect x="45" y="245" width="154" height="100" rx="14" fill="#e1ece8" stroke="#bed0d9"/><text x="87" y="306" font-size="32" fill="#264658" font-weight="600">规则</text><text x="214" y="306" font-size="32" fill="#264658" font-weight="400">→</text><rect x="265" y="245" width="330" height="100" rx="14" fill="#fff" stroke="#bed0d9"/><text x="290" y="305" font-size="29" fill="#264658" font-weight="400">匹配当前规则</text><text x="612" y="306" font-size="32" fill="#264658" font-weight="400">→</text><rect x="665" y="245" width="290" height="100" rx="14" fill="#fff" stroke="#bed0d9"/><text x="685" y="305" font-size="26" fill="#264658" font-weight="400">代理组 / 直连 / 拒绝</text><rect x="45" y="375" width="154" height="100" rx="14" fill="#e1eaf3" stroke="#bed0d9"/><text x="87" y="436" font-size="32" fill="#264658" font-weight="600">全局</text><text x="214" y="436" font-size="32" fill="#264658" font-weight="400">→</text><rect x="265" y="375" width="330" height="100" rx="14" fill="#fff" stroke="#bed0d9"/><text x="290" y="435" font-size="29" fill="#264658" font-weight="400">使用 GLOBAL 当前选择</text><text x="612" y="436" font-size="32" fill="#264658" font-weight="400">→</text><rect x="665" y="375" width="290" height="100" rx="14" fill="#fff" stroke="#bed0d9"/><text x="685" y="435" font-size="26" fill="#264658" font-weight="400">选中的节点或策略</text><rect x="45" y="505" width="154" height="100" rx="14" fill="#efe9df" stroke="#bed0d9"/><text x="87" y="566" font-size="32" fill="#264658" font-weight="600">直连</text><text x="214" y="566" font-size="32" fill="#264658" font-weight="400">→</text><rect x="265" y="505" width="330" height="100" rx="14" fill="#fff" stroke="#bed0d9"/><text x="290" y="565" font-size="29" fill="#264658" font-weight="400">使用本地网络</text><text x="612" y="566" font-size="32" fill="#264658" font-weight="400">→</text><rect x="665" y="505" width="290" height="100" rx="14" fill="#fff" stroke="#bed0d9"/><text x="685" y="565" font-size="26" fill="#264658" font-weight="400">直接连接目标</text><text x="45" y="645" font-size="26" fill="#5d7380" font-weight="400">未进入客户端的连接,不会仅因切换模式而被接管。</text></g></svg>

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 366 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 MiB

@@ -1,3 +0,0 @@
安卓开始使用
A lime-green phone tilted diagonally against midnight indigo, three paper-like configuration cards slide into phone and become an orange flowing connection ribbon; playful but mature geometric editorial illustration, energetic diagonals and spacious composition, no robot mascot.
Watermark: clashfreenode.com; imagegen; 2026-11-01
Binary file not shown.

Before

Width:  |  Height:  |  Size: 491 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 MiB

@@ -1 +0,0 @@
Generate a single 1536x1024 landscape editorial cover. Material/style reference only: the attached image illustrates convincing thick paper cutouts, paper fibers, miniature constructed volumes, soft directional light, mature premium papercraft mixed-media art. DO NOT reuse its composition, boxes, devices, landscape wallpaper, botanical corners, or same color scheme. We need a radically distinct idea, camera view and spatial arrangement for each article, not a family of identical product trays. Physically credible handcrafted diorama and cut-paper collage, sophisticated tactile materials, no flat clip-art, no neon/sci-fi glossy 3D. Let the described subject fill the canvas, preserve safe text margins. Exact large readable heading: "Android 开始使用". Exact small readable watermark lower-right: "clashfreenode.com". No other text. Scene: DYNAMIC DIAGONAL CUT-PAPER CONVEYOR SCULPTURE, playful but mature. An articulate lime-green folded paper courier figure inspired by an Android robot stands at the center operating a red lever. Ochre paper conveyor bands deliver three large ivory configuration cards into a cobalt arched gateway bearing a simple power pictogram. Pink and lime palette with dark navy contrasts, tightly cropped action, realistic cardstock folds and shadows. No real phone, laptop, trays, trees or landscape screens.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 519 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 MiB

Loaded 100 of 340 files, more files were not shown because too many files have changed in this diff. Show more