CorpusController.php 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Carbon\Carbon;
  4. use App\Models\Sentence;
  5. use App\Models\Channel;
  6. use App\Models\PaliText;
  7. use App\Models\WbwTemplate;
  8. use App\Models\WbwBlock;
  9. use App\Models\Wbw;
  10. use App\Models\Discussion;
  11. use App\Models\PaliSentence;
  12. use App\Models\SentSimIndex;
  13. use App\Models\CustomBookSentence;
  14. use App\Models\CustomBook;
  15. use Illuminate\Support\Str;
  16. use Illuminate\Http\Request;
  17. use Illuminate\Support\Facades\Cache;
  18. use App\Tools\RedisClusters;
  19. use App\Http\Api\MdRender;
  20. use App\Http\Api\SuggestionApi;
  21. use App\Http\Api\ChannelApi;
  22. use App\Http\Api\UserApi;
  23. use App\Http\Api\StudioApi;
  24. use App\Http\Api\AuthApi;
  25. use Illuminate\Support\Facades\Log;
  26. use Illuminate\Support\Arr;
  27. use App\Http\Resources\TocResource;
  28. use Illuminate\Support\Facades\Redis;
  29. class CorpusController extends Controller
  30. {
  31. protected $result = [
  32. "uid"=> '',
  33. "title"=> '',
  34. "path"=>[],
  35. "sub_title"=> '',
  36. "summary"=> '',
  37. "content"=> '',
  38. "content_type"=> "html",
  39. "toc" => [],
  40. "status"=>30,
  41. "lang"=> "",
  42. "created_at"=> "",
  43. "updated_at"=> "",
  44. ];
  45. protected $wbwChannels = [];
  46. //句子需要查询的列
  47. protected $selectCol = [
  48. 'uid',
  49. 'book_id',
  50. 'paragraph',
  51. 'word_start',
  52. "word_end",
  53. 'channel_uid',
  54. 'content',
  55. 'content_type',
  56. 'editor_uid',
  57. 'acceptor_uid',
  58. 'pr_edit_at',
  59. 'create_time',
  60. 'modify_time',
  61. 'created_at',
  62. 'updated_at',
  63. ];
  64. protected $userUuid=null;
  65. protected $debug=[];
  66. public function __construct()
  67. {
  68. }
  69. /**
  70. * Display a listing of the resource.
  71. *
  72. * @return \Illuminate\Http\Response
  73. */
  74. public function index(Request $request)
  75. {
  76. //
  77. switch ($request->get('view')) {
  78. case 'para':
  79. return $this->showPara($request);
  80. break;
  81. default:
  82. # code...
  83. break;
  84. }
  85. }
  86. /**
  87. * Store a newly created resource in storage.
  88. *
  89. * @param \Illuminate\Http\Request $request
  90. * @return \Illuminate\Http\Response
  91. */
  92. public function store(Request $request)
  93. {
  94. //
  95. }
  96. /**
  97. * Display the specified resource.
  98. *
  99. * @param \App\Models\Sentence $sentence
  100. * @return \Illuminate\Http\Response
  101. */
  102. public function show(Sentence $sentence)
  103. {
  104. //
  105. }
  106. public function getSentTpl($id,$channels,$mode='edit',$onlyProps=false,$format='react'){
  107. $sent = [];
  108. $sentId = \explode('-',$id);
  109. if(count($sentId) !== 4){
  110. return false;
  111. }
  112. $bookId = (int)$sentId[0];
  113. if( $bookId < 1000){
  114. if($mode==='read'){
  115. $channelId = ChannelApi::getSysChannel('_System_Pali_VRI_');
  116. }else{
  117. $channelId = ChannelApi::getSysChannel('_System_Wbw_VRI_');
  118. }
  119. }else{
  120. $channelId = CustomBook::where('book_id',$bookId)->value('channel_id');
  121. }
  122. if(isset($channelId) && $channelId){
  123. array_push($channels,$channelId);
  124. }
  125. $record = Sentence::select($this->selectCol)
  126. ->where('book_id',$sentId[0])
  127. ->where('paragraph',$sentId[1])
  128. ->where('word_start',(int)$sentId[2])
  129. ->where('word_end',(int)$sentId[3])
  130. ->whereIn('channel_uid',$channels)
  131. ->get();
  132. $channelIndex = $this->getChannelIndex($channels);
  133. if(isset($toSentFormat)){
  134. foreach ($toSentFormat as $key => $org) {
  135. $record[] = $org;
  136. }
  137. }
  138. //获取wbw channel
  139. //目前默认的 wbw channel 是第一个translation channel
  140. foreach ($channels as $channel) {
  141. # code...
  142. if($channelIndex[$channel]->type==='translation'){
  143. $this->wbwChannels[] = $channel;
  144. break;
  145. }
  146. }
  147. return $this->makeContent($record,$mode,$channelIndex,[],$onlyProps,false,$format);
  148. }
  149. /**
  150. * Display the specified resource.
  151. * @param \Illuminate\Http\Request $request
  152. * @param string $id
  153. * @return \Illuminate\Http\Response
  154. */
  155. public function showSent(Request $request, string $id)
  156. {
  157. $user = AuthApi::current($request);
  158. if($user){
  159. $this->userUuid = $user['user_uid'];
  160. }
  161. $channels = \explode('_',$request->get('channels'));
  162. $this->result['uid'] = "";
  163. $this->result['title'] = "";
  164. $this->result['subtitle'] = "";
  165. $this->result['summary'] = "";
  166. $this->result['lang'] = "";
  167. $this->result['status'] = 30;
  168. $this->result['content'] = $this->getSentTpl($id,$channels,$request->get('mode','edit'));
  169. return $this->ok($this->result);
  170. }
  171. /**
  172. * 获取某句子的全部译文
  173. * @param \Illuminate\Http\Request $request
  174. * @param string $type
  175. * @param string $id
  176. * @return \Illuminate\Http\Response
  177. */
  178. public function showSentences(Request $request, string $type, string $id){
  179. $user = AuthApi::current($request);
  180. if($user){
  181. $this->userUuid = $user['user_uid'];
  182. }
  183. $param = \explode('_',$id);
  184. $sentId = \explode('-',$param[0]);
  185. $channels = [];
  186. #获取channel类型
  187. $sentChannel = Sentence::select('channel_uid')
  188. ->where('book_id',$sentId[0])
  189. ->where('paragraph',$sentId[1])
  190. ->where('word_start',$sentId[2])
  191. ->where('word_end',$sentId[3])
  192. ->get();
  193. foreach ($sentChannel as $key => $value) {
  194. # code...
  195. $channels[] = $value->channel_uid;
  196. }
  197. $channelInfo = Channel::whereIn("uid",$channels)->select(['uid','type','name'])->get();
  198. $indexChannel = [];
  199. $channels = [];
  200. foreach ($channelInfo as $key => $value) {
  201. # code...
  202. if($value->type === $type){
  203. $indexChannel[$value->uid] = $value;
  204. $channels[] = $value->uid;
  205. }
  206. }
  207. //获取句子数据
  208. $record = Sentence::select($this->selectCol)
  209. ->where('book_id',$sentId[0])
  210. ->where('paragraph',$sentId[1])
  211. ->where('word_start',$sentId[2])
  212. ->where('word_end',$sentId[3])
  213. ->whereIn('channel_uid',$channels)
  214. ->orderBy('paragraph')
  215. ->orderBy('word_start')
  216. ->get();
  217. if(count($record) ===0){
  218. return $this->error("no data");
  219. }
  220. $this->result['uid'] = "";
  221. $this->result['title'] = "";
  222. $this->result['subtitle'] = "";
  223. $this->result['summary'] = "";
  224. $this->result['lang'] = "";
  225. $this->result['status'] = 30;
  226. $this->result['content'] = $this->makeContent($record,$mode,$indexChannel);
  227. return $this->ok($this->result);
  228. }
  229. /**
  230. * Store a newly created resource in storage.
  231. * @param \Illuminate\Http\Request $request
  232. * @param string $id
  233. * @param string $mode
  234. * @return \Illuminate\Http\Response
  235. */
  236. public function showPara(Request $request)
  237. {
  238. if($request->has('debug')){
  239. $this->debug = explode(',',$request->get('debug'));
  240. }
  241. $user = AuthApi::current($request);
  242. if($user){
  243. $this->userUuid = $user['user_uid'];
  244. }
  245. //
  246. $channels = [];
  247. if($request->get('mode') === 'edit'){
  248. //翻译模式加载json格式原文
  249. $channels[] = ChannelApi::getSysChannel('_System_Wbw_VRI_');
  250. }else{
  251. //阅读模式加载html格式原文
  252. $channels[] = ChannelApi::getSysChannel('_System_Pali_VRI_');
  253. }
  254. if($request->has('channels')){
  255. if(strpos($request->get('channels'),',') === FALSE){
  256. $getChannel = explode('_',$request->get('channels'));
  257. }else{
  258. $getChannel = explode(',',$request->get('channels'));
  259. }
  260. $channels = array_merge($channels,$getChannel );
  261. }
  262. $para = explode(",",$request->get('par'));
  263. //段落所在章节
  264. $parent = PaliText::where('book',$request->get('book'))
  265. ->where('paragraph',$para[0])->first();
  266. $chapter = PaliText::where('book',$request->get('book'))
  267. ->where('paragraph',$parent->parent)->first();
  268. if($chapter){
  269. if(empty($chapter->toc)){
  270. $this->result['title'] = "unknown";
  271. }else{
  272. $this->result['title'] = $chapter->toc;
  273. $this->result['sub_title'] = $chapter->toc;
  274. $this->result['path'] = json_decode($parent->path);
  275. }
  276. }
  277. $paraFrom = $para[0];
  278. $paraTo = end($para);
  279. $indexedHeading = [];
  280. #获取channel索引表
  281. $tranChannels = [];
  282. $channelInfo = Channel::whereIn("uid",$channels)->select(['uid','type','name'])->get();
  283. foreach ($channelInfo as $key => $value) {
  284. # code...
  285. if($value->type==="translation" ){
  286. $tranChannels[] = $value->uid;
  287. }
  288. }
  289. $indexChannel = [];
  290. $indexChannel = $this->getChannelIndex($channels);
  291. //获取wbw channel
  292. //目前默认的 wbw channel 是第一个translation channel
  293. foreach ($channels as $key => $value) {
  294. # code...
  295. if($indexChannel[$value]->type==='translation'){
  296. $this->wbwChannels[] = $value;
  297. break;
  298. }
  299. }
  300. //章节译文标题
  301. $title = Sentence::select($this->selectCol)
  302. ->where('book_id',$parent->book)
  303. ->where('paragraph',$parent->parent)
  304. ->whereIn('channel_uid',$tranChannels)
  305. ->first();
  306. if($title){
  307. $this->result['title'] = MdRender::render($title->content,[$title->channel_uid]);
  308. }
  309. /**
  310. * 获取句子数据
  311. */
  312. $record = Sentence::select($this->selectCol)
  313. ->where('book_id',$request->get('book'))
  314. ->whereIn('paragraph',$para)
  315. ->whereIn('channel_uid',$channels)
  316. ->orderBy('paragraph')
  317. ->orderBy('word_start')
  318. ->get();
  319. if(count($record) ===0){
  320. $this->result['content'] = "<span>No Data</span>";
  321. }else{
  322. $this->result['content'] = $this->makeContent($record,$request->get('mode','read'),$indexChannel,$indexedHeading,false,true);
  323. }
  324. return $this->ok($this->result);
  325. }
  326. /**
  327. * Store a newly created resource in storage.
  328. * @param \Illuminate\Http\Request $request
  329. * @param string $id
  330. * @return \Illuminate\Http\Response
  331. */
  332. public function showChapter(Request $request, string $id)
  333. {
  334. if($request->has('debug')){
  335. $this->debug = explode(',',$request->get('debug'));
  336. }
  337. $user = AuthApi::current($request);
  338. if($user){
  339. $this->userUuid = $user['user_uid'];
  340. }
  341. //
  342. $sentId = \explode('-',$id);
  343. $channels = [];
  344. if($request->has('channels')){
  345. if(strpos($request->get('channels'),',') === FALSE){
  346. $channels = explode('_',$request->get('channels'));
  347. }else{
  348. $channels = explode(',',$request->get('channels'));
  349. }
  350. }
  351. $mode = $request->get('mode','read');
  352. if($mode === 'read'){
  353. //阅读模式加载html格式原文
  354. $channelId = ChannelApi::getSysChannel('_System_Pali_VRI_');
  355. }else{
  356. //翻译模式加载json格式原文
  357. $channelId = ChannelApi::getSysChannel('_System_Wbw_VRI_');
  358. }
  359. if($channelId !== false){
  360. $channels[] = $channelId;
  361. }
  362. $chapter = PaliText::where('book',$sentId[0])->where('paragraph',$sentId[1])->first();
  363. if(!$chapter){
  364. return $this->error("no data");
  365. }
  366. $paraFrom = $sentId[1];
  367. $paraTo = $sentId[1]+$chapter->chapter_len-1;
  368. if(empty($chapter->toc)){
  369. $this->result['title'] = "unknown";
  370. }else{
  371. $this->result['title'] = $chapter->toc;
  372. $this->result['sub_title'] = $chapter->toc;
  373. $this->result['path'] = json_decode($chapter->path);
  374. }
  375. //获取标题
  376. $heading = PaliText::select(["book","paragraph","level"])
  377. ->where('book',$sentId[0])
  378. ->whereBetween('paragraph',[$paraFrom,$paraTo])
  379. ->where('level','<',8)
  380. ->get();
  381. //将标题段落转成索引数组 以便输出标题层级
  382. $indexedHeading = [];
  383. foreach ($heading as $key => $value) {
  384. # code...
  385. $indexedHeading["{$value->book}-{$value->paragraph}"] = $value->level;
  386. }
  387. #获取channel索引表
  388. $tranChannels = [];
  389. $channelInfo = Channel::whereIn("uid",$channels)->select(['uid','type','name'])->get();
  390. foreach ($channelInfo as $key => $value) {
  391. # code...
  392. if($value->type==="translation" ){
  393. $tranChannels[] = $value->uid;
  394. }
  395. }
  396. $indexChannel = [];
  397. $indexChannel = $this->getChannelIndex($channels);
  398. //获取wbw channel
  399. //目前默认的 wbw channel 是第一个translation channel
  400. foreach ($channels as $key => $value) {
  401. # code...
  402. if($indexChannel[$value]->type==='translation'){
  403. $this->wbwChannels[] = $value;
  404. break;
  405. }
  406. }
  407. $title = Sentence::select($this->selectCol)
  408. ->where('book_id',$sentId[0])
  409. ->where('paragraph',$sentId[1])
  410. ->whereIn('channel_uid',$tranChannels)
  411. ->first();
  412. if($title){
  413. $this->result['title'] = MdRender::render($title->content,[$title->channel_uid]);
  414. }
  415. /**
  416. * 获取句子数据
  417. * 算法:
  418. * 1. 如果标题和下一级第一个标题之间有段落。只输出这些段落和子目录
  419. * 2. 如果标题和下一级第一个标题之间没有间隔 且 chapter 长度大于10000个字符 且有子目录,只输出子目录
  420. * 3. 如果二者都不是,lazy load
  421. */
  422. //1. 计算 标题和下一级第一个标题之间 是否有间隔
  423. $nextChapter = PaliText::where('book',$sentId[0])
  424. ->where('paragraph',">",$sentId[1])
  425. ->where('level','<',8)
  426. ->orderBy('paragraph')
  427. ->value('paragraph');
  428. $between = $nextChapter - $sentId[1];
  429. //查找子目录
  430. $chapterLen = $chapter->chapter_len;
  431. $toc = PaliText::where('book',$sentId[0])
  432. ->whereBetween('paragraph',[$paraFrom+1,$paraFrom+$chapterLen-1])
  433. ->where('level','<',8)
  434. ->orderBy('paragraph')
  435. ->select(['book','paragraph','level','toc'])
  436. ->get();
  437. $maxLen = 3000;
  438. if($between > 1){
  439. //有间隔
  440. $paraTo = $nextChapter - 1;
  441. }else{
  442. if($chapter->chapter_strlen > $maxLen){
  443. if(count($toc)>0){
  444. //有子目录只输出标题和目录
  445. $paraTo = $paraFrom;
  446. }else{
  447. //没有子目录 全部输出
  448. }
  449. }else{
  450. //章节小。全部输出 不输出子目录
  451. $toc = [];
  452. }
  453. }
  454. $pFrom = $request->get('from',$paraFrom);
  455. $pTo = $request->get('to',$paraTo);
  456. //根据句子的长度找到这次应该加载的段落
  457. $paliText = PaliText::select(['paragraph','lenght'])
  458. ->where('book',$sentId[0])
  459. ->whereBetween('paragraph',[$pFrom,$pTo])
  460. ->orderBy('paragraph')
  461. ->get();
  462. $sumLen = 0;
  463. $currTo = $pTo;
  464. foreach ($paliText as $para) {
  465. $sumLen += $para->lenght;
  466. if($sumLen > $maxLen){
  467. $currTo = $para->paragraph;
  468. break;
  469. }
  470. }
  471. $record = Sentence::select($this->selectCol)
  472. ->where('book_id',$sentId[0])
  473. ->whereBetween('paragraph',[$pFrom,$currTo])
  474. ->whereIn('channel_uid',$channels)
  475. ->orderBy('paragraph')
  476. ->orderBy('word_start')
  477. ->get();
  478. if(count($record) ===0){
  479. return $this->error("no data");
  480. }
  481. $this->result['content'] = $this->makeContent($record,$mode,$indexChannel,$indexedHeading,false,true);
  482. if(!$request->has('from')){
  483. //第一次才显示toc
  484. $this->result['toc'] = TocResource::collection($toc);
  485. }
  486. if($currTo < $pTo){
  487. $this->result['from'] = $currTo+1;
  488. $this->result['to'] = $pTo;
  489. $this->result['paraId'] = $id;
  490. $this->result['channels'] = $request->get('channels');
  491. $this->result['mode'] = $request->get('mode');
  492. }
  493. return $this->ok($this->result);
  494. }
  495. private function getChannelIndex($channels,$type=null){
  496. #获取channel索引表
  497. $channelInfo = Channel::whereIn("uid",$channels)
  498. ->select(['uid','type','name','owner_uid'])->get();
  499. $indexChannel = [];
  500. foreach ($channels as $key => $channelId) {
  501. $channelInfo = Channel::where("uid",$channelId)
  502. ->select(['uid','type','name','owner_uid'])->first();
  503. if(!$channelInfo){
  504. Log::error('no channel id'.$channelId);
  505. continue;
  506. }
  507. if($type !== null && $channelInfo->type !== $type){
  508. continue;
  509. }
  510. $indexChannel[$channelId] = $channelInfo;
  511. $indexChannel[$channelId]->studio = StudioApi::getById($channelInfo->owner_uid);
  512. }
  513. return $indexChannel;
  514. }
  515. /**
  516. * 根据句子库数据生成文章内容
  517. * $record 句子数据
  518. * $mode read | edit | wbw
  519. * $indexChannel channel索引
  520. * $indexedHeading 标题索引 用于给段落加标题标签 <h1> ect.
  521. */
  522. private function makeContent($record,$mode,$indexChannel,$indexedHeading=[],$onlyProps=false,$paraMark=false,$format='react'){
  523. $content = [];
  524. $lastSent = "0-0";
  525. $sentCount = 0;
  526. $sent = [];
  527. $sent["origin"] = [];
  528. $sent["translation"] = [];
  529. //获取句子编号列表
  530. $sentList = [];
  531. foreach ($record as $key => $value) {
  532. $currSentId = "{$value->book_id}-{$value->paragraph}-{$value->word_start}-{$value->word_end}";
  533. $sentList[$currSentId]=[$value->book_id ,$value->paragraph,$value->word_start,$value->word_end];
  534. $value->sid = "{$currSentId}_{$value->channel_uid}";
  535. }
  536. $channelsId = array();
  537. $count = 0;
  538. foreach ($indexChannel as $channelId => $info){
  539. if($count>0){
  540. $channelsId[] = $channelId;
  541. }
  542. $count++;
  543. }
  544. //遍历列表查找每个句子的所有channel的数据,并填充
  545. $currPara = "";
  546. foreach ($sentList as $currSentId => $arrSentId) {
  547. $para = $arrSentId[0]."-".$arrSentId[1];
  548. if($currPara !== $para){
  549. $currPara = $para;
  550. //输出段落标记
  551. if($paraMark){
  552. $sentInPara = array();
  553. foreach ($sentList as $sentId => $sentParam) {
  554. if($sentParam[0]===$arrSentId[0] &&
  555. $sentParam[1]===$arrSentId[1]){
  556. $sentInPara[] = $sentId;
  557. }
  558. }
  559. //输出段落起始
  560. if(!empty($currPara)){
  561. $content[] = '</MdTpl>';
  562. }
  563. $markProps = base64_encode(\json_encode([
  564. 'book'=>$arrSentId[0],
  565. 'para'=>$arrSentId[1],
  566. 'channels'=>$channelsId,
  567. 'sentences'=>$sentInPara,
  568. ])) ;
  569. $content[] = "<MdTpl tpl='para-shell' props='{$markProps}' >";
  570. }
  571. }
  572. $sent = $this->newSent($arrSentId[0],$arrSentId[1],$arrSentId[2],$arrSentId[3]);
  573. foreach ($indexChannel as $channelId => $info) {
  574. # code...
  575. $sid = "{$currSentId}_{$channelId}";
  576. if(isset($info->studio)){
  577. $studioInfo = $info->studio;
  578. }else{
  579. $studioInfo = null;
  580. }
  581. $newSent = [
  582. "content"=>"",
  583. "html"=> "",
  584. "book"=> $arrSentId[0],
  585. "para"=> $arrSentId[1],
  586. "wordStart"=> $arrSentId[2],
  587. "wordEnd"=> $arrSentId[3],
  588. "channel"=> [
  589. "name"=>$info->name,
  590. "type"=>$info->type,
  591. "id"=> $info->uid,
  592. ],
  593. "studio" => $studioInfo,
  594. "updateAt"=> "",
  595. "suggestionCount" => SuggestionApi::getCountBySent($arrSentId[0],$arrSentId[1],$arrSentId[2],$arrSentId[3],$channelId),
  596. ];
  597. $row = Arr::first($record,function($value,$key) use($sid){
  598. return $value->sid===$sid;
  599. });
  600. if($row){
  601. $newSent['id'] = $row->uid;
  602. $newSent['content'] = $row->content;
  603. $newSent['contentType'] = $row->content_type;
  604. $newSent['html'] = '';
  605. $newSent["editor"]=UserApi::getByUuid($row->editor_uid);
  606. /**
  607. * TODO 刷库改数据
  608. * 旧版api没有更新updated_at所以造成旧版的数据updated_at数据比modify_time 要晚
  609. */
  610. $newSent['updateAt'] = $row->updated_at; //
  611. $newSent['updateAt'] = date("Y-m-d H:i:s.",$row->modify_time/1000).($row->modify_time%1000)." UTC";
  612. $newSent['createdAt'] = $row->created_at;
  613. if($mode !== "read"){
  614. if(isset($row->acceptor_uid) && !empty($row->acceptor_uid)){
  615. $newSent["acceptor"]=UserApi::getByUuid($row->acceptor_uid);
  616. $newSent["prEditAt"]=$row->pr_edit_at;
  617. }
  618. }
  619. switch ($info->type) {
  620. case 'wbw':
  621. case 'original':
  622. //
  623. // 在编辑模式下。
  624. // 如果是原文,查看是否有逐词解析数据,
  625. // 有的话优先显示。
  626. // 阅读模式直接显示html原文
  627. // 传过来的数据一定有一个原文channel
  628. //
  629. if($mode === "read"){
  630. $newSent['content'] = "";
  631. $newSent['html'] = MdRender::render($row->content,[$row->channel_uid],
  632. null,$mode,"translation",
  633. $row->content_type,$format);
  634. }else{
  635. if($row->content_type==='json'){
  636. $newSent['channel']['type'] = "wbw";
  637. if(isset($this->wbwChannels[0])){
  638. $newSent['channel']['name'] = $indexChannel[$this->wbwChannels[0]]->name;
  639. $newSent['channel']['id'] = $this->wbwChannels[0];
  640. //存在一个translation channel
  641. //尝试查找逐词解析数据。找到,替换现有数据
  642. $wbwData = $this->getWbw($arrSentId[0],$arrSentId[1],$arrSentId[2],$arrSentId[3],
  643. $this->wbwChannels[0]);
  644. if($wbwData){
  645. $newSent['content'] = $wbwData;
  646. $newSent['contentType'] = 'json';
  647. $newSent['html'] = "";
  648. }
  649. }
  650. }else{
  651. $newSent['content'] = $row->content;
  652. $newSent['html'] = MdRender::render($row->content,[$row->channel_uid],
  653. null,$mode,"translation",
  654. $row->content_type,$format);
  655. }
  656. }
  657. break;
  658. case 'nissaya':
  659. $newSent['html'] = RedisClusters::remember("/sent/{$channelId}/{$currSentId}/{$format}",
  660. config('mint.cache.expire'),
  661. function() use($row,$mode,$format){
  662. return MdRender::render($row->content,[$row->channel_uid],
  663. null,$mode,"nissaya",
  664. $row->content_type,$format);
  665. });
  666. break;
  667. default:
  668. /**
  669. * 译文需要markdown渲染
  670. * 包涵术语的不用cache
  671. */
  672. if(strpos($row->content,'[[')===false){
  673. $newSent['html'] = MdRender::render($row->content,[$row->channel_uid],
  674. null,$mode,'translation',
  675. $row->content_type,$format);
  676. /*
  677. RedisClusters::remember("/sent/{$channelId}/{$currSentId}/{$format}",
  678. config('mint.cache.expire'),
  679. function() use($row,$mode,$format){
  680. return MdRender::render($row->content,[$row->channel_uid],
  681. null,$mode,'translation',
  682. $row->content_type,$format);
  683. });
  684. */
  685. }else{
  686. $mdRender = new MdRender(
  687. [
  688. 'debug'=>$this->debug,
  689. 'format'=>$format,
  690. 'mode'=>$mode,
  691. 'channelType'=>'translation',
  692. 'contentType'=>$row->content_type,
  693. ]);
  694. $newSent['html'] = $mdRender->convert($row->content,[$row->channel_uid]);
  695. }
  696. break;
  697. }
  698. }
  699. switch ($info->type) {
  700. case 'wbw':
  701. case 'original':
  702. array_push($sent["origin"],$newSent);
  703. break;
  704. default:
  705. array_push($sent["translation"],$newSent);
  706. break;
  707. }
  708. }
  709. if($onlyProps){
  710. return $sent;
  711. }
  712. $content = $this->pushSent($content,$sent,0,$mode);
  713. }
  714. if($paraMark){
  715. $content[] = '</MdTpl>';
  716. }
  717. $output = \implode("",$content);
  718. return "<div>{$output}</div>";
  719. }
  720. public function getWbw($book,$para,$start,$end,$channel){
  721. /**
  722. * 非阅读模式下。原文使用逐词解析数据。
  723. * 优先加载第一个translation channel 如果没有。加载默认逐词解析。
  724. */
  725. //获取逐词解析数据
  726. $wbwBlock = WbwBlock::where('channel_uid',$channel)
  727. ->where('book_id',$book)
  728. ->where('paragraph',$para)
  729. ->select('uid')
  730. ->first();
  731. if(!$wbwBlock){
  732. return false;
  733. }
  734. //找到逐词解析数据
  735. $wbwData = Wbw::where('block_uid',$wbwBlock->uid)
  736. ->whereBetween('wid',[$start,$end])
  737. ->select(['book_id','paragraph','wid','data','uid'])
  738. ->orderBy('wid')
  739. ->get();
  740. $wbwContent = [];
  741. foreach ($wbwData as $wbwrow) {
  742. $wbw = str_replace("&nbsp;",' ',$wbwrow->data);
  743. $wbw = str_replace("<br>",' ',$wbw);
  744. $xmlString = "<root>" . $wbw . "</root>";
  745. try{
  746. $xmlWord = simplexml_load_string($xmlString);
  747. }catch(Exception $e){
  748. continue;
  749. }
  750. $wordsList = $xmlWord->xpath('//word');
  751. foreach ($wordsList as $word) {
  752. $case = \str_replace(['#','.'],['$',''],$word->case->__toString());
  753. $case = \str_replace('$$','$',$case);
  754. $case = trim($case);
  755. $case = trim($case,"$");
  756. $wbwId = explode('-',$word->id->__toString());
  757. $wbwData = [
  758. 'uid'=>$wbwrow->uid,
  759. 'book'=>$wbwrow->book_id,
  760. 'para'=>$wbwrow->paragraph,
  761. 'sn'=> array_slice($wbwId,2),
  762. 'word'=>['value'=>$word->pali->__toString(),'status'=>0],
  763. 'real'=> ['value'=>$word->real->__toString(),'status'=>0],
  764. 'meaning'=> ['value'=>$word->mean->__toString() ,'status'=>0],
  765. 'type'=> ['value'=>$word->type->__toString(),'status'=>0],
  766. 'grammar'=> ['value'=>$word->gramma->__toString(),'status'=>0],
  767. 'case'=> ['value'=>$word->case->__toString(),'status'=>0],
  768. 'parent'=> ['value'=>$word->parent->__toString(),'status'=>0],
  769. 'style'=> ['value'=>$word->style->__toString(),'status'=>0],
  770. 'factors'=> ['value'=>$word->org->__toString(),'status'=>0],
  771. 'factorMeaning'=> ['value'=>$word->om->__toString(),'status'=>0],
  772. 'confidence'=> $word->cf->__toString(),
  773. 'hasComment'=>Discussion::where('res_id',$wbwrow->uid)->exists(),
  774. ];
  775. if(isset($word->parent2)){
  776. $wbwData['parent2']['value'] = $word->parent2->__toString();
  777. if(isset($word->parent2['status'])){
  778. $wbwData['parent2']['status'] = (int)$word->parent2['status'];
  779. }else{
  780. $wbwData['parent2']['status'] = 0;
  781. }
  782. }
  783. if(isset($word->pg)){
  784. $wbwData['grammar2']['value'] = $word->pg->__toString();
  785. if(isset($word->pg['status'])){
  786. $wbwData['grammar2']['status'] = (int)$word->pg['status'];
  787. }else{
  788. $wbwData['grammar2']['status'] = 0;
  789. }
  790. }
  791. if(isset($word->rela)){
  792. $wbwData['relation']['value'] = $word->rela->__toString();
  793. if(isset($word->rela['status'])){
  794. $wbwData['relation']['status'] = (int)$word->rela['status'];
  795. }else{
  796. $wbwData['relation']['status'] = 7;
  797. }
  798. }
  799. if(isset($word->bmt)){
  800. $wbwData['bookMarkText']['value'] = $word->bmt->__toString();
  801. if(isset($word->bmt['status'])){
  802. $wbwData['bookMarkText']['status'] = (int)$word->bmt['status'];
  803. }else{
  804. $wbwData['bookMarkText']['status'] = 7;
  805. }
  806. }
  807. if(isset($word->bmc)){
  808. $wbwData['bookMarkColor']['value'] = $word->bmc->__toString();
  809. if(isset($word->bmc['status'])){
  810. $wbwData['bookMarkColor']['status'] = (int)$word->bmc['status'];
  811. }else{
  812. $wbwData['bookMarkColor']['status'] = 7;
  813. }
  814. }
  815. if(isset($word->note)){
  816. $wbwData['note']['value'] = $word->note->__toString();
  817. if(isset($word->note['status'])){
  818. $wbwData['note']['status'] = (int)$word->note['status'];
  819. }else{
  820. $wbwData['note']['status'] = 7;
  821. }
  822. }
  823. if(isset($word->cf)){
  824. $wbwData['confidence'] = (float)$word->cf->__toString();
  825. }
  826. if(isset($word->attachments)){
  827. $wbwData['attachments'] = json_decode($word->attachments->__toString());
  828. }
  829. if(isset($word->pali['status'])){
  830. $wbwData['word']['status'] = (int)$word->pali['status'];
  831. }
  832. if(isset($word->real['status'])){
  833. $wbwData['real']['status'] = (int)$word->real['status'];
  834. }
  835. if(isset($word->mean['status'])){
  836. $wbwData['meaning']['status'] = (int)$word->mean['status'];
  837. }
  838. if(isset($word->type['status'])){
  839. $wbwData['type']['status'] = (int)$word->type['status'];
  840. }
  841. if(isset($word->gramma['status'])){
  842. $wbwData['grammar']['status'] = (int)$word->gramma['status'];
  843. }
  844. if(isset($word->case['status'])){
  845. $wbwData['case']['status'] = (int)$word->case['status'];
  846. }
  847. if(isset($word->parent['status'])){
  848. $wbwData['parent']['status'] = (int)$word->parent['status'];
  849. }
  850. if(isset($word->org['status'])){
  851. $wbwData['factors']['status'] = (int)$word->org['status'];
  852. }
  853. if(isset($word->om['status'])){
  854. $wbwData['factorMeaning']['status'] = (int)$word->om['status'];
  855. }
  856. $wbwContent[] = $wbwData;
  857. }
  858. }
  859. if(count($wbwContent)===0){
  860. return false;
  861. }
  862. return \json_encode($wbwContent,JSON_UNESCAPED_UNICODE);
  863. }
  864. /**
  865. * 将句子放进结果列表
  866. */
  867. private function pushSent($result,$sent,$level=0,$mode='read'){
  868. $sentProps = base64_encode(\json_encode($sent)) ;
  869. if($mode === 'read'){
  870. $sentWidget = "<MdTpl tpl='sentread' props='{$sentProps}' ></MdTpl>";
  871. }else{
  872. $sentWidget = "<MdTpl tpl='sentedit' props='{$sentProps}' ></MdTpl>";
  873. }
  874. //增加标题的html标记
  875. if($level>0){
  876. $sentWidget = "<h{$level}>".$sentWidget."</h{$level}>";
  877. }
  878. array_push($result,$sentWidget);
  879. return $result;
  880. }
  881. private function newSent($book,$para,$word_start,$word_end){
  882. $sent = [
  883. "id"=>"{$book}-{$para}-{$word_start}-{$word_end}",
  884. "book"=>$book,
  885. "para"=>$para,
  886. "wordStart"=>$word_start,
  887. "wordEnd"=>$word_end,
  888. "origin"=>[],
  889. "translation"=>[],
  890. ];
  891. if($book<1000){
  892. #生成channel 数量列表
  893. $sentId = "{$book}-{$para}-{$word_start}-{$word_end}";
  894. $channelCount = CorpusController::_sentCanReadCount($book,$para,$word_start,$word_end,$this->userUuid);
  895. $path = json_decode(PaliText::where('book',$book)->where('paragraph',$para)->value("path"),true);
  896. $sent["path"] = [];
  897. foreach ($path as $key => $value) {
  898. # code...
  899. $value['paliTitle'] = $value['title'];
  900. $sent["path"][] = $value;
  901. }
  902. $sent["tranNum"] = $channelCount['tranNum'];
  903. $sent["nissayaNum"] = $channelCount['nissayaNum'];
  904. $sent["commNum"] = $channelCount['commNum'];
  905. $sent["originNum"] = $channelCount['originNum'];
  906. $sent["simNum"] = $channelCount['simNum'];
  907. }
  908. return $sent;
  909. }
  910. public static function _sentCanReadCount($book,$para,$start,$end,$userUuid=null){
  911. $keyCanRead="/channel/can-read/";
  912. if($userUuid){
  913. $keyCanRead .= $userUuid;
  914. }else{
  915. $keyCanRead .= 'guest';
  916. }
  917. $channelCanRead = RedisClusters::remember($keyCanRead,
  918. config('mint.cache.expire'),
  919. function() use($userUuid){
  920. return ChannelApi::getCanReadByUser($userUuid);
  921. });
  922. $channels = Sentence::where('book_id',$book)
  923. ->where('paragraph',$para)
  924. ->where('word_start',$start)
  925. ->where('word_end',$end)
  926. ->where('strlen','<>',0)
  927. ->whereIn('channel_uid',$channelCanRead)
  928. ->select('channel_uid')
  929. ->groupBy('channel_uid')
  930. ->get();
  931. $channelList = [];
  932. foreach ($channels as $key => $value) {
  933. # code...
  934. if(Str::isUuid($value->channel_uid)){
  935. $channelList[] = $value->channel_uid;
  936. }
  937. }
  938. $simId = PaliSentence::where('book',$book)
  939. ->where('paragraph',$para)
  940. ->where('word_begin',$start)
  941. ->where('word_end',$end)
  942. ->value('id');
  943. if($simId){
  944. $output["simNum"]=SentSimIndex::where('sent_id',$simId)->value('count');
  945. }else{
  946. $output["simNum"]=0;
  947. }
  948. $channelInfo = Channel::whereIn("uid",$channelList)->select('type')->get();
  949. $output["tranNum"]=0;
  950. $output["nissayaNum"]=0;
  951. $output["commNum"]=0;
  952. $output["originNum"]=0;
  953. foreach ($channelInfo as $key => $value) {
  954. # code...
  955. switch($value->type){
  956. case "translation":
  957. $output["tranNum"]++;
  958. break;
  959. case "nissaya":
  960. $output["nissayaNum"]++;
  961. break;
  962. case "commentary":
  963. $output["commNum"]++;
  964. break;
  965. case "original":
  966. $output["originNum"]++;
  967. break;
  968. }
  969. }
  970. return $output;
  971. }
  972. /**
  973. * 获取某个句子的相关资源的句子数量
  974. */
  975. public static function sentCanReadCount($book,$para,$start,$end,$userUuid=null){
  976. $sentId = "{$book}-{$para}-{$start}-{$end}";
  977. $hKey = "/sentence/res-count/{$sentId}/";
  978. if($userUuid){
  979. $key = $userUuid;
  980. }else{
  981. $key = 'guest';
  982. }
  983. if(Redis::hExists($hKey,$key)){
  984. return json_decode(Redis::hGet($hKey,$key),true);
  985. }else{
  986. $channelCount = CorpusController::_sentCanReadCount($book,$para,$start,$end,$userUuid);
  987. Redis::hSet($hKey,$key,json_encode($channelCount));
  988. return $channelCount;
  989. }
  990. }
  991. private function markdownRender($input){
  992. }
  993. /**
  994. * Update the specified resource in storage.
  995. *
  996. * @param \Illuminate\Http\Request $request
  997. * @param \App\Models\Sentence $sentence
  998. * @return \Illuminate\Http\Response
  999. */
  1000. public function update(Request $request, Sentence $sentence)
  1001. {
  1002. //
  1003. }
  1004. /**
  1005. * Remove the specified resource from storage.
  1006. *
  1007. * @param \App\Models\Sentence $sentence
  1008. * @return \Illuminate\Http\Response
  1009. */
  1010. public function destroy(Sentence $sentence)
  1011. {
  1012. //
  1013. }
  1014. }