2
0

SentenceController.php 22 KB

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