SentenceController.php 16 KB

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