SentenceController.php 23 KB

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