8 changed files with 590 additions and 105 deletions

No files matched your search

@@ -0,0 +1,24 @@
<?php
namespace App\Console\Commands;
use App\Services\Ranking\SitePublisher;
use App\Services\Ranking\WeeklyRanking;
use Illuminate\Console\Command;
final class RegisterPublishedRankingMerchants extends Command
{
protected $signature = 'ranking:register-published-merchants';
protected $description = '为已发布的单商家测评补登记商家';
public function handle(): int
{
$ranking = new WeeklyRanking(new SitePublisher(dirname(base_path())));
$names = $ranking->registerPublishedMerchants();
$this->info('新增自动登记商家 '.count($names).' 家。');
foreach ($names as $name) {
$this->line($name);
}
return self::SUCCESS;
}
}
+16 -4
View File
@@ -8,11 +8,23 @@ use Symfony\Component\Yaml\Yaml;
final class ArticleArtifact
{
public function build(array $data): array
public function build(array $data, bool $legacyPermalink = false): array
{
validator($data, ['source_key' => 'required|string|max:160', 'revision' => 'required|string|size:64', 'generation' => 'required|integer|min:1', 'title' => 'required|string|max:200', 'text' => 'present|string|max:100000', 'sent_at' => 'required|date', 'images' => 'present|array|max:30', 'images.*.sha256' => 'required|regex:/^[a-f0-9]{64}$/D', 'images.*.mime' => 'required|in:image/png,image/jpeg,image/webp,image/gif', 'images.*.bytes' => 'required|integer|min:1|max:20971520'])->validate();
validator($data, ['links' => 'sometimes|array|max:100', 'links.*.offset' => 'required|integer|min:0', 'links.*.length' => 'required|integer|min:1', 'links.*.url' => 'required|string|max:4096'])->validate();
$code = 'telefox-'.substr(hash('sha256', $data['source_key']), 0, 24);
$sourceHash = hash('sha256', $data['source_key']);
$slug = substr($sourceHash, 0, 24);
$code = 'telefox-'.$slug;
$relativePath = 'jccp/'.$code.'.md';
$root = config('content_center.site_root');
$oldPermalink = '/jccp/'.$code.'/';
// The on-disk name still identifies the same source for updates and deletions.
$receiptPath = $root.'/laravel/storage/app/private/content-center/publications/'.$sourceHash.'.json';
$receipt = is_file($receiptPath) ? json_decode(file_get_contents($receiptPath), true, flags: JSON_THROW_ON_ERROR) : null;
$keepOldPermalink = ($receipt['source_key'] ?? null) === $data['source_key']
&& ($receipt['permalink'] ?? null) === $oldPermalink
&& ($receipt['status'] === 'published' || is_file($root.'/vuepress/docs/'.$relativePath));
$permalink = $legacyPermalink || $keepOldPermalink ? $oldPermalink : '/jccp/'.$slug.'/';
$body = "<div v-pre>\n".implode("\n", array_map(fn ($s) => '<p>'.htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8').'</p>', explode("\n", $data['text'])))."\n</div>\n\n";
$review = ReviewFormat::build($data);
if ($review) {
@@ -21,7 +33,7 @@ final class ArticleArtifact
foreach ($data['images'] as $image) {
$body .= '![频道图片](/content-assets/'.$image['sha256'].self::extension($image['mime']).")\n\n";
}
$meta = ['title' => $review['title'] ?? $data['title'], 'createTime' => CarbonImmutable::parse($data['sent_at'], 'UTC')->setTimezone('Asia/Shanghai')->format('Y-m-d H:i:s'), 'permalink' => '/jccp/'.$code.'/', 'articleCode' => $code, 'tags' => $review['tags'] ?? [], 'sourceKey' => $data['source_key']];
$meta = ['title' => $review['title'] ?? $data['title'], 'createTime' => CarbonImmutable::parse($data['sent_at'], 'UTC')->setTimezone('Asia/Shanghai')->format('Y-m-d H:i:s'), 'permalink' => $permalink, 'articleCode' => $code, 'tags' => $review['tags'] ?? [], 'sourceKey' => $data['source_key']];
$series = TitleSeries::metadata($meta['title'], $data['source_key']);
$meta = array_replace($meta, $series);
$document = ['meta' => $meta, 'body' => $body];
@@ -29,7 +41,7 @@ final class ArticleArtifact
$document = ArticleDocument::enrich($document);
}
return ['source_key' => $data['source_key'], 'revision' => $data['revision'], 'generation' => $data['generation'], 'article_code' => $code, 'relative_path' => 'jccp/'.$code.'.md', 'permalink' => $meta['permalink'], 'title' => $document['meta']['title'], 'format_version' => 'ttc-native-v2', 'markdown' => "---\n".Yaml::dump($document['meta'], 6, 2)."---\n".$document['body'], 'images' => $data['images']];
return ['source_key' => $data['source_key'], 'revision' => $data['revision'], 'generation' => $data['generation'], 'article_code' => $code, 'relative_path' => $relativePath, 'permalink' => $permalink, 'title' => $document['meta']['title'], 'format_version' => 'ttc-native-v2', 'markdown' => "---\n".Yaml::dump($document['meta'], 6, 2)."---\n".$document['body'], 'images' => $data['images']];
}
public static function extension(string $mime): string
+25 -4
View File
@@ -2,6 +2,7 @@
namespace App\ContentCenter;
use App\Services\Ranking\MerchantRegistry;
use App\Services\Ranking\SitePublisher;
use App\Services\Ranking\WeeklyRanking;
use RuntimeException;
@@ -15,9 +16,14 @@ final class Publication
return $publisher->locked(function () use ($data, $publisher) {
// Sequence allocation and hash checking share the publication lock.
$artifact = app(ArticleArtifact::class)->build($data['input']);
$hash = ArticleArtifact::hash($artifact);
abort_unless(hash_equals($hash, $data['approved_hash']), 409, '待发稿已变化,必须重新审核。');
$builder = app(ArticleArtifact::class);
$artifact = $builder->build($data['input']);
$hash = $data['approved_hash'];
// A draft approved before the URL change can differ only in its permalink.
if (!hash_equals($hash, ArticleArtifact::hash($artifact))) {
$legacy = $builder->build($data['input'], legacyPermalink: true);
abort_unless(hash_equals($hash, ArticleArtifact::hash($legacy)), 409, '待发稿已变化,必须重新审核。');
}
$directory = config('content_center.site_root').'/laravel/storage/app/private/content-center/publications';
if (! is_dir($directory)) {
mkdir($directory, 0700, true);
@@ -64,7 +70,7 @@ final class Publication
$this->atomic($receipt, json_encode($record, JSON_THROW_ON_ERROR), 0600);
$old = is_file($path) ? file_get_contents($path) : null;
try {
$this->atomic($path, $artifact['markdown'], 0644);
$this->atomic($path, self::siteMarkdown($artifact['markdown']), 0644);
(new WeeklyRanking($publisher))->renderCurrent();
$publisher->build();
} catch (\Throwable) {
@@ -75,6 +81,7 @@ final class Publication
}
throw new RuntimeException('网站构建失败,原文章已恢复;按同一发布编号重试。');
}
(new MerchantRegistry($publisher->root))->registerPublished([$path]);
TitleSeries::commit($artifact['source_key'], $artifact);
$record['status'] = 'published';
$record['published_at'] = now()->toIso8601String();
@@ -154,6 +161,20 @@ final class Publication
});
}
public static function siteMarkdown(string $markdown): string
{
$end = strpos($markdown, "\n---\n", 4);
if (! str_starts_with($markdown, "---\n") || $end === false) {
return $markdown;
}
// Symfony YAML dumps an empty array as a mapping by default. Plume expects tag strings.
// Keep the signed artifact untouched and normalize only its static-site representation.
$frontmatter = substr($markdown, 0, $end);
$normalized = preg_replace('/^tags:\h*\{\h*\}\h*$/m', 'tags: []', $frontmatter, 1);
return $normalized.substr($markdown, $end);
}
private function atomic(string $path, string $data, int $mode): void
{
if (! is_dir(dirname($path))) {
+54 -97
View File
@@ -2,6 +2,10 @@
namespace App\Http\Controllers\Api;
use App\Services\Ranking\ArticleDocument;
use App\Services\Ranking\MerchantRegistry;
use App\Services\Ranking\SitePublisher;
use App\Services\Ranking\WeeklyRanking;
use App\Services\TomTool\Flow;
use App\Services\TomTool\HttpV2;
use App\Services\TomTool\Telegram\Slave as TeleSlave;
@@ -39,18 +43,24 @@ class ArticleController
$this->sKey = $aArg["key"] ?? '';
$this->aConfig = $aArg["config"] ?? '';
if ($this->sCmd == "del") {
$this->cmd_del();
} else if ($this->sCmd == "new") {
$this->cmd_new();
} else {
$sMsg = "未找到cmd的对应处理:".$this->sCmd;
echo $sMsg;
throw new \Exception($sMsg);
}
$this->_npmBuild();
$publisher = new SitePublisher(dirname(base_path()), env('vue_path_node', 'node'));
$publisher->locked(function () use ($publisher) {
if ($this->sCmd == "del") {
$this->cmd_del();
} elseif ($this->sCmd == "new") {
$this->cmd_new();
} else {
throw new \Exception("未找到cmd的对应处理:".$this->sCmd);
}
// Updating availability never changes this week's membership or score.
(new WeeklyRanking($publisher))->renderCurrent();
$publisher->build();
if ($this->sCmd === 'new' && in_array('jccp', $this->aConfig['category'] ?? [], true)) {
$path = $publisher->root.'/vuepress/docs/jccp/'.$this->sArticleCode.'.md';
(new MerchantRegistry($publisher->root))->registerPublished([$path]);
}
});
$arr["aNewPath"] = $this->aNewPath;
echo json_encode($oFlow->setDataA($arr)->done()->getResult());
@@ -71,8 +81,14 @@ class ArticleController
{
$aCategory = $this->aConfig["category"] ?? ["⚠️ 未得到category"];
if (!preg_match('/^[A-Za-z0-9_:-]+$/', $this->sArticleCode)) {
throw new \RuntimeException('文章编号格式异常');
}
foreach ($aCategory as $sCategoryRow) {
$sFileDir = "../../vuepress/docs/{$sCategoryRow}/";
if (!is_string($sCategoryRow) || $sCategoryRow === '' || preg_match('~[\\\\/]|^\.{1,2}$~', $sCategoryRow)) {
throw new \RuntimeException('文章分类格式异常');
}
$sFileDir = dirname(base_path())."/vuepress/docs/{$sCategoryRow}/";
$sFileName = $this->sArticleCode.".md";
$sFilePath = $sFileDir.$sFileName;
@@ -92,94 +108,35 @@ class ArticleController
}
private function _npmBuild()
{
$sVuePathNode = $_ENV['vue_path_node'];
$sVuePath = base_path();
$sVuePath = dirname($sVuePath);
$sVuePath .= "/vuepress";
$sCmd = "cd {$sVuePath} && {$sVuePathNode} ./node_modules/.bin/vuepress build docs";
exec($sCmd . " 2>&1", $output, $returnVar);
$logFile = $sVuePath . "/build.log";
file_put_contents($logFile, implode("\n", $output) . "\n", FILE_APPEND);
if ($returnVar === 0) {
// echo " - VuePress 构建成功!静态文件已生成在 docs/.vuepress/dist\n";
} else {
$sMsg = "VuePress构建失败,请查看日志: ".json_encode($output);
throw new \Exception($sMsg);
}
}
public function cmd_new()
{
$aCategory = $this->aConfig["category"] ?? ["⚠️ 未得到category"];
$aTag = $this->aConfig["tag"] ?? ["⚠️ 未得到tag"];
$sTitle = $this->aArg["article"]["title"] ?? "⚠️ 未得到title";
$sContent = $this->aArg["article"]["content"] ?? "⚠️ 未得到content";
$sEnter = "
";
list(, $iCode) = explode("-", $this->sArticleCode);
foreach ($aCategory as $sCategoryRow) {
$sHead = "---";
$sHead .= $sEnter;
$sHead .= "title: ".$sTitle;
$sHead .= $sEnter;
$sHead .= "tags: ";
$sHead .= $sEnter;
foreach ($aTag as $sTagRow){
$sHead .= " - ".$sTagRow;
$sHead .= $sEnter;
}
$sHead .= "createTime: ".$this->sDate;
$sHead .= $sEnter;
$sTmp = "/{$sCategoryRow}/".$iCode."/";
$this->aNewPath[] = $sTitle." -> new https://".$_ENV["APP_URL"].$sTmp;
$sHead .= "permalink: ".$sTmp;
$sHead .= $sEnter;
$sHead .= "---";
$sArticleFull = $sHead;
$sArticleFull .= $sContent;
$sFileDir = "../../vuepress/docs/{$sCategoryRow}/";
$sFileName = $this->sArticleCode.".md";
$sFilePath = $sFileDir.$sFileName;
if (!file_exists($sFileDir)) {
if (mkdir($sFileDir, 0777, true)) {
// $oFlow->step("文件夹创建成功:$sFileDir\n");
} else {
$sMsg = "创建失败,请检查权限。\n";
echo $sMsg;
throw new \Exception($sMsg);
}
}
$fileHandle = fopen($sFilePath, 'w');
if ($fileHandle === false) {
$sMsg = "错误:无法打开或创建文件 $sFilePath。";
echo $sMsg;
throw new \Exception($sMsg);
} else {
fwrite($fileHandle, $sArticleFull);
fclose($fileHandle);
}
$categories = $this->aConfig['category'] ?? [];
$tags = $this->aConfig['tag'] ?? [];
$title = $this->aArg['article']['title'] ?? '⚠️ 未得到title';
$content = $this->aArg['article']['content'] ?? '⚠️ 未得到content';
$parts = explode('-', $this->sArticleCode, 2);
if (count($parts) !== 2 || !preg_match('/^[A-Za-z0-9_:-]+$/', $this->sArticleCode)) {
throw new \RuntimeException('文章编号格式异常');
}
foreach ($categories as $category) {
if (!is_string($category) || $category === '' || preg_match('~[\\\\/]|^\.{1,2}$~', $category)) {
throw new \RuntimeException('文章分类格式异常');
}
$path = dirname(base_path()).'/vuepress/docs/'.$category.'/'.$this->sArticleCode.'.md';
$existing = is_file($path) ? ArticleDocument::read($path)['meta'] : [];
$meta = $existing;
$meta['title'] = $title;
$meta['baseTitle'] = \App\Services\Ranking\Score::baseTitle($title);
$meta['tags'] = $tags;
$meta['createTime'] = $existing['createTime'] ?? $this->sDate;
$meta['permalink'] = $existing['permalink'] ?? '/'.$category.'/'.$parts[1].'/';
$meta['articleCode'] = $this->sArticleCode;
$document = ArticleDocument::enrich(['meta' => $meta, 'body' => $content]);
ArticleDocument::write($path, ArticleDocument::render($document));
$this->aNewPath[] = $document['meta']['title'].' -> new https://'.$_ENV['APP_URL'].$meta['permalink'];
}
}
}
//---
@@ -0,0 +1,124 @@
<?php
declare(strict_types=1);
namespace App\Services\Ranking;
use RuntimeException;
use Symfony\Component\Yaml\Exception\ParseException;
final class MerchantRegistry
{
private array $aliases = [];
private array $discovered = [];
private array $nonMerchantPrefixes;
private string $hash;
private string $discoveredPath;
public function __construct(private readonly string $root)
{
$path = $root.'/laravel/config/ranking-merchants.json';
if (!is_file($path)) throw new \RuntimeException('缺少商家登记文件 laravel/config/ranking-merchants.json');
$raw = file_get_contents($path);
$data = json_decode($raw, true, flags: JSON_THROW_ON_ERROR);
if (($data['version'] ?? null) !== 1 || !is_array($data['merchants'] ?? null)) throw new \RuntimeException('商家登记格式异常');
foreach ($data['merchants'] as $id => $merchant) {
if (!is_string($id) || !preg_match('/^[a-z0-9][a-z0-9-]*$/', $id) || !is_string($merchant['name'] ?? null) || trim($merchant['name']) === '' || !is_array($merchant['aliases'] ?? null)) throw new \RuntimeException('商家登记条目异常');
foreach (array_merge([$merchant['name']], $merchant['aliases']) as $alias) {
if (!is_string($alias) || trim($alias) === '') throw new \RuntimeException('商家别名不能为空');
$alias = trim($alias);
if (isset($this->aliases[$alias]) && $this->aliases[$alias]['merchant_id'] !== $id) throw new \RuntimeException('商家别名冲突:'.$alias);
$this->aliases[$alias] = ['status' => 'known', 'merchant_id' => $id, 'merchant_name' => $merchant['name']];
}
}
$this->nonMerchantPrefixes = $data['non_merchant_title_prefixes'] ?? [];
if (!is_array($this->nonMerchantPrefixes)) throw new \RuntimeException('综合测评配置格式异常');
foreach ($this->nonMerchantPrefixes as $prefix) if (!is_string($prefix) || trim($prefix) === '') throw new \RuntimeException('综合测评前缀不能为空');
$this->hash = hash('sha256', $raw);
$this->discoveredPath = $root.'/laravel/storage/app/weekly-ranking/discovered-merchants.json';
if (is_file($this->discoveredPath)) {
$names = json_decode(file_get_contents($this->discoveredPath), true, flags: JSON_THROW_ON_ERROR);
if (!is_array($names) || !array_is_list($names)) {
throw new RuntimeException('自动商家登记格式异常');
}
foreach ($names as $name) {
if (!is_string($name) || trim($name) === '') {
throw new RuntimeException('自动商家名称不能为空');
}
$this->discovered[$name] = $name;
}
}
}
public function fingerprint(array $candidates): string
{
// A newly published merchant outside the frozen candidates needs no rebuild.
$relevant = [];
foreach ($candidates as $candidate) {
$identity = $this->resolve($candidate['title']);
if (($identity['automatic'] ?? false) === true) {
$relevant[] = $identity['merchant_id'];
}
}
return $relevant === [] ? $this->hash : hash('sha256', $this->hash.implode('', $relevant));
}
public function resolve(string $title): array
{
$title = trim(Score::baseTitle($title));
foreach ($this->nonMerchantPrefixes as $prefix) {
if (str_starts_with($title, $prefix)) return ['status' => 'non_merchant', 'extracted_name' => null];
}
// Curated aliases take precedence over names derived from a review title.
if (isset($this->aliases[$title])) return $this->aliases[$title] + ['extracted_name' => $title];
if (!preg_match('/^(.+?)机场(?:(?:第[0-9一二三四五六七八九十百]+次)?测评(?:\s*&\s*测速)?|测速(?:(第[0-9]+次))?)$/u', $title, $match) || trim($match[1]) === '') {
return ['status' => 'unknown', 'extracted_name' => null];
}
$name = trim($match[1]);
if (!isset($this->aliases[$name]) && isset($this->discovered[$name])) {
return ['status' => 'known', 'merchant_id' => 'auto-'.hash('sha256', $name), 'merchant_name' => $name, 'extracted_name' => $name, 'automatic' => true];
}
return ($this->aliases[$name] ?? ['status' => 'unknown']) + ['extracted_name' => $name];
}
// The caller holds the publication lock. Backfill also checks for a published copy.
public function registerPublished(array $paths, bool $backfill = false): array
{
$names = [];
$dist = $this->root.'/vuepress/docs/.vuepress/dist';
foreach ($paths as $path) {
try {
$meta = ArticleDocument::read($path)['meta'];
} catch (RuntimeException|ParseException $error) {
if ($backfill) {
continue;
}
throw $error;
}
$link = $meta['permalink'] ?? null;
$title = $meta['baseTitle'] ?? $meta['title'] ?? null;
if (($meta['draft'] ?? false) || ($meta['article'] ?? true) === false || !is_string($title)
|| !is_string($link) || !preg_match('~^/jccp/(?!\.{1,2}/)[^/\x5c\s?#]+/$~uD', $link)) {
continue;
}
if ($backfill) {
$published = $dist.$link.'index.html';
if (!is_file($published) || filemtime($path) > filemtime($published)) {
continue;
}
}
$identity = $this->resolve($title);
$name = $identity['extracted_name'];
if ($identity['status'] === 'unknown' && $name !== null) {
$names[$name] = $name;
}
}
if ($names !== []) {
$all = array_values($this->discovered + $names);
sort($all, SORT_STRING);
ArticleDocument::write($this->discoveredPath, json_encode($all, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR)."\n");
$this->discovered += $names;
}
return array_values($names);
}
}
@@ -0,0 +1,322 @@
<?php
declare(strict_types=1);
namespace App\Services\Ranking;
use DateTimeImmutable;
use DateTimeZone;
final class WeeklyRanking
{
public const MERCHANT_POLICY = 'latest-per-merchant-v2';
private readonly string $docs;
private readonly string $state;
public function __construct(private readonly SitePublisher $publisher)
{
$this->docs = $publisher->root.'/vuepress/docs';
$this->state = $publisher->root.'/laravel/storage/app/weekly-ranking';
}
public static function period(DateTimeImmutable $now): DateTimeImmutable
{
$now = $now->setTimezone(new DateTimeZone('Asia/Shanghai'));
$monday = $now->modify('monday this week')->setTime(14, 0);
return $now < $monday ? $monday->modify('-7 days') : $monday;
}
public static function monthStart(DateTimeImmutable $cutoff): DateTimeImmutable
{
$previous = $cutoff->modify('first day of previous month');
$day = min((int) $cutoff->format('j'), (int) $previous->format('t'));
return $previous->setDate((int) $previous->format('Y'), (int) $previous->format('n'), $day);
}
public static function timestamp(mixed $value): ?int
{
if (!is_string($value) || !preg_match('/^\d{4}[-\/]\d{2}[-\/]\d{2}(?:[ T]\d{2}:\d{2}(?::\d{2})?)?$/', $value)) {
return null;
}
$value = str_replace(['/', 'T'], ['-', ' '], $value);
$format = strlen($value) === 10 ? '!Y-m-d' : (strlen($value) === 16 ? '!Y-m-d H:i' : '!Y-m-d H:i:s');
$date = DateTimeImmutable::createFromFormat($format, $value, new DateTimeZone('Asia/Shanghai'));
$errors = DateTimeImmutable::getLastErrors();
return $date !== false && ($errors === false || ($errors['warning_count'] === 0 && $errors['error_count'] === 0)) ? $date->getTimestamp() : null;
}
public function backfill(): array
{
$changed = 0;
$skipped = [];
foreach ($this->paths() as $path) {
try {
$document = ArticleDocument::read($path);
if (Score::parse($document['body']) === null) {
$skipped[] = basename($path);
continue;
}
$updated = ArticleDocument::enrich($document);
$updated['meta']['articleCode'] ??= pathinfo($path, PATHINFO_FILENAME);
$rendered = ArticleDocument::render($updated);
if ($rendered !== file_get_contents($path)) {
ArticleDocument::write($path, $rendered);
$changed++;
}
} catch (\Throwable) {
$skipped[] = basename($path);
}
}
return ['changed' => $changed, 'skipped' => $skipped];
}
private function paths(): array
{
$directory = $this->docs.'/jccp';
if (!is_dir($directory)) {
return [];
}
$paths = [];
$iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS));
foreach ($iterator as $file) {
if ($file->isFile() && !$file->isLink() && strtolower($file->getExtension()) === 'md') {
$paths[] = $file->getPathname();
}
}
sort($paths, SORT_STRING);
return $paths;
}
public function registerPublishedMerchants(): array
{
return $this->publisher->locked(fn () => (new MerchantRegistry($this->publisher->root))->registerPublished($this->paths(), backfill: true));
}
public function select(DateTimeImmutable $now): array
{
$cutoff = self::period($now);
$articles = [];
$excluded = [];
foreach ($this->paths() as $path) {
try {
$document = ArticleDocument::read($path);
$meta = $document['meta'];
$score = Score::parse($document['body']);
$timestamp = self::timestamp($meta['createTime'] ?? null);
$link = $meta['permalink'] ?? null;
if (($meta['draft'] ?? false) === true || ($meta['article'] ?? true) === false) {
continue;
}
if ($score === null || $timestamp === null || $timestamp >= $cutoff->getTimestamp() || !is_string($link) || !preg_match('~^/jccp/[^\s?#]+/$~u', $link)) {
$excluded[] = basename($path);
continue;
}
$code = (string) ($meta['articleCode'] ?? pathinfo($path, PATHINFO_FILENAME));
$articles[] = [
'article_code' => $code,
'source' => substr($path, strlen($this->docs) + 1),
'title' => Score::title((string) ($meta['baseTitle'] ?? $meta['title'] ?? ''), $score),
'permalink' => $link,
'article_date' => $meta['createTime'],
'timestamp' => $timestamp,
'scores' => $score['items'],
'review_excerpt' => ReviewExcerpt::fromBody($document['body']),
'total' => $score['total'],
'max' => $score['max'],
'tags' => is_array($meta['tags'] ?? null) ? $meta['tags'] : [],
'excerpt' => is_string($meta['excerpt'] ?? null) ? $meta['excerpt'] : '',
'cover' => is_string($meta['cover'] ?? null) ? $meta['cover'] : null,
'lang' => (string) ($meta['lang'] ?? 'zh-CN'),
];
} catch (\Throwable) {
$excluded[] = basename($path);
}
}
usort($articles, fn ($a, $b) => $b['timestamp'] <=> $a['timestamp'] ?: strcmp($a['article_code'], $b['article_code']));
// De-duplicate the same article if a legacy copy exists in a nested directory.
$unique = [];
foreach ($articles as $article) {
$unique[$article['article_code']] ??= $article;
}
$candidates = array_slice(array_values($unique), 0, 20);
return $this->merchantSnapshot([
'week' => self::period($now)->format('Y-m-d'),
'timezone' => 'Asia/Shanghai',
'selection_policy' => 'latest-20',
'candidate_limit' => 20,
'winner_limit' => 10,
'window_start' => null,
'window_end' => $cutoff->format(DATE_ATOM),
'generated_at' => $now->setTimezone(new DateTimeZone('Asia/Shanghai'))->format(DATE_ATOM),
'candidate_count' => count($candidates),
'candidates' => $candidates,
'items' => [],
'excluded' => $excluded,
], new MerchantRegistry($this->publisher->root));
}
private function merchantSnapshot(array $snapshot, MerchantRegistry $registry): array
{
$ordered = $snapshot['candidates'];
usort($ordered, fn ($a, $b) => $b['timestamp'] <=> $a['timestamp'] ?: strcmp($a['article_code'], $b['article_code']));
$merchants = [];
$excluded = [];
$duplicates = [];
foreach ($ordered as $article) {
$identity = $registry->resolve($article['title']);
if ($identity['status'] !== 'known') {
$excluded[] = ['article_code' => $article['article_code'], 'title' => $article['title'], 'status' => $identity['status'], 'extracted_name' => $identity['extracted_name']];
continue;
}
$id = $identity['merchant_id'];
if (isset($merchants[$id])) {
$duplicates[] = ['article_code' => $article['article_code'], 'merchant_id' => $id, 'kept_article_code' => $merchants[$id]['article_code']];
continue;
}
$merchants[$id] = $article + ['merchant_id' => $id, 'merchant_name' => $identity['merchant_name']];
}
// Keep the original 20 article candidates frozen; identity only affects winners.
$snapshot['items'] = self::rank(array_values($merchants));
$snapshot['winner_limit'] = 10;
$snapshot['merchant_policy'] = self::MERCHANT_POLICY;
$snapshot['merchant_registry_hash'] = $registry->fingerprint($snapshot['candidates']);
$snapshot['merchant_count'] = count($merchants);
$snapshot['merchant_exclusions'] = $excluded;
$snapshot['merchant_duplicates'] = $duplicates;
return $snapshot;
}
private static function rank(array $candidates): array
{
$winners = $candidates;
usort($winners, fn ($a, $b) => $b['total'] <=> $a['total'] ?: $b['timestamp'] <=> $a['timestamp'] ?: strcmp($a['article_code'], $b['article_code']));
$winners = array_slice($winners, 0, 10);
foreach ($winners as $index => &$winner) {
$winner['rank'] = $index + 1;
}
unset($winner);
return $winners;
}
public function current(): ?array
{
$path = $this->state.'/current.json';
return is_file($path) ? json_decode(file_get_contents($path), true, flags: JSON_THROW_ON_ERROR) : null;
}
public function refresh(DateTimeImmutable $now, callable $build): array
{
return $this->publisher->locked(function () use ($now, $build) {
$week = self::period($now)->format('Y-m-d');
$current = $this->current();
$registry = new MerchantRegistry($this->publisher->root);
$currentRegistryHash = $registry->fingerprint($current['candidates'] ?? []);
if (($current['week'] ?? null) === $week && ($current['selection_policy'] ?? null) === 'latest-20'
&& ($current['winner_limit'] ?? null) === 10 && ($current['merchant_policy'] ?? null) === self::MERCHANT_POLICY
&& ($current['merchant_registry_hash'] ?? null) === $currentRegistryHash) {
return ['updated' => false, 'snapshot' => $current];
}
$pendingPath = $this->state.'/pending-'.$week.'.json';
if (is_file($pendingPath)) {
$snapshot = json_decode(file_get_contents($pendingPath), true, flags: JSON_THROW_ON_ERROR);
} elseif (($current['week'] ?? null) === $week && ($current['selection_policy'] ?? null) === 'latest-20') {
$snapshot = $current; // Migrate this week's original candidates, never rescan.
} else {
$snapshot = $this->select($now);
}
if (($snapshot['selection_policy'] ?? null) !== 'latest-20') $snapshot = $this->select($now);
if (($snapshot['merchant_policy'] ?? null) !== self::MERCHANT_POLICY
|| ($snapshot['merchant_registry_hash'] ?? null) !== $registry->fingerprint($snapshot['candidates'])
|| ($snapshot['winner_limit'] ?? null) !== 10) {
$snapshot = $this->merchantSnapshot($snapshot, $registry);
}
ArticleDocument::write($pendingPath, $this->json($snapshot));
$pagePath = $this->publisher->root.'/vuepress/data/weekly-ranking.json';
$previousPage = is_file($pagePath) ? file_get_contents($pagePath) : null;
try {
$this->renderPage($snapshot);
$build();
} catch (\Throwable $error) {
if ($previousPage !== null) {
ArticleDocument::write($pagePath, $previousPage);
} elseif (is_file($pagePath)) {
unlink($pagePath);
}
throw $error;
}
if ($current !== null && ($current['selection_policy'] ?? null) !== 'latest-20') {
ArticleDocument::write($this->state.'/before-latest-20-'.$current['week'].'.json', $this->json($current));
}
if ($current !== null && ($current['selection_policy'] ?? null) === 'latest-20' && ($current['winner_limit'] ?? null) !== 10) {
ArticleDocument::write($this->state.'/before-top-10-'.$current['week'].'.json', $this->json($current));
}
if ($current !== null && (($current['merchant_policy'] ?? null) !== self::MERCHANT_POLICY
|| ($current['merchant_registry_hash'] ?? null) !== $currentRegistryHash)) {
$backup = $this->state.'/before-merchant-dedup-'.$current['week'].'-'.substr(hash('sha256', $this->json($current)), 0, 12).'.json';
if (!is_file($backup)) ArticleDocument::write($backup, $this->json($current));
}
ArticleDocument::write($this->state.'/history-'.$week.'.json', $this->json($snapshot));
ArticleDocument::write($this->state.'/current.json', $this->json($snapshot));
unlink($pendingPath);
return ['updated' => true, 'snapshot' => $snapshot];
});
}
public function renderCurrent(): void
{
if (($snapshot = $this->current()) !== null) {
$this->renderPage($snapshot);
}
}
private function json(array $value): string
{
return json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)."\n";
}
private function renderPage(array $snapshot): void
{
$posts = [];
foreach ($snapshot['items'] as $item) {
$available = false;
$review = $item['review_excerpt'] ?? '';
$document = null;
$source = $item['source'];
if (!str_contains($source, '..') && str_starts_with($source, 'jccp/')) {
try {
$document = ArticleDocument::read($this->docs.'/'.$source);
$available = ($document['meta']['draft'] ?? false) !== true
&& ($document['meta']['article'] ?? true) !== false
&& ($document['meta']['permalink'] ?? null) === $item['permalink'];
} catch (\Throwable) {}
}
// Legacy snapshots did not store the review; keep scores frozen and use
// the source review only for those existing snapshots.
if (!array_key_exists('review_excerpt', $item) && $available && $document !== null) {
$review = ReviewExcerpt::fromBody($document['body']);
}
// The display format can evolve without changing the frozen score or order.
$title = Score::title($item['title'], ['total' => $item['total'], 'max' => $item['max']]);
$posts[] = [
'path' => $item['permalink'],
'title' => $title,
'createTime' => str_replace('-', '/', $item['article_date']),
'tags' => $item['tags'] ?? [],
'categoryList' => [],
'excerpt' => $review.RatingExcerpt::fromScores($item['scores'] ?? []),
'cover' => $item['cover'] ?? null,
'lang' => $item['lang'] ?? 'zh-CN',
'rank' => $item['rank'],
'available' => $available,
];
}
$path = $this->publisher->root.'/vuepress/data/weekly-ranking.json';
$content = $this->json([
'week' => $snapshot['week'],
'posts' => $posts,
]);
if (!is_file($path) || file_get_contents($path) !== $content) {
ArticleDocument::write($path, $content);
}
}
}
+4
View File
@@ -15,6 +15,10 @@ return Application::configure(basePath: dirname(__DIR__))
)
->withMiddleware(function (Middleware $middleware) {
$middleware->append(\App\ContentCenter\ProtectLegacyImport::class);
// The signed content contract allows an empty caption for image-only drafts.
$middleware->convertEmptyStringsToNull(except: [
static fn (\Illuminate\Http\Request $request): bool => $request->is('api/content/v1/preview', 'api/content/v1/publish'),
]);
$middleware->alias([
//'test' => \App\Http\Middleware\Test::class,
]);
@@ -39,6 +39,7 @@ final class ContentCenterTest extends TestCase
File::makeDirectory($this->root.'/vuepress/node_modules/.bin', 0755, true);
File::makeDirectory($this->root.'/vuepress/docs/jccp', 0755, true);
File::makeDirectory($this->root.'/laravel/storage/app/weekly-ranking', 0755, true);
ArticleDocument::write($this->root.'/laravel/config/ranking-merchants.json', '{"version":1,"merchants":{}}');
file_put_contents($this->root.'/vuepress/node_modules/.bin/vuepress', '<?php $dest=$argv[array_search("--dest",$argv)+1];mkdir($dest,0755,true);file_put_contents($dest."/index.html","isolated test build");');
config(['content_center.environment' => 'local', 'content_center.enabled' => true, 'content_center.atom_key' => str_repeat('k', 40), 'content_center.atom_url' => 'http://atom.loc', 'content_center.site_root' => $this->root, 'content_center.node' => PHP_BINARY, 'cache.default' => 'array']);
}
@@ -76,6 +77,26 @@ final class ContentCenterTest extends TestCase
$this->signed('/api/content/v1/preview', $this->input(), $nonce)->assertStatus(409);
}
public function test_signed_preview_and_publish_preserve_an_empty_caption(): void
{
$bytes = base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', true);
$image = ['sha256' => hash('sha256', $bytes), 'mime' => 'image/gif', 'bytes' => strlen($bytes)];
$input = array_replace($this->input(), ['text' => '', 'images' => [$image]]);
$response = $this->signed('/api/content/v1/preview', $input)->assertOk();
$this->assertStringContainsString('/content-assets/'.$image['sha256'].'.gif', $response->json('artifact.markdown'));
$directory = $this->root.'/vuepress/docs/.vuepress/public/content-assets';
File::ensureDirectoryExists($directory);
file_put_contents($directory.'/'.$image['sha256'].'.gif', $bytes);
$payload = ['approval_id' => (string) Str::uuid(), 'approved_hash' => $response->json('artifact_hash'), 'input' => $input];
$this->signed('/api/content/v1/publish', $payload)->assertOk()->assertJsonPath('receipt.artifact_hash', $payload['approved_hash']);
unset($input['text']);
$this->signed('/api/content/v1/preview', $input)->assertUnprocessable()->assertJsonValidationErrors('text');
$input['text'] = null;
$this->signed('/api/content/v1/preview', $input)->assertUnprocessable()->assertJsonValidationErrors('text');
}
private function reviewInput(): array
{
return array_replace($this->input(), ['title' => '#测试云 #vless', 'text' => "#测试云 #vless\n\n📊 主观评分\n稳定 ★★☆☆☆\n速度 ★★☆☆☆\n延迟 ★★★☆☆\n性价比 ★★★☆☆\n(以上评分仅供参考)\n\n😀机场自介:\n自介内容\n\n😀 链接导航\n官网:点击进入\n\n😀主观点评\n点评内容 <script>bad()</script> {{ danger }}\n\n😀翻翻墙提醒您\n原始提醒"]);