ChannelProgressService.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Models\Channel;
  4. use App\Models\CustomBook;
  5. use App\Models\Sentence;
  6. use App\Services\UserService;
  7. use Illuminate\Auth\Access\AuthorizationException;
  8. use Illuminate\Support\Collection;
  9. /**
  10. * 一批句子在各 channel 的完成度(编辑器的「选版本」面板用)。
  11. *
  12. * 取代 v2 `ChannelController@progress`(`POST /v2/channel-progress`)。v2 那份逐个 channel 查句子(N+1);
  13. * 这里固定 4 次查询:原文长度、有内容的 channel、channel 本身、各 channel 的已译句子。
  14. *
  15. * 列哪些 channel:这些句子上**有译文且看得见**的,加上**我能写的**(没译文也列,好让人挑一个开始写)。
  16. * 给了 `studio` 就只列该 studio(本人或团队)名下的——团队空间传团队 uuid。
  17. */
  18. class ChannelProgressService
  19. {
  20. /** 一次最多查多少句(一章通常几百句) */
  21. public const MAX_SENTENCES = 2000;
  22. /** 原文所在的系统 channel(巴利三藏);自定义书(book ≥ 1000)的原文在 custom_books.channel_id */
  23. private const PALI_CHANNEL = '_System_Pali_VRI_';
  24. private const CUSTOM_BOOK_FROM = 1000;
  25. public function __construct(private readonly ChannelAbilityService $abilities) {}
  26. /**
  27. * @param list<string> $sentences `book-para-wordStart-wordEnd`,格式不对的忽略
  28. * @return Collection<int, Channel> 每个 channel 挂好 abilities、final、content_created_at、content_updated_at
  29. *
  30. * @throws AuthorizationException 给了 studio,但不是本人也不是该团队成员
  31. */
  32. public function forSentences(array $sentences, ?string $viewerUid, ?string $studioUid): Collection
  33. {
  34. if ($studioUid !== null && ($viewerUid === null || ! $this->abilities->canListStudio($viewerUid, $studioUid))) {
  35. throw new AuthorizationException(__('messages.channel_studio_forbidden'));
  36. }
  37. $coords = $this->parse($sentences);
  38. if ($coords === []) {
  39. return collect();
  40. }
  41. $lengths = $this->originalLengths($coords);
  42. $keys = array_keys($coords);
  43. $tuples = array_values($coords);
  44. // 有内容的 channel(不分谁的,下面再套可见性)
  45. $withContent = Sentence::query()
  46. ->whereIns(['book_id', 'paragraph', 'word_start', 'word_end'], $tuples)
  47. ->where('strlen', '>', 0)
  48. ->distinct()
  49. ->pluck('channel_uid')
  50. ->all();
  51. $query = Channel::query()
  52. ->with([UserService::eagerLoadActor('owner')[0], 'ownerGroup:uid,name'])
  53. ->where(function ($q) use ($withContent, $viewerUid) {
  54. $q->where(function ($inner) use ($withContent, $viewerUid) {
  55. $inner->whereIn('uid', $withContent);
  56. $this->abilities->scopeListable($inner, $viewerUid);
  57. });
  58. if ($viewerUid !== null) {
  59. $q->orWhere(fn ($inner) => $this->abilities->scopeWritable($inner, $viewerUid));
  60. }
  61. })
  62. ->when($studioUid, fn ($q, string $uid) => $q->where('owner_uid', $uid))
  63. ->orderByDesc('updated_at')
  64. ->orderBy('uid');
  65. $channels = $query->get();
  66. if ($channels->isEmpty()) {
  67. return $channels;
  68. }
  69. // 各 channel 在这批句子上的已译行,一次取完
  70. $done = [];
  71. Sentence::query()
  72. ->whereIns(['book_id', 'paragraph', 'word_start', 'word_end'], $tuples)
  73. ->whereIn('channel_uid', $channels->pluck('uid')->all())
  74. ->where('strlen', '>', 0)
  75. ->get(['channel_uid', 'book_id', 'paragraph', 'word_start', 'word_end', 'created_at', 'updated_at'])
  76. ->each(function (Sentence $row) use (&$done) {
  77. $done[$row->channel_uid][] = $row;
  78. });
  79. $abilities = $this->abilities->abilitiesMany($channels, $viewerUid);
  80. foreach ($channels as $channel) {
  81. $rows = $done[$channel->uid] ?? [];
  82. $translated = [];
  83. foreach ($rows as $row) {
  84. $translated["{$row->book_id}-{$row->paragraph}-{$row->word_start}-{$row->word_end}"] = true;
  85. }
  86. $channel->setAttribute('abilities', $abilities[$channel->uid]);
  87. $channel->setAttribute('final', $rows === [] ? null : array_map(
  88. fn (string $key) => [$lengths[$key] ?? 0, isset($translated[$key])],
  89. $keys,
  90. ));
  91. $channel->setAttribute('content_created_at', $rows === [] ? null : collect($rows)->min('created_at'));
  92. $channel->setAttribute('content_updated_at', $rows === [] ? null : collect($rows)->max('updated_at'));
  93. }
  94. return $channels;
  95. }
  96. /**
  97. * 句子 id → [book, para, start, end],保持请求顺序、去重。
  98. *
  99. * @param list<string> $sentences
  100. * @return array<string, array{0: int, 1: int, 2: int, 3: int}>
  101. */
  102. private function parse(array $sentences): array
  103. {
  104. $coords = [];
  105. foreach ($sentences as $id) {
  106. $parts = explode('-', (string) $id);
  107. if (count($parts) !== 4 || array_filter($parts, fn ($p) => ! ctype_digit($p)) !== []) {
  108. continue;
  109. }
  110. $coords[implode('-', array_map('intval', $parts))] = array_map('intval', $parts);
  111. }
  112. return $coords;
  113. }
  114. /**
  115. * 每句原文的字符数(巴利三藏在系统原文 channel,自定义书在它自己的原文 channel)。
  116. *
  117. * @param array<string, array{0: int, 1: int, 2: int, 3: int}> $coords
  118. * @return array<string, int>
  119. */
  120. private function originalLengths(array $coords): array
  121. {
  122. $pali = Channel::where('name', self::PALI_CHANNEL)
  123. ->where('owner_uid', config('mint.admin.root_uuid'))
  124. ->value('uid');
  125. $customBooks = array_unique(array_filter(
  126. array_map(fn (array $c) => $c[0], $coords),
  127. fn (int $book) => $book >= self::CUSTOM_BOOK_FROM,
  128. ));
  129. $customChannels = $customBooks === []
  130. ? []
  131. : CustomBook::whereIn('book_id', $customBooks)->pluck('channel_id', 'book_id')->all();
  132. $tuples = [];
  133. foreach ($coords as $c) {
  134. $channel = $c[0] >= self::CUSTOM_BOOK_FROM ? ($customChannels[$c[0]] ?? $pali) : $pali;
  135. if ($channel) {
  136. $tuples[] = [...$c, $channel];
  137. }
  138. }
  139. if ($tuples === []) {
  140. return [];
  141. }
  142. $lengths = [];
  143. Sentence::query()
  144. ->whereIns(['book_id', 'paragraph', 'word_start', 'word_end', 'channel_uid'], $tuples)
  145. ->get(['book_id', 'paragraph', 'word_start', 'word_end', 'strlen'])
  146. ->each(function (Sentence $row) use (&$lengths) {
  147. $lengths["{$row->book_id}-{$row->paragraph}-{$row->word_start}-{$row->word_end}"] = (int) $row->strlen;
  148. });
  149. return $lengths;
  150. }
  151. }