CorpusController.php 41 KB

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