SentenceController.php 23 KB

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