SentenceController.php 19 KB

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