SentenceController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. $jwt = JWT::decode($access_token, new Key($key . $key, 'HS512'));
  274. if (isset($jwt->book) && $jwt->book !== 0 && $jwt->book !== $book) {
  275. return false;
  276. }
  277. }
  278. }
  279. return true;
  280. }
  281. /**
  282. * 新建多个句子
  283. * 如果句子存在,修改
  284. *
  285. * @return Response
  286. */
  287. public function store(Request $request)
  288. {
  289. // 鉴权
  290. $user = AuthService::current($request);
  291. if (! $user) {
  292. // 未登录用户
  293. return $this->error(__('auth.failed'), 401, 401);
  294. }
  295. if (! $request->has('sentences')) {
  296. return $this->error('no date', 200, 200);
  297. }
  298. $destChannel = null;
  299. if ($request->has('channel')) {
  300. if ($this->UserCanEdit(
  301. $user['user_uid'],
  302. $request->input('channel'),
  303. (int)$request->input('book', 0),
  304. $request->input('access_token', null)
  305. )) {
  306. $destChannel = Channel::where('uid', $request->input('channel'))->first();
  307. } else {
  308. return $this->error(__('auth.failed'), 403, 403);
  309. }
  310. }
  311. $sentFirst = null;
  312. $changedSent = [];
  313. foreach ($request->input('sentences') as $key => $sent) {
  314. // 权限
  315. if (! $request->has('channel')) {
  316. if ($this->UserCanEdit(
  317. $user['user_uid'],
  318. $sent['channel_uid'],
  319. (int)$sent['book_id'],
  320. isset($sent['access_token']) ? $sent['access_token'] : null
  321. )) {
  322. $destChannel = Channel::where('uid', $sent['channel_uid'])->first();
  323. } else {
  324. continue;
  325. }
  326. }
  327. /*
  328. $destChannel = Channel::where('uid', $sent['channel_uid'])->first();
  329. if (!$destChannel) {
  330. continue;
  331. }
  332. if ($destChannel->owner_uid !== $user["user_uid"]) {
  333. //判断是否为协作
  334. $power = ShareApi::getResPower($user["user_uid"], $destChannel->uid, 2);
  335. if ($power < 20) {
  336. //判断token
  337. if (!isset($sent['access_token'])) {
  338. continue;
  339. }
  340. $key = AccessToken::where('res_id', $destChannel->uid)->value('token');
  341. $jwt = JWT::decode($sent['access_token'], new Key($key, 'HS512'));
  342. if ($jwt->book !== $sent['book_id']) {
  343. continue;
  344. }
  345. }
  346. }
  347. */
  348. if ($sentFirst === null) {
  349. $sentFirst = $sent;
  350. }
  351. $row = Sentence::firstOrNew([
  352. 'book_id' => $sent['book_id'],
  353. 'paragraph' => $sent['paragraph'],
  354. 'word_start' => $sent['word_start'],
  355. 'word_end' => $sent['word_end'],
  356. 'channel_uid' => $destChannel->uid,
  357. ], [
  358. 'id' => app('snowflake')->id(),
  359. 'uid' => Str::uuid(),
  360. ]);
  361. $row->content = $sent['content'];
  362. if (isset($sent['content_type']) && ! empty($sent['content_type'])) {
  363. $row->content_type = $sent['content_type'];
  364. }
  365. $row->strlen = mb_strlen($sent['content'], 'UTF-8');
  366. $row->language = $destChannel->lang;
  367. $row->status = $destChannel->status;
  368. if ($request->has('copy')) {
  369. // 复制句子,保留原作者信息
  370. $row->editor_uid = $sent['editor_uid'];
  371. $row->acceptor_uid = $user['user_uid'];
  372. $row->pr_edit_at = $sent['updated_at'];
  373. if ($request->has('fork_from')) {
  374. $row->fork_at = now();
  375. }
  376. } else {
  377. $row->editor_uid = $user['user_uid'];
  378. $row->acceptor_uid = null;
  379. $row->pr_edit_at = null;
  380. }
  381. $row->create_time = time() * 1000;
  382. $row->modify_time = time() * 1000;
  383. $row->save();
  384. $changedSent[] = $row->uid;
  385. // 保存历史记录
  386. if ($request->has('copy')) {
  387. $fork_from = $request->input('fork_from', null);
  388. $this->sentenceService->saveHistory(
  389. $row->uid,
  390. $sent['editor_uid'],
  391. $sent['content'],
  392. $user['user_uid'],
  393. $fork_from
  394. );
  395. } else {
  396. $this->sentenceService->saveHistory($row->uid, $user['user_uid'], $sent['content'], $user['user_uid']);
  397. }
  398. // 清除缓存
  399. $sentId = "{$sent['book_id']}-{$sent['paragraph']}-{$sent['word_start']}-{$sent['word_end']}";
  400. $hKey = "/sentence/res-count/{$sentId}/";
  401. Redis::del($hKey);
  402. }
  403. if ($sentFirst !== null) {
  404. Mq::publish('progress', [
  405. 'book' => $sentFirst['book_id'],
  406. 'para' => $sentFirst['paragraph'],
  407. 'channel' => $destChannel->uid,
  408. ]);
  409. }
  410. $result = Sentence::whereIn('uid', $changedSent)->get();
  411. return $this->ok([
  412. 'rows' => SentResource::collection($result),
  413. 'count' => count($result),
  414. ]);
  415. }
  416. /**
  417. * Display the specified resource.
  418. *
  419. * @return Response
  420. */
  421. public function show(Sentence $sentence)
  422. {
  423. //
  424. return $this->ok(new SentResource($sentence));
  425. }
  426. /**
  427. * 修改单个句子
  428. *
  429. * @param string $id book_para_start_end_channel
  430. * @return Response
  431. */
  432. public function update(Request $request, $id)
  433. {
  434. //
  435. $param = \explode('_', $id);
  436. // 鉴权
  437. $user = AuthService::current($request);
  438. if (! $user) {
  439. // 未登录鉴权失败
  440. return $this->error(__('auth.failed'), 403, 403);
  441. }
  442. $channel = Channel::where('uid', $param[4])->first();
  443. if (! $channel) {
  444. return $this->error('not found channel');
  445. }
  446. if ($channel->owner_uid !== $user['user_uid']) {
  447. // 判断是否为协作
  448. $power = ShareApi::getResPower($user['user_uid'], $channel->uid, 2);
  449. if ($power < 20) {
  450. return $this->error(__('auth.failed'), 403, 403);
  451. }
  452. }
  453. $sent = Sentence::firstOrNew([
  454. 'book_id' => $param[0],
  455. 'paragraph' => $param[1],
  456. 'word_start' => $param[2],
  457. 'word_end' => $param[3],
  458. 'channel_uid' => $param[4],
  459. ], [
  460. 'id' => app('snowflake')->id(),
  461. 'uid' => Str::orderedUuid(),
  462. 'create_time' => time() * 1000,
  463. ]);
  464. $sent->content = $request->input('content');
  465. if ($request->has('contentType')) {
  466. $sent->content_type = $request->input('contentType');
  467. }
  468. $sent->language = $channel->lang;
  469. $sent->status = $channel->status;
  470. $sent->strlen = mb_strlen($request->input('content'), 'UTF-8');
  471. $sent->modify_time = time() * 1000;
  472. if ($request->has('prEditor')) {
  473. $realEditor = $request->input('prEditor');
  474. $sent->acceptor_uid = $user['user_uid'];
  475. $sent->pr_edit_at = $request->input('prEditAt');
  476. $sent->pr_id = $request->input('prId');
  477. } else {
  478. $realEditor = $user['user_uid'];
  479. $sent->acceptor_uid = null;
  480. $sent->pr_edit_at = null;
  481. $sent->pr_id = null;
  482. }
  483. $sent->editor_uid = $realEditor;
  484. $sent->save();
  485. $sent = $sent->refresh();
  486. // 清除缓存
  487. $sentId = "{$sent['book_id']}-{$sent['paragraph']}-{$sent['word_start']}-{$sent['word_end']}";
  488. $hKey = "/sentence/res-count/{$sentId}/";
  489. Redis::del($hKey);
  490. OpsLog::debug($user['user_uid'], $sent);
  491. // 清除cache
  492. $channelId = $param[4];
  493. $currSentId = "{$param[0]}-{$param[1]}-{$param[2]}-{$param[3]}";
  494. Cache::forget("/sent/{$channelId}/{$currSentId}");
  495. // 保存历史记录
  496. if ($request->has('prEditor')) {
  497. $this->sentenceService->saveHistory(
  498. $sent->uid,
  499. $realEditor,
  500. $request->input('content'),
  501. $user['user_uid'],
  502. null,
  503. $request->input('prUuid'),
  504. );
  505. } else {
  506. $this->sentenceService->saveHistory($sent->uid, $realEditor, $request->input('content'));
  507. }
  508. Mq::publish('progress', [
  509. 'book' => $param[0],
  510. 'para' => $param[1],
  511. 'channel' => $channelId,
  512. ]);
  513. Mq::publish('content', new SentResource($sent));
  514. if ($channel->type === 'nissaya' && $sent->content_type === 'json') {
  515. $this->updateWbwAnalyses($sent->content, $channel->lang, $user['user_id']);
  516. }
  517. return $this->ok(new SentResource($sent));
  518. }
  519. /**
  520. * Remove the specified resource from storage.
  521. *
  522. * @return Response
  523. */
  524. public function destroy(Sentence $sentence)
  525. {
  526. //
  527. }
  528. private function updateWbwAnalyses($data, $lang, $editorId)
  529. {
  530. $wbwData = json_decode($data);
  531. $currWbwId = 0;
  532. $prefix = 'wbw-preference';
  533. foreach ($wbwData as $key => $word) {
  534. // code...
  535. if (count($word->sn) === 1) {
  536. $currWbwId = $word->uid;
  537. WbwAnalysis::where('wbw_id', $word->uid)->delete();
  538. }
  539. $newData = [
  540. 'wbw_id' => $currWbwId,
  541. 'wbw_word' => $word->real->value,
  542. 'book_id' => $word->book,
  543. 'paragraph' => $word->para,
  544. 'wid' => $word->sn[0],
  545. 'type' => 0,
  546. 'data' => '',
  547. 'confidence' => 100,
  548. 'lang' => $lang,
  549. 'editor_id' => $editorId,
  550. 'created_at' => now(),
  551. 'updated_at' => now(),
  552. ];
  553. $newData['type'] = 3;
  554. if (! empty($word->meaning->value)) {
  555. $newData['data'] = $word->meaning->value;
  556. WbwAnalysis::insert($newData);
  557. Cache::put("{$prefix}/{$word->real->value}/3/{$editorId}", $word->meaning->value);
  558. Cache::put("{$prefix}/{$word->real->value}/3/0", $word->meaning->value);
  559. }
  560. if (isset($word->factors) && isset($word->factorMeaning)) {
  561. $factors = explode('+', str_replace('-', '+', $word->factors->value));
  562. $factorMeaning = explode('+', str_replace('-', '+', $word->factorMeaning->value));
  563. foreach ($factors as $key => $factor) {
  564. if (isset($factorMeaning[$key])) {
  565. if (! empty($factorMeaning[$key])) {
  566. $newData['wbw_word'] = $factor;
  567. $newData['data'] = $factorMeaning[$key];
  568. $newData['type'] = 5;
  569. WbwAnalysis::insert($newData);
  570. Cache::put("{$prefix}/{$factor}/5/{$editorId}", $factorMeaning[$key]);
  571. Cache::put("{$prefix}/{$factor}/5/0", $factorMeaning[$key]);
  572. }
  573. }
  574. }
  575. }
  576. }
  577. }
  578. }