2
0

SentenceController.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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. $key = AccessToken::where('res_id', $channelId)->value('token');
  292. $jwt = JWT::decode($sent['access_token'], new Key($key, 'HS512'));
  293. if ($jwt->book !== $sent['book_id']) {
  294. continue;
  295. }
  296. } else {
  297. continue;
  298. }
  299. }
  300. }
  301. if ($sentFirst === null) {
  302. $sentFirst = $sent;
  303. }
  304. $row = Sentence::firstOrNew([
  305. "book_id" => $sent['book_id'],
  306. "paragraph" => $sent['paragraph'],
  307. "word_start" => $sent['word_start'],
  308. "word_end" => $sent['word_end'],
  309. "channel_uid" => $channel->uid,
  310. ], [
  311. "id" => app('snowflake')->id(),
  312. "uid" => Str::uuid(),
  313. ]);
  314. $row->content = $sent['content'];
  315. if (isset($sent['content_type']) && !empty($sent['content_type'])) {
  316. $row->content_type = $sent['content_type'];
  317. }
  318. $row->strlen = mb_strlen($sent['content'], "UTF-8");
  319. $row->language = $channel->lang;
  320. $row->status = $channel->status;
  321. if ($request->has('copy')) {
  322. //复制句子,保留原作者信息
  323. $row->editor_uid = $sent["editor_uid"];
  324. $row->acceptor_uid = $user["user_uid"];
  325. $row->pr_edit_at = $sent["updated_at"];
  326. if ($request->has('fork_from')) {
  327. $row->fork_at = now();
  328. }
  329. } else {
  330. $row->editor_uid = $user["user_uid"];
  331. $row->acceptor_uid = null;
  332. $row->pr_edit_at = null;
  333. }
  334. $row->create_time = time() * 1000;
  335. $row->modify_time = time() * 1000;
  336. $row->save();
  337. $changedSent[] = $row->uid;
  338. //保存历史记录
  339. if ($request->has('copy')) {
  340. $fork_from = $request->get('fork_from', null);
  341. $this->saveHistory(
  342. $row->uid,
  343. $sent["editor_uid"],
  344. $sent['content'],
  345. $user["user_uid"],
  346. $fork_from
  347. );
  348. } else {
  349. $this->saveHistory($row->uid, $user["user_uid"], $sent['content'], $user["user_uid"]);
  350. }
  351. //清除缓存
  352. $sentId = "{$sent['book_id']}-{$sent['paragraph']}-{$sent['word_start']}-{$sent['word_end']}";
  353. $hKey = "/sentence/res-count/{$sentId}/";
  354. Redis::del($hKey);
  355. }
  356. if ($sentFirst !== null) {
  357. Mq::publish('progress', [
  358. 'book' => $sentFirst['book_id'],
  359. 'para' => $sentFirst['paragraph'],
  360. 'channel' => $channel->uid,
  361. ]);
  362. }
  363. $result = Sentence::whereIn('uid', $changedSent)->get();
  364. return $this->ok([
  365. 'rows' => SentResource::collection($result),
  366. 'count' => count($result)
  367. ]);
  368. }
  369. private function saveHistory($uid, $editor, $content, $user_uid = null, $fork_from = null, $pr_from = null)
  370. {
  371. $newHis = new SentHistory();
  372. $newHis->id = app('snowflake')->id();
  373. $newHis->sent_uid = $uid;
  374. $newHis->user_uid = $editor;
  375. if (empty($content)) {
  376. $newHis->content = "";
  377. } else {
  378. $newHis->content = $content;
  379. }
  380. if ($fork_from) {
  381. $newHis->fork_from = $fork_from;
  382. $newHis->accepter_uid = $user_uid;
  383. }
  384. if ($pr_from) {
  385. $newHis->pr_from = $pr_from;
  386. $newHis->accepter_uid = $user_uid;
  387. }
  388. $newHis->create_time = time() * 1000;
  389. $newHis->save();
  390. }
  391. /**
  392. * Display the specified resource.
  393. *
  394. * @param \App\Models\Sentence $sentence
  395. * @return \Illuminate\Http\Response
  396. */
  397. public function show(Sentence $sentence)
  398. {
  399. //
  400. return $this->ok(new SentResource($sentence));
  401. }
  402. /**
  403. * 修改单个句子
  404. *
  405. * @param \Illuminate\Http\Request $request
  406. * @param string $id book_para_start_end_channel
  407. * @return \Illuminate\Http\Response
  408. */
  409. public function update(Request $request, $id)
  410. {
  411. //
  412. $param = \explode('_', $id);
  413. //鉴权
  414. $user = AuthApi::current($request);
  415. if (!$user) {
  416. //未登录鉴权失败
  417. return $this->error(__('auth.failed'), 403, 403);
  418. }
  419. $channel = Channel::where('uid', $param[4])->first();
  420. if (!$channel) {
  421. return $this->error("not found channel");
  422. }
  423. if ($channel->owner_uid !== $user["user_uid"]) {
  424. // 判断是否为协作
  425. $power = ShareApi::getResPower($user["user_uid"], $channel->uid, 2);
  426. if ($power < 20) {
  427. return $this->error(__('auth.failed'), 403, 403);
  428. }
  429. }
  430. $sent = Sentence::firstOrNew([
  431. "book_id" => $param[0],
  432. "paragraph" => $param[1],
  433. "word_start" => $param[2],
  434. "word_end" => $param[3],
  435. "channel_uid" => $param[4],
  436. ], [
  437. "id" => app('snowflake')->id(),
  438. "uid" => Str::orderedUuid(),
  439. "create_time" => time() * 1000,
  440. ]);
  441. $sent->content = $request->get('content');
  442. if ($request->has('contentType')) {
  443. $sent->content_type = $request->get('contentType');
  444. }
  445. $sent->language = $channel->lang;
  446. $sent->status = $channel->status;
  447. $sent->strlen = mb_strlen($request->get('content'), "UTF-8");
  448. $sent->modify_time = time() * 1000;
  449. if ($request->has('prEditor')) {
  450. $realEditor = $request->get('prEditor');
  451. $sent->acceptor_uid = $user["user_uid"];
  452. $sent->pr_edit_at = $request->get('prEditAt');
  453. $sent->pr_id = $request->get('prId');
  454. } else {
  455. $realEditor = $user["user_uid"];
  456. $sent->acceptor_uid = null;
  457. $sent->pr_edit_at = null;
  458. $sent->pr_id = null;
  459. }
  460. $sent->editor_uid = $realEditor;
  461. $sent->save();
  462. $sent = $sent->refresh();
  463. //清除缓存
  464. $sentId = "{$sent['book_id']}-{$sent['paragraph']}-{$sent['word_start']}-{$sent['word_end']}";
  465. $hKey = "/sentence/res-count/{$sentId}/";
  466. Redis::del($hKey);
  467. OpsLog::debug($user["user_uid"], $sent);
  468. //清除cache
  469. $channelId = $param[4];
  470. $currSentId = "{$param[0]}-{$param[1]}-{$param[2]}-{$param[3]}";
  471. RedisClusters::forget("/sent/{$channelId}/{$currSentId}");
  472. //保存历史记录
  473. if ($request->has('prEditor')) {
  474. $this->saveHistory(
  475. $sent->uid,
  476. $realEditor,
  477. $request->get('content'),
  478. $user["user_uid"],
  479. null,
  480. $request->get('prUuid'),
  481. );
  482. } else {
  483. $this->saveHistory($sent->uid, $realEditor, $request->get('content'));
  484. }
  485. Mq::publish('progress', [
  486. 'book' => $param[0],
  487. 'para' => $param[1],
  488. 'channel' => $channelId,
  489. ]);
  490. Mq::publish('content', new SentResource($sent));
  491. if ($channel->type === 'nissaya' && $sent->content_type === 'json') {
  492. $this->updateWbwAnalyses($sent->content, $channel->lang, $user["user_id"]);
  493. }
  494. return $this->ok(new SentResource($sent));
  495. }
  496. /**
  497. * Remove the specified resource from storage.
  498. *
  499. * @param \App\Models\Sentence $sentence
  500. * @return \Illuminate\Http\Response
  501. */
  502. public function destroy(Sentence $sentence)
  503. {
  504. //
  505. }
  506. private function updateWbwAnalyses($data, $lang, $editorId)
  507. {
  508. $wbwData = json_decode($data);
  509. $currWbwId = 0;
  510. $prefix = 'wbw-preference';
  511. foreach ($wbwData as $key => $word) {
  512. # code...
  513. if (count($word->sn) === 1) {
  514. $currWbwId = $word->uid;
  515. WbwAnalysis::where('wbw_id', $word->uid)->delete();
  516. }
  517. $newData = [
  518. 'wbw_id' => $currWbwId,
  519. 'wbw_word' => $word->real->value,
  520. 'book_id' => $word->book,
  521. 'paragraph' => $word->para,
  522. 'wid' => $word->sn[0],
  523. 'type' => 0,
  524. 'data' => '',
  525. 'confidence' => 100,
  526. 'lang' => $lang,
  527. 'editor_id' => $editorId,
  528. 'created_at' => now(),
  529. 'updated_at' => now()
  530. ];
  531. $newData['type'] = 3;
  532. if (!empty($word->meaning->value)) {
  533. $newData['data'] = $word->meaning->value;
  534. WbwAnalysis::insert($newData);
  535. RedisClusters::put("{$prefix}/{$word->real->value}/3/{$editorId}", $word->meaning->value);
  536. RedisClusters::put("{$prefix}/{$word->real->value}/3/0", $word->meaning->value);
  537. }
  538. if (isset($word->factors) && isset($word->factorMeaning)) {
  539. $factors = explode('+', str_replace('-', '+', $word->factors->value));
  540. $factorMeaning = explode('+', str_replace('-', '+', $word->factorMeaning->value));
  541. foreach ($factors as $key => $factor) {
  542. if (isset($factorMeaning[$key])) {
  543. if (!empty($factorMeaning[$key])) {
  544. $newData['wbw_word'] = $factor;
  545. $newData['data'] = $factorMeaning[$key];
  546. $newData['type'] = 5;
  547. WbwAnalysis::insert($newData);
  548. RedisClusters::put("{$prefix}/{$factor}/5/{$editorId}", $factorMeaning[$key]);
  549. RedisClusters::put("{$prefix}/{$factor}/5/0", $factorMeaning[$key]);
  550. }
  551. }
  552. }
  553. }
  554. }
  555. }
  556. }