SentenceController.php 20 KB

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