ChannelService.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Exceptions\BusinessException;
  4. use App\Models\Channel;
  5. use App\Models\DhammaTerm;
  6. use App\Models\Sentence;
  7. use App\Models\WbwBlock;
  8. use App\Services\UserService;
  9. use Illuminate\Auth\Access\AuthorizationException;
  10. use Illuminate\Contracts\Pagination\LengthAwarePaginator;
  11. use Illuminate\Database\Eloquent\Builder;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Str;
  14. use Illuminate\Validation\ValidationException;
  15. /**
  16. * channel 本身:公开目录、某个 studio 的工作区列表、我能写的、详情、建、改、删。
  17. *
  18. * 取代 v2 `ChannelController`(index 的 public / system / studio / studio-all / user-edit、
  19. * show、store、update、patch、destroy、showMyNumber)。v2 那份原地保留不动(铁律 2),不共用代码。
  20. * 权限一律经 {@see ChannelAbilityService};channels 表的写入只给人类({@see AgentGrantService::assertHuman()})。
  21. *
  22. * 列表行与详情都挂上 `abilities`(本人能做什么)、可选的 `progress`(带 book + para 时,该章的完成度),
  23. * Resource 直接读,不查库。
  24. */
  25. class ChannelService
  26. {
  27. /** 列表可排序的字段;progress 只在带 book + para 时有意义 */
  28. public const ORDERS = ['updated_at', 'created_at', 'name', 'progress'];
  29. /** 列表要的列(不取 config 等大字段) */
  30. private const COLUMNS = [
  31. 'channels.uid', 'channels.name', 'channels.summary', 'channels.type', 'channels.lang',
  32. 'channels.status', 'channels.is_system', 'channels.owner_uid', 'channels.source_type',
  33. 'channels.source_id', 'channels.created_at', 'channels.updated_at',
  34. ];
  35. public function __construct(
  36. private readonly ChannelAbilityService $abilities,
  37. private readonly AgentGrantService $agents,
  38. ) {}
  39. /**
  40. * 公开目录:全网公开的 channel;`system=true` 只要系统 channel(不论 status)。
  41. *
  42. * @param array{search?: string|null, type?: string, lang?: string, system?: bool, book?: int, para?: int, order?: string, dir?: string} $filters
  43. * @return LengthAwarePaginator<int, Channel>
  44. */
  45. public function listPublic(array $filters, ?string $viewerUid, int $perPage): LengthAwarePaginator
  46. {
  47. $query = $this->base($filters);
  48. if (! empty($filters['system'])) {
  49. // 系统 channel 不论 status 都列(巴利原文等是 status 10,按名字找它的调用方要能找到)
  50. $query->where('channels.is_system', true);
  51. } else {
  52. $query->where('channels.status', '>=', Channel::STATUS_PUBLIC);
  53. }
  54. return $this->page($query, $filters, $viewerUid, $perPage);
  55. }
  56. /**
  57. * 某个 studio(本人或团队)的工作区列表。
  58. *
  59. * `relation`:own 它名下的(默认),shared 直接共享给它的(**不含**经团队转来的——团队的东西在团队空间里看),
  60. * all 两者合起来。`collaborator`:只看某个拥有者共享过来的。
  61. *
  62. * @param array{relation?: string, collaborator?: string, search?: string|null, type?: string, lang?: string, book?: int, para?: int, order?: string, dir?: string} $filters
  63. * @return LengthAwarePaginator<int, Channel>
  64. *
  65. * @throws AuthorizationException 不是本人,也不是该团队成员
  66. */
  67. public function listForStudio(string $studioUid, string $viewerUid, array $filters, int $perPage): LengthAwarePaginator
  68. {
  69. if (! $this->abilities->canListStudio($viewerUid, $studioUid)) {
  70. throw new AuthorizationException(__('messages.channel_studio_forbidden'));
  71. }
  72. $relation = $filters['relation'] ?? 'own';
  73. $shared = $relation === 'own' ? [] : $this->abilities->sharedTo($studioUid);
  74. $query = $this->base($filters)->where(function (Builder $q) use ($relation, $studioUid, $shared) {
  75. if ($relation !== 'shared') {
  76. $q->orWhere('channels.owner_uid', $studioUid);
  77. }
  78. if ($relation !== 'own') {
  79. $q->orWhereIn('channels.uid', $shared);
  80. }
  81. });
  82. if ($relation === 'shared') {
  83. $query->where('channels.owner_uid', '<>', $studioUid);
  84. }
  85. if (! empty($filters['collaborator'])) {
  86. $query->where('channels.owner_uid', $filters['collaborator']);
  87. }
  88. return $this->page($query, $filters, $viewerUid, $perPage);
  89. }
  90. /**
  91. * 我能写内容的 channel,跨 studio(本人的、团队的、共享的)。写入前挑 channel 用。
  92. *
  93. * @param array{search?: string|null, type?: string, lang?: string, book?: int, para?: int, order?: string, dir?: string} $filters
  94. * @return LengthAwarePaginator<int, Channel>
  95. */
  96. public function listWritable(string $viewerUid, array $filters, int $perPage): LengthAwarePaginator
  97. {
  98. $query = $this->base($filters);
  99. $this->abilities->scopeWritable($query, $viewerUid);
  100. return $this->page($query, $filters, $viewerUid, $perPage);
  101. }
  102. /**
  103. * 详情:看不见就 403。
  104. *
  105. * @throws AuthorizationException
  106. */
  107. public function show(Channel $channel, ?string $viewerUid): Channel
  108. {
  109. $abilities = $this->abilities->abilities($channel, $viewerUid);
  110. if (! $abilities['read']) {
  111. throw new AuthorizationException(__('messages.channel_forbidden'));
  112. }
  113. return $this->decorate($channel, $abilities);
  114. }
  115. /**
  116. * 在 studio(本人或团队)名下建 channel。同一 studio 里不能重名。
  117. *
  118. * @param array{name: string, type: string, lang: string, summary?: string|null, status?: int, source_type?: string|null, source_id?: string|null} $data
  119. *
  120. * @throws AuthorizationException 不能在这个 studio 名下建,或是 AI 模型
  121. * @throws ValidationException 重名
  122. */
  123. public function create(string $studioUid, string $actorUid, int $actorId, array $data): Channel
  124. {
  125. $this->agents->assertHuman($actorUid);
  126. if (! $this->abilities->canCreateIn($actorUid, $studioUid)) {
  127. throw new AuthorizationException(__('messages.channel_studio_forbidden'));
  128. }
  129. $this->guardUniqueName($studioUid, $data['name']);
  130. $now = time() * 1000;
  131. $channel = new Channel;
  132. $channel->forceFill($data + [
  133. 'id' => app('snowflake')->id(),
  134. 'uid' => (string) Str::uuid(),
  135. 'owner_uid' => $studioUid,
  136. 'editor_id' => $actorId,
  137. 'status' => Channel::STATUS_PRIVATE,
  138. 'create_time' => $now,
  139. 'modify_time' => $now,
  140. ])->save();
  141. // refresh 而不是 fresh:要保留 wasRecentlyCreated,Laravel 才会回 201
  142. return $this->decorate($channel->refresh(), $this->abilities->abilities($channel, $actorUid));
  143. }
  144. /**
  145. * 改信息(只改传了的字段)。改名时同一 studio 里不能重名。
  146. *
  147. * @param array{name?: string, type?: string, lang?: string, summary?: string|null, status?: int, source_type?: string|null, source_id?: string|null, config?: string|null} $data
  148. *
  149. * @throws AuthorizationException
  150. * @throws ValidationException
  151. */
  152. public function update(Channel $channel, string $actorUid, array $data): Channel
  153. {
  154. $this->agents->assertHuman($actorUid);
  155. $abilities = $this->abilities->abilities($channel, $actorUid);
  156. if (! $abilities['update']) {
  157. throw new AuthorizationException(__('messages.channel_forbidden'));
  158. }
  159. if (isset($data['name']) && $data['name'] !== $channel->name) {
  160. $this->guardUniqueName($channel->owner_uid, $data['name'], $channel->uid);
  161. }
  162. if (array_key_exists('config', $data)) {
  163. // json 列,模型上没有 cast(加 cast 会改变 v2 读到的类型),这里自己编码
  164. $data['config'] = $data['config'] === null ? null : json_encode($data['config'], JSON_UNESCAPED_UNICODE);
  165. }
  166. $channel->forceFill($data + ['modify_time' => time() * 1000])->save();
  167. return $this->decorate($channel->fresh(), $abilities);
  168. }
  169. /**
  170. * 软删除。channel 下已有译文、术语或逐词时拒绝(与 v2 同口径)。返回被删的 channel(AIP-164)。
  171. *
  172. * @throws AuthorizationException
  173. * @throws BusinessException 下面还有内容(409)
  174. */
  175. public function delete(Channel $channel, string $actorUid): Channel
  176. {
  177. $this->agents->assertHuman($actorUid);
  178. $abilities = $this->abilities->abilities($channel, $actorUid);
  179. if (! $abilities['delete']) {
  180. throw new AuthorizationException(__('messages.channel_forbidden'));
  181. }
  182. $content = array_filter([
  183. 'sentence' => Sentence::where('channel_uid', $channel->uid)->exists(),
  184. 'term' => DhammaTerm::where('channal', $channel->uid)->exists(),
  185. 'wbw' => WbwBlock::where('channel_uid', $channel->uid)->exists(),
  186. ]);
  187. if ($content !== []) {
  188. throw new BusinessException(
  189. __('messages.channel_has_content'),
  190. 409,
  191. 'channel-has-content',
  192. ['content' => array_keys($content)],
  193. );
  194. }
  195. DB::transaction(fn () => $channel->delete());
  196. return $this->decorate($channel, $abilities);
  197. }
  198. /**
  199. * 所有列表共用的查询:列、拥有者预加载、筛选、可选的章节进度。
  200. *
  201. * @param array<string, mixed> $filters
  202. * @return Builder<Channel>
  203. */
  204. private function base(array $filters): Builder
  205. {
  206. $query = Channel::query()
  207. ->select(self::COLUMNS)
  208. ->with([UserService::eagerLoadActor('owner')[0], 'ownerGroup:uid,name'])
  209. ->when($filters['search'] ?? null, fn (Builder $q, string $v) => $q->where('channels.name', 'ilike', '%'.$v.'%'))
  210. ->when($filters['type'] ?? null, fn (Builder $q, string $v) => $q->where('channels.type', $v))
  211. ->when($filters['lang'] ?? null, fn (Builder $q, string $v) => $q->where('channels.lang', $v));
  212. if (isset($filters['book'], $filters['para'])) {
  213. $query->addSelect('progress_chapters.progress')
  214. ->leftJoin('progress_chapters', function ($join) use ($filters) {
  215. $join->on('progress_chapters.channel_id', '=', 'channels.uid')
  216. ->where('progress_chapters.book', $filters['book'])
  217. ->where('progress_chapters.para', $filters['para']);
  218. });
  219. }
  220. return $query;
  221. }
  222. /**
  223. * 排序、分页,整页挂上 abilities。
  224. *
  225. * @param Builder<Channel> $query
  226. * @param array<string, mixed> $filters
  227. * @return LengthAwarePaginator<int, Channel>
  228. */
  229. private function page(Builder $query, array $filters, ?string $viewerUid, int $perPage): LengthAwarePaginator
  230. {
  231. $order = $filters['order'] ?? 'updated_at';
  232. if (! in_array($order, self::ORDERS, true) || ($order === 'progress' && ! isset($filters['book'], $filters['para']))) {
  233. $order = 'updated_at';
  234. }
  235. $column = $order === 'progress' ? 'progress_chapters.progress' : "channels.{$order}";
  236. $dir = ($filters['dir'] ?? 'desc') === 'asc' ? 'asc' : 'desc';
  237. $page = $query->orderByRaw("{$column} {$dir} nulls last")
  238. ->orderBy('channels.uid')
  239. ->paginate($perPage);
  240. $abilities = $this->abilities->abilitiesMany($page->getCollection(), $viewerUid);
  241. foreach ($page->getCollection() as $channel) {
  242. $this->decorate($channel, $abilities[$channel->uid]);
  243. }
  244. return $page;
  245. }
  246. /**
  247. * @param array{read: bool, write: bool, update: bool, delete: bool} $abilities
  248. */
  249. private function decorate(Channel $channel, array $abilities): Channel
  250. {
  251. $channel->loadMissing([UserService::eagerLoadActor('owner')[0], 'ownerGroup:uid,name']);
  252. $channel->setAttribute('abilities', $abilities);
  253. return $channel;
  254. }
  255. /**
  256. * @throws ValidationException
  257. */
  258. private function guardUniqueName(string $studioUid, string $name, ?string $exceptUid = null): void
  259. {
  260. $exists = Channel::where('owner_uid', $studioUid)
  261. ->where('name', $name)
  262. ->when($exceptUid, fn (Builder $q, string $uid) => $q->where('uid', '<>', $uid))
  263. ->exists();
  264. if ($exists) {
  265. throw ValidationException::withMessages(['name' => __('messages.channel_name_exists')]);
  266. }
  267. }
  268. }