CorpusController.php 42 KB

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