ChannelLinkService.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Models\Channel;
  4. use App\Models\ChannelLink;
  5. use Illuminate\Auth\Access\AuthorizationException;
  6. use Illuminate\Support\Collection;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Validation\ValidationException;
  9. /**
  10. * channel 之间的关系设置(`channel_links` 表):继承自、降级、捆绑的逐词、术语路径。
  11. *
  12. * 服务端只记录,不在任何读取路径上使用它们——降级怎么拼接、术语按什么顺序取,由客户端决定。
  13. * 新能力,没有对应的 v2 端点。
  14. *
  15. * - 读:能读这个 channel 的人都能看;指向的 channel 若已删除或查看者看不见,就不出现
  16. * - 写:能改这个 channel 信息的人({@see ChannelAbilityService} 的 update);AI 模型不能写
  17. */
  18. class ChannelLinkService
  19. {
  20. private const TRANSLATION = 'translation';
  21. private const TARGET_COLUMNS = ['uid', 'name', 'type', 'lang', 'status', 'is_system', 'owner_uid'];
  22. public function __construct(
  23. private readonly ChannelAbilityService $abilities,
  24. private readonly AgentGrantService $agents,
  25. ) {}
  26. /**
  27. * 一个 channel 的全部关系设置。
  28. *
  29. * @return array{channel_id: string, derived_from: Channel|null, wbw: Channel|null, fallback: list<Channel>, term_source: list<Channel>, can_update: bool}
  30. *
  31. * @throws AuthorizationException 看不见这个 channel
  32. */
  33. public function get(Channel $channel, ?string $viewerUid): array
  34. {
  35. $abilities = $this->abilities->abilities($channel, $viewerUid);
  36. if (! $abilities['read']) {
  37. throw new AuthorizationException(__('messages.channel_forbidden'));
  38. }
  39. $links = ChannelLink::where('channel_uid', $channel->uid)
  40. ->with(['target' => fn ($q) => $q->select(self::TARGET_COLUMNS)])
  41. ->orderBy('kind')
  42. ->orderBy('position')
  43. ->get()
  44. ->filter(fn (ChannelLink $link) => $link->target !== null); // 指向的 channel 已软删
  45. $readable = $this->abilities->abilitiesMany($links->pluck('target')->unique('uid'), $viewerUid);
  46. $visible = $links->filter(fn (ChannelLink $link) => $readable[$link->target_uid]['read'] ?? false);
  47. return [
  48. 'channel_id' => $channel->uid,
  49. 'derived_from' => $this->targetsOf($visible, ChannelLink::DERIVED_FROM)->first(),
  50. 'wbw' => $this->targetsOf($visible, ChannelLink::WBW)->first(),
  51. 'fallback' => $this->targetsOf($visible, ChannelLink::FALLBACK)->all(),
  52. 'term_source' => $this->targetsOf($visible, ChannelLink::TERM_SOURCE)->all(),
  53. 'can_update' => $abilities['update'],
  54. ];
  55. }
  56. /**
  57. * 改关系设置:传了哪个键就整体替换哪一种(单值传 null = 清掉,列表传 [] = 清空),没传的不动。
  58. *
  59. * @param array{derived_from?: string|null, wbw?: string|null, fallback?: list<string>, term_source?: list<string>} $data
  60. * @return array{channel_id: string, derived_from: Channel|null, wbw: Channel|null, fallback: list<Channel>, term_source: list<Channel>, can_update: bool}
  61. *
  62. * @throws AuthorizationException 不能改这个 channel,或是 AI 模型
  63. * @throws ValidationException 指向自己、指向看不见 / 不存在的 channel、逐词目标类型不对
  64. */
  65. public function update(Channel $channel, string $actorUid, array $data): array
  66. {
  67. $this->agents->assertHuman($actorUid);
  68. if (! $this->abilities->abilities($channel, $actorUid)['update']) {
  69. throw new AuthorizationException(__('messages.channel_forbidden'));
  70. }
  71. $wanted = $this->normalize($data);
  72. $this->guardTargets($channel, $actorUid, $wanted);
  73. DB::transaction(function () use ($channel, $wanted) {
  74. foreach ($wanted as $kind => $targets) {
  75. ChannelLink::where('channel_uid', $channel->uid)->where('kind', $kind)->delete();
  76. foreach ($targets as $position => $target) {
  77. ChannelLink::create([
  78. 'channel_uid' => $channel->uid,
  79. 'kind' => $kind,
  80. 'target_uid' => $target,
  81. 'position' => $position,
  82. ]);
  83. }
  84. }
  85. });
  86. return $this->get($channel, $actorUid);
  87. }
  88. /**
  89. * 入参 → kind => 有序的目标 uid 列表(单值的 kind 最多一个)。
  90. *
  91. * @param array<string, mixed> $data
  92. * @return array<string, list<string>>
  93. */
  94. private function normalize(array $data): array
  95. {
  96. $wanted = [];
  97. foreach (ChannelLink::SINGLE as $kind) {
  98. if (array_key_exists($kind, $data)) {
  99. $wanted[$kind] = $data[$kind] === null ? [] : [(string) $data[$kind]];
  100. }
  101. }
  102. foreach (array_keys(ChannelLink::LISTS) as $kind) {
  103. if (array_key_exists($kind, $data)) {
  104. $wanted[$kind] = array_values(array_map('strval', $data[$kind] ?? []));
  105. }
  106. }
  107. return $wanted;
  108. }
  109. /**
  110. * 目标必须存在(未删除)、设置人看得见、不是自己。按类型还有三条:
  111. * - 捆绑的逐词必须是 wbw 类型
  112. * - 降级版本必须与本 channel 同类型(缺段时拿来顶替,类型不同就接不上)
  113. * - 术语路径只对 translation channel 有效,目标也只能是 translation(清空总是允许的)
  114. *
  115. * 错误挂在具体的字段上。
  116. *
  117. * @param array<string, list<string>> $wanted
  118. *
  119. * @throws ValidationException
  120. */
  121. private function guardTargets(Channel $channel, string $actorUid, array $wanted): void
  122. {
  123. $uids = array_values(array_unique(array_merge(...array_values($wanted ?: [[]]))));
  124. $targets = $uids === []
  125. ? collect()
  126. : Channel::whereIn('uid', $uids)->get(self::TARGET_COLUMNS)->keyBy('uid');
  127. $readable = $this->abilities->abilitiesMany($targets->values(), $actorUid);
  128. $errors = [];
  129. if (! empty($wanted[ChannelLink::TERM_SOURCE]) && $channel->type !== self::TRANSLATION) {
  130. $errors[ChannelLink::TERM_SOURCE] = __('messages.channel_link_term_source_channel');
  131. unset($wanted[ChannelLink::TERM_SOURCE]);
  132. }
  133. foreach ($wanted as $kind => $list) {
  134. foreach ($list as $i => $uid) {
  135. $field = in_array($kind, ChannelLink::SINGLE, true) ? $kind : "{$kind}.{$i}";
  136. $target = $targets->get($uid);
  137. if ($uid === $channel->uid) {
  138. $errors[$field] = __('messages.channel_link_self');
  139. } elseif ($target === null || ! ($readable[$uid]['read'] ?? false)) {
  140. $errors[$field] = __('messages.channel_link_target_missing');
  141. } elseif ($kind === ChannelLink::WBW && $target->type !== 'wbw') {
  142. $errors[$field] = __('messages.channel_link_wbw_type');
  143. } elseif ($kind === ChannelLink::FALLBACK && $target->type !== $channel->type) {
  144. $errors[$field] = __('messages.channel_link_fallback_type');
  145. } elseif ($kind === ChannelLink::TERM_SOURCE && $target->type !== self::TRANSLATION) {
  146. $errors[$field] = __('messages.channel_link_term_source_type');
  147. }
  148. }
  149. }
  150. if ($errors !== []) {
  151. throw ValidationException::withMessages($errors);
  152. }
  153. }
  154. /**
  155. * @param Collection<int, ChannelLink> $links
  156. * @return Collection<int, Channel>
  157. */
  158. private function targetsOf(Collection $links, string $kind): Collection
  159. {
  160. return $links->where('kind', $kind)->sortBy('position')->map(fn (ChannelLink $link) => $link->target)->values();
  161. }
  162. }