CorpusController.php 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  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. //输出段落起始
  557. if(!empty($currPara)){
  558. $content[] = '</MdTpl>';
  559. }
  560. $markProps = base64_encode(\json_encode([
  561. 'book'=>$arrSentId[0],
  562. 'para'=>$arrSentId[1],
  563. 'channels'=>$channelsId,
  564. 'sentences'=>$sentInPara,
  565. ])) ;
  566. $content[] = "<MdTpl tpl='para-shell' props='{$markProps}' >";
  567. }
  568. }
  569. $sent = $this->newSent($arrSentId[0],$arrSentId[1],$arrSentId[2],$arrSentId[3]);
  570. foreach ($indexChannel as $channelId => $info) {
  571. # code...
  572. $sid = "{$currSentId}_{$channelId}";
  573. if(isset($info->studio)){
  574. $studioInfo = $info->studio;
  575. }else{
  576. $studioInfo = null;
  577. }
  578. $newSent = [
  579. "content"=>"",
  580. "html"=> "",
  581. "book"=> $arrSentId[0],
  582. "para"=> $arrSentId[1],
  583. "wordStart"=> $arrSentId[2],
  584. "wordEnd"=> $arrSentId[3],
  585. "channel"=> [
  586. "name"=>$info->name,
  587. "type"=>$info->type,
  588. "id"=> $info->uid,
  589. ],
  590. "studio" => $studioInfo,
  591. "updateAt"=> "",
  592. "suggestionCount" => SuggestionApi::getCountBySent($arrSentId[0],$arrSentId[1],$arrSentId[2],$arrSentId[3],$channelId),
  593. ];
  594. $row = Arr::first($record,function($value,$key) use($sid){
  595. return $value->sid===$sid;
  596. });
  597. if($row){
  598. $newSent['id'] = $row->uid;
  599. $newSent['content'] = $row->content;
  600. $newSent['contentType'] = $row->content_type;
  601. $newSent['html'] = '';
  602. $newSent["editor"]=UserApi::getByUuid($row->editor_uid);
  603. /**
  604. * TODO 刷库改数据
  605. * 旧版api没有更新updated_at所以造成旧版的数据updated_at数据比modify_time 要晚
  606. */
  607. $newSent['updateAt'] = $row->updated_at; //
  608. $newSent['updateAt'] = date("Y-m-d H:i:s.",$row->modify_time/1000).($row->modify_time%1000)." UTC";
  609. $newSent['createdAt'] = $row->created_at;
  610. if($mode !== "read"){
  611. if(isset($row->acceptor_uid) && !empty($row->acceptor_uid)){
  612. $newSent["acceptor"]=UserApi::getByUuid($row->acceptor_uid);
  613. $newSent["prEditAt"]=$row->pr_edit_at;
  614. }
  615. }
  616. switch ($info->type) {
  617. case 'wbw':
  618. case 'original':
  619. //
  620. // 在编辑模式下。
  621. // 如果是原文,查看是否有逐词解析数据,
  622. // 有的话优先显示。
  623. // 阅读模式直接显示html原文
  624. // 传过来的数据一定有一个原文channel
  625. //
  626. if($mode !== "read" && $row->content_type==='json'){
  627. $newSent['channel']['type'] = "wbw";
  628. if(isset($this->wbwChannels[0])){
  629. $newSent['channel']['name'] = $indexChannel[$this->wbwChannels[0]]->name;
  630. $newSent['channel']['id'] = $this->wbwChannels[0];
  631. //存在一个translation channel
  632. //尝试查找逐词解析数据。找到,替换现有数据
  633. $wbwData = $this->getWbw($arrSentId[0],$arrSentId[1],$arrSentId[2],$arrSentId[3],
  634. $this->wbwChannels[0]);
  635. if($wbwData){
  636. $newSent['content'] = $wbwData;
  637. $newSent['contentType'] = 'json';
  638. $newSent['html'] = "";
  639. }
  640. }
  641. }else{
  642. $newSent['content'] = "";
  643. //$newSent['html'] = $row->content;
  644. $newSent['html'] = MdRender::render($row->content,[$row->channel_uid],
  645. null,$mode,"translation",
  646. $row->content_type,$format);
  647. }
  648. break;
  649. case 'nissaya':
  650. $newSent['html'] = RedisClusters::remember("/sent/{$channelId}/{$currSentId}/{$format}",
  651. config('mint.cache.expire'),
  652. function() use($row,$mode,$format){
  653. return MdRender::render($row->content,[$row->channel_uid],
  654. null,$mode,"nissaya",
  655. $row->content_type,$format);
  656. });
  657. break;
  658. default:
  659. /**
  660. * 译文需要markdown渲染
  661. * 包涵术语的不用cache
  662. */
  663. if(strpos($row->content,'[[')===false){
  664. $newSent['html'] = MdRender::render($row->content,[$row->channel_uid],
  665. null,$mode,'translation',
  666. $row->content_type,$format);
  667. /*
  668. RedisClusters::remember("/sent/{$channelId}/{$currSentId}/{$format}",
  669. config('mint.cache.expire'),
  670. function() use($row,$mode,$format){
  671. return MdRender::render($row->content,[$row->channel_uid],
  672. null,$mode,'translation',
  673. $row->content_type,$format);
  674. });
  675. */
  676. }else{
  677. $mdRender = new MdRender(
  678. [
  679. 'debug'=>$this->debug,
  680. 'format'=>$format,
  681. 'mode'=>$mode,
  682. 'channelType'=>'translation',
  683. 'contentType'=>$row->content_type,
  684. ]);
  685. $newSent['html'] = $mdRender->convert($row->content,[$row->channel_uid]);
  686. }
  687. break;
  688. }
  689. }
  690. switch ($info->type) {
  691. case 'wbw':
  692. case 'original':
  693. array_push($sent["origin"],$newSent);
  694. break;
  695. default:
  696. array_push($sent["translation"],$newSent);
  697. break;
  698. }
  699. }
  700. if($onlyProps){
  701. return $sent;
  702. }
  703. $content = $this->pushSent($content,$sent,0,$mode);
  704. }
  705. if($paraMark){
  706. $content[] = '</MdTpl>';
  707. }
  708. $output = \implode("",$content);
  709. return "<div>{$output}</div>";
  710. }
  711. public function getWbw($book,$para,$start,$end,$channel){
  712. /**
  713. * 非阅读模式下。原文使用逐词解析数据。
  714. * 优先加载第一个translation channel 如果没有。加载默认逐词解析。
  715. */
  716. //获取逐词解析数据
  717. $wbwBlock = WbwBlock::where('channel_uid',$channel)
  718. ->where('book_id',$book)
  719. ->where('paragraph',$para)
  720. ->select('uid')
  721. ->first();
  722. if(!$wbwBlock){
  723. return false;
  724. }
  725. //找到逐词解析数据
  726. $wbwData = Wbw::where('block_uid',$wbwBlock->uid)
  727. ->whereBetween('wid',[$start,$end])
  728. ->select(['book_id','paragraph','wid','data','uid'])
  729. ->orderBy('wid')
  730. ->get();
  731. $wbwContent = [];
  732. foreach ($wbwData as $wbwrow) {
  733. $wbw = str_replace("&nbsp;",' ',$wbwrow->data);
  734. $wbw = str_replace("<br>",' ',$wbw);
  735. $xmlString = "<root>" . $wbw . "</root>";
  736. try{
  737. $xmlWord = simplexml_load_string($xmlString);
  738. }catch(Exception $e){
  739. continue;
  740. }
  741. $wordsList = $xmlWord->xpath('//word');
  742. foreach ($wordsList as $word) {
  743. $case = \str_replace(['#','.'],['$',''],$word->case->__toString());
  744. $case = \str_replace('$$','$',$case);
  745. $case = trim($case);
  746. $case = trim($case,"$");
  747. $wbwId = explode('-',$word->id->__toString());
  748. $wbwData = [
  749. 'uid'=>$wbwrow->uid,
  750. 'book'=>$wbwrow->book_id,
  751. 'para'=>$wbwrow->paragraph,
  752. 'sn'=> array_slice($wbwId,2),
  753. 'word'=>['value'=>$word->pali->__toString(),'status'=>0],
  754. 'real'=> ['value'=>$word->real->__toString(),'status'=>0],
  755. 'meaning'=> ['value'=>$word->mean->__toString() ,'status'=>0],
  756. 'type'=> ['value'=>$word->type->__toString(),'status'=>0],
  757. 'grammar'=> ['value'=>$word->gramma->__toString(),'status'=>0],
  758. 'case'=> ['value'=>$word->case->__toString(),'status'=>0],
  759. 'parent'=> ['value'=>$word->parent->__toString(),'status'=>0],
  760. 'style'=> ['value'=>$word->style->__toString(),'status'=>0],
  761. 'factors'=> ['value'=>$word->org->__toString(),'status'=>0],
  762. 'factorMeaning'=> ['value'=>$word->om->__toString(),'status'=>0],
  763. 'confidence'=> $word->cf->__toString(),
  764. 'hasComment'=>Discussion::where('res_id',$wbwrow->uid)->exists(),
  765. ];
  766. if(isset($word->parent2)){
  767. $wbwData['parent2']['value'] = $word->parent2->__toString();
  768. if(isset($word->parent2['status'])){
  769. $wbwData['parent2']['status'] = (int)$word->parent2['status'];
  770. }else{
  771. $wbwData['parent2']['status'] = 0;
  772. }
  773. }
  774. if(isset($word->pg)){
  775. $wbwData['grammar2']['value'] = $word->pg->__toString();
  776. if(isset($word->pg['status'])){
  777. $wbwData['grammar2']['status'] = (int)$word->pg['status'];
  778. }else{
  779. $wbwData['grammar2']['status'] = 0;
  780. }
  781. }
  782. if(isset($word->rela)){
  783. $wbwData['relation']['value'] = $word->rela->__toString();
  784. if(isset($word->rela['status'])){
  785. $wbwData['relation']['status'] = (int)$word->rela['status'];
  786. }else{
  787. $wbwData['relation']['status'] = 7;
  788. }
  789. }
  790. if(isset($word->bmt)){
  791. $wbwData['bookMarkText']['value'] = $word->bmt->__toString();
  792. if(isset($word->bmt['status'])){
  793. $wbwData['bookMarkText']['status'] = (int)$word->bmt['status'];
  794. }else{
  795. $wbwData['bookMarkText']['status'] = 7;
  796. }
  797. }
  798. if(isset($word->bmc)){
  799. $wbwData['bookMarkColor']['value'] = $word->bmc->__toString();
  800. if(isset($word->bmc['status'])){
  801. $wbwData['bookMarkColor']['status'] = (int)$word->bmc['status'];
  802. }else{
  803. $wbwData['bookMarkColor']['status'] = 7;
  804. }
  805. }
  806. if(isset($word->note)){
  807. $wbwData['note']['value'] = $word->note->__toString();
  808. if(isset($word->note['status'])){
  809. $wbwData['note']['status'] = (int)$word->note['status'];
  810. }else{
  811. $wbwData['note']['status'] = 7;
  812. }
  813. }
  814. if(isset($word->cf)){
  815. $wbwData['confidence'] = (float)$word->cf->__toString();
  816. }
  817. if(isset($word->attachments)){
  818. $wbwData['attachments'] = json_decode($word->attachments->__toString());
  819. }
  820. if(isset($word->pali['status'])){
  821. $wbwData['word']['status'] = (int)$word->pali['status'];
  822. }
  823. if(isset($word->real['status'])){
  824. $wbwData['real']['status'] = (int)$word->real['status'];
  825. }
  826. if(isset($word->mean['status'])){
  827. $wbwData['meaning']['status'] = (int)$word->mean['status'];
  828. }
  829. if(isset($word->type['status'])){
  830. $wbwData['type']['status'] = (int)$word->type['status'];
  831. }
  832. if(isset($word->gramma['status'])){
  833. $wbwData['grammar']['status'] = (int)$word->gramma['status'];
  834. }
  835. if(isset($word->case['status'])){
  836. $wbwData['case']['status'] = (int)$word->case['status'];
  837. }
  838. if(isset($word->parent['status'])){
  839. $wbwData['parent']['status'] = (int)$word->parent['status'];
  840. }
  841. if(isset($word->org['status'])){
  842. $wbwData['factors']['status'] = (int)$word->org['status'];
  843. }
  844. if(isset($word->om['status'])){
  845. $wbwData['factorMeaning']['status'] = (int)$word->om['status'];
  846. }
  847. $wbwContent[] = $wbwData;
  848. }
  849. }
  850. if(count($wbwContent)===0){
  851. return false;
  852. }
  853. return \json_encode($wbwContent,JSON_UNESCAPED_UNICODE);
  854. }
  855. /**
  856. * 将句子放进结果列表
  857. */
  858. private function pushSent($result,$sent,$level=0,$mode='read'){
  859. $sentProps = base64_encode(\json_encode($sent)) ;
  860. if($mode === 'read'){
  861. $sentWidget = "<MdTpl tpl='sentread' props='{$sentProps}' ></MdTpl>";
  862. }else{
  863. $sentWidget = "<MdTpl tpl='sentedit' props='{$sentProps}' ></MdTpl>";
  864. }
  865. //增加标题的html标记
  866. if($level>0){
  867. $sentWidget = "<h{$level}>".$sentWidget."</h{$level}>";
  868. }
  869. array_push($result,$sentWidget);
  870. return $result;
  871. }
  872. private function newSent($book,$para,$word_start,$word_end){
  873. $sent = [
  874. "id"=>"{$book}-{$para}-{$word_start}-{$word_end}",
  875. "book"=>$book,
  876. "para"=>$para,
  877. "wordStart"=>$word_start,
  878. "wordEnd"=>$word_end,
  879. "origin"=>[],
  880. "translation"=>[],
  881. ];
  882. if($book<1000){
  883. #生成channel 数量列表
  884. $sentId = "{$book}-{$para}-{$word_start}-{$word_end}";
  885. $channelCount = CorpusController::_sentCanReadCount($book,$para,$word_start,$word_end,$this->userUuid);
  886. $path = json_decode(PaliText::where('book',$book)->where('paragraph',$para)->value("path"),true);
  887. $sent["path"] = [];
  888. foreach ($path as $key => $value) {
  889. # code...
  890. $value['paliTitle'] = $value['title'];
  891. $sent["path"][] = $value;
  892. }
  893. $sent["tranNum"] = $channelCount['tranNum'];
  894. $sent["nissayaNum"] = $channelCount['nissayaNum'];
  895. $sent["commNum"] = $channelCount['commNum'];
  896. $sent["originNum"] = $channelCount['originNum'];
  897. $sent["simNum"] = $channelCount['simNum'];
  898. }
  899. return $sent;
  900. }
  901. public static function _sentCanReadCount($book,$para,$start,$end,$userUuid=null){
  902. $keyCanRead="/channel/can-read/";
  903. if($userUuid){
  904. $keyCanRead .= $userUuid;
  905. }else{
  906. $keyCanRead .= 'guest';
  907. }
  908. $channelCanRead = RedisClusters::remember($keyCanRead,
  909. config('mint.cache.expire'),
  910. function() use($userUuid){
  911. return ChannelApi::getCanReadByUser($userUuid);
  912. });
  913. $channels = Sentence::where('book_id',$book)
  914. ->where('paragraph',$para)
  915. ->where('word_start',$start)
  916. ->where('word_end',$end)
  917. ->where('strlen','<>',0)
  918. ->whereIn('channel_uid',$channelCanRead)
  919. ->select('channel_uid')
  920. ->groupBy('channel_uid')
  921. ->get();
  922. $channelList = [];
  923. foreach ($channels as $key => $value) {
  924. # code...
  925. if(Str::isUuid($value->channel_uid)){
  926. $channelList[] = $value->channel_uid;
  927. }
  928. }
  929. $simId = PaliSentence::where('book',$book)
  930. ->where('paragraph',$para)
  931. ->where('word_begin',$start)
  932. ->where('word_end',$end)
  933. ->value('id');
  934. if($simId){
  935. $output["simNum"]=SentSimIndex::where('sent_id',$simId)->value('count');
  936. }else{
  937. $output["simNum"]=0;
  938. }
  939. $channelInfo = Channel::whereIn("uid",$channelList)->select('type')->get();
  940. $output["tranNum"]=0;
  941. $output["nissayaNum"]=0;
  942. $output["commNum"]=0;
  943. $output["originNum"]=0;
  944. foreach ($channelInfo as $key => $value) {
  945. # code...
  946. switch($value->type){
  947. case "translation":
  948. $output["tranNum"]++;
  949. break;
  950. case "nissaya":
  951. $output["nissayaNum"]++;
  952. break;
  953. case "commentary":
  954. $output["commNum"]++;
  955. break;
  956. case "original":
  957. $output["originNum"]++;
  958. break;
  959. }
  960. }
  961. return $output;
  962. }
  963. /**
  964. * 获取某个句子的相关资源的句子数量
  965. */
  966. public static function sentCanReadCount($book,$para,$start,$end,$userUuid=null){
  967. $sentId = "{$book}-{$para}-{$start}-{$end}";
  968. $hKey = "/sentence/res-count/{$sentId}/";
  969. if($userUuid){
  970. $key = $userUuid;
  971. }else{
  972. $key = 'guest';
  973. }
  974. if(Redis::hExists($hKey,$key)){
  975. return json_decode(Redis::hGet($hKey,$key),true);
  976. }else{
  977. $channelCount = CorpusController::_sentCanReadCount($book,$para,$start,$end,$userUuid);
  978. Redis::hSet($hKey,$key,json_encode($channelCount));
  979. return $channelCount;
  980. }
  981. }
  982. private function markdownRender($input){
  983. }
  984. /**
  985. * Update the specified resource in storage.
  986. *
  987. * @param \Illuminate\Http\Request $request
  988. * @param \App\Models\Sentence $sentence
  989. * @return \Illuminate\Http\Response
  990. */
  991. public function update(Request $request, Sentence $sentence)
  992. {
  993. //
  994. }
  995. /**
  996. * Remove the specified resource from storage.
  997. *
  998. * @param \App\Models\Sentence $sentence
  999. * @return \Illuminate\Http\Response
  1000. */
  1001. public function destroy(Sentence $sentence)
  1002. {
  1003. //
  1004. }
  1005. }