CorpusController.php 40 KB

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