TermIndexService.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Channel;
  4. use App\Models\DhammaTerm;
  5. use App\Models\GroupInfo;
  6. use App\Models\TermCategory;
  7. use App\Models\UserInfo;
  8. use App\Services\Markup\Format;
  9. use App\Services\Markup\MarkupService;
  10. use App\Services\Markup\RenderOptions;
  11. use Illuminate\Database\Eloquent\ModelNotFoundException;
  12. /**
  13. * 术语写进 OpenSearch(全站搜索用)。v2 与 v3 的写入、`IndexTerm` 命令共用。
  14. *
  15. * 渲染用新渲染器({@see MarkupService}):内容 = 摘要 + 正文,按 content_type 的方言解析,
  16. * 模板按术语所在 channel 取数。分类与质量优先取 v3 的列(term_categories、quality),
  17. * 没有时(v2 写入的条目)从正文的 `{{category|…}}` / `{{quality|…}}` 抽。
  18. */
  19. class TermIndexService
  20. {
  21. public function __construct(
  22. protected OpenSearchService $openSearchService,
  23. protected MarkupService $markup,
  24. ) {}
  25. /**
  26. * 构建单条词条文档并写入 OpenSearch
  27. *
  28. * @param string $guid DhammaTerm 的 guid
  29. */
  30. public function index(string $guid): void
  31. {
  32. $document = $this->buildDocument($guid);
  33. $this->openSearchService->create($document['id'], $document);
  34. }
  35. /**
  36. * 构建单条词条的 OpenSearch 文档(不写入)
  37. *
  38. * 文档结构遵循新版 mapping:
  39. * title.text.pali / title.text.zh → 全文检索
  40. * title.suggest.pali / title.suggest.zh → 自动建议
  41. * content.text.pali / content.text.zh → 正文内容
  42. *
  43. * @param string $guid DhammaTerm 的 guid
  44. * @return array<string, mixed>
  45. *
  46. * @throws ModelNotFoundException 术语不存在(含已删除)
  47. */
  48. public function buildDocument(string $guid): array
  49. {
  50. $term = DhammaTerm::where('guid', $guid)->firstOrFail();
  51. $channelName = $term->channal ? (string) Channel::where('uid', $term->channal)->value('name') : '';
  52. $studioName = (string) (UserInfo::where('userid', $term->owner)->value('username')
  53. ?? GroupInfo::where('uid', $term->owner)->value('name')
  54. ?? '');
  55. $summary = trim((string) $term->summary);
  56. $options = [
  57. 'channels' => $term->channal ? [$term->channal] : [],
  58. 'contentType' => $term->effectiveContentType(),
  59. ];
  60. $rendered = $this->markup->renderManyAs([
  61. 'body' => $options + ['source' => trim($summary."\n\n".(string) $term->note)],
  62. 'summary' => $options + ['source' => $summary !== '' ? $summary : (string) $term->note],
  63. ], new RenderOptions(lang: $term->language ?: 'zh-Hans'), [Format::Html, Format::Text]);
  64. $display = (string) $rendered[Format::Html->value]['body'];
  65. $plainText = (string) $rendered[Format::Text->value]['body'];
  66. $summaryText = $this->firstLine((string) $rendered[Format::Text->value]['summary'], $summary !== '');
  67. $categories = TermCategory::where('term_guid', $term->guid)->orderBy('position')->pluck('category')->all()
  68. ?: $this->extractCategories((string) $term->note);
  69. $quality = $term->quality ?: $this->extractFirstQuality((string) $term->note);
  70. $tags = [];
  71. foreach ($categories as $category) {
  72. $tags[] = "category:{$category}";
  73. }
  74. if (! empty($quality)) {
  75. $tags[] = "quality:{$quality}";
  76. }
  77. return [
  78. 'id' => "term_{$term->guid}",
  79. 'resource_id' => $term->guid,
  80. 'resource_type' => 'term',
  81. 'title' => [
  82. 'text' => [
  83. 'pali' => $term->word,
  84. 'zh' => $term->meaning,
  85. ],
  86. 'suggest' => [
  87. 'pali' => [$term->word],
  88. 'zh' => [$term->meaning],
  89. ],
  90. ],
  91. 'summary' => [
  92. 'text' => $summaryText,
  93. ],
  94. // TODO: 补充语言判断,将内容放入对应的 text.pali 或 text.zh 字段
  95. 'content' => [
  96. 'text' => ['zh' => $plainText !== '' ? $plainText : (string) $term->meaning],
  97. 'display' => $display !== '' ? $display : (string) $term->meaning,
  98. ],
  99. 'bold_single' => [$term->meaning, $term->word],
  100. 'related_id' => $term->word,
  101. 'category' => null,
  102. 'tags' => $tags,
  103. 'language' => $term->language,
  104. 'updated_at' => now()->toIso8601String(),
  105. 'path' => "{$studioName}/{$channelName}",
  106. 'metadata' => ['channel' => $term->channal],
  107. ];
  108. }
  109. /**
  110. * 摘要纯文本:给了 summary 就整段用;没给取正文第一段(纯文本里段落之间只隔一个换行)。
  111. */
  112. private function firstLine(string $text, bool $whole): string
  113. {
  114. if ($whole) {
  115. return trim($text);
  116. }
  117. foreach (preg_split('/\n/u', $text) ?: [] as $line) {
  118. if (trim($line) !== '') {
  119. return trim($line);
  120. }
  121. }
  122. return '';
  123. }
  124. /**
  125. * 提取 Markdown 中的 {{category|...}} 分类标签
  126. *
  127. * @return array<int, string>
  128. */
  129. private function extractCategories(string $content): array
  130. {
  131. if (empty($content)) {
  132. return [];
  133. }
  134. preg_match_all('/\{\{category\|([^}]+)\}\}/u', $content, $matches);
  135. return array_values(array_filter(array_map(
  136. fn ($item) => trim($item),
  137. $matches[1] ?? []
  138. )));
  139. }
  140. /**
  141. * 提取 Markdown 中第一个 {{quality|...}} 标签内的内容
  142. */
  143. private function extractFirstQuality(string $content): string
  144. {
  145. if (empty($content)) {
  146. return '';
  147. }
  148. preg_match('/\{\{quality\|([^}]+)\}\}/u', $content, $matches);
  149. return isset($matches[1]) ? trim($matches[1]) : '';
  150. }
  151. }