SentenceController.php 20 KB

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