SentenceController.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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') === 'channel' ||
  191. $request->get('view') === 'chapter' ||
  192. $request->get('view') === 'paragraph' ||
  193. $request->get('view') === 'my-edit'
  194. ){
  195. $output["rows"] = SentResource::collection($result);
  196. }else{
  197. $output["rows"] = $result;
  198. }
  199. if(isset($totalStrLen)){
  200. $output['total_strlen'] = $totalStrLen;
  201. }
  202. return $this->ok($output);
  203. }else{
  204. return $this->error("没有查询到数据");
  205. }
  206. }
  207. /**
  208. * 用channel 和句子编号列表查询句子
  209. */
  210. public function sent_in_channel(Request $request){
  211. $sent = $request->get('sentences') ;
  212. $query = [];
  213. foreach ($sent as $value) {
  214. # code...
  215. $ids = explode('-',$value);
  216. if(count($ids)===4){
  217. $query[] = $ids;
  218. }
  219. }
  220. $table = Sentence::select(['id','book_id','paragraph','word_start','word_end','content','channel_uid','updated_at'])
  221. ->where('channel_uid', $request->get('channel'))
  222. ->whereIns(['book_id','paragraph','word_start','word_end'],$query);
  223. $result = $table->get();
  224. if($result){
  225. return $this->ok(["rows"=>$result,"count"=>count($result)]);
  226. }else{
  227. return $this->error("没有查询到数据");
  228. }
  229. }
  230. /**
  231. * Show the form for creating a new resource.
  232. *
  233. * @return \Illuminate\Http\Response
  234. */
  235. public function create()
  236. {
  237. //
  238. }
  239. /**
  240. * 新建多个句子
  241. * 如果句子存在,修改
  242. * @param \Illuminate\Http\Request $request
  243. * @return \Illuminate\Http\Response
  244. */
  245. public function store(Request $request)
  246. {
  247. //鉴权
  248. $user = AuthApi::current($request);
  249. if(!$user ){
  250. //未登录用户
  251. return $this->error(__('auth.failed'),401,401);
  252. }
  253. $channel = Channel::where('uid',$request->get('channel'))->first();
  254. if(!$channel){
  255. return $this->error(__('auth.failed'),403,403);
  256. }
  257. if($channel->owner_uid !== $user["user_uid"]){
  258. //判断是否为协作
  259. $power = ShareApi::getResPower($user["user_uid"],$channel->uid,2);
  260. if($power < 20){
  261. return $this->error(__('auth.failed'),403,403);
  262. }
  263. }
  264. $sentFirst=null;
  265. $changedSent = [];
  266. foreach ($request->get('sentences') as $key => $sent) {
  267. # code...
  268. if($sentFirst === null){
  269. $sentFirst = $sent;
  270. }
  271. $row = Sentence::firstOrNew([
  272. "book_id"=>$sent['book_id'],
  273. "paragraph"=>$sent['paragraph'],
  274. "word_start"=>$sent['word_start'],
  275. "word_end"=>$sent['word_end'],
  276. "channel_uid"=>$channel->uid,
  277. ],[
  278. "id"=>app('snowflake')->id(),
  279. "uid"=>Str::uuid(),
  280. ]);
  281. $row->content = $sent['content'];
  282. if(isset($sent['content_type']) && !empty($sent['content_type'])){
  283. $row->content_type = $sent['content_type'];
  284. }
  285. $row->strlen = mb_strlen($sent['content'],"UTF-8");
  286. $row->language = $channel->lang;
  287. $row->status = $channel->status;
  288. if($request->has('copy')){
  289. //复制句子,保留原作者信息
  290. $row->editor_uid = $sent["editor_uid"];
  291. $row->acceptor_uid = $user["user_uid"];
  292. $row->pr_edit_at = $sent["updated_at"];
  293. if($request->has('fork_from')){
  294. $row->fork_at = now();
  295. }
  296. }else{
  297. $row->editor_uid = $user["user_uid"];
  298. $row->acceptor_uid = null;
  299. $row->pr_edit_at = null;
  300. }
  301. $row->create_time = time()*1000;
  302. $row->modify_time = time()*1000;
  303. $row->save();
  304. $changedSent[] = $row->uid;
  305. //保存历史记录
  306. if($request->has('copy')){
  307. $fork_from = $request->get('fork_from',null);
  308. $this->saveHistory($row->uid,
  309. $sent["editor_uid"],
  310. $sent['content'],
  311. $user["user_uid"],
  312. $fork_from);
  313. }else{
  314. $this->saveHistory($row->uid,$user["user_uid"],$sent['content'],$user["user_uid"]);
  315. }
  316. //清除缓存
  317. $sentId = "{$sent['book_id']}-{$sent['paragraph']}-{$sent['word_start']}-{$sent['word_end']}";
  318. $hKey = "/sentence/res-count/{$sentId}/";
  319. Redis::del($hKey);
  320. }
  321. if($sentFirst !== null){
  322. Mq::publish('progress',['book'=>$sentFirst['book_id'],
  323. 'para'=>$sentFirst['paragraph'],
  324. 'channel'=>$channel->uid,
  325. ]);
  326. }
  327. $result = Sentence::whereIn('uid', $changedSent)->get();
  328. return $this->ok([
  329. 'rows'=>SentResource::collection($result),
  330. 'count'=>count($result)
  331. ]);
  332. }
  333. private function saveHistory($uid,$editor,$content,$user_uid=null,$fork_from=null,$pr_from=null){
  334. $newHis = new SentHistory();
  335. $newHis->id = app('snowflake')->id();
  336. $newHis->sent_uid = $uid;
  337. $newHis->user_uid = $editor;
  338. if(empty($content)){
  339. $newHis->content = "";
  340. }else{
  341. $newHis->content = $content;
  342. }
  343. if($fork_from){
  344. $newHis->fork_from = $fork_from;
  345. $newHis->accepter_uid = $user_uid;
  346. }
  347. if($pr_from){
  348. $newHis->pr_from = $pr_from;
  349. $newHis->accepter_uid = $user_uid;
  350. }
  351. $newHis->create_time = time()*1000;
  352. $newHis->save();
  353. }
  354. /**
  355. * Display the specified resource.
  356. *
  357. * @param \App\Models\Sentence $sentence
  358. * @return \Illuminate\Http\Response
  359. */
  360. public function show(Sentence $sentence)
  361. {
  362. //
  363. return $this->ok(new SentResource($sentence));
  364. }
  365. /**
  366. * 修改单个句子
  367. *
  368. * @param \Illuminate\Http\Request $request
  369. * @param string $id book_para_start_end_channel
  370. * @return \Illuminate\Http\Response
  371. */
  372. public function update(Request $request, $id)
  373. {
  374. //
  375. $param = \explode('_',$id);
  376. //鉴权
  377. $user = AuthApi::current($request);
  378. if(!$user){
  379. //未登录鉴权失败
  380. return $this->error(__('auth.failed'),403,403);
  381. }
  382. $channel = Channel::where('uid',$param[4])->first();
  383. if(!$channel){
  384. return $this->error("not found channel");
  385. }
  386. if($channel->owner_uid !== $user["user_uid"]){
  387. // 判断是否为协作
  388. $power = ShareApi::getResPower($user["user_uid"],$channel->uid,2);
  389. if($power < 20){
  390. return $this->error(__('auth.failed'),403,403);
  391. }
  392. }
  393. $sent = Sentence::firstOrNew([
  394. "book_id"=>$param[0],
  395. "paragraph"=>$param[1],
  396. "word_start"=>$param[2],
  397. "word_end"=>$param[3],
  398. "channel_uid"=>$param[4],
  399. ],[
  400. "id"=>app('snowflake')->id(),
  401. "uid"=>Str::orderedUuid(),
  402. "create_time"=>time()*1000,
  403. ]);
  404. $sent->content = $request->get('content');
  405. if($request->has('contentType')){
  406. $sent->content_type = $request->get('contentType');
  407. }
  408. $sent->language = $channel->lang;
  409. $sent->status = $channel->status;
  410. $sent->strlen = mb_strlen($request->get('content'),"UTF-8");
  411. $sent->modify_time = time()*1000;
  412. if($request->has('prEditor')){
  413. $realEditor = $request->get('prEditor');
  414. $sent->acceptor_uid = $user["user_uid"];
  415. $sent->pr_edit_at = $request->get('prEditAt');
  416. $sent->pr_id = $request->get('prId');
  417. }else{
  418. $realEditor = $user["user_uid"];
  419. $sent->acceptor_uid = null;
  420. $sent->pr_edit_at = null;
  421. $sent->pr_id = null;
  422. }
  423. $sent->editor_uid = $realEditor;
  424. $sent->save();
  425. $sent = $sent->refresh();
  426. //清除缓存
  427. $sentId = "{$sent['book_id']}-{$sent['paragraph']}-{$sent['word_start']}-{$sent['word_end']}";
  428. $hKey = "/sentence/res-count/{$sentId}/";
  429. Redis::del($hKey);
  430. OpsLog::debug($user["user_uid"],$sent);
  431. //清除cache
  432. $channelId = $param[4];
  433. $currSentId = "{$param[0]}-{$param[1]}-{$param[2]}-{$param[3]}";
  434. RedisClusters::forget("/sent/{$channelId}/{$currSentId}");
  435. //保存历史记录
  436. if($request->has('prEditor')){
  437. $this->saveHistory($sent->uid,
  438. $realEditor,
  439. $request->get('content'),
  440. $user["user_uid"],
  441. null,
  442. $request->get('prUuid'),
  443. );
  444. }else{
  445. $this->saveHistory($sent->uid,$realEditor,$request->get('content'));
  446. }
  447. Mq::publish('progress',['book'=>$param[0],
  448. 'para'=>$param[1],
  449. 'channel'=>$channelId,
  450. ]);
  451. Mq::publish('content',new SentResource($sent));
  452. if($channel->type === 'nissaya' && $sent->content_type === 'json'){
  453. $this->updateWbwAnalyses($sent->content,$channel->lang,$user["user_id"]);
  454. }
  455. return $this->ok(new SentResource($sent));
  456. }
  457. /**
  458. * Remove the specified resource from storage.
  459. *
  460. * @param \App\Models\Sentence $sentence
  461. * @return \Illuminate\Http\Response
  462. */
  463. public function destroy(Sentence $sentence)
  464. {
  465. //
  466. }
  467. private function updateWbwAnalyses($data,$lang,$editorId){
  468. $wbwData = json_decode($data);
  469. $currWbwId = 0;
  470. $prefix = 'wbw-preference';
  471. foreach ($wbwData as $key => $word) {
  472. # code...
  473. if(count($word->sn) === 1 ){
  474. $currWbwId = $word->uid;
  475. WbwAnalysis::where('wbw_id',$word->uid)->delete();
  476. }
  477. $newData = [
  478. 'wbw_id' => $currWbwId,
  479. 'wbw_word' => $word->real->value,
  480. 'book_id' => $word->book,
  481. 'paragraph' => $word->para,
  482. 'wid' => $word->sn[0],
  483. 'type' => 0,
  484. 'data' => '',
  485. 'confidence' => 100,
  486. 'lang' => $lang,
  487. 'editor_id'=>$editorId,
  488. 'created_at'=>now(),
  489. 'updated_at'=>now()
  490. ];
  491. $newData['type'] = 3;
  492. if(!empty($word->meaning->value)){
  493. $newData['data'] = $word->meaning->value;
  494. WbwAnalysis::insert($newData);
  495. RedisClusters::put("{$prefix}/{$word->real->value}/3/{$editorId}",$word->meaning->value);
  496. RedisClusters::put("{$prefix}/{$word->real->value}/3/0",$word->meaning->value);
  497. }
  498. if(isset($word->factors) && isset($word->factorMeaning)){
  499. $factors = explode('+',str_replace('-','+',$word->factors->value));
  500. $factorMeaning = explode('+',str_replace('-','+',$word->factorMeaning->value));
  501. foreach ($factors as $key => $factor) {
  502. if(isset($factorMeaning[$key])){
  503. if(!empty($factorMeaning[$key])){
  504. $newData['wbw_word'] = $factor;
  505. $newData['data'] = $factorMeaning[$key];
  506. $newData['type'] = 5;
  507. WbwAnalysis::insert($newData);
  508. RedisClusters::put("{$prefix}/{$factor}/5/{$editorId}",$factorMeaning[$key]);
  509. RedisClusters::put("{$prefix}/{$factor}/5/0",$factorMeaning[$key]);
  510. }
  511. }
  512. }
  513. }
  514. }
  515. }
  516. }