CorpusController.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  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. if(empty($chapter->toc)){
  367. $this->result['title'] = "unknown";
  368. }else{
  369. $this->result['title'] = $chapter->toc;
  370. $this->result['sub_title'] = $chapter->toc;
  371. $this->result['path'] = json_decode($chapter->path);
  372. }
  373. $paraFrom = $sentId[1];
  374. $paraTo = $sentId[1]+$chapter->chapter_len-1;
  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. if($between > 1){
  438. //有间隔
  439. $paraTo = $nextChapter - 1;
  440. }else{
  441. if($chapter->chapter_strlen>2000){
  442. if(count($toc)>0){
  443. //有子目录只输出标题和目录
  444. $paraTo = $paraFrom;
  445. }else{
  446. //没有子目录 全部输出
  447. }
  448. }else{
  449. //章节小。全部输出 不输出章节
  450. $toc = [];
  451. }
  452. }
  453. $pFrom = $request->get('from',$paraFrom);
  454. $pTo = $request->get('to',$paraTo);
  455. //根据句子的长度找到这次应该加载的句子
  456. $maxLen = 3000;
  457. $paliText = PaliText::select(['paragraph','lenght'])
  458. ->where('book',$sentId[0])
  459. ->whereBetween('paragraph',[$pFrom,$pTo])
  460. ->get();
  461. $sumLen = 0;
  462. $currTo = $pTo;
  463. foreach ($paliText as $para) {
  464. $sumLen += $para->lenght;
  465. if($sumLen > $maxLen){
  466. $currTo = $para->paragraph;
  467. break;
  468. }
  469. }
  470. $record = Sentence::select($this->selectCol)
  471. ->where('book_id',$sentId[0])
  472. ->whereBetween('paragraph',[$pFrom,$currTo])
  473. ->whereIn('channel_uid',$channels)
  474. ->orderBy('paragraph')
  475. ->orderBy('word_start')
  476. ->get();
  477. if(count($record) ===0){
  478. return $this->error("no data");
  479. }
  480. $this->result['content'] = $this->makeContent($record,$mode,$indexChannel,$indexedHeading,false,true);
  481. if(!$request->has('from')){
  482. //第一次才显示toc
  483. $this->result['toc'] = TocResource::collection($toc);
  484. }
  485. if($currTo < $pTo){
  486. $this->result['from'] = $currTo+1;
  487. $this->result['to'] = $pTo;
  488. $this->result['paraId'] = $id;
  489. $this->result['channels'] = $request->get('channels');
  490. $this->result['mode'] = $request->get('mode');
  491. }
  492. return $this->ok($this->result);
  493. }
  494. private function getChannelIndex($channels,$type=null){
  495. #获取channel索引表
  496. $channelInfo = Channel::whereIn("uid",$channels)
  497. ->select(['uid','type','name','owner_uid'])->get();
  498. $indexChannel = [];
  499. foreach ($channelInfo as $key => $value) {
  500. # code...
  501. if($type !== null && $value->type !== $type){
  502. continue;
  503. }
  504. $indexChannel[$value->uid] = $value;
  505. }
  506. foreach ($indexChannel as $uid => $value) {
  507. # 查询studio
  508. $indexChannel[$uid]->studio = StudioApi::getById($value->owner_uid);
  509. }
  510. return $indexChannel;
  511. }
  512. /**
  513. * 根据句子库数据生成文章内容
  514. * $record 句子数据
  515. * $mode read | edit | wbw
  516. * $indexChannel channel索引
  517. * $indexedHeading 标题索引 用于给段落加标题标签 <h1> ect.
  518. */
  519. private function makeContent($record,$mode,$indexChannel,$indexedHeading=[],$onlyProps=false,$paraMark=false,$format='react'){
  520. $content = [];
  521. $lastSent = "0-0";
  522. $sentCount = 0;
  523. $sent = [];
  524. $sent["origin"] = [];
  525. $sent["translation"] = [];
  526. //获取句子编号列表
  527. $sentList = [];
  528. foreach ($record as $key => $value) {
  529. $currSentId = "{$value->book_id}-{$value->paragraph}-{$value->word_start}-{$value->word_end}";
  530. $sentList[$currSentId]=[$value->book_id ,$value->paragraph,$value->word_start,$value->word_end];
  531. $value->sid = "{$currSentId}_{$value->channel_uid}";
  532. }
  533. $channelsId = array();
  534. $count = 0;
  535. foreach ($indexChannel as $channelId => $info){
  536. if($count>0){
  537. $channelsId[] = $channelId;
  538. }
  539. $count++;
  540. }
  541. //遍历列表查找每个句子的所有channel的数据,并填充
  542. $currPara = "";
  543. foreach ($sentList as $currSentId => $arrSentId) {
  544. $para = $arrSentId[0]."-".$arrSentId[1];
  545. if($currPara !== $para){
  546. $currPara = $para;
  547. //输出段落标记
  548. if($paraMark){
  549. $sentInPara = array();
  550. foreach ($sentList as $sentId => $sentParam) {
  551. if($sentParam[0]===$arrSentId[0] &&
  552. $sentParam[1]===$arrSentId[1]){
  553. $sentInPara[] = $sentId;
  554. }
  555. }
  556. $mark = [
  557. 'book'=>$arrSentId[0],
  558. 'para'=>$arrSentId[1],
  559. 'channels'=>$channelsId,
  560. 'sentences'=>$sentInPara,
  561. ];
  562. $markProps = base64_encode(\json_encode($mark)) ;
  563. $paraWidget = "<MdTpl tpl='para' props='{$markProps}' ></MdTpl>";
  564. $content[] = $paraWidget;
  565. }
  566. }
  567. $sent = $this->newSent($arrSentId[0],$arrSentId[1],$arrSentId[2],$arrSentId[3]);
  568. foreach ($indexChannel as $channelId => $info) {
  569. # code...
  570. $sid = "{$currSentId}_{$channelId}";
  571. if(isset($info->studio)){
  572. $studioInfo = $info->studio;
  573. }else{
  574. $studioInfo = null;
  575. }
  576. $newSent = [
  577. "content"=>"",
  578. "html"=> "",
  579. "book"=> $arrSentId[0],
  580. "para"=> $arrSentId[1],
  581. "wordStart"=> $arrSentId[2],
  582. "wordEnd"=> $arrSentId[3],
  583. "channel"=> [
  584. "name"=>$info->name,
  585. "type"=>$info->type,
  586. "id"=> $info->uid,
  587. ],
  588. "studio" => $studioInfo,
  589. "updateAt"=> "",
  590. "suggestionCount" => SuggestionApi::getCountBySent($arrSentId[0],$arrSentId[1],$arrSentId[2],$arrSentId[3],$channelId),
  591. ];
  592. $row = Arr::first($record,function($value,$key) use($sid){
  593. return $value->sid===$sid;
  594. });
  595. if($row){
  596. $newSent['id'] = $row->uid;
  597. $newSent['content'] = $row->content;
  598. $newSent['contentType'] = $row->content_type;
  599. $newSent['html'] = '';
  600. $newSent["editor"]=UserApi::getByUuid($row->editor_uid);
  601. /**
  602. * TODO 刷库改数据
  603. * 旧版api没有更新updated_at所以造成旧版的数据updated_at数据比modify_time 要晚
  604. */
  605. $newSent['updateAt'] = $row->updated_at; //
  606. $newSent['updateAt'] = date("Y-m-d H:i:s.",$row->modify_time/1000).($row->modify_time%1000)." UTC";
  607. $newSent['createdAt'] = $row->created_at;
  608. if($mode !== "read"){
  609. if(isset($row->acceptor_uid) && !empty($row->acceptor_uid)){
  610. $newSent["acceptor"]=UserApi::getByUuid($row->acceptor_uid);
  611. $newSent["prEditAt"]=$row->pr_edit_at;
  612. }
  613. }
  614. switch ($info->type) {
  615. case 'wbw':
  616. case 'original':
  617. //
  618. // 在编辑模式下。
  619. // 如果是原文,查看是否有逐词解析数据,
  620. // 有的话优先显示。
  621. // 阅读模式直接显示html原文
  622. // 传过来的数据一定有一个原文channel
  623. //
  624. if($mode !== "read"){
  625. if($info->content_type==='json'){
  626. $newSent['channel']['type'] = "wbw";
  627. if(isset($this->wbwChannels[0])){
  628. $newSent['channel']['name'] = $indexChannel[$this->wbwChannels[0]]->name;
  629. $newSent['channel']['id'] = $this->wbwChannels[0];
  630. //存在一个translation channel
  631. //尝试查找逐词解析数据。找到,替换现有数据
  632. $wbwData = $this->getWbw($arrSentId[0],$arrSentId[1],$arrSentId[2],$arrSentId[3],
  633. $this->wbwChannels[0]);
  634. if($wbwData){
  635. $newSent['content'] = $wbwData;
  636. $newSent['contentType'] = 'json';
  637. $newSent['html'] = "";
  638. }
  639. }
  640. }
  641. }else{
  642. $newSent['content'] = "";
  643. $newSent['html'] = $row->content;
  644. }
  645. break;
  646. case 'nissaya':
  647. $newSent['html'] = RedisClusters::remember("/sent/{$channelId}/{$currSentId}/{$format}",
  648. config('mint.cache.expire'),
  649. function() use($row,$mode,$format){
  650. return MdRender::render($row->content,[$row->channel_uid],
  651. null,$mode,"nissaya",
  652. $row->content_type,$format);
  653. });
  654. break;
  655. default:
  656. /**
  657. * 译文需要markdown渲染
  658. * 包涵术语的不用cache
  659. */
  660. if(strpos($row->content,'[[')===false){
  661. $newSent['html'] = MdRender::render($row->content,[$row->channel_uid],
  662. null,$mode,'translation',
  663. $row->content_type,$format);
  664. /*
  665. RedisClusters::remember("/sent/{$channelId}/{$currSentId}/{$format}",
  666. config('mint.cache.expire'),
  667. function() use($row,$mode,$format){
  668. return MdRender::render($row->content,[$row->channel_uid],
  669. null,$mode,'translation',
  670. $row->content_type,$format);
  671. });
  672. */
  673. }else{
  674. $mdRender = new MdRender(
  675. [
  676. 'debug'=>$this->debug,
  677. 'format'=>$format,
  678. 'mode'=>$mode,
  679. 'channelType'=>'translation',
  680. 'contentType'=>$row->content_type,
  681. ]);
  682. $newSent['html'] = $mdRender->convert($row->content,[$row->channel_uid]);
  683. }
  684. break;
  685. }
  686. }
  687. switch ($info->type) {
  688. case 'wbw':
  689. case 'original':
  690. array_push($sent["origin"],$newSent);
  691. break;
  692. default:
  693. array_push($sent["translation"],$newSent);
  694. break;
  695. }
  696. }
  697. if($onlyProps){
  698. return $sent;
  699. }
  700. $content = $this->pushSent($content,$sent,0,$mode);
  701. }
  702. $output = \implode("",$content);
  703. return "<div>{$output}</div>";
  704. }
  705. public function getWbw($book,$para,$start,$end,$channel){
  706. /**
  707. * 非阅读模式下。原文使用逐词解析数据。
  708. * 优先加载第一个translation channel 如果没有。加载默认逐词解析。
  709. */
  710. //获取逐词解析数据
  711. $wbwBlock = WbwBlock::where('channel_uid',$channel)
  712. ->where('book_id',$book)
  713. ->where('paragraph',$para)
  714. ->select('uid')
  715. ->first();
  716. if(!$wbwBlock){
  717. return false;
  718. }
  719. //找到逐词解析数据
  720. $wbwData = Wbw::where('block_uid',$wbwBlock->uid)
  721. ->whereBetween('wid',[$start,$end])
  722. ->select(['book_id','paragraph','wid','data','uid'])
  723. ->orderBy('wid')
  724. ->get();
  725. $wbwContent = [];
  726. foreach ($wbwData as $wbwrow) {
  727. $wbw = str_replace("&nbsp;",' ',$wbwrow->data);
  728. $wbw = str_replace("<br>",' ',$wbw);
  729. $xmlString = "<root>" . $wbw . "</root>";
  730. try{
  731. $xmlWord = simplexml_load_string($xmlString);
  732. }catch(Exception $e){
  733. continue;
  734. }
  735. $wordsList = $xmlWord->xpath('//word');
  736. foreach ($wordsList as $word) {
  737. $case = \str_replace(['#','.'],['$',''],$word->case->__toString());
  738. $case = \str_replace('$$','$',$case);
  739. $case = trim($case);
  740. $case = trim($case,"$");
  741. $wbwId = explode('-',$word->id->__toString());
  742. $wbwData = [
  743. 'uid'=>$wbwrow->uid,
  744. 'book'=>$wbwrow->book_id,
  745. 'para'=>$wbwrow->paragraph,
  746. 'sn'=> array_slice($wbwId,2),
  747. 'word'=>['value'=>$word->pali->__toString(),'status'=>0],
  748. 'real'=> ['value'=>$word->real->__toString(),'status'=>0],
  749. 'meaning'=> ['value'=>$word->mean->__toString() ,'status'=>0],
  750. 'type'=> ['value'=>$word->type->__toString(),'status'=>0],
  751. 'grammar'=> ['value'=>$word->gramma->__toString(),'status'=>0],
  752. 'case'=> ['value'=>$word->case->__toString(),'status'=>0],
  753. 'parent'=> ['value'=>$word->parent->__toString(),'status'=>0],
  754. 'style'=> ['value'=>$word->style->__toString(),'status'=>0],
  755. 'factors'=> ['value'=>$word->org->__toString(),'status'=>0],
  756. 'factorMeaning'=> ['value'=>$word->om->__toString(),'status'=>0],
  757. 'confidence'=> $word->cf->__toString(),
  758. 'hasComment'=>Discussion::where('res_id',$wbwrow->uid)->exists(),
  759. ];
  760. if(isset($word->parent2)){
  761. $wbwData['parent2']['value'] = $word->parent2->__toString();
  762. if(isset($word->parent2['status'])){
  763. $wbwData['parent2']['status'] = (int)$word->parent2['status'];
  764. }else{
  765. $wbwData['parent2']['status'] = 0;
  766. }
  767. }
  768. if(isset($word->pg)){
  769. $wbwData['grammar2']['value'] = $word->pg->__toString();
  770. if(isset($word->pg['status'])){
  771. $wbwData['grammar2']['status'] = (int)$word->pg['status'];
  772. }else{
  773. $wbwData['grammar2']['status'] = 0;
  774. }
  775. }
  776. if(isset($word->rela)){
  777. $wbwData['relation']['value'] = $word->rela->__toString();
  778. if(isset($word->rela['status'])){
  779. $wbwData['relation']['status'] = (int)$word->rela['status'];
  780. }else{
  781. $wbwData['relation']['status'] = 7;
  782. }
  783. }
  784. if(isset($word->bmt)){
  785. $wbwData['bookMarkText']['value'] = $word->bmt->__toString();
  786. if(isset($word->bmt['status'])){
  787. $wbwData['bookMarkText']['status'] = (int)$word->bmt['status'];
  788. }else{
  789. $wbwData['bookMarkText']['status'] = 7;
  790. }
  791. }
  792. if(isset($word->bmc)){
  793. $wbwData['bookMarkColor']['value'] = $word->bmc->__toString();
  794. if(isset($word->bmc['status'])){
  795. $wbwData['bookMarkColor']['status'] = (int)$word->bmc['status'];
  796. }else{
  797. $wbwData['bookMarkColor']['status'] = 7;
  798. }
  799. }
  800. if(isset($word->note)){
  801. $wbwData['note']['value'] = $word->note->__toString();
  802. if(isset($word->note['status'])){
  803. $wbwData['note']['status'] = (int)$word->note['status'];
  804. }else{
  805. $wbwData['note']['status'] = 7;
  806. }
  807. }
  808. if(isset($word->cf)){
  809. $wbwData['confidence'] = (float)$word->cf->__toString();
  810. }
  811. if(isset($word->attachments)){
  812. $wbwData['attachments'] = json_decode($word->attachments->__toString());
  813. }
  814. if(isset($word->pali['status'])){
  815. $wbwData['word']['status'] = (int)$word->pali['status'];
  816. }
  817. if(isset($word->real['status'])){
  818. $wbwData['real']['status'] = (int)$word->real['status'];
  819. }
  820. if(isset($word->mean['status'])){
  821. $wbwData['meaning']['status'] = (int)$word->mean['status'];
  822. }
  823. if(isset($word->type['status'])){
  824. $wbwData['type']['status'] = (int)$word->type['status'];
  825. }
  826. if(isset($word->gramma['status'])){
  827. $wbwData['grammar']['status'] = (int)$word->gramma['status'];
  828. }
  829. if(isset($word->case['status'])){
  830. $wbwData['case']['status'] = (int)$word->case['status'];
  831. }
  832. if(isset($word->parent['status'])){
  833. $wbwData['parent']['status'] = (int)$word->parent['status'];
  834. }
  835. if(isset($word->org['status'])){
  836. $wbwData['factors']['status'] = (int)$word->org['status'];
  837. }
  838. if(isset($word->om['status'])){
  839. $wbwData['factorMeaning']['status'] = (int)$word->om['status'];
  840. }
  841. $wbwContent[] = $wbwData;
  842. }
  843. }
  844. if(count($wbwContent)===0){
  845. return false;
  846. }
  847. return \json_encode($wbwContent,JSON_UNESCAPED_UNICODE);
  848. }
  849. /**
  850. * 将句子放进结果列表
  851. */
  852. private function pushSent($result,$sent,$level=0,$mode='read'){
  853. $sentProps = base64_encode(\json_encode($sent)) ;
  854. if($mode === 'read'){
  855. $sentWidget = "<MdTpl tpl='sentread' props='{$sentProps}' ></MdTpl>";
  856. }else{
  857. $sentWidget = "<MdTpl tpl='sentedit' props='{$sentProps}' ></MdTpl>";
  858. }
  859. //增加标题的html标记
  860. if($level>0){
  861. $sentWidget = "<h{$level}>".$sentWidget."</h{$level}>";
  862. }
  863. array_push($result,$sentWidget);
  864. return $result;
  865. }
  866. private function newSent($book,$para,$word_start,$word_end){
  867. $sent = [
  868. "id"=>"{$book}-{$para}-{$word_start}-{$word_end}",
  869. "book"=>$book,
  870. "para"=>$para,
  871. "wordStart"=>$word_start,
  872. "wordEnd"=>$word_end,
  873. "origin"=>[],
  874. "translation"=>[],
  875. ];
  876. if($book<1000){
  877. #生成channel 数量列表
  878. $sentId = "{$book}-{$para}-{$word_start}-{$word_end}";
  879. $channelCount = CorpusController::_sentCanReadCount($book,$para,$word_start,$word_end,$this->userUuid);
  880. $path = json_decode(PaliText::where('book',$book)->where('paragraph',$para)->value("path"),true);
  881. $sent["path"] = [];
  882. foreach ($path as $key => $value) {
  883. # code...
  884. $value['paliTitle'] = $value['title'];
  885. $sent["path"][] = $value;
  886. }
  887. $sent["tranNum"] = $channelCount['tranNum'];
  888. $sent["nissayaNum"] = $channelCount['nissayaNum'];
  889. $sent["commNum"] = $channelCount['commNum'];
  890. $sent["originNum"] = $channelCount['originNum'];
  891. $sent["simNum"] = $channelCount['simNum'];
  892. }
  893. return $sent;
  894. }
  895. public static function _sentCanReadCount($book,$para,$start,$end,$userUuid=null){
  896. $keyCanRead="/channel/can-read/";
  897. if($userUuid){
  898. $keyCanRead .= $userUuid;
  899. }else{
  900. $keyCanRead .= 'guest';
  901. }
  902. $channelCanRead = RedisClusters::remember($keyCanRead,
  903. config('mint.cache.expire'),
  904. function() use($userUuid){
  905. return ChannelApi::getCanReadByUser($userUuid);
  906. });
  907. $channels = Sentence::where('book_id',$book)
  908. ->where('paragraph',$para)
  909. ->where('word_start',$start)
  910. ->where('word_end',$end)
  911. ->where('strlen','<>',0)
  912. ->whereIn('channel_uid',$channelCanRead)
  913. ->select('channel_uid')
  914. ->groupBy('channel_uid')
  915. ->get();
  916. $channelList = [];
  917. foreach ($channels as $key => $value) {
  918. # code...
  919. if(Str::isUuid($value->channel_uid)){
  920. $channelList[] = $value->channel_uid;
  921. }
  922. }
  923. $simId = PaliSentence::where('book',$book)
  924. ->where('paragraph',$para)
  925. ->where('word_begin',$start)
  926. ->where('word_end',$end)
  927. ->value('id');
  928. if($simId){
  929. $output["simNum"]=SentSimIndex::where('sent_id',$simId)->value('count');
  930. }else{
  931. $output["simNum"]=0;
  932. }
  933. $channelInfo = Channel::whereIn("uid",$channelList)->select('type')->get();
  934. $output["tranNum"]=0;
  935. $output["nissayaNum"]=0;
  936. $output["commNum"]=0;
  937. $output["originNum"]=0;
  938. foreach ($channelInfo as $key => $value) {
  939. # code...
  940. switch($value->type){
  941. case "translation":
  942. $output["tranNum"]++;
  943. break;
  944. case "nissaya":
  945. $output["nissayaNum"]++;
  946. break;
  947. case "commentary":
  948. $output["commNum"]++;
  949. break;
  950. case "original":
  951. $output["originNum"]++;
  952. break;
  953. }
  954. }
  955. return $output;
  956. }
  957. /**
  958. * 获取某个句子的相关资源的句子数量
  959. */
  960. public static function sentCanReadCount($book,$para,$start,$end,$userUuid=null){
  961. $sentId = "{$book}-{$para}-{$start}-{$end}";
  962. $hKey = "/sentence/res-count/{$sentId}/";
  963. if($userUuid){
  964. $key = $userUuid;
  965. }else{
  966. $key = 'guest';
  967. }
  968. if(Redis::hExists($hKey,$key)){
  969. return json_decode(Redis::hGet($hKey,$key),true);
  970. }else{
  971. $channelCount = CorpusController::_sentCanReadCount($book,$para,$start,$end,$userUuid);
  972. Redis::hSet($hKey,$key,json_encode($channelCount));
  973. return $channelCount;
  974. }
  975. }
  976. private function markdownRender($input){
  977. }
  978. /**
  979. * Update the specified resource in storage.
  980. *
  981. * @param \Illuminate\Http\Request $request
  982. * @param \App\Models\Sentence $sentence
  983. * @return \Illuminate\Http\Response
  984. */
  985. public function update(Request $request, Sentence $sentence)
  986. {
  987. //
  988. }
  989. /**
  990. * Remove the specified resource from storage.
  991. *
  992. * @param \App\Models\Sentence $sentence
  993. * @return \Illuminate\Http\Response
  994. */
  995. public function destroy(Sentence $sentence)
  996. {
  997. //
  998. }
  999. }