SentenceController.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Models\Sentence;
  4. use App\Models\Channel;
  5. use App\Models\SentHistory;
  6. use App\Models\WbwAnalysis;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Support\Str;
  9. use Illuminate\Support\Facades\Log;
  10. use Illuminate\Support\Facades\Cache;
  11. use Illuminate\Support\Facades\Redis;
  12. use App\Http\Resources\SentResource;
  13. use App\Http\Api\AuthApi;
  14. use App\Http\Api\ShareApi;
  15. use App\Http\Api\ChannelApi;
  16. use App\Http\Api\PaliTextApi;
  17. use App\Http\Api\Mq;
  18. use App\Models\AccessToken;
  19. use App\Tools\RedisClusters;
  20. use App\Tools\OpsLog;
  21. use Firebase\JWT\JWT;
  22. use Firebase\JWT\Key;
  23. class SentenceController extends Controller
  24. {
  25. /**
  26. * Display a listing of the resource.
  27. *
  28. * @return \Illuminate\Http\Response
  29. */
  30. public function index(Request $request)
  31. {
  32. $user = AuthApi::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->get('view')) {
  51. case 'public':
  52. //获取全部公开的译文
  53. //首先获取某个类型的 channel 列表
  54. $channels = [];
  55. $channel_type = $request->get('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->get('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->get('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->get('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->get('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->get('type', 'translation');
  106. $channelTable = Channel::where("type", $type)->select(['uid', 'name']);
  107. $channelPub = $channelTable->where('status', 30)->get();
  108. $user = AuthApi::current($request);
  109. $channelShare = array();
  110. $channelMy = array();
  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->get('excludes'));
  148. foreach ($channelCanRead as $key => $value) {
  149. # code...
  150. if (!in_array($key, $excludeChannels)) {
  151. $channels[] = $key;
  152. }
  153. }
  154. $sent = explode('-', $request->get('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->get('book'), $request->get('para'));
  165. $table = Sentence::where('ver', '>', 1)
  166. ->where('book_id', $request->get('book'))
  167. ->whereBetween('paragraph', $chapter)
  168. ->whereIn('channel_uid', explode(',', $request->get('channels')));
  169. break;
  170. case 'paragraph':
  171. $table = Sentence::where('ver', '>', 1)
  172. ->where('book_id', $request->get('book'))
  173. ->whereIn('paragraph', explode(',', $request->get('para')))
  174. ->whereIn('channel_uid', explode(',', $request->get('channels')))
  175. ->orderBy('book_id')->orderBy('paragraph')->orderBy('word_start');
  176. break;
  177. case 'my-edit':
  178. //我编辑的
  179. if (!$user) {
  180. return $this->error(__('auth.failed'), 401, 401);
  181. }
  182. $table = Sentence::where('editor_uid', $user['user_uid'])
  183. ->where('ver', '>', 1);
  184. break;
  185. default:
  186. # code...
  187. break;
  188. }
  189. if (!empty($request->get("key"))) {
  190. $table = $table->where('content', 'like', '%' . $request->get("key") . '%');
  191. }
  192. $count = $table->count();
  193. if ($request->get('strlen', false)) {
  194. $totalStrLen = $table->sum('strlen');
  195. }
  196. if ($request->get('view') !== 'paragraph') {
  197. $table = $table->orderBy(
  198. $request->get('order', 'updated_at'),
  199. $request->get('dir', 'desc')
  200. );
  201. }
  202. $table = $table->skip($request->get("offset", 0))
  203. ->take($request->get('limit', 1000));
  204. $result = $table->get();
  205. if ($result) {
  206. $output = ["count" => $count];
  207. if (
  208. $request->get('view') === 'sent-can-read' ||
  209. $request->get('view') === 'channel' ||
  210. $request->get('view') === 'chapter' ||
  211. $request->get('view') === 'paragraph' ||
  212. $request->get('view') === 'my-edit'
  213. ) {
  214. $output["rows"] = SentResource::collection($result);
  215. } else {
  216. $output["rows"] = $result;
  217. }
  218. if (isset($totalStrLen)) {
  219. $output['total_strlen'] = $totalStrLen;
  220. }
  221. return $this->ok($output);
  222. } else {
  223. return $this->error("没有查询到数据");
  224. }
  225. }
  226. /**
  227. * 用channel 和句子编号列表查询句子
  228. */
  229. public function sent_in_channel(Request $request)
  230. {
  231. $sent = $request->get('sentences');
  232. $query = [];
  233. foreach ($sent as $value) {
  234. # code...
  235. $ids = explode('-', $value);
  236. if (count($ids) === 4) {
  237. $query[] = $ids;
  238. }
  239. }
  240. $table = Sentence::select(['id', 'book_id', 'paragraph', 'word_start', 'word_end', 'content', 'channel_uid', 'updated_at'])
  241. ->where('channel_uid', $request->get('channel'))
  242. ->whereIns(['book_id', 'paragraph', 'word_start', 'word_end'], $query);
  243. $result = $table->get();
  244. if ($result) {
  245. return $this->ok(["rows" => $result, "count" => count($result)]);
  246. } else {
  247. return $this->error("没有查询到数据");
  248. }
  249. }
  250. private function UserCanEdit($userId, $channelId, $book, $access_token = null)
  251. {
  252. $channel = Channel::where('uid', $channelId)->first();
  253. if (!$channel) {
  254. return false;
  255. }
  256. if ($channel->owner_uid !== $userId) {
  257. //判断是否为协作
  258. $power = ShareApi::getResPower($userId, $channel->uid, 2);
  259. if ($power < 20) {
  260. //判断token
  261. if (!$access_token) {
  262. Log::error('no access token');
  263. return false;
  264. }
  265. $key = AccessToken::where('res_id', $channelId)->value('token');
  266. $jwt = JWT::decode($access_token, new Key($key, 'HS512'));
  267. Log::debug('access token', ['jwt' => $jwt]);
  268. if ($jwt->book !== $book) {
  269. Log::error('access token error');
  270. return false;
  271. }
  272. }
  273. }
  274. return true;
  275. }
  276. /**
  277. * 新建多个句子
  278. * 如果句子存在,修改
  279. * @param \Illuminate\Http\Request $request
  280. * @return \Illuminate\Http\Response
  281. */
  282. public function store(Request $request)
  283. {
  284. //鉴权
  285. $user = AuthApi::current($request);
  286. if (!$user) {
  287. //未登录用户
  288. return $this->error(__('auth.failed'), 401, 401);
  289. }
  290. if (!$request->has('sentences')) {
  291. return $this->error('no date', 200, 200);
  292. }
  293. $destChannel = null;
  294. if ($request->has('channel')) {
  295. if ($this->UserCanEdit(
  296. $user["user_uid"],
  297. $request->get('channel'),
  298. $request->get('book', 0),
  299. $request->get('access_token', null)
  300. )) {
  301. $destChannel = Channel::where('uid', $request->get('channel'))->first();;
  302. } else {
  303. return $this->error(__('auth.failed'), 403, 403);
  304. }
  305. }
  306. $sentFirst = null;
  307. $changedSent = [];
  308. foreach ($request->get('sentences') as $key => $sent) {
  309. # 权限
  310. if (!$request->has('channel')) {
  311. if ($this->UserCanEdit(
  312. $user["user_uid"],
  313. $sent['channel_uid'],
  314. $sent['book_id'],
  315. isset($sent['access_token']) ? $sent['access_token'] : null
  316. )) {
  317. $destChannel = Channel::where('uid', $sent['channel_uid'])->first();;
  318. } else {
  319. continue;
  320. }
  321. }
  322. /*
  323. $destChannel = Channel::where('uid', $sent['channel_uid'])->first();
  324. if (!$destChannel) {
  325. continue;
  326. }
  327. if ($destChannel->owner_uid !== $user["user_uid"]) {
  328. //判断是否为协作
  329. $power = ShareApi::getResPower($user["user_uid"], $destChannel->uid, 2);
  330. if ($power < 20) {
  331. //判断token
  332. if (!isset($sent['access_token'])) {
  333. Log::error('no access token');
  334. continue;
  335. }
  336. $key = AccessToken::where('res_id', $destChannel->uid)->value('token');
  337. $jwt = JWT::decode($sent['access_token'], new Key($key, 'HS512'));
  338. Log::debug('access token', ['jwt' => $jwt]);
  339. if ($jwt->book !== $sent['book_id']) {
  340. Log::error('access token error');
  341. continue;
  342. }
  343. }
  344. }
  345. */
  346. if ($sentFirst === null) {
  347. $sentFirst = $sent;
  348. }
  349. $row = Sentence::firstOrNew([
  350. "book_id" => $sent['book_id'],
  351. "paragraph" => $sent['paragraph'],
  352. "word_start" => $sent['word_start'],
  353. "word_end" => $sent['word_end'],
  354. "channel_uid" => $destChannel->uid,
  355. ], [
  356. "id" => app('snowflake')->id(),
  357. "uid" => Str::uuid(),
  358. ]);
  359. $row->content = $sent['content'];
  360. if (isset($sent['content_type']) && !empty($sent['content_type'])) {
  361. $row->content_type = $sent['content_type'];
  362. }
  363. $row->strlen = mb_strlen($sent['content'], "UTF-8");
  364. $row->language = $destChannel->lang;
  365. $row->status = $destChannel->status;
  366. if ($request->has('copy')) {
  367. //复制句子,保留原作者信息
  368. $row->editor_uid = $sent["editor_uid"];
  369. $row->acceptor_uid = $user["user_uid"];
  370. $row->pr_edit_at = $sent["updated_at"];
  371. if ($request->has('fork_from')) {
  372. $row->fork_at = now();
  373. }
  374. } else {
  375. $row->editor_uid = $user["user_uid"];
  376. $row->acceptor_uid = null;
  377. $row->pr_edit_at = null;
  378. }
  379. $row->create_time = time() * 1000;
  380. $row->modify_time = time() * 1000;
  381. $row->save();
  382. $changedSent[] = $row->uid;
  383. //保存历史记录
  384. if ($request->has('copy')) {
  385. $fork_from = $request->get('fork_from', null);
  386. $this->saveHistory(
  387. $row->uid,
  388. $sent["editor_uid"],
  389. $sent['content'],
  390. $user["user_uid"],
  391. $fork_from
  392. );
  393. } else {
  394. $this->saveHistory($row->uid, $user["user_uid"], $sent['content'], $user["user_uid"]);
  395. }
  396. //清除缓存
  397. $sentId = "{$sent['book_id']}-{$sent['paragraph']}-{$sent['word_start']}-{$sent['word_end']}";
  398. $hKey = "/sentence/res-count/{$sentId}/";
  399. Redis::del($hKey);
  400. }
  401. if ($sentFirst !== null) {
  402. Mq::publish('progress', [
  403. 'book' => $sentFirst['book_id'],
  404. 'para' => $sentFirst['paragraph'],
  405. 'channel' => $destChannel->uid,
  406. ]);
  407. }
  408. $result = Sentence::whereIn('uid', $changedSent)->get();
  409. return $this->ok([
  410. 'rows' => SentResource::collection($result),
  411. 'count' => count($result)
  412. ]);
  413. }
  414. private function saveHistory($uid, $editor, $content, $user_uid = null, $fork_from = null, $pr_from = null)
  415. {
  416. $newHis = new SentHistory();
  417. $newHis->id = app('snowflake')->id();
  418. $newHis->sent_uid = $uid;
  419. $newHis->user_uid = $editor;
  420. if (empty($content)) {
  421. $newHis->content = "";
  422. } else {
  423. $newHis->content = $content;
  424. }
  425. if ($fork_from) {
  426. $newHis->fork_from = $fork_from;
  427. $newHis->accepter_uid = $user_uid;
  428. }
  429. if ($pr_from) {
  430. $newHis->pr_from = $pr_from;
  431. $newHis->accepter_uid = $user_uid;
  432. }
  433. $newHis->create_time = time() * 1000;
  434. $newHis->save();
  435. }
  436. /**
  437. * Display the specified resource.
  438. *
  439. * @param \App\Models\Sentence $sentence
  440. * @return \Illuminate\Http\Response
  441. */
  442. public function show(Sentence $sentence)
  443. {
  444. //
  445. return $this->ok(new SentResource($sentence));
  446. }
  447. /**
  448. * 修改单个句子
  449. *
  450. * @param \Illuminate\Http\Request $request
  451. * @param string $id book_para_start_end_channel
  452. * @return \Illuminate\Http\Response
  453. */
  454. public function update(Request $request, $id)
  455. {
  456. //
  457. $param = \explode('_', $id);
  458. //鉴权
  459. $user = AuthApi::current($request);
  460. if (!$user) {
  461. //未登录鉴权失败
  462. return $this->error(__('auth.failed'), 403, 403);
  463. }
  464. $channel = Channel::where('uid', $param[4])->first();
  465. if (!$channel) {
  466. return $this->error("not found channel");
  467. }
  468. if ($channel->owner_uid !== $user["user_uid"]) {
  469. // 判断是否为协作
  470. $power = ShareApi::getResPower($user["user_uid"], $channel->uid, 2);
  471. if ($power < 20) {
  472. return $this->error(__('auth.failed'), 403, 403);
  473. }
  474. }
  475. $sent = Sentence::firstOrNew([
  476. "book_id" => $param[0],
  477. "paragraph" => $param[1],
  478. "word_start" => $param[2],
  479. "word_end" => $param[3],
  480. "channel_uid" => $param[4],
  481. ], [
  482. "id" => app('snowflake')->id(),
  483. "uid" => Str::orderedUuid(),
  484. "create_time" => time() * 1000,
  485. ]);
  486. $sent->content = $request->get('content');
  487. if ($request->has('contentType')) {
  488. $sent->content_type = $request->get('contentType');
  489. }
  490. $sent->language = $channel->lang;
  491. $sent->status = $channel->status;
  492. $sent->strlen = mb_strlen($request->get('content'), "UTF-8");
  493. $sent->modify_time = time() * 1000;
  494. if ($request->has('prEditor')) {
  495. $realEditor = $request->get('prEditor');
  496. $sent->acceptor_uid = $user["user_uid"];
  497. $sent->pr_edit_at = $request->get('prEditAt');
  498. $sent->pr_id = $request->get('prId');
  499. } else {
  500. $realEditor = $user["user_uid"];
  501. $sent->acceptor_uid = null;
  502. $sent->pr_edit_at = null;
  503. $sent->pr_id = null;
  504. }
  505. $sent->editor_uid = $realEditor;
  506. $sent->save();
  507. $sent = $sent->refresh();
  508. //清除缓存
  509. $sentId = "{$sent['book_id']}-{$sent['paragraph']}-{$sent['word_start']}-{$sent['word_end']}";
  510. $hKey = "/sentence/res-count/{$sentId}/";
  511. Redis::del($hKey);
  512. OpsLog::debug($user["user_uid"], $sent);
  513. //清除cache
  514. $channelId = $param[4];
  515. $currSentId = "{$param[0]}-{$param[1]}-{$param[2]}-{$param[3]}";
  516. RedisClusters::forget("/sent/{$channelId}/{$currSentId}");
  517. //保存历史记录
  518. if ($request->has('prEditor')) {
  519. $this->saveHistory(
  520. $sent->uid,
  521. $realEditor,
  522. $request->get('content'),
  523. $user["user_uid"],
  524. null,
  525. $request->get('prUuid'),
  526. );
  527. } else {
  528. $this->saveHistory($sent->uid, $realEditor, $request->get('content'));
  529. }
  530. Mq::publish('progress', [
  531. 'book' => $param[0],
  532. 'para' => $param[1],
  533. 'channel' => $channelId,
  534. ]);
  535. Mq::publish('content', new SentResource($sent));
  536. if ($channel->type === 'nissaya' && $sent->content_type === 'json') {
  537. $this->updateWbwAnalyses($sent->content, $channel->lang, $user["user_id"]);
  538. }
  539. return $this->ok(new SentResource($sent));
  540. }
  541. /**
  542. * Remove the specified resource from storage.
  543. *
  544. * @param \App\Models\Sentence $sentence
  545. * @return \Illuminate\Http\Response
  546. */
  547. public function destroy(Sentence $sentence)
  548. {
  549. //
  550. }
  551. private function updateWbwAnalyses($data, $lang, $editorId)
  552. {
  553. $wbwData = json_decode($data);
  554. $currWbwId = 0;
  555. $prefix = 'wbw-preference';
  556. foreach ($wbwData as $key => $word) {
  557. # code...
  558. if (count($word->sn) === 1) {
  559. $currWbwId = $word->uid;
  560. WbwAnalysis::where('wbw_id', $word->uid)->delete();
  561. }
  562. $newData = [
  563. 'wbw_id' => $currWbwId,
  564. 'wbw_word' => $word->real->value,
  565. 'book_id' => $word->book,
  566. 'paragraph' => $word->para,
  567. 'wid' => $word->sn[0],
  568. 'type' => 0,
  569. 'data' => '',
  570. 'confidence' => 100,
  571. 'lang' => $lang,
  572. 'editor_id' => $editorId,
  573. 'created_at' => now(),
  574. 'updated_at' => now()
  575. ];
  576. $newData['type'] = 3;
  577. if (!empty($word->meaning->value)) {
  578. $newData['data'] = $word->meaning->value;
  579. WbwAnalysis::insert($newData);
  580. RedisClusters::put("{$prefix}/{$word->real->value}/3/{$editorId}", $word->meaning->value);
  581. RedisClusters::put("{$prefix}/{$word->real->value}/3/0", $word->meaning->value);
  582. }
  583. if (isset($word->factors) && isset($word->factorMeaning)) {
  584. $factors = explode('+', str_replace('-', '+', $word->factors->value));
  585. $factorMeaning = explode('+', str_replace('-', '+', $word->factorMeaning->value));
  586. foreach ($factors as $key => $factor) {
  587. if (isset($factorMeaning[$key])) {
  588. if (!empty($factorMeaning[$key])) {
  589. $newData['wbw_word'] = $factor;
  590. $newData['data'] = $factorMeaning[$key];
  591. $newData['type'] = 5;
  592. WbwAnalysis::insert($newData);
  593. RedisClusters::put("{$prefix}/{$factor}/5/{$editorId}", $factorMeaning[$key]);
  594. RedisClusters::put("{$prefix}/{$factor}/5/0", $factorMeaning[$key]);
  595. }
  596. }
  597. }
  598. }
  599. }
  600. }
  601. }