2
0

ChannelV3Test.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. <?php
  2. use App\Models\Channel;
  3. use App\Models\ProgressChapter;
  4. use Illuminate\Foundation\Testing\RefreshDatabase;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Str;
  7. uses(RefreshDatabase::class);
  8. /**
  9. * v3 channel:公开目录、studio 列表、我能写的、详情、建、改、删。
  10. *
  11. * 端点:
  12. * GET /api/v3/channels 公开目录(可不登录;system=true 只要系统 channel)
  13. * GET /api/v3/channels/editable 我能写的(登录)
  14. * GET /api/v3/channels/{channel} 详情(公开谁都能看;私有看权限)
  15. * PATCH /api/v3/channels/{channel} 改信息
  16. * DELETE /api/v3/channels/{channel} 软删(有内容 409)
  17. * GET /api/v3/studios/{studio}/channels studio(本人或团队)的工作区列表
  18. * POST /api/v3/studios/{studio}/channels 在 studio 名下建
  19. *
  20. * 这里断言的是形状而非契约(spectator 未安装,见 v3-resource skill 第 3 步)。
  21. */
  22. function privateChannel(string $ownerUid, string $name = 'private channel'): string
  23. {
  24. $uid = makeChannel($ownerUid, $name);
  25. Channel::where('uid', $uid)->update(['status' => Channel::STATUS_PRIVATE]);
  26. return $uid;
  27. }
  28. function channelIds(array $data): array
  29. {
  30. return array_column($data, 'id');
  31. }
  32. /* ---------------- 详情与权限矩阵 ---------------- */
  33. it('shows public channels to anyone and hides private ones', function () {
  34. $owner = makeStudio('owner');
  35. $public = makeChannel($owner, 'pub');
  36. $private = privateChannel($owner);
  37. $this->getJson("/api/v3/channels/{$public}")
  38. ->assertOk()
  39. ->assertJsonPath('data.id', $public)
  40. ->assertJsonPath('data.owner.kind', 'user')
  41. ->assertJsonPath('data.owner.id', $owner)
  42. ->assertJsonPath('data.abilities', ['read' => true, 'write' => false, 'update' => false, 'delete' => false]);
  43. $this->getJson("/api/v3/channels/{$private}")->assertForbidden();
  44. $this->getJson("/api/v3/channels/{$private}", authHeader(makeStudio('stranger')))->assertForbidden();
  45. $this->getJson("/api/v3/channels/{$private}", authHeader($owner))
  46. ->assertOk()
  47. ->assertJsonPath('data.abilities', ['read' => true, 'write' => true, 'update' => true, 'delete' => true]);
  48. });
  49. it('derives abilities on a team channel from the team role', function (string $role, array $abilities) {
  50. [$team, $users] = makeTeam();
  51. $channel = privateChannel($team, 'team channel');
  52. $response = $this->getJson("/api/v3/channels/{$channel}", authHeader($users[$role]));
  53. if ($abilities === []) {
  54. $response->assertForbidden();
  55. return;
  56. }
  57. $response->assertOk()
  58. ->assertJsonPath('data.owner.kind', 'team')
  59. ->assertJsonPath('data.owner.id', $team)
  60. ->assertJsonPath('data.abilities', $abilities);
  61. })->with([
  62. 'owner' => ['owner', ['read' => true, 'write' => true, 'update' => true, 'delete' => true]],
  63. 'manager' => ['manager', ['read' => true, 'write' => true, 'update' => true, 'delete' => false]],
  64. 'editor' => ['editor', ['read' => true, 'write' => true, 'update' => true, 'delete' => false]],
  65. 'reader' => ['reader', ['read' => true, 'write' => false, 'update' => false, 'delete' => false]],
  66. 'outsider' => ['outsider', []],
  67. ]);
  68. it('derives abilities from share power, including shares to my team', function (int $power, bool $viaTeam, array $abilities) {
  69. $me = makeStudio('me');
  70. $channel = privateChannel(makeStudio('author'));
  71. if ($viaTeam) {
  72. $team = makeGroup(makeStudio('team-owner'));
  73. addGroupMember($team, $me);
  74. grantChannelShare($channel, $team, $power, true);
  75. } else {
  76. grantChannelShare($channel, $me, $power);
  77. }
  78. $this->getJson("/api/v3/channels/{$channel}", authHeader($me))
  79. ->assertOk()
  80. ->assertJsonPath('data.abilities', $abilities);
  81. })->with([
  82. 'reader' => [10, false, ['read' => true, 'write' => false, 'update' => false, 'delete' => false]],
  83. 'editor' => [20, false, ['read' => true, 'write' => true, 'update' => false, 'delete' => false]],
  84. 'manager' => [30, false, ['read' => true, 'write' => true, 'update' => true, 'delete' => false]],
  85. 'editor via team' => [20, true, ['read' => true, 'write' => true, 'update' => false, 'delete' => false]],
  86. ]);
  87. it('lets anyone read system channels, even private ones', function () {
  88. $root = makeStudio('root');
  89. $pali = makeChannel($root, '_System_Pali_VRI_');
  90. Channel::where('uid', $pali)->update(['is_system' => true, 'status' => Channel::STATUS_PRIVATE]);
  91. makeSentence($pali, 7, 7, 1, 'namo');
  92. $this->getJson("/api/v3/channels/{$pali}")->assertOk()->assertJsonPath('data.abilities.read', true);
  93. expect(channelIds($this->getJson('/api/v3/channels?system=true')->json('data')))->toBe([$pali]);
  94. expect(channelIds($this->getJson('/api/v3/tipitaka-paragraph-channels/7/7')->json('data')))->toBe([$pali]);
  95. // 普通公开目录不列私有的系统 channel
  96. expect(channelIds($this->getJson('/api/v3/channels')->json('data')))->toBe([]);
  97. });
  98. it('never lets anyone update or delete a system channel', function () {
  99. $owner = makeStudio('root');
  100. $channel = makeChannel($owner, '_System_Test_');
  101. Channel::where('uid', $channel)->update(['is_system' => true]);
  102. $this->getJson("/api/v3/channels/{$channel}", authHeader($owner))
  103. ->assertJsonPath('data.abilities.update', false)
  104. ->assertJsonPath('data.abilities.delete', false);
  105. $this->patchJson("/api/v3/channels/{$channel}", ['name' => 'x'], authHeader($owner))->assertForbidden();
  106. });
  107. /* ---------------- 公开目录 ---------------- */
  108. it('lists public channels only, with optional system filter and search', function () {
  109. $owner = makeStudio('owner');
  110. $public = makeChannel($owner, 'Alpha public');
  111. privateChannel($owner, 'Alpha private');
  112. $system = makeChannel($owner, 'Alpha system');
  113. Channel::where('uid', $system)->update(['is_system' => true]);
  114. expect(channelIds($this->getJson('/api/v3/channels?search=alpha')->assertOk()->json('data')))
  115. ->toEqualCanonicalizing([$public, $system]);
  116. expect(channelIds($this->getJson('/api/v3/channels?system=true')->json('data')))->toBe([$system]);
  117. });
  118. it('adds chapter progress when book and para are given, and sorts by it', function () {
  119. $owner = makeStudio('owner');
  120. $low = makeChannel($owner, 'low');
  121. $high = makeChannel($owner, 'high');
  122. makeChannel($owner, 'none');
  123. foreach ([[$low, 0.2], [$high, 0.9]] as [$channel, $progress]) {
  124. (new ProgressChapter)->forceFill([
  125. 'uid' => (string) Str::uuid(), 'book' => 1, 'para' => 10, 'channel_id' => $channel,
  126. 'lang' => 'zh', 'all_trans' => 100, 'public' => 100, 'progress' => $progress,
  127. ])->save();
  128. }
  129. $data = $this->getJson('/api/v3/channels?book=1&para=10&order=progress')->assertOk()->json('data');
  130. expect(array_slice(channelIds($data), 0, 2))->toBe([$high, $low]);
  131. expect($data[0]['progress'])->toBe(0.9);
  132. expect($data[2]['progress'])->toBeNull();
  133. expect($this->getJson('/api/v3/channels')->json('data.0'))->not->toHaveKey('progress');
  134. });
  135. it('rejects a para without a book', function () {
  136. $this->getJson('/api/v3/channels?para=3')->assertUnprocessable()->assertJsonValidationErrors('book');
  137. });
  138. it('does not query per channel in lists', function () {
  139. $me = makeStudio('me');
  140. $countQueriesFor = function (int $extra) use ($me): int {
  141. for ($i = 0; $i < $extra; $i++) {
  142. makeChannel(makeStudio('o-'.Str::random(8)), 'n1 '.Str::random(5));
  143. }
  144. DB::flushQueryLog();
  145. DB::enableQueryLog();
  146. $this->getJson('/api/v3/channels?search=n1', authHeader($me))->assertOk();
  147. $count = count(DB::getQueryLog());
  148. DB::disableQueryLog();
  149. return $count;
  150. };
  151. expect($countQueriesFor(8))->toBe($countQueriesFor(1));
  152. });
  153. /* ---------------- studio 列表 ---------------- */
  154. it('lists my own and directly shared channels, not those shared to my teams', function () {
  155. $me = makeStudio('me');
  156. $mine = privateChannel($me, 'mine');
  157. $direct = privateChannel(makeStudio('a'), 'direct');
  158. grantChannelShare($direct, $me, 10);
  159. $team = makeGroup(makeStudio('team-owner'));
  160. addGroupMember($team, $me);
  161. $viaTeam = privateChannel(makeStudio('b'), 'via team');
  162. grantChannelShare($viaTeam, $team, 20, true);
  163. $list = fn (string $relation) => channelIds(
  164. $this->getJson("/api/v3/studios/{$me}/channels?relation={$relation}", authHeader($me))->assertOk()->json('data')
  165. );
  166. expect($list('own'))->toBe([$mine]);
  167. expect($list('shared'))->toBe([$direct]);
  168. expect($list('all'))->toEqualCanonicalizing([$mine, $direct]);
  169. $this->getJson("/api/v3/studios/{$me}/channels?relation=shared", authHeader($me))->assertJsonPath('meta.total', 1);
  170. });
  171. it('lists a team\'s own and shared channels in its teamspace', function () {
  172. [$team, $users] = makeTeam();
  173. $owned = privateChannel($team, 'team owned');
  174. $shared = privateChannel(makeStudio('author'), 'shared to team');
  175. grantChannelShare($shared, $team, 20, true);
  176. privateChannel($users['reader'], 'reader personal');
  177. $list = fn (string $relation) => channelIds(
  178. $this->getJson("/api/v3/studios/{$team}/channels?relation={$relation}", authHeader($users['reader']))->assertOk()->json('data')
  179. );
  180. expect($list('own'))->toBe([$owned]);
  181. expect($list('shared'))->toBe([$shared]);
  182. });
  183. it('filters shared channels by collaborator', function () {
  184. $me = makeStudio('me');
  185. $a = makeStudio('a');
  186. $fromA = privateChannel($a, 'from a');
  187. $fromB = privateChannel(makeStudio('b'), 'from b');
  188. grantChannelShare($fromA, $me, 10);
  189. grantChannelShare($fromB, $me, 10);
  190. expect(channelIds($this->getJson("/api/v3/studios/{$me}/channels?relation=shared&collaborator={$a}", authHeader($me))->json('data')))
  191. ->toBe([$fromA]);
  192. });
  193. it('hides a studio list from strangers and requires login', function () {
  194. [$team, $users] = makeTeam();
  195. $this->getJson("/api/v3/studios/{$team}/channels", authHeader($users['outsider']))->assertForbidden();
  196. $this->getJson("/api/v3/studios/{$users['owner']}/channels", authHeader($users['editor']))->assertForbidden();
  197. $this->getJson("/api/v3/studios/{$team}/channels")->assertUnauthorized();
  198. });
  199. /* ---------------- 新建 ---------------- */
  200. it('creates channels in my studio or in a team I can create in', function (string $role, int $status) {
  201. [$team, $users] = makeTeam();
  202. $actor = $users[$role];
  203. $studio = $role === 'self' ? $actor : $team;
  204. $response = $this->postJson("/api/v3/studios/{$studio}/channels", [
  205. 'name' => 'new channel', 'type' => 'translation', 'lang' => 'zh-Hans',
  206. ], authHeader($actor));
  207. $response->assertStatus($status);
  208. if ($status === 201) {
  209. $response->assertJsonPath('data.status', Channel::STATUS_PRIVATE)
  210. ->assertJsonPath('data.owner.id', $studio)
  211. ->assertJsonPath('data.abilities.update', true);
  212. expect(Channel::where('owner_uid', $studio)->where('name', 'new channel')->exists())->toBeTrue();
  213. }
  214. })->with([
  215. 'team owner' => ['owner', 201],
  216. 'team manager' => ['manager', 201],
  217. 'team editor' => ['editor', 403],
  218. 'team reader' => ['reader', 403],
  219. 'outsider' => ['outsider', 403],
  220. ]);
  221. it('creates a channel in my own studio', function () {
  222. $me = makeStudio('me');
  223. $this->postJson("/api/v3/studios/{$me}/channels", ['name' => 'x', 'type' => 'translation', 'lang' => 'en'], authHeader($me))
  224. ->assertCreated()
  225. ->assertJsonPath('data.owner.kind', 'user');
  226. });
  227. it('rejects duplicate names within a studio and bad input', function () {
  228. $me = makeStudio('me');
  229. makeChannel($me, 'dup');
  230. $this->postJson("/api/v3/studios/{$me}/channels", ['name' => 'dup', 'type' => 'translation', 'lang' => 'en'], authHeader($me))
  231. ->assertUnprocessable()->assertJsonValidationErrors('name');
  232. $this->postJson("/api/v3/studios/{$me}/channels", ['name' => 'x', 'type' => 'bogus'], authHeader($me))
  233. ->assertUnprocessable()->assertJsonValidationErrors(['type', 'lang']);
  234. });
  235. it('does not let AI models create, update or delete channels', function () {
  236. $owner = makeStudio('owner');
  237. $model = makeModelAccount($owner);
  238. $channel = makeChannel($model, 'model owned');
  239. $this->postJson("/api/v3/studios/{$model}/channels", ['name' => 'x', 'type' => 'translation', 'lang' => 'en'], authHeader($model))
  240. ->assertForbidden();
  241. $this->patchJson("/api/v3/channels/{$channel}", ['name' => 'y'], authHeader($model))->assertForbidden();
  242. $this->deleteJson("/api/v3/channels/{$channel}", [], authHeader($model))->assertForbidden();
  243. });
  244. /* ---------------- 改 ---------------- */
  245. it('updates only the fields sent', function () {
  246. $me = makeStudio('me');
  247. $channel = makeChannel($me, 'before');
  248. Channel::where('uid', $channel)->update(['summary' => 'keep me']);
  249. $this->patchJson("/api/v3/channels/{$channel}", ['name' => 'after', 'status' => 10], authHeader($me))
  250. ->assertOk()
  251. ->assertJsonPath('data.name', 'after')
  252. ->assertJsonPath('data.status', 10)
  253. ->assertJsonPath('data.summary', 'keep me');
  254. });
  255. it('lets team editors update a team channel but not readers', function () {
  256. [$team, $users] = makeTeam();
  257. $channel = privateChannel($team);
  258. $this->patchJson("/api/v3/channels/{$channel}", ['summary' => 'edited'], authHeader($users['editor']))->assertOk();
  259. $this->patchJson("/api/v3/channels/{$channel}", ['summary' => 'nope'], authHeader($users['reader']))->assertForbidden();
  260. });
  261. it('does not register PUT on channels', function () {
  262. $me = makeStudio('me');
  263. $channel = makeChannel($me);
  264. $this->putJson("/api/v3/channels/{$channel}", ['name' => 'x'], authHeader($me))->assertMethodNotAllowed();
  265. });
  266. /* ---------------- 删 ---------------- */
  267. it('soft deletes an empty channel and returns it', function () {
  268. $me = makeStudio('me');
  269. $channel = makeChannel($me);
  270. $this->deleteJson("/api/v3/channels/{$channel}", [], authHeader($me))
  271. ->assertOk()
  272. ->assertJsonPath('data.id', $channel);
  273. $this->assertSoftDeleted('channels', ['uid' => $channel]);
  274. $this->getJson("/api/v3/channels/{$channel}")->assertNotFound();
  275. });
  276. it('refuses to delete a channel with translations', function () {
  277. $me = makeStudio('me');
  278. $channel = makeChannel($me);
  279. makeSentence($channel, 1, 1, 1, 'text');
  280. $this->deleteJson("/api/v3/channels/{$channel}", [], authHeader($me))
  281. ->assertConflict()
  282. ->assertJsonPath('content', ['sentence']);
  283. });
  284. it('lets only the team owner delete a team channel', function () {
  285. [$team, $users] = makeTeam();
  286. $channel = privateChannel($team);
  287. $this->deleteJson("/api/v3/channels/{$channel}", [], authHeader($users['manager']))->assertForbidden();
  288. $this->deleteJson("/api/v3/channels/{$channel}", [], authHeader($users['owner']))->assertOk();
  289. });
  290. /* ---------------- 我能写的 ---------------- */
  291. it('lists channels I can write to across studios, with working search', function () {
  292. $me = makeStudio('me');
  293. $mine = privateChannel($me, 'pali mine');
  294. $editorTeam = makeGroup(makeStudio('t1'));
  295. addGroupMember($editorTeam, $me, 2, 'editor');
  296. $teamChannel = privateChannel($editorTeam, 'pali team');
  297. $readerTeam = makeGroup(makeStudio('t2'));
  298. addGroupMember($readerTeam, $me);
  299. privateChannel($readerTeam, 'pali read-only team');
  300. $shared = privateChannel(makeStudio('a'), 'pali shared 20');
  301. grantChannelShare($shared, $me, 20);
  302. $readOnly = privateChannel(makeStudio('b'), 'pali shared 10');
  303. grantChannelShare($readOnly, $me, 10);
  304. makeChannel(makeStudio('c'), 'pali public');
  305. expect(channelIds($this->getJson('/api/v3/channels/editable?search=PALI', authHeader($me))->assertOk()->json('data')))
  306. ->toEqualCanonicalizing([$mine, $teamChannel, $shared]);
  307. expect(channelIds($this->getJson('/api/v3/channels/editable?search=team', authHeader($me))->json('data')))
  308. ->toBe([$teamChannel]);
  309. $this->getJson('/api/v3/channels/editable')->assertUnauthorized();
  310. });
  311. /* ---------------- 公开不列出(status 20) ---------------- */
  312. it('lets anyone open an unlisted channel but keeps it out of public lists', function () {
  313. $owner = makeStudio('owner');
  314. $unlisted = makeChannel($owner, 'unlisted channel');
  315. Channel::where('uid', $unlisted)->update(['status' => Channel::STATUS_UNLISTED]);
  316. makeSentence($unlisted, 8, 8, 1, 'text');
  317. (new ProgressChapter)->forceFill([
  318. 'uid' => (string) Str::uuid(), 'book' => 8, 'para' => 8, 'channel_id' => $unlisted,
  319. 'lang' => 'zh', 'all_trans' => 100, 'public' => 100, 'progress' => 1.0,
  320. ])->save();
  321. $stranger = authHeader(makeStudio('stranger'));
  322. // 拿到链接能看(不登录也行),但不能改
  323. $this->getJson("/api/v3/channels/{$unlisted}")
  324. ->assertOk()
  325. ->assertJsonPath('data.abilities', ['read' => true, 'write' => false, 'update' => false, 'delete' => false]);
  326. // 面向他人的列表一律不出现
  327. expect(channelIds($this->getJson('/api/v3/channels', $stranger)->json('data')))->not->toContain($unlisted);
  328. expect(channelIds($this->getJson('/api/v3/tipitaka-channels?lang=zh')->json('data')))->not->toContain($unlisted);
  329. expect(channelIds($this->getJson('/api/v3/tipitaka-paragraph-channels/8/8', $stranger)->json('data')))->not->toContain($unlisted);
  330. expect(array_column(array_column($this->getJson('/api/v3/tipitaka-chapter-channels/8/8', $stranger)->json('data'), 'channel'), 'id'))
  331. ->not->toContain($unlisted);
  332. // 拥有者自己的列表里照常
  333. expect(channelIds($this->getJson("/api/v3/studios/{$owner}/channels", authHeader($owner))->json('data')))->toContain($unlisted);
  334. expect(channelIds($this->getJson('/api/v3/tipitaka-paragraph-channels/8/8', authHeader($owner))->json('data')))->toContain($unlisted);
  335. });
  336. it('accepts unlisted as a status and rejects unknown ones', function () {
  337. $me = makeStudio('me');
  338. $channel = makeChannel($me);
  339. $this->patchJson("/api/v3/channels/{$channel}", ['status' => Channel::STATUS_UNLISTED], authHeader($me))
  340. ->assertOk()
  341. ->assertJsonPath('data.status', 20);
  342. $this->patchJson("/api/v3/channels/{$channel}", ['status' => 15], authHeader($me))
  343. ->assertUnprocessable()
  344. ->assertJsonValidationErrors('status');
  345. $this->postJson("/api/v3/studios/{$me}/channels", ['name' => 'u', 'type' => 'translation', 'lang' => 'en', 'status' => 20], authHeader($me))
  346. ->assertCreated()
  347. ->assertJsonPath('data.status', 20);
  348. });