2
0

UserDictController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Http\Api\DictApi;
  4. use App\Http\Api\StudioApi;
  5. use App\Http\Resources\UserDictResource;
  6. use App\Models\DictInfo;
  7. use App\Models\UserDict;
  8. use App\Services\AuthService;
  9. use Illuminate\Http\Request;
  10. use Illuminate\Support\Facades\Redis;
  11. use Illuminate\Support\Str;
  12. class UserDictController extends Controller
  13. {
  14. /**
  15. * 列出用户词典条目
  16. *
  17. * 按 view 指定的口径返回 user_dict 记录,支持按单词、词根、词典过滤,以及分页与排序。
  18. * 需要登录的口径:all、studio;studio 口径还要求 name 指定的 studio 属于当前用户,否则返回 auth.failed。
  19. * community 口径只返回 status>5 且来源为 _USER_WBW_/_USER_DICT_ 的社区公开数据。
  20. * 返回 rows 与 count(过滤后总数)。
  21. *
  22. * @queryParam view string required 查询口径。all=全部;studio=某 studio 创建者的用户词条;user=cookie 中用户的词条(排除系统汇总);word=按单词查全部;community=社区公开词条;compound=复合词机器人词典;dict=指定词典。Enum: all,studio,user,word,community,compound,dict
  23. * @queryParam name string studio 口径为 studio 名;dict 口径为系统词典短名。Example: robot_compound
  24. * @queryParam id string dict 口径下直接指定的词典 uid(与 name 二选一)
  25. * @queryParam word string 要查询的单词,word/community/compound 口径必填;其他口径传入时也会追加过滤
  26. * @queryParam parent string 按词根(parent)过滤
  27. * @queryParam dict string 按词典短名(dict_info.shortname)过滤,解析为 uuid 后才生效
  28. * @queryParam search string 按单词前缀模糊搜索
  29. * @queryParam order string 排序字段。Default: updated_at
  30. * @queryParam dir string 排序方向。Enum: asc,desc Default: desc
  31. * @queryParam offset integer 跳过的记录数。Default: 0
  32. * @queryParam limit integer 返回条数上限。Default: 200
  33. */
  34. public function index(Request $request)
  35. {
  36. //
  37. $result = false;
  38. $indexCol = [
  39. 'id',
  40. 'word',
  41. 'type',
  42. 'grammar',
  43. 'mean',
  44. 'parent',
  45. 'note',
  46. 'status',
  47. 'factors',
  48. 'confidence',
  49. 'dict_id',
  50. 'source',
  51. 'updated_at',
  52. 'creator_id',
  53. ];
  54. switch ($request->input('view')) {
  55. case 'all':
  56. // 获取studio内所有channel
  57. $user = AuthService::current($request);
  58. if (! $user) {
  59. return $this->error(__('auth.failed'));
  60. }
  61. $table = UserDict::select($indexCol);
  62. break;
  63. case 'studio':
  64. // 获取studio内所有channel
  65. $user = AuthService::current($request);
  66. if (! $user) {
  67. return $this->error(__('auth.failed'));
  68. }
  69. // 判断当前用户是否有指定的studio的权限
  70. if ($user['user_uid'] !== StudioApi::getIdByName($request->input('name'))) {
  71. return $this->error(__('auth.failed'));
  72. }
  73. $table = UserDict::select($indexCol)
  74. ->where('creator_id', $user['user_id'])
  75. ->whereIn('source', ['_USER_WBW_', '_USER_DICT_']);
  76. break;
  77. case 'user':
  78. // code...
  79. $table = UserDict::select($indexCol)
  80. ->where('creator_id', $_COOKIE['user_id'])
  81. ->where('source', '<>', '_SYS_USER_WBW_');
  82. break;
  83. case 'word':
  84. $table = UserDict::select($indexCol)
  85. ->where('word', $request->input('word'));
  86. break;
  87. case 'community':
  88. $table = UserDict::select($indexCol)
  89. ->where('word', $request->input('word'))
  90. ->where('status', '>', 5)
  91. ->where(function ($query) {
  92. $query->where('source', '_USER_WBW_')
  93. ->orWhere('source', '_USER_DICT_');
  94. });
  95. break;
  96. case 'compound':
  97. $dict_id = DictApi::getSysDict('robot_compound');
  98. // FIXME: $this->error(...) 没有 return,取不到词典时不会中断,会继续用 false 去查询。应改为 return $this->error(...)。
  99. if ($dict_id === false) {
  100. $this->error('no robot_compound');
  101. }
  102. $table = UserDict::where('dict_id', $dict_id)->where('word', $request->input('word'));
  103. break;
  104. case 'dict':
  105. $dict_id = false;
  106. if ($request->has('name')) {
  107. $dict_id = DictApi::getSysDict($request->input('name'));
  108. } elseif ($request->has('id')) {
  109. $dict_id = $request->input('id');
  110. }
  111. // FIXME: $this->error(...) 没有 return,词典不存在时不会中断,会继续用 false 去查询。应改为 return $this->error(...)。
  112. if ($dict_id === false) {
  113. $this->error('no dict', [], 404);
  114. }
  115. $table = UserDict::select($indexCol)
  116. ->where('dict_id', $dict_id);
  117. // FIXME: 这里缺 break,会贯穿到 default(当前恰好无副作用,但属于隐患)。应补上 break;。
  118. default:
  119. // code...
  120. break;
  121. }
  122. // FIXME: view 不在枚举内(含缺省)时 $table 从未被赋值,下面的 $table->count() 会 fatal error。
  123. // 建议 default 分支直接 return $this->error('无法识别的参数view', 400, 400)。
  124. if ($request->has('search')) {
  125. $table->where('word', 'like', $request->input('search').'%');
  126. }
  127. if (($request->has('word'))) {
  128. $table = $table->where('word', $request->input('word'));
  129. }
  130. if (($request->has('parent'))) {
  131. $table = $table->where('parent', $request->input('parent'));
  132. }
  133. if (($request->has('dict'))) {
  134. $dictId = DictInfo::where('shortname', $request->input('dict'))->value('id');
  135. if (Str::isUuid($dictId)) {
  136. $table = $table->where('dict_id', $dictId);
  137. }
  138. }
  139. $count = $table->count();
  140. $table->orderBy(
  141. $request->input('order', 'updated_at'),
  142. $request->input('dir', 'desc')
  143. );
  144. $table->skip($request->input('offset', 0))
  145. ->take($request->input('limit', 200));
  146. $result = $table->get();
  147. return $this->ok(['rows' => UserDictResource::collection($result), 'count' => $count]);
  148. }
  149. /**
  150. * 批量新增/更新用户词典条目
  151. *
  152. * 需要登录。data 是 JSON 字符串,解码后逐条处理:以 creator_id + word 以及请求中给出的
  153. * type/grammar/parent/mean/factors 组合判重,不存在则插入(自动生成雪花 id、按 view 写入 source、
  154. * 记录 create_time 与 creator_id),已存在则只更新 note 与 confidence。
  155. * 新增且 status>5 时会同步刷新系统汇总词典 _SYS_USER_WBW_;每次新增都会刷新该单词的 Redis 缓存 dict/user。
  156. * 返回 [新增条数, 汇总表更新结果]。
  157. *
  158. * @bodyParam view string required 数据来源口径,决定写入的 source:dict=_USER_DICT_,wbw=_USER_WBW_。Enum: dict,wbw
  159. * @bodyParam data string required 词条数组的 JSON 字符串,每项含 word(必填)及可选 type、grammar、parent、mean、factors、factormean、note、confidence、status、language
  160. */
  161. public function store(Request $request)
  162. {
  163. //
  164. $user = AuthService::current($request);
  165. // FIXME: $this->error('not login') 没有 return,未登录时会继续往下执行并在 $user['user_id'] 处 fatal error。
  166. // 应改为 return $this->error(__('auth.failed'), [], 401)。
  167. if (! $user) {
  168. $this->error('not login');
  169. }
  170. $_data = json_decode($request->input('data'), true);
  171. switch ($request->input('view')) {
  172. case 'dict':
  173. $src = '_USER_DICT_';
  174. break;
  175. case 'wbw':
  176. $src = '_USER_WBW_';
  177. break;
  178. default:
  179. $this->error('not view');
  180. break;
  181. }
  182. // 查询用户重复的数据
  183. $iOk = 0;
  184. $updateOk = 0;
  185. foreach ($_data as $key => $word) {
  186. // code...
  187. $table = UserDict::where('creator_id', $user['user_id'])
  188. ->where('word', $word['word']);
  189. if (isset($word['type'])) {
  190. $table = $table->where('type', $word['type']);
  191. }
  192. if (isset($word['grammar'])) {
  193. $table = $table->where('grammar', $word['grammar']);
  194. }
  195. if (isset($word['parent'])) {
  196. $table = $table->where('parent', $word['parent']);
  197. }
  198. if (isset($word['mean'])) {
  199. $table = $table->where('mean', $word['mean']);
  200. }
  201. if (isset($word['factors'])) {
  202. $table = $table->where('factors', $word['factors']);
  203. }
  204. $isDoesntExist = $table->doesntExist();
  205. if ($isDoesntExist) {
  206. // 不存在插入数据
  207. $word['id'] = app('snowflake')->id();
  208. $word['source'] = $src;
  209. $word['create_time'] = time() * 1000;
  210. $word['creator_id'] = $user['user_id'];
  211. $id = UserDict::insert($word);
  212. if (isset($word['status']) && $word['status'] > 5) {
  213. $updateOk = $this->update_sys_wbw($word);
  214. } else {
  215. $updateOk = true;
  216. }
  217. $this->update_redis($word);
  218. $iOk++;
  219. } else {
  220. // 存在,修改数据
  221. $origin = $table->first();
  222. if (isset($word['note'])) {
  223. $origin->note = $word['note'];
  224. }
  225. if (isset($word['confidence'])) {
  226. $origin->confidence = $word['confidence'];
  227. }
  228. $origin->save();
  229. }
  230. }
  231. return $this->ok([$iOk, $updateOk]);
  232. }
  233. /**
  234. * 查询单条用户词典记录
  235. *
  236. * 按主键查找,不做登录与权限校验;查不到返回「没有查询到数据」。
  237. *
  238. * @urlParam userdict string required 词条 id
  239. */
  240. public function show($id)
  241. {
  242. //
  243. $result = UserDict::find($id);
  244. if ($result) {
  245. return $this->ok($result);
  246. } else {
  247. return $this->error('没有查询到数据');
  248. }
  249. }
  250. /**
  251. * 更新单条用户词典记录
  252. *
  253. * 把请求体中的全部字段直接写入该记录(未做字段白名单与权限校验)。
  254. * 更新成功后同步刷新系统汇总词典 _SYS_USER_WBW_ 与该单词的 Redis 缓存 dict/user。
  255. * 没有记录被更新时返回「没有查询到数据」。
  256. *
  257. * @urlParam userdict string required 词条 id
  258. *
  259. * @bodyParam word string 单词
  260. * @bodyParam type string 词性
  261. * @bodyParam grammar string 语法属性
  262. * @bodyParam parent string 词根
  263. * @bodyParam mean string 词义
  264. * @bodyParam factors string 复合词拆分
  265. * @bodyParam factormean string 复合词各部分词义
  266. * @bodyParam note string 备注
  267. * @bodyParam confidence integer 置信度
  268. * @bodyParam status integer 状态,大于 5 表示公开到社区
  269. * @bodyParam language string 语言代码
  270. */
  271. public function update(Request $request, $id)
  272. {
  273. //
  274. // FIXME: 安全问题。直接把 $request->all() 整体落库,既无字段白名单(可改 creator_id、source、dict_id 等)
  275. // 也无登录与创建者校验,任何人都能改任意词条。应先鉴权并只允许更新白名单字段。
  276. $newData = $request->all();
  277. $result = UserDict::where('id', $id)
  278. ->update($newData);
  279. if ($result) {
  280. $updateOk = $this->update_sys_wbw($newData);
  281. $this->update_redis($newData);
  282. return $this->ok([$result, $updateOk]);
  283. } else {
  284. return $this->error('没有查询到数据');
  285. }
  286. }
  287. /**
  288. * 删除用户词典记录(支持批量)
  289. *
  290. * 需要登录,未登录返回 403。传了查询参数 id(JSON 数组)时走批量分支,逐条只删除 creator_id
  291. * 等于当前用户的记录,返回 [实际删除条数, 汇总表更新结果];否则删除路径参数指定的单条记录,
  292. * 非本人创建返回 auth.failed。两种分支都会同步刷新 _SYS_USER_WBW_ 汇总与 Redis 缓存 dict/user。
  293. *
  294. * @urlParam userdict string required 要删除的词条 id(未传查询参数 id 时使用)
  295. *
  296. * @queryParam id string 要批量删除的词条 id 数组的 JSON 字符串。Example: ["123","456"]
  297. */
  298. public function destroy(Request $request, $id)
  299. {
  300. //
  301. $user = AuthService::current($request);
  302. if (! $user) {
  303. return $this->error(__('auth.failed'), [], 403);
  304. }
  305. $user_id = $user['user_id'];
  306. if ($request->has('id')) {
  307. $arrId = json_decode($request->input('id'), true);
  308. $count = 0;
  309. $updateOk = false;
  310. foreach ($arrId as $key => $id) {
  311. // 找到对应数据
  312. // FIXME: find() 可能返回 null,下一行对 null 取属性会 fatal error。应先判空再处理。
  313. $data = UserDict::find($id);
  314. // 查看是否有权限删除
  315. if ($data->creator_id == $user_id) {
  316. $result = UserDict::where('id', $id)
  317. ->delete();
  318. $count += $result;
  319. $updateOk = $this->update_sys_wbw($data);
  320. $this->update_redis($data);
  321. }
  322. }
  323. return $this->ok([$count, $updateOk]);
  324. } else {
  325. // 删除单个单词
  326. $userDict = UserDict::find($id);
  327. // 判断当前用户是否有指定的studio的权限
  328. // FIXME: $userDict 可能为 null(fatal error);且用 (int) 与 creator_id 做 !== 严格比较,
  329. // creator_id 若是字符串列则永远不相等,会误判为无权限。建议先判空并改用 == 或统一类型。
  330. if ((int) $user_id !== $userDict->creator_id) {
  331. return $this->error(__('auth.failed'));
  332. }
  333. $delete = $userDict->delete();
  334. return $this->ok($delete);
  335. }
  336. }
  337. /**
  338. * 批量删除用户词典记录(旧接口)
  339. *
  340. * 不走 AuthService,凭据取自 cookie 中的 user_id,只删除该用户创建的记录。
  341. * 每删一条都会同步刷新 _SYS_USER_WBW_ 汇总与该单词的 Redis 缓存 dict/user。
  342. * 返回 deleted(实际删除条数)。
  343. *
  344. * @queryParam id string required 要删除的词条 id 数组的 JSON 字符串。Example: ["123","456"]
  345. */
  346. public function delete(Request $request)
  347. {
  348. // FIXME: 本方法不走 AuthService,凭据直接取自 $_COOKIE['user_id'](见下方 $param),
  349. // 未登录时会 undefined array key。应改用 AuthService::current($request) 并在未登录时返回 401。
  350. $arrId = json_decode($request->input('id'), true);
  351. $count = 0;
  352. $updateOk = false;
  353. foreach ($arrId as $key => $id) {
  354. $data = UserDict::where('id', $id)->first();
  355. if ($data) {
  356. // 找到对应数据
  357. $param = [
  358. 'id' => $id,
  359. 'creator_id' => $_COOKIE['user_id'],
  360. ];
  361. $del = UserDict::where($param)->delete();
  362. $count += $del;
  363. $updateOk = $this->update_sys_wbw($data);
  364. $this->update_redis($data);
  365. }
  366. }
  367. return $this->ok(['deleted' => $count]);
  368. }
  369. /*
  370. 更新系统wbw汇总表
  371. */
  372. private function update_sys_wbw($data)
  373. {
  374. // 查询用户重复的数据
  375. if (! isset($data['type'])) {
  376. $data['type'] = null;
  377. }
  378. if (! isset($data['grammar'])) {
  379. $data['grammar'] = null;
  380. }
  381. if (! isset($data['parent'])) {
  382. $data['parent'] = null;
  383. }
  384. if (! isset($data['mean'])) {
  385. $data['mean'] = null;
  386. }
  387. if (! isset($data['factors'])) {
  388. $data['factors'] = null;
  389. }
  390. if (! isset($data['factormean'])) {
  391. $data['factormean'] = null;
  392. }
  393. $count = UserDict::where('word', $data['word'])
  394. ->where('type', $data['type'])
  395. ->where('grammar', $data['grammar'])
  396. ->where('parent', $data['parent'])
  397. ->where('mean', $data['mean'])
  398. ->where('factors', $data['factors'])
  399. ->where('factormean', $data['factormean'])
  400. ->where('source', $data['source'])
  401. ->count();
  402. if ($count === 0) {
  403. // 没有任何用户有这个数据
  404. // 删除数据
  405. $result = UserDict::where('word', $data['word'])
  406. ->where('type', $data['type'])
  407. ->where('grammar', $data['grammar'])
  408. ->where('parent', $data['parent'])
  409. ->where('mean', $data['mean'])
  410. ->where('factors', $data['factors'])
  411. ->where('factormean', $data['factormean'])
  412. ->where('source', '_SYS_USER_WBW_')
  413. ->delete();
  414. return $result;
  415. } else {
  416. // 更新或新增
  417. // 查询最早上传这个数据的用户
  418. $creator_id = UserDict::where('word', $data['word'])
  419. ->where('type', $data['type'])
  420. ->where('grammar', $data['grammar'])
  421. ->where('parent', $data['parent'])
  422. ->where('mean', $data['mean'])
  423. ->where('factors', $data['factors'])
  424. ->where('factormean', $data['factormean'])
  425. ->whereIn('source', ['_USER_WBW_', '_USER_DICT_'])
  426. ->orderby('created_at', 'asc')
  427. ->value('creator_id');
  428. $count = UserDict::where('word', $data['word'])
  429. ->where('type', $data['type'])
  430. ->where('grammar', $data['grammar'])
  431. ->where('parent', $data['parent'])
  432. ->where('mean', $data['mean'])
  433. ->where('factors', $data['factors'])
  434. ->where('factormean', $data['factormean'])
  435. ->where('source', '_SYS_USER_WBW_')
  436. ->count();
  437. if ($count === 0) {
  438. // 社区字典没有 新增
  439. $result = UserDict::insert(
  440. [
  441. 'id' => app('snowflake')->id(),
  442. 'word' => $data['word'],
  443. 'type' => $data['type'],
  444. 'grammar' => $data['grammar'],
  445. 'parent' => $data['parent'],
  446. 'mean' => $data['mean'],
  447. 'factors' => $data['factors'],
  448. 'factormean' => $data['factormean'],
  449. 'language' => $data['language'],
  450. 'source' => '_SYS_USER_WBW_',
  451. 'creator_id' => $data['creator_id'],
  452. 'ref_counter' => 1,
  453. 'dict_id' => DictApi::getSysDict('community_extract'),
  454. 'create_time' => time() * 1000,
  455. ]
  456. );
  457. } else {
  458. // 有,更新
  459. $result = UserDict::where('word', $data['word'])
  460. ->where('type', $data['type'])
  461. ->where('grammar', $data['grammar'])
  462. ->where('parent', $data['parent'])
  463. ->where('mean', $data['mean'])
  464. ->where('factors', $data['factors'])
  465. ->where('factormean', $data['factormean'])
  466. ->where('source', '_SYS_USER_WBW_')
  467. ->update(
  468. [
  469. 'creator_id' => $creator_id,
  470. 'ref_counter' => $count,
  471. ]
  472. );
  473. }
  474. return $result;
  475. }
  476. }
  477. private function update_redis($word)
  478. {
  479. // 更新 redis
  480. $Fetch = UserDict::where(['word' => $word['word'], 'source' => '_USER_WBW_'])->get();
  481. $redisWord = [];
  482. foreach ($Fetch as $one) {
  483. // code...
  484. $redisWord[] = [
  485. $one['id'],
  486. $one['word'],
  487. $one['type'],
  488. $one['grammar'],
  489. $one['parent'],
  490. $one['mean'],
  491. $one['note'],
  492. $one['factors'],
  493. $one['factormean'],
  494. $one['status'],
  495. $one['confidence'],
  496. $one['creator_id'],
  497. $one['source'],
  498. $one['language'],
  499. ];
  500. }
  501. $redisData = json_encode($redisWord, JSON_UNESCAPED_UNICODE);
  502. Redis::hSet('dict/user', $word['word'], $redisData);
  503. $redisData1 = Redis::hGet('dict/user', $word['word']);
  504. // 更新redis结束
  505. }
  506. }