Просмотр исходного кода

♻️ (api-v13): ChannelApi 的纯能力拆到 ChannelService,v3 禁用 ChannelApi

- 新建 App\Services\ChannelService(summary / summaries / systemUid / byNameOrFail /
  userBookUid),返回值与原来一致;getByIds 由逐个查询改为一次查询
- ChannelApi 的这五个方法改成转发壳;五个权限方法是 v2 口径,原地保留、不转发
  (v3 用 V3\ChannelAbilityService)
- v3 阅读渲染会走到的 TemplateRender / PaliContentService 取系统 channel 改调 ChannelService
- tests/Unit/V3ArchTest.php:arch 规则禁止 V3 命名空间与 ChannelService 引用 ChannelApi

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda 14 часов назад
Родитель
Сommit
3d0e18d0e6

+ 35 - 80
api-v13/app/Http/Api/ChannelApi.php

@@ -3,41 +3,37 @@
 namespace App\Http\Api;
 
 use App\Models\Channel;
-use Illuminate\Support\Facades\Log;
-use Illuminate\Support\Str;
-
+use App\Services\ChannelService;
+use App\Services\V3\ChannelAbilityService;
+
+/**
+ * **v2 专用,v3 代码一律不准引用本类。**
+ *
+ * 两部分:
+ * - 纯能力(取 channel 摘要、系统 channel、自定义书 channel):**冻结的转发壳**,实现全在
+ *   {@see ChannelService},新代码直接注入它。保留这些方法只为 v2 的几十个调用点不必改。
+ * - 权限判定(`getCanReadByUser` … `canManageByUser`):v2 的旧口径——只认拥有者本人 + 共享,
+ *   不认团队角色、不排除软删以外的状态。**不转发到 v3**:v3 的口径(团队角色、status 20 公开不列出)
+ *   在 {@see ChannelAbilityService},把 v2 转过去等于改 v2 权限(铁律 1)。
+ *   原地留着,随 v4 下线删除。
+ *
+ * @deprecated 纯能力用 App\Services\ChannelService;权限用 App\Services\V3\ChannelAbilityService
+ */
 class ChannelApi
 {
+    /** @deprecated 用 ChannelService::summary() */
     public static function getById(?string $id)
     {
-        if (! Str::isUuid($id)) {
-            return false;
-        }
-        $channel = Channel::where('uid', $id)->first();
-        if ($channel) {
-            return [
-                'id' => $id,
-                'name' => $channel['name'],
-                'type' => $channel['type'],
-                'lang' => $channel['lang'],
-                'studio_id' => $channel['owner_uid'],
-                'status' => $channel['status'],
-            ];
-        } else {
-            return false;
-        }
+        return self::service()->summary($id);
     }
 
+    /** @deprecated 用 ChannelService::summaries() */
     public static function getByIds(array $ids)
     {
-        $channels = [];
-        foreach ($ids as $id) {
-            $channels[] = self::getById($id);
-        }
-
-        return $channels;
+        return self::service()->summaries($ids);
     }
 
+    /** v2 口径,v3 用 ChannelAbilityService::scopeListable() / abilities() */
     public static function getCanReadByUser($userUuid = null)
     {
         // 获取 user 在某章节 所有有权限的 channel 列表
@@ -70,6 +66,7 @@ class ChannelApi
         return $output;
     }
 
+    /** v2 口径,v3 用 ChannelAbilityService::writableUids() */
     public static function getCanEditByUser($userUuid = null)
     {
         // 获取 user 在某章节 所有有权限的 channel 列表
@@ -107,6 +104,7 @@ class ChannelApi
         return in_array($channelUid, $channels);
     }
 
+    /** v2 口径,v3 用 ChannelAbilityService::canWrite() */
     public static function userCanEdit($userUid, $channelUid)
     {
         $channels = ChannelApi::getCanEditByUser($userUid);
@@ -122,74 +120,31 @@ class ChannelApi
         return $isOwner;
     }
 
+    /** @deprecated 用 ChannelService::systemUid() */
     public static function getSysChannel($channel_name, $fallback = '')
     {
-        $channel = Channel::where('name', $channel_name)
-            ->where('owner_uid', config('mint.admin.root_uuid'))
-            ->first();
-        if (! $channel) {
-            if (! empty($fallback)) {
-                $channel = Channel::where('name', $fallback)
-                    ->where('owner_uid', config('mint.admin.root_uuid'))
-                    ->first();
-                if (! $channel) {
-                    return false;
-                } else {
-                    return $channel->uid;
-                }
-            }
-
-            return false;
-        } else {
-            return $channel->uid;
-        }
+        return self::service()->systemUid((string) $channel_name, (string) $fallback);
     }
 
+    /** @deprecated 用 ChannelService::byNameOrFail() */
     public static function getChannelByName($name)
     {
-        $channel = Channel::where('name', $name)
-            ->first();
-        if (! $channel) {
-            throw new \Exception('channel is invalid');
-        }
-
-        return $channel;
+        return self::service()->byNameOrFail((string) $name);
     }
 
     /**
      * 获取某个studio 的某个语言的自定义书的channel
      * 如果没有,建立
+     *
+     * @deprecated 用 ChannelService::userBookUid()
      */
     public static function userBookGetOrCreate($studioId, $lang, $status)
     {
-        $channelName = '_user_book_'.$lang;
-        $channel = Channel::where('owner_uid', $studioId)
-            ->where('name', $channelName)->first();
-        if ($channel) {
-            return $channel->uid;
-        }
-        $channelUuid = Str::uuid();
-        $channel = new Channel;
-        $channel->id = app('snowflake')->id();
-        $channel->uid = $channelUuid;
-        $channel->owner_uid = $studioId;
-        $channel->name = $channelName;
-        $channel->type = 'original';
-        $channel->lang = $lang;
-        $channel->editor_id = 0;
-        $channel->is_system = true;
-        $channel->create_time = time() * 1000;
-        $channel->modify_time = time() * 1000;
-        $channel->status = $status;
-        $saveOk = $channel->save();
-        if ($saveOk) {
-            Log::debug('copy user book : create channel success name='.$channelName);
-
-            return $channel->uid;
-        } else {
-            Log::error('copy user book : create channel fail.', ['channel' => $channelName, 'studioId' => $studioId]);
-
-            return false;
-        }
+        return self::service()->userBookUid((string) $studioId, (string) $lang, (int) $status);
+    }
+
+    private static function service(): ChannelService
+    {
+        return app(ChannelService::class);
     }
 }

