CorpusController.php 41 KB

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