SentenceController.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. /**
  251. * Show the form for creating a new resource.
  252. *
  253. * @return \Illuminate\Http\Response
  254. */
  255. public function create()
  256. {
  257. //
  258. }
  259. /**
  260. * 新建多个句子
  261. * 如果句子存在,修改
  262. * @param \Illuminate\Http\Request $request
  263. * @return \Illuminate\Http\Response
  264. */
  265. public function store(Request $request)
  266. {
  267. //鉴权
  268. $user = AuthApi::current($request);
  269. if (!$user) {
  270. //未登录用户
  271. return $this->error(__('auth.failed'), 401, 401);
  272. }
  273. if (!$request->has('sentences')) {
  274. return $this->error('no date', 200, 200);
  275. }
  276. $sentFirst = null;
  277. $changedSent = [];
  278. foreach ($request->get('sentences') as $key => $sent) {
  279. # 权限
  280. $channelId = $sent['channel_uid'];
  281. $channel = Channel::where('uid', $channelId)->first();
  282. if (!$channel) {
  283. continue;
  284. }
  285. if ($channel->owner_uid !== $user["user_uid"]) {
  286. //判断是否为协作
  287. $power = ShareApi::getResPower($user["user_uid"], $channel->uid, 2);
  288. if ($power < 20) {
  289. //判断token
  290. if (!isset($sent['access_token'])) {
  291. Log::error('no access token');
  292. continue;
  293. }
  294. $key = AccessToken::where('res_id', $channelId)->value('token');
  295. $jwt = JWT::decode($sent['access_token'], new Key($key, 'HS512'));
  296. Log::debug('access token', ['jwt' => $jwt]);
  297. if ($jwt->book !== $sent['book_id']) {
  298. Log::error('access token error');
  299. continue;
  300. }
  301. }
  302. }
  303. if ($sentFirst === null) {
  304. $sentFirst = $sent;
  305. }
  306. $row = Sentence::firstOrNew([
  307. "book_id" => $sent['book_id'],
  308. "paragraph" => $sent['paragraph'],
  309. "word_start" => $sent['word_start'],
  310. "word_end" => $sent['word_end'],
  311. "channel_uid" => $channel->uid,
  312. ], [
  313. "id" => app('snowflake')->id(),
  314. "uid" => Str::uuid(),
  315. ]);
  316. $row->content = $sent['content'];
  317. if (isset($sent['content_type']) && !empty($sent['content_type'])) {
  318. $row->content_type = $sent['content_type'];
  319. }
  320. $row->strlen = mb_strlen($sent['content'], "UTF-8");
  321. $row->language = $channel->lang;
  322. $row->status = $channel->status;
  323. if ($request->has('copy')) {
  324. //复制句子,保留原作者信息
  325. $row->editor_uid = $sent["editor_uid"];
  326. $row->acceptor_uid = $user["user_uid"];
  327. $row->pr_edit_at = $sent["updated_at"];
  328. if ($request->has('fork_from')) {
  329. $row->fork_at = now();
  330. }
  331. } else {
  332. $row->editor_uid = $user["user_uid"];
  333. $row->acceptor_uid = null;
  334. $row->pr_edit_at = null;
  335. }
  336. $row->create_time = time() * 1000;
  337. $row->modify_time = time() * 1000;
  338. $row->save();
  339. $changedSent[] = $row->uid;
  340. //保存历史记录
  341. if ($request->has('copy')) {
  342. $fork_from = $request->get('fork_from', null);
  343. $this->saveHistory(
  344. $row->uid,
  345. $sent["editor_uid"],
  346. $sent['content'],
  347. $user["user_uid"],
  348. $fork_from
  349. );
  350. } else {
  351. $this->saveHistory($row->uid, $user["user_uid"], $sent['content'], $user["user_uid"]);
  352. }
  353. //清除缓存
  354. $sentId = "{$sent['book_id']}-{$sent['paragraph']}-{$sent['word_start']}-{$sent['word_end']}";
  355. $hKey = "/sentence/res-count/{$sentId}/";
  356. Redis::del($hKey);
  357. }
  358. if ($sentFirst !== null) {
  359. Mq::publish('progress', [
  360. 'book' => $sentFirst['book_id'],
  361. 'para' => $sentFirst['paragraph'],
  362. 'channel' => $channel->uid,
  363. ]);
  364. }
  365. $result = Sentence::whereIn('uid', $changedSent)->get();
  366. return $this->ok([
  367. 'rows' => SentResource::collection($result),
  368. 'count' => count($result)
  369. ]);
  370. }
  371. private function saveHistory($uid, $editor, $content, $user_uid = null, $fork_from = null, $pr_from = null)
  372. {
  373. $newHis = new SentHistory();
  374. $newHis->id = app('snowflake')->id();
  375. $newHis->sent_uid = $uid;
  376. $newHis->user_uid = $editor;
  377. if (empty($content)) {
  378. $newHis->content = "";
  379. } else {
  380. $newHis->content = $content;
  381. }
  382. if ($fork_from) {
  383. $newHis->fork_from = $fork_from;
  384. $newHis->accepter_uid = $user_uid;
  385. }
  386. if ($pr_from) {
  387. $newHis->pr_from = $pr_from;
  388. $newHis->accepter_uid = $user_uid;
  389. }
  390. $newHis->create_time = time() * 1000;
  391. $newHis->save();
  392. }
  393. /**
  394. * Display the specified resource.
  395. *
  396. * @param \App\Models\Sentence $sentence
  397. * @return \Illuminate\Http\Response
  398. */
  399. public function show(Sentence $sentence)
  400. {
  401. //
  402. return $this->ok(new SentResource($sentence));
  403. }
  404. /**
  405. * 修改单个句子
  406. *
  407. * @param \Illuminate\Http\Request $request
  408. * @param string $id book_para_start_end_channel
  409. * @return \Illuminate\Http\Response
  410. */
  411. public function update(Request $request, $id)
  412. {
  413. //
  414. $param = \explode('_', $id);
  415. //鉴权
  416. $user = AuthApi::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->get('content');
  444. if ($request->has('contentType')) {
  445. $sent->content_type = $request->get('contentType');
  446. }
  447. $sent->language = $channel->lang;
  448. $sent->status = $channel->status;
  449. $sent->strlen = mb_strlen($request->get('content'), "UTF-8");
  450. $sent->modify_time = time() * 1000;
  451. if ($request->has('prEditor')) {
  452. $realEditor = $request->get('prEditor');
  453. $sent->acceptor_uid = $user["user_uid"];
  454. $sent->pr_edit_at = $request->get('prEditAt');
  455. $sent->pr_id = $request->get('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. RedisClusters::forget("/sent/{$channelId}/{$currSentId}");
  474. //保存历史记录
  475. if ($request->has('prEditor')) {
  476. $this->saveHistory(
  477. $sent->uid,
  478. $realEditor,
  479. $request->get('content'),
  480. $user["user_uid"],
  481. null,
  482. $request->get('prUuid'),
  483. );
  484. } else {
  485. $this->saveHistory($sent->uid, $realEditor, $request->get('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. * @param \App\Models\Sentence $sentence
  502. * @return \Illuminate\Http\Response
  503. */
  504. public function destroy(Sentence $sentence)
  505. {
  506. //
  507. }
  508. private function updateWbwAnalyses($data, $lang, $editorId)
  509. {
  510. $wbwData = json_decode($data);
  511. $currWbwId = 0;
  512. $prefix = 'wbw-preference';
  513. foreach ($wbwData as $key => $word) {
  514. # code...
  515. if (count($word->sn) === 1) {
  516. $currWbwId = $word->uid;
  517. WbwAnalysis::where('wbw_id', $word->uid)->delete();
  518. }
  519. $newData = [
  520. 'wbw_id' => $currWbwId,
  521. 'wbw_word' => $word->real->value,
  522. 'book_id' => $word->book,
  523. 'paragraph' => $word->para,
  524. 'wid' => $word->sn[0],
  525. 'type' => 0,
  526. 'data' => '',
  527. 'confidence' => 100,
  528. 'lang' => $lang,
  529. 'editor_id' => $editorId,
  530. 'created_at' => now(),
  531. 'updated_at' => now()
  532. ];
  533. $newData['type'] = 3;
  534. if (!empty($word->meaning->value)) {
  535. $newData['data'] = $word->meaning->value;
  536. WbwAnalysis::insert($newData);
  537. RedisClusters::put("{$prefix}/{$word->real->value}/3/{$editorId}", $word->meaning->value);
  538. RedisClusters::put("{$prefix}/{$word->real->value}/3/0", $word->meaning->value);
  539. }
  540. if (isset($word->factors) && isset($word->factorMeaning)) {
  541. $factors = explode('+', str_replace('-', '+', $word->factors->value));
  542. $factorMeaning = explode('+', str_replace('-', '+', $word->factorMeaning->value));
  543. foreach ($factors as $key => $factor) {
  544. if (isset($factorMeaning[$key])) {
  545. if (!empty($factorMeaning[$key])) {
  546. $newData['wbw_word'] = $factor;
  547. $newData['data'] = $factorMeaning[$key];
  548. $newData['type'] = 5;
  549. WbwAnalysis::insert($newData);
  550. RedisClusters::put("{$prefix}/{$factor}/5/{$editorId}", $factorMeaning[$key]);
  551. RedisClusters::put("{$prefix}/{$factor}/5/0", $factorMeaning[$key]);
  552. }
  553. }
  554. }
  555. }
  556. }
  557. }
  558. }