2
0

SentenceController.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Http\Api\ChannelApi;
  4. use App\Http\Api\Mq;
  5. use App\Http\Api\PaliTextApi;
  6. use App\Http\Api\ShareApi;
  7. use App\Http\Resources\SentResource;
  8. use App\Models\AccessToken;
  9. use App\Models\Channel;
  10. use App\Models\Sentence;
  11. use App\Models\WbwAnalysis;
  12. use App\Services\AuthService;
  13. use App\Services\SentenceService;
  14. use App\Tools\OpsLog;
  15. use Firebase\JWT\JWT;
  16. use Firebase\JWT\Key;
  17. use Illuminate\Http\Request;
  18. use Illuminate\Http\Response;
  19. use Illuminate\Support\Facades\Cache;
  20. use Illuminate\Support\Facades\Redis;
  21. use Illuminate\Support\Str;
  22. class SentenceController extends Controller
  23. {
  24. public function __construct(protected SentenceService $sentenceService) {}
  25. /**
  26. * Display a listing of the resource.
  27. *
  28. * @return Response
  29. */
  30. public function index(Request $request)
  31. {
  32. $user = AuthService::current($request);
  33. $result = false;
  34. $indexCol = [
  35. 'id',
  36. 'uid',
  37. 'book_id',
  38. 'paragraph',
  39. 'word_start',
  40. 'word_end',
  41. 'content',
  42. 'content_type',
  43. 'channel_uid',
  44. 'editor_uid',
  45. 'fork_at',
  46. 'acceptor_uid',
  47. 'pr_edit_at',
  48. 'updated_at',
  49. ];
  50. switch ($request->input('view')) {
  51. case 'public':
  52. // 获取全部公开的译文
  53. // 首先获取某个类型的 channel 列表
  54. $channels = [];
  55. $channel_type = $request->input('channel_type', 'translation');
  56. if ($channel_type === 'original') {
  57. $pali_channel = ChannelApi::getSysChannel('_System_Pali_VRI_');
  58. if ($pali_channel !== false) {
  59. $channels[] = $pali_channel;
  60. }
  61. } else {
  62. $channelList = Channel::where('type', $channel_type)
  63. ->where('status', 30)
  64. ->select('uid')->get();
  65. foreach ($channelList as $channel) {
  66. // code...
  67. $channels[] = $channel->uid;
  68. }
  69. }
  70. $table = Sentence::select($indexCol)
  71. ->whereIn('channel_uid', $channels)
  72. ->where('updated_at', '>', $request->input('updated_after', '1970-1-1'));
  73. break;
  74. case 'fulltext':
  75. if (isset($_COOKIE['user_uid'])) {
  76. $userUid = $_COOKIE['user_uid'];
  77. }
  78. $key = $request->input('key');
  79. if (empty($key)) {
  80. return $this->error('没有关键词');
  81. }
  82. $table = Sentence::select($indexCol)
  83. ->where('content', 'like', '%'.$key.'%')
  84. ->where('editor_uid', $userUid);
  85. break;
  86. case 'channel':
  87. // 句子编号列表在某个channel下的全部内容
  88. $sent = explode(',', $request->input('sentence'));
  89. $query = [];
  90. foreach ($sent as $value) {
  91. // code...
  92. $ids = explode('-', $value);
  93. $query[] = $ids;
  94. }
  95. $table = Sentence::select($indexCol)
  96. ->where('channel_uid', $request->input('channel'))
  97. ->whereIns(['book_id', 'paragraph', 'word_start', 'word_end'], $query);
  98. break;
  99. case 'sent-can-read':
  100. /**
  101. * 某句的全部译文
  102. */
  103. // 获取用户有阅读权限的所有channel
  104. // 全网公开
  105. $type = $request->input('type', 'translation');
  106. $channelTable = Channel::where('type', $type)->select(['uid', 'name']);
  107. $channelPub = $channelTable->where('status', 30)->get();
  108. $user = AuthService::current($request);
  109. $channelShare = [];
  110. $channelMy = [];
  111. if ($user) {
  112. // 自己的
  113. $channelMy = Channel::where('owner_uid', $user['user_uid'])
  114. ->where('type', $type)
  115. ->get();
  116. // 协作
  117. $channelShare = ShareApi::getResList($user['user_uid'], 2);
  118. }
  119. $channelCanRead = [];
  120. foreach ($channelPub as $key => $value) {
  121. $channelCanRead[$value->uid] = [
  122. 'id' => $value->uid,
  123. 'role' => 'member',
  124. 'name' => $value->name,
  125. ];
  126. }
  127. foreach ($channelShare as $key => $value) {
  128. if ($value['type'] === $type) {
  129. $channelCanRead[$value['res_id']] = [
  130. 'id' => $value['res_id'],
  131. 'role' => 'member',
  132. 'name' => $value['res_title'],
  133. ];
  134. if ($value['power'] >= 20) {
  135. $channelCanRead[$value['res_id']]['role'] = 'editor';
  136. }
  137. }
  138. }
  139. foreach ($channelMy as $key => $value) {
  140. $channelCanRead[$value->uid] = [
  141. 'id' => $value->uid,
  142. 'role' => 'owner',
  143. 'name' => $value->name,
  144. ];
  145. }
  146. $channels = [];
  147. $excludeChannels = explode(',', $request->input('excludes'));
  148. foreach ($channelCanRead as $key => $value) {
  149. // code...
  150. if (! in_array($key, $excludeChannels)) {
  151. $channels[] = $key;
  152. }
  153. }
  154. $sent = explode('-', $request->input('sentence'));
  155. $table = Sentence::select($indexCol)
  156. ->whereIn('channel_uid', $channels)
  157. ->where('ver', '>', 1)
  158. ->where('book_id', $sent[0])
  159. ->where('paragraph', $sent[1])
  160. ->where('word_start', $sent[2])
  161. ->where('word_end', $sent[3]);
  162. break;
  163. case 'chapter':
  164. $chapter = PaliTextApi::getChapterStartEnd($request->input('book'), $request->input('para'));
  165. $table = Sentence::where('ver', '>', 1)
  166. ->where('book_id', $request->input('book'))
  167. ->whereBetween('paragraph', $chapter)
  168. ->whereIn('channel_uid', explode(',', $request->input('channels')));
  169. break;
  170. case 'paragraph':
  171. $table = Sentence::where('ver', '>', 1)
  172. ->where('book_id', $request->input('book'))
  173. ->whereIn('paragraph', explode(',', $request->input('para')))
  174. ->orderBy('book_id')->orderBy('paragraph')->orderBy('word_start');
  175. if ($request->has('channels')) {
  176. $table = $table->whereIn('channel_uid', explode(',', $request->input('channels')));
  177. }
  178. if ($request->has('channel_type')) {
  179. $table = $table->type($request->input('channel_type'));
  180. }
  181. if ($request->has('lang')) {
  182. $table = $table->language($request->input('lang'));
  183. }
  184. break;
  185. case 'my-edit':
  186. // 我编辑的
  187. if (! $user) {
  188. return $this->error(__('auth.failed'), 401, 401);
  189. }
  190. $table = Sentence::where('editor_uid', $user['user_uid'])
  191. ->where('ver', '>', 1);
  192. break;
  193. default:
  194. // code...
  195. break;
  196. }
  197. if (! empty($request->input('key'))) {
  198. $table = $table->where('content', 'like', '%'.$request->input('key').'%');
  199. }
  200. $count = $table->count();
  201. if ($request->input('strlen', false)) {
  202. $totalStrLen = $table->sum('strlen');
  203. }
  204. if ($request->input('view') !== 'paragraph') {
  205. $table = $table->orderBy(
  206. $request->input('order', 'updated_at'),
  207. $request->input('dir', 'desc')
  208. );
  209. }
  210. $table = $table->skip($request->input('offset', 0))
  211. ->take($request->input('limit', 1000));
  212. $result = $table->get();
  213. if ($result) {
  214. $output = ['count' => $count];
  215. if (
  216. $request->input('view') === 'sent-can-read' ||
  217. $request->input('view') === 'channel' ||
  218. $request->input('view') === 'chapter' ||
  219. $request->input('view') === 'paragraph' ||
  220. $request->input('view') === 'my-edit'
  221. ) {
  222. $output['rows'] = SentResource::collection($result);
  223. } else {
  224. $output['rows'] = $result;
  225. }
  226. if (isset($totalStrLen)) {
  227. $output['total_strlen'] = $totalStrLen;
  228. }
  229. return $this->ok($output);
  230. } else {
  231. return $this->ok([]);
  232. }
  233. }
  234. /**
  235. * 用channel 和句子编号列表查询句子
  236. */
  237. public function sent_in_channel(Request $request)
  238. {
  239. $sent = $request->input('sentences');
  240. $query = [];
  241. foreach ($sent as $value) {
  242. // code...
  243. $ids = explode('-', $value);
  244. if (count($ids) === 4) {
  245. $query[] = $ids;
  246. }
  247. }
  248. $table = Sentence::select(['id', 'book_id', 'paragraph', 'word_start', 'word_end', 'content', 'channel_uid', 'updated_at'])
  249. ->where('channel_uid', $request->input('channel'))
  250. ->whereIns(['book_id', 'paragraph', 'word_start', 'word_end'], $query);
  251. $result = $table->get();
  252. if ($result) {
  253. return $this->ok(['rows' => $result, 'count' => count($result)]);
  254. } else {
  255. return $this->error('没有查询到数据');
  256. }
  257. }
  258. private function UserCanEdit(string $userId, string $channelId, int $book, $access_token = null)
  259. {
  260. $channel = Channel::where('uid', $channelId)->first();
  261. if (! $channel) {
  262. return false;
  263. }
  264. if ($channel->owner_uid !== $userId) {
  265. // 判断是否为协作
  266. $power = ShareApi::getResPower($userId, $channel->uid, 2);
  267. if ($power < 20) {
  268. // 判断token
  269. if (! $access_token) {
  270. return false;
  271. }
  272. $key = AccessToken::where('res_id', $channelId)->value('token');
  273. if (! $key) {
  274. return false;
  275. }
  276. try {
  277. // access token 现在带 exp,过期会抛 ExpiredException;
  278. // 伪造/损坏的 token 同样抛异常。一律当作无权,不要冒泡成 500。
  279. $jwt = JWT::decode($access_token, new Key($key.$key, 'HS512'));
  280. } catch (\Exception $e) {
  281. return false;
  282. }
  283. if (isset($jwt->book) && $jwt->book !== 0 && $jwt->book !== $book) {
  284. return false;
  285. }
  286. }
  287. }
  288. return true;
  289. }
  290. /**
  291. * 新建多个句子
  292. * 如果句子存在,修改
  293. *
  294. * @return Response
  295. */
  296. public function store(Request $request)
  297. {
  298. // 鉴权
  299. $user = AuthService::current($request);
  300. if (! $user) {
  301. // 未登录用户
  302. return $this->error(__('auth.failed'), 401, 401);
  303. }
  304. if (! $request->has('sentences')) {
  305. return $this->error('no date', 200, 200);
  306. }
  307. $destChannel = null;
  308. if ($request->has('channel')) {
  309. if ($this->UserCanEdit(
  310. $user['user_uid'],
  311. $request->input('channel'),
  312. (int) $request->input('book', 0),
  313. $request->input('access_token', null)
  314. )) {
  315. $destChannel = Channel::where('uid', $request->input('channel'))->first();
  316. } else {
  317. return $this->error(__('auth.failed'), 403, 403);
  318. }
  319. }
  320. $sentFirst = null;
  321. $changedSent = [];
  322. foreach ($request->input('sentences') as $key => $sent) {
  323. // 权限
  324. if (! $request->has('channel')) {
  325. if ($this->UserCanEdit(
  326. $user['user_uid'],
  327. $sent['channel_uid'],
  328. (int) $sent['book_id'],
  329. isset($sent['access_token']) ? $sent['access_token'] : null
  330. )) {
  331. $destChannel = Channel::where('uid', $sent['channel_uid'])->first();
  332. } else {
  333. continue;
  334. }
  335. }
  336. /*
  337. $destChannel = Channel::where('uid', $sent['channel_uid'])->first();
  338. if (!$destChannel) {
  339. continue;
  340. }
  341. if ($destChannel->owner_uid !== $user["user_uid"]) {
  342. //判断是否为协作
  343. $power = ShareApi::getResPower($user["user_uid"], $destChannel->uid, 2);
  344. if ($power < 20) {
  345. //判断token
  346. if (!isset($sent['access_token'])) {
  347. continue;
  348. }
  349. $key = AccessToken::where('res_id', $destChannel->uid)->value('token');
  350. $jwt = JWT::decode($sent['access_token'], new Key($key, 'HS512'));
  351. if ($jwt->book !== $sent['book_id']) {
  352. continue;
  353. }
  354. }
  355. }
  356. */
  357. if ($sentFirst === null) {
  358. $sentFirst = $sent;
  359. }
  360. $row = Sentence::firstOrNew([
  361. 'book_id' => $sent['book_id'],
  362. 'paragraph' => $sent['paragraph'],
  363. 'word_start' => $sent['word_start'],
  364. 'word_end' => $sent['word_end'],
  365. 'channel_uid' => $destChannel->uid,
  366. ], [
  367. 'id' => app('snowflake')->id(),
  368. 'uid' => Str::uuid(),
  369. ]);
  370. $row->content = $sent['content'];
  371. if (isset($sent['content_type']) && ! empty($sent['content_type'])) {
  372. $row->content_type = $sent['content_type'];
  373. }
  374. $row->strlen = mb_strlen($sent['content'], 'UTF-8');
  375. $row->language = $destChannel->lang;
  376. $row->status = $destChannel->status;
  377. if ($request->has('copy')) {
  378. // 复制句子,保留原作者信息
  379. $row->editor_uid = $sent['editor_uid'];
  380. $row->acceptor_uid = $user['user_uid'];
  381. $row->pr_edit_at = $sent['updated_at'];
  382. if ($request->has('fork_from')) {
  383. $row->fork_at = now();
  384. }
  385. } else {
  386. $row->editor_uid = $user['user_uid'];
  387. $row->acceptor_uid = null;
  388. $row->pr_edit_at = null;
  389. }
  390. $row->create_time = time() * 1000;
  391. $row->modify_time = time() * 1000;
  392. $row->save();
  393. $changedSent[] = $row->uid;
  394. // 保存历史记录
  395. if ($request->has('copy')) {
  396. $fork_from = $request->input('fork_from', null);
  397. $this->sentenceService->saveHistory(
  398. $row->uid,
  399. $sent['editor_uid'],
  400. $sent['content'],
  401. $user['user_uid'],
  402. $fork_from
  403. );
  404. } else {
  405. $this->sentenceService->saveHistory($row->uid, $user['user_uid'], $sent['content'], $user['user_uid']);
  406. }
  407. // 清除缓存
  408. $sentId = "{$sent['book_id']}-{$sent['paragraph']}-{$sent['word_start']}-{$sent['word_end']}";
  409. $hKey = "/sentence/res-count/{$sentId}/";
  410. Redis::del($hKey);
  411. }
  412. if ($sentFirst !== null) {
  413. Mq::publish('progress', [
  414. 'book' => $sentFirst['book_id'],
  415. 'para' => $sentFirst['paragraph'],
  416. 'channel' => $destChannel->uid,
  417. ]);
  418. }
  419. $result = Sentence::whereIn('uid', $changedSent)->get();
  420. return $this->ok([
  421. 'rows' => SentResource::collection($result),
  422. 'count' => count($result),
  423. ]);
  424. }
  425. /**
  426. * Display the specified resource.
  427. *
  428. * @return Response
  429. */
  430. public function show(Sentence $sentence)
  431. {
  432. //
  433. return $this->ok(new SentResource($sentence));
  434. }
  435. /**
  436. * 修改单个句子
  437. *
  438. * @param string $id book_para_start_end_channel
  439. * @return Response
  440. */
  441. public function update(Request $request, $id)
  442. {
  443. //
  444. $param = \explode('_', $id);
  445. // 鉴权
  446. $user = AuthService::current($request);
  447. if (! $user) {
  448. // 未登录鉴权失败
  449. return $this->error(__('auth.failed'), 403, 403);
  450. }
  451. $channel = Channel::where('uid', $param[4])->first();
  452. if (! $channel) {
  453. return $this->error('not found channel');
  454. }
  455. if ($channel->owner_uid !== $user['user_uid']) {
  456. // 判断是否为协作
  457. $power = ShareApi::getResPower($user['user_uid'], $channel->uid, 2);
  458. if ($power < 20) {
  459. return $this->error(__('auth.failed'), 403, 403);
  460. }
  461. }
  462. $sent = Sentence::firstOrNew([
  463. 'book_id' => $param[0],
  464. 'paragraph' => $param[1],
  465. 'word_start' => $param[2],
  466. 'word_end' => $param[3],
  467. 'channel_uid' => $param[4],
  468. ], [
  469. 'id' => app('snowflake')->id(),
  470. 'uid' => Str::orderedUuid(),
  471. 'create_time' => time() * 1000,
  472. ]);
  473. $sent->content = $request->input('content');
  474. if ($request->has('contentType')) {
  475. $sent->content_type = $request->input('contentType');
  476. }
  477. $sent->language = $channel->lang;
  478. $sent->status = $channel->status;
  479. $sent->strlen = mb_strlen($request->input('content'), 'UTF-8');
  480. $sent->modify_time = time() * 1000;
  481. if ($request->has('prEditor')) {
  482. $realEditor = $request->input('prEditor');
  483. $sent->acceptor_uid = $user['user_uid'];
  484. $sent->pr_edit_at = $request->input('prEditAt');
  485. $sent->pr_id = $request->input('prId');
  486. } else {
  487. $realEditor = $user['user_uid'];
  488. $sent->acceptor_uid = null;
  489. $sent->pr_edit_at = null;
  490. $sent->pr_id = null;
  491. }
  492. $sent->editor_uid = $realEditor;
  493. $sent->save();
  494. $sent = $sent->refresh();
  495. // 清除缓存
  496. $sentId = "{$sent['book_id']}-{$sent['paragraph']}-{$sent['word_start']}-{$sent['word_end']}";
  497. $hKey = "/sentence/res-count/{$sentId}/";
  498. Redis::del($hKey);
  499. OpsLog::debug($user['user_uid'], $sent);
  500. // 清除cache
  501. $channelId = $param[4];
  502. $currSentId = "{$param[0]}-{$param[1]}-{$param[2]}-{$param[3]}";
  503. Cache::forget("/sent/{$channelId}/{$currSentId}");
  504. // 保存历史记录
  505. if ($request->has('prEditor')) {
  506. $this->sentenceService->saveHistory(
  507. $sent->uid,
  508. $realEditor,
  509. $request->input('content'),
  510. $user['user_uid'],
  511. null,
  512. $request->input('prUuid'),
  513. );
  514. } else {
  515. $this->sentenceService->saveHistory($sent->uid, $realEditor, $request->input('content'));
  516. }
  517. Mq::publish('progress', [
  518. 'book' => $param[0],
  519. 'para' => $param[1],
  520. 'channel' => $channelId,
  521. ]);
  522. Mq::publish('content', new SentResource($sent));
  523. if ($channel->type === 'nissaya' && $sent->content_type === 'json') {
  524. $this->updateWbwAnalyses($sent->content, $channel->lang, $user['user_id']);
  525. }
  526. return $this->ok(new SentResource($sent));
  527. }
  528. /**
  529. * Remove the specified resource from storage.
  530. *
  531. * @return Response
  532. */
  533. public function destroy(Sentence $sentence)
  534. {
  535. //
  536. }
  537. private function updateWbwAnalyses($data, $lang, $editorId)
  538. {
  539. $wbwData = json_decode($data);
  540. $currWbwId = 0;
  541. $prefix = 'wbw-preference';
  542. foreach ($wbwData as $key => $word) {
  543. // code...
  544. if (count($word->sn) === 1) {
  545. $currWbwId = $word->uid;
  546. WbwAnalysis::where('wbw_id', $word->uid)->delete();
  547. }
  548. $newData = [
  549. 'wbw_id' => $currWbwId,
  550. 'wbw_word' => $word->real->value,
  551. 'book_id' => $word->book,
  552. 'paragraph' => $word->para,
  553. 'wid' => $word->sn[0],
  554. 'type' => 0,
  555. 'data' => '',
  556. 'confidence' => 100,
  557. 'lang' => $lang,
  558. 'editor_id' => $editorId,
  559. 'created_at' => now(),
  560. 'updated_at' => now(),
  561. ];
  562. $newData['type'] = 3;
  563. if (! empty($word->meaning->value)) {
  564. $newData['data'] = $word->meaning->value;
  565. WbwAnalysis::insert($newData);
  566. Cache::put("{$prefix}/{$word->real->value}/3/{$editorId}", $word->meaning->value);
  567. Cache::put("{$prefix}/{$word->real->value}/3/0", $word->meaning->value);
  568. }
  569. if (isset($word->factors) && isset($word->factorMeaning)) {
  570. $factors = explode('+', str_replace('-', '+', $word->factors->value));
  571. $factorMeaning = explode('+', str_replace('-', '+', $word->factorMeaning->value));
  572. foreach ($factors as $key => $factor) {
  573. if (isset($factorMeaning[$key])) {
  574. if (! empty($factorMeaning[$key])) {
  575. $newData['wbw_word'] = $factor;
  576. $newData['data'] = $factorMeaning[$key];
  577. $newData['type'] = 5;
  578. WbwAnalysis::insert($newData);
  579. Cache::put("{$prefix}/{$factor}/5/{$editorId}", $factorMeaning[$key]);
  580. Cache::put("{$prefix}/{$factor}/5/0", $factorMeaning[$key]);
  581. }
  582. }
  583. }
  584. }
  585. }
  586. }
  587. }