SentenceController.php 21 KB

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