+ 3 - 2
api-v13/app/Http/Api/TemplateRender.php

@@ -11,6 +11,7 @@ use App\Models\Discussion;
 use App\Models\PageNumber;
 use App\Models\PaliText;
 use App\Services\ArticleService;
+use App\Services\ChannelService;
 use App\Tools\Tools;
 use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Str;
@@ -425,7 +426,7 @@ class TemplateRender
 
         if (! $tplParam) {
             $this->info('没有,再查社区', 'term');
-            $community_channel = ChannelApi::getSysChannel('_community_term_zh-hans_');
+            $community_channel = app(ChannelService::class)->systemUid('_community_term_zh-hans_');
             $table = DhammaTerm::where('word', $word);
             if (! empty($tag)) {
                 $table = $table->where('tag', $tag);
@@ -1374,7 +1375,7 @@ class TemplateRender
         $word = $this->get_param($this->param, 'word', 1);
         $props = ['word' => $word];
 
-        $localTermChannel = ChannelApi::getSysChannel(
+        $localTermChannel = app(ChannelService::class)->systemUid(
             '_System_Grammar_Term_'.strtolower($this->lang).'_',
             '_System_Grammar_Term_en_'
         );

+ 146 - 0
api-v13/app/Services/ChannelService.php

@@ -0,0 +1,146 @@
+<?php
+
+namespace App\Services;
+
+use App\Models\Channel;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Str;
+
+/**
+ * channel 的纯能力(v2 / v3 共享):按 uid / 名字取 channel、取系统 channel、建用户自定义书的 channel。
+ *
+ * 只放与请求、响应形状、权限无关的逻辑。**权限判定不在这里**:
+ * v3 用 {@see V3\ChannelAbilityService}(认团队角色与共享),
+ * v2 的旧口径(只认拥有者本人 + 共享)留在 `App\Http\Api\ChannelApi`,随 v4 下线删除。
+ *
+ * 取代 `App\Http\Api\ChannelApi` 的同名逻辑,那边只剩转发壳。
+ */
+class ChannelService
+{
+    /**
+     * channel 摘要;不是 uuid 或不存在返回 false。
+     *
+     * `studio_id` 是 owner_uid(v2 的字段名,转发壳要原样返回)。
+     *
+     * @return array{id: string, name: string, type: string, lang: string, studio_id: string, status: int}|false
+     */
+    public function summary(?string $uid): array|false
+    {
+        if (! Str::isUuid($uid)) {
+            return false;
+        }
+        $channel = Channel::where('uid', $uid)->first(['uid', 'name', 'type', 'lang', 'owner_uid', 'status']);
+
+        return $channel ? $this->toSummary($uid, $channel) : false;
+    }
+
+    /**
+     * 批量取摘要,按传入顺序一一对应;查不到的位置是 false。一次查询。
+     *
+     * @param  array<int, string|null>  $uids
+     * @return list<array{id: string, name: string, type: string, lang: string, studio_id: string, status: int}|false>
+     */
+    public function summaries(array $uids): array
+    {
+        $valid = array_values(array_filter($uids, fn ($uid) => Str::isUuid($uid)));
+        $found = $valid === []
+            ? collect()
+            : Channel::whereIn('uid', array_unique($valid))
+                ->get(['uid', 'name', 'type', 'lang', 'owner_uid', 'status'])
+                ->keyBy(fn (Channel $channel) => (string) $channel->uid);
+
+        $result = [];
+        foreach ($uids as $uid) {
+            $channel = Str::isUuid($uid) ? $found->get($uid) : null;
+            $result[] = $channel ? $this->toSummary($uid, $channel) : false;
+        }
+
+        return $result;
+    }
+
+    /**
+     * 系统 channel(root 账号名下、按名字找)的 uid;找不到时试 $fallback,都没有返回 false。
+     */
+    public function systemUid(string $name, string $fallback = ''): string|false
+    {
+        $uid = $this->rootChannelUid($name);
+        if ($uid === false && $fallback !== '') {
+            $uid = $this->rootChannelUid($fallback);
+        }
+
+        return $uid;
+    }
+
+    /**
+     * 按名字取 channel(不限拥有者,取第一条)。
+     *
+     * @throws \Exception channel 不存在
+     */
+    public function byNameOrFail(string $name): Channel
+    {
+        $channel = Channel::where('name', $name)->first();
+        if (! $channel) {
+            throw new \Exception('channel is invalid');
+        }
+
+        return $channel;
+    }
+
+    /**
+     * 某个 studio 某个语言的「自定义书」channel(`_user_book_{lang}`)的 uid,没有就建一个。
+     * 建失败返回 false。
+     */
+    public function userBookUid(string $studioUid, string $lang, int $status): string|false
+    {
+        $name = '_user_book_'.$lang;
+        $existing = Channel::where('owner_uid', $studioUid)->where('name', $name)->value('uid');
+        if ($existing) {
+            return (string) $existing;
+        }
+
+        $channel = new Channel;
+        $channel->id = app('snowflake')->id();
+        $channel->uid = (string) Str::uuid();
+        $channel->owner_uid = $studioUid;
+        $channel->name = $name;
+        $channel->type = 'original';
+        $channel->lang = $lang;
+        $channel->editor_id = 0;
+        $channel->is_system = true;
+        $channel->create_time = time() * 1000;
+        $channel->modify_time = time() * 1000;
+        $channel->status = $status;
+        if (! $channel->save()) {
+            Log::error('copy user book : create channel fail.', ['channel' => $name, 'studioId' => $studioUid]);
+
+            return false;
+        }
+        Log::debug('copy user book : create channel success name='.$name);
+
+        return $channel->uid;
+    }
+
+    private function rootChannelUid(string $name): string|false
+    {
+        $uid = Channel::where('name', $name)
+            ->where('owner_uid', config('mint.admin.root_uuid'))
+            ->value('uid');
+
+        return $uid ? (string) $uid : false;
+    }
+
+    /**
+     * @return array{id: string, name: string, type: string, lang: string, studio_id: string, status: int}
+     */
+    private function toSummary(string $uid, Channel $channel): array
+    {
+        return [
+            'id' => $uid,
+            'name' => $channel->name,
+            'type' => $channel->type,
+            'lang' => $channel->lang,
+            'studio_id' => $channel->owner_uid,
+            'status' => $channel->status,
+        ];
+    }
+}

+ 2 - 2
api-v13/app/Services/PaliContentService.php

@@ -612,10 +612,10 @@ class PaliContentService
         if ($param['original']) {
             if ($param['mode'] === 'read') {
                 // 阅读模式加载html格式原文
-                $channelId = ChannelApi::getSysChannel('_System_Pali_VRI_');
+                $channelId = app(ChannelService::class)->systemUid('_System_Pali_VRI_');
             } else {
                 // 翻译模式加载json格式原文
-                $channelId = ChannelApi::getSysChannel('_System_Wbw_VRI_');
+                $channelId = app(ChannelService::class)->systemUid('_System_Wbw_VRI_');
             }
         }
 

+ 77 - 0
api-v13/tests/Feature/ChannelServiceTest.php

@@ -0,0 +1,77 @@
+<?php
+
+use App\Http\Api\ChannelApi;
+use App\Models\Channel;
+use App\Services\ChannelService;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/*
+ * ChannelService 是 ChannelApi 纯能力部分的新家;ChannelApi 那几个方法只剩转发壳,返回值必须与原来一致。
+ */
+
+it('summarises a channel the way v2 getById did', function () {
+    $owner = makeStudio('owner');
+    $uid = makeChannel($owner, 'my channel');
+
+    $expected = [
+        'id' => $uid, 'name' => 'my channel', 'type' => 'translation',
+        'lang' => 'zh-Hans', 'studio_id' => $owner, 'status' => 30,
+    ];
+    expect(app(ChannelService::class)->summary($uid))->toBe($expected)
+        ->and(ChannelApi::getById($uid))->toBe($expected)
+        ->and(ChannelApi::getById('not-a-uuid'))->toBeFalse()
+        ->and(ChannelApi::getById(null))->toBeFalse()
+        ->and(ChannelApi::getById((string) Str::uuid()))->toBeFalse();
+});
+
+it('summarises many channels in input order with false for misses, in one query', function () {
+    $owner = makeStudio('owner');
+    $a = makeChannel($owner, 'a');
+    $b = makeChannel($owner, 'b');
+    $missing = (string) Str::uuid();
+
+    DB::enableQueryLog();
+    $result = ChannelApi::getByIds([$b, 'bad', $missing, $a, $b]);
+    expect(DB::getQueryLog())->toHaveCount(1);
+
+    expect(array_map(fn ($row) => $row === false ? false : $row['name'], $result))
+        ->toBe(['b', false, false, 'a', 'b']);
+});
+
+it('finds a system channel by name under the root account, with a fallback', function () {
+    $root = config('mint.admin.root_uuid');
+    $en = makeChannel($root, '_System_Grammar_Term_en_');
+    makeChannel(makeStudio('someone'), '_System_Grammar_Term_my_');   // 不是 root 名下的不算
+
+    $service = app(ChannelService::class);
+    expect($service->systemUid('_System_Grammar_Term_en_'))->toBe($en)
+        ->and($service->systemUid('_System_Grammar_Term_my_'))->toBeFalse()
+        ->and($service->systemUid('_System_Grammar_Term_my_', '_System_Grammar_Term_en_'))->toBe($en)
+        ->and(ChannelApi::getSysChannel('_nope_', '_also_nope_'))->toBeFalse();
+});
+
+it('gets or creates the user book channel of a studio', function () {
+    $studio = makeStudio('owner');
+    $existing = makeChannel($studio, '_user_book_pali');
+
+    expect(ChannelApi::userBookGetOrCreate($studio, 'pali', 30))->toBe($existing);
+
+    $created = ChannelApi::userBookGetOrCreate($studio, 'zh-Hans', '10');
+    expect($created)->toBeString()
+        ->and(Channel::find($created))
+        ->name->toBe('_user_book_zh-Hans')
+        ->owner_uid->toBe($studio)
+        ->is_system->toBeTrue()
+        ->status->toBe(10);
+    expect(ChannelApi::userBookGetOrCreate($studio, 'zh-Hans', 10))->toBe($created);
+});
+
+it('gets a channel by name or throws', function () {
+    $uid = makeChannel(makeStudio('owner'), '_System_commentary_');
+
+    expect(ChannelApi::getChannelByName('_System_commentary_')->uid)->toBe($uid);
+    ChannelApi::getChannelByName('_missing_');
+})->throws(Exception::class, 'channel is invalid');

+ 19 - 0
api-v13/tests/Unit/V3ArchTest.php

@@ -0,0 +1,19 @@
+<?php
+
+/*
+ * v3 不准依赖 v2 的帮手类:纯能力走 App\Services 根下的 Service,权限走 App\Services\V3\*AbilityService。
+ *
+ * 每个命名空间单独一条:`expect([...])` 数组写法配 `not->toUse` 会空过(pest-plugin-arch 4.0.2 实测)。
+ */
+
+foreach ([
+    'App\Http\Controllers\V3',
+    'App\Http\Requests\V3',
+    'App\Http\Resources\V3',
+    'App\Services\V3',
+    'App\Services\ChannelService',
+] as $layer) {
+    arch("{$layer} does not use ChannelApi")
+        ->expect($layer)
+        ->not->toUse('App\Http\Api\ChannelApi');
+}