WikiService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Channel;
  4. use App\Models\DhammaTerm;
  5. use App\Models\TermCategory;
  6. use App\Services\Markup\Format;
  7. use App\Services\Markup\MarkupService;
  8. use App\Services\Markup\RenderOptions;
  9. use App\Services\V3\ChannelAbilityService;
  10. use Illuminate\Auth\Access\AuthorizationException;
  11. use Illuminate\Database\Eloquent\Builder;
  12. use Illuminate\Database\Eloquent\ModelNotFoundException;
  13. use Illuminate\Support\Collection;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Str;
  16. /**
  17. * library 百科页(`/library/wiki/*`)的数据:按分类列词条、词条详情、相关词条、其它版本。
  18. *
  19. * 直接查库,不经 OpenSearch:质量取 dhamma_terms.quality,分类取 term_categories(v3 写入时从正文
  20. * `{{category|…}}` 抽出),摘要取 summary 或正文第一段。正文用新渲染器({@see MarkupService})出 HTML。
  21. *
  22. * 列表、相关词条、其它版本只列公开的:所在 channel 会被列出(status 30 或系统 channel,
  23. * {@see ChannelAbilityService::scopeListable()}),或 studio 级术语(不属于任何 channel)。
  24. * 按 guid 打开的词条页按「能访问」判(公开不列出的也能看,私有 403)。
  25. */
  26. class WikiService
  27. {
  28. /** 质量等级,数值越小越高;空按 pending */
  29. public const QUALITY_RANK = ['featured' => 1, 'standard' => 2, 'draft' => 3, 'pending' => 4];
  30. public function __construct(
  31. private readonly ChannelAbilityService $channels,
  32. private readonly MarkupService $markup,
  33. private readonly UserService $users,
  34. ) {}
  35. /**
  36. * 某组分类下的词条,质量不低于 $minQuality。同一个「词 + 释义」只留质量最高的一条。
  37. *
  38. * @param list<string> $categories
  39. * @return list<array{id: string, word: string, zh: string, quality: string}>
  40. */
  41. public function categoryEntries(array $categories, string $lang, string $minQuality): array
  42. {
  43. if ($categories === []) {
  44. return [];
  45. }
  46. $maxRank = self::QUALITY_RANK[$minQuality] ?? 4;
  47. $terms = $this->publicTerms($lang)
  48. ->whereIn('guid', TermCategory::query()->selectRaw('term_guid::text')->whereIn('category', $categories))
  49. ->orderBy('word')
  50. ->limit(1000)
  51. ->get(['guid', 'word', 'meaning', 'quality']);
  52. $unique = [];
  53. foreach ($terms as $term) {
  54. $quality = $term->quality ?? 'pending';
  55. $rank = self::QUALITY_RANK[$quality] ?? 4;
  56. if ($rank > $maxRank) {
  57. continue;
  58. }
  59. $key = mb_strtolower(trim($term->word).'|'.trim($term->meaning));
  60. if (isset($unique[$key]) && (self::QUALITY_RANK[$unique[$key]['quality']] ?? 4) <= $rank) {
  61. continue;
  62. }
  63. $unique[$key] = ['id' => (string) $term->guid, 'word' => (string) $term->word, 'zh' => (string) $term->meaning, 'quality' => $quality];
  64. }
  65. return array_values($unique);
  66. }
  67. /**
  68. * 按 guid 或词找要显示的词条。
  69. *
  70. * - guid:这一条,拿到链接就能看(公开不列出的也行),私有 channel 的 403
  71. * - 词:先找该语言社区 channel(`_community_translation_{lang}_`)里的,没有就取公开词条里质量最高、最近更新的
  72. *
  73. * @throws AuthorizationException guid 指向私有 channel 的术语
  74. */
  75. public function find(string $lang, string $wordOrId): ?DhammaTerm
  76. {
  77. if (Str::isUuid($wordOrId)) {
  78. return $this->accessibleTerm($wordOrId);
  79. }
  80. $community = Channel::where('name', '_community_translation_'.strtolower($lang).'_')
  81. ->where('owner_uid', config('mint.admin.root_uuid'))
  82. ->value('uid');
  83. if ($community) {
  84. $term = DhammaTerm::where('channal', $community)->where('word', $wordOrId)->first();
  85. if ($term) {
  86. return $term;
  87. }
  88. }
  89. return $this->publicTerms($lang)
  90. ->where('word', $wordOrId)
  91. ->orderByRaw("case coalesce(quality, 'pending') when 'featured' then 1 when 'standard' then 2 when 'draft' then 3 else 4 end")
  92. ->orderByDesc('updated_at')
  93. ->first();
  94. }
  95. /**
  96. * 按 guid 取一条:拿到链接就能看,与「会不会被列出」无关。
  97. *
  98. * channel 是公开(30)或公开不列出(20)、系统 channel、或 studio 级术语都能看;
  99. * library 没有登录态,私有 channel 的一律 403({@see ChannelAbilityService::assertReadable()}),
  100. * 术语或它所在的 channel 不存在(含软删)返回 null(404)。
  101. *
  102. * @throws AuthorizationException
  103. */
  104. private function accessibleTerm(string $guid): ?DhammaTerm
  105. {
  106. $term = DhammaTerm::where('guid', $guid)->first();
  107. if ($term === null) {
  108. return null;
  109. }
  110. $channelUid = $term->channelUid();
  111. if ($channelUid !== null) {
  112. try {
  113. $this->channels->assertReadable($channelUid, null);
  114. } catch (ModelNotFoundException) {
  115. return null;
  116. }
  117. }
  118. return $term;
  119. }
  120. /**
  121. * 重定向的目标(`word` 或 `word@tag`):先在同一 channel(studio 级的在同一 owner 的 studio 级术语)里找,
  122. * 找不到返回 null(读者停在原词条上)。
  123. */
  124. public function redirectTarget(DhammaTerm $term): ?DhammaTerm
  125. {
  126. $redirect = trim((string) $term->redirect);
  127. if ($redirect === '') {
  128. return null;
  129. }
  130. [$word, $tag] = array_pad(explode('@', $redirect, 2), 2, '');
  131. $query = DhammaTerm::query()->where('word', $word);
  132. $tag === ''
  133. ? $query->where(fn (Builder $q) => $q->whereNull('tag')->orWhere('tag', ''))
  134. : $query->where('tag', $tag);
  135. $term->channelUid() !== null
  136. ? $query->where('channal', $term->channelUid())
  137. : $query->studioLevel()->where('owner', $term->owner);
  138. $target = $query->first();
  139. return $target && $target->guid !== $term->guid ? $target : null;
  140. }
  141. /**
  142. * 正文 HTML:摘要 + 正文(摘要在前,不加分隔),用词条所在 channel 解析模板。
  143. *
  144. * 正文里的分类(`{{category|…}}`,渲染器输出 `span.tpl-category[data-category]`)换成指向
  145. * 该分类词条列表的链接,$lang 是当前百科页的语言。
  146. */
  147. public function contentHtml(DhammaTerm $term, string $lang): string
  148. {
  149. $source = trim(trim((string) $term->summary)."\n\n".(string) $term->note);
  150. $html = (string) $this->markup->render($source, new RenderOptions(
  151. format: Format::Html,
  152. channels: $term->channal ? [$term->channal] : [],
  153. contentType: $term->effectiveContentType(),
  154. lang: $term->language ?: 'zh-Hans',
  155. ));
  156. return (string) preg_replace_callback(
  157. '#<span class="tpl-category" data-category="([^"]*)">(.*?)</span>#u',
  158. function (array $m) use ($lang) {
  159. $name = html_entity_decode($m[1], ENT_QUOTES | ENT_HTML5);
  160. $url = route('library.wiki.index', ['lang' => $lang, 'category' => $name]);
  161. return '<a class="tpl-category" href="'.e($url).'">'.$m[2].'</a>';
  162. },
  163. $html,
  164. );
  165. }
  166. /**
  167. * 这条词条的分类(按正文里出现的顺序)。
  168. *
  169. * @return list<string>
  170. */
  171. public function categoriesOf(DhammaTerm $term): array
  172. {
  173. return TermCategory::where('term_guid', $term->guid)->orderBy('position')->pluck('category')->all();
  174. }
  175. /**
  176. * 与它共享分类的其它公开词条,最多 $limit 条,共享分类越多越靠前。
  177. *
  178. * @param list<string> $categories
  179. * @return list<array{word: string, zh: string, lang: string}>
  180. */
  181. public function related(DhammaTerm $term, array $categories, int $limit = 5): array
  182. {
  183. if ($categories === []) {
  184. return [];
  185. }
  186. $shared = TermCategory::query()
  187. ->selectRaw('term_guid::text as guid, count(*) as shared')
  188. ->whereIn('category', $categories)
  189. ->where('term_guid', '<>', $term->guid)
  190. ->groupBy('term_guid');
  191. return $this->publicTerms(null)
  192. ->joinSub($shared, 'shared', 'shared.guid', '=', 'dhamma_terms.guid')
  193. ->orderByDesc('shared.shared')
  194. ->orderBy('dhamma_terms.word')
  195. ->limit($limit)
  196. ->get(['dhamma_terms.word', 'dhamma_terms.meaning', 'dhamma_terms.language'])
  197. ->map(fn (DhammaTerm $t) => ['word' => (string) $t->word, 'zh' => (string) $t->meaning, 'lang' => (string) $t->language])
  198. ->all();
  199. }
  200. /**
  201. * 词条的编辑者与协作者(人类授权代写的 AI 模型),给词条头部的头像组用。
  202. *
  203. * @return list<array{name: string, username: string, avatar: string|null, initials: string, color: string}>
  204. */
  205. public function editors(DhammaTerm $term): array
  206. {
  207. $term->loadMissing([...UserService::eagerLoadActor(), UserService::eagerLoadAssistant('coEditor')]);
  208. $people = [$this->users->actor($term->user, $term->aiModel)];
  209. if ($term->coEditor) {
  210. $people[] = $this->users->assistantProfile($term->coEditor);
  211. }
  212. return array_map(fn (array $p) => [
  213. 'name' => (string) $p['nickName'],
  214. 'username' => (string) $p['userName'],
  215. 'avatar' => ($p['avatar'] ?? '') ?: null,
  216. 'initials' => mb_substr((string) $p['nickName'], 0, 2),
  217. 'color' => TipitakaCatalogService::channelColor((string) $p['id']),
  218. ], $people);
  219. }
  220. /**
  221. * 同一个词的其它公开版本(其它 channel、其它语言),最多 $limit 条。摘要是纯文本。
  222. *
  223. * @return list<array{type: string, id: string, lang: string, title: string, quality: string, category: string, snippet: string, updated: string}>
  224. */
  225. public function otherVersions(DhammaTerm $term, int $limit = 10): array
  226. {
  227. $versions = $this->publicTerms(null)
  228. ->where('word', $term->word)
  229. ->where('guid', '<>', $term->guid)
  230. ->orderByDesc('updated_at')
  231. ->limit($limit)
  232. ->get(['guid', 'word', 'meaning', 'language', 'quality', 'summary', 'note', 'content_type', 'channal', 'updated_at']);
  233. return $this->withSnippets($versions)->map(fn (DhammaTerm $t) => [
  234. 'type' => 'term',
  235. 'id' => (string) $t->guid,
  236. 'lang' => (string) $t->language,
  237. 'title' => (string) $t->meaning,
  238. 'quality' => $t->quality ?? 'pending',
  239. 'category' => '法义术语',
  240. 'snippet' => (string) $t->snippet,
  241. 'updated' => $t->updated_at?->toIso8601String() ?? '',
  242. ])->all();
  243. }
  244. /**
  245. * 公开的词条:所在 channel 会被列出,或 studio 级术语。$lang 给了就只要这种语言的。
  246. *
  247. * @return Builder<DhammaTerm>
  248. */
  249. private function publicTerms(?string $lang): Builder
  250. {
  251. $query = DhammaTerm::query()->where(function (Builder $q) {
  252. $q->studioLevel()->orWhereIn('channal', function ($sub) {
  253. $sub->selectRaw('uid::text')->from('channels')->whereNull('deleted_at');
  254. $this->channels->scopeListable($sub, null);
  255. });
  256. });
  257. if ($lang !== null) {
  258. $query->whereIn(DB::raw('lower(language)'), $this->languageVariants($lang));
  259. }
  260. return $query;
  261. }
  262. /**
  263. * 库里的语言写法不统一(zh-Hans / zh-hans / zh)。
  264. *
  265. * @return list<string>
  266. */
  267. private function languageVariants(string $lang): array
  268. {
  269. $lang = strtolower($lang);
  270. return match ($lang) {
  271. 'zh-hans', 'zh-cn', 'zh' => ['zh-hans', 'zh-cn', 'zh'],
  272. 'zh-hant', 'zh-tw' => ['zh-hant', 'zh-tw'],
  273. default => [$lang],
  274. };
  275. }
  276. /**
  277. * 给每条挂上纯文本摘要(`snippet`):有 summary 用它,没有取正文第一段。整批渲染一次。
  278. *
  279. * @param Collection<int, DhammaTerm> $terms
  280. * @return Collection<int, DhammaTerm>
  281. */
  282. private function withSnippets(Collection $terms): Collection
  283. {
  284. $items = [];
  285. foreach ($terms as $term) {
  286. $summary = trim((string) $term->summary);
  287. $items[$term->guid] = [
  288. 'source' => $summary !== '' ? $summary : (string) $term->note,
  289. 'channels' => $term->channal ? [$term->channal] : [],
  290. 'contentType' => $term->effectiveContentType(),
  291. ];
  292. }
  293. $texts = $items === [] ? [] : $this->markup->renderMany($items, new RenderOptions(format: Format::Text));
  294. return $terms->each(function (DhammaTerm $term) use ($texts) {
  295. $text = (string) ($texts[$term->guid] ?? '');
  296. $first = '';
  297. foreach (preg_split('/\n/u', $text) ?: [] as $line) {
  298. if (trim($line) !== '') {
  299. $first = trim($line);
  300. break;
  301. }
  302. }
  303. $term->snippet = Str::limit($first, 200);
  304. });
  305. }
  306. }