SentenceController.php 21 KB

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