SentenceController.php 20 KB

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