DhammaTermController.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Models\DhammaTerm;
  4. use App\Models\Channel;
  5. use Illuminate\Http\Request;
  6. use Illuminate\Support\Facades\Cache;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Str;
  9. use App\Http\Api\AuthApi;
  10. use App\Http\Api\StudioApi;
  11. use App\Http\Api\ChannelApi;
  12. use App\Http\Api\ShareApi;
  13. use App\Tools\Tools;
  14. use App\Http\Resources\TermResource;
  15. use Illuminate\Support\Facades\App;
  16. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  17. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  18. use Illuminate\Support\Facades\Log;
  19. class DhammaTermController extends Controller
  20. {
  21. /**
  22. * Display a listing of the resource.
  23. *
  24. * @return \Illuminate\Http\Response
  25. */
  26. public function index(Request $request)
  27. {
  28. $result=false;
  29. $indexCol = ['id','guid','word','meaning',
  30. 'other_meaning','note','tag','language',
  31. 'channal','owner','editor_id',
  32. 'created_at','updated_at'];
  33. switch ($request->get('view')) {
  34. case 'create-by-channel':
  35. # 新建术语时。根据术语所在channel 给出新建术语所需数据。如语言,备选意思等。
  36. #获取channel信息
  37. $currChannel = Channel::where('uid',$request->get('channel'))->first();
  38. if(!$currChannel){
  39. return $this->error(__('auth.failed'));
  40. }
  41. #TODO 查询studio信息
  42. #获取同studio的channel列表
  43. $studioChannels = Channel::where('owner_uid',$currChannel->owner_uid)
  44. ->select(['name','uid'])
  45. ->get();
  46. #获取全网意思列表
  47. $meanings = DhammaTerm::where('word',$request->get('word'))
  48. ->where('language',$currChannel->lang)
  49. ->select(['meaning','other_meaning'])
  50. ->get();
  51. $meaningList=[];
  52. foreach ($meanings as $key => $value) {
  53. # code...
  54. $meaning1 = [$value->meaning];
  55. if(!empty($value->other_meaning)){
  56. $meaning2 = \explode(',',$value->other_meaning);
  57. $meaning1 = array_merge($meaning1,$meaning2);
  58. }
  59. foreach ($meaning1 as $key => $value) {
  60. # code...
  61. if(isset($meaningList[$value])){
  62. $meaningList[$value]++;
  63. }else{
  64. $meaningList[$value] = 1;
  65. }
  66. }
  67. }
  68. $meaningCount = [];
  69. foreach ($meaningList as $key => $value) {
  70. # code...
  71. $meaningCount[] = ['meaning'=>$key,'count'=>$value];
  72. }
  73. return $this->ok([
  74. "word"=>$request->get('word'),
  75. "meaningCount"=>$meaningCount,
  76. "studioChannels"=>$studioChannels,
  77. "language"=>$currChannel->lang,
  78. 'studio'=>StudioApi::getById($currChannel->owner_uid),
  79. ]);
  80. break;
  81. case 'studio':
  82. # 获取 studio 内所有 term
  83. $user = AuthApi::current($request);
  84. if(!$user){
  85. return $this->error(__('auth.failed'),[],401);
  86. }
  87. //判断当前用户是否有指定的studio的权限
  88. if($user['user_uid'] !== StudioApi::getIdByName($request->get('name'))){
  89. return $this->error(__('auth.failed'),[],403);
  90. }
  91. $table = DhammaTerm::select($indexCol)
  92. ->where('owner', $user["user_uid"]);
  93. break;
  94. case 'channel':
  95. # 获取 studio 内所有 term
  96. $user = AuthApi::current($request);
  97. if(!$user){
  98. return $this->error(__('auth.failed'));
  99. }
  100. //判断当前用户是否有指定的 channel 的权限
  101. $channel = Channel::find($request->get('id'));
  102. if($user['user_uid'] !== $channel->owner_uid ){
  103. //看是否为协作
  104. $power = ShareApi::getResPower($user['user_uid'],$request->get('id'));
  105. if($power === 0){
  106. return $this->error(__('auth.failed'),[],403);
  107. }
  108. }
  109. $table = DhammaTerm::select($indexCol)
  110. ->where('channal', $request->get('id'));
  111. break;
  112. case 'show':
  113. return $this->ok(DhammaTerm::find($request->get('id')));
  114. break;
  115. case 'user':
  116. # code...
  117. $userUid = $_COOKIE['user_uid'];
  118. $search = $request->get('search');
  119. $table = DhammaTerm::select($indexCol)
  120. ->where('owner', $userUid);
  121. break;
  122. case 'word':
  123. $table = DhammaTerm::select($indexCol)
  124. ->where('word', $request->get("word"));
  125. break;
  126. case 'hot-meaning':
  127. $key='term/hot_meaning';
  128. $value = Cache::get($key, function()use($request) {
  129. $hotMeaning=[];
  130. $words = DhammaTerm::select('word')
  131. ->where('language',$request->get("language"))
  132. ->groupby('word')
  133. ->get();
  134. foreach ($words as $key => $word) {
  135. # code...
  136. $result = DhammaTerm::select(DB::raw('count(*) as word_count, meaning'))
  137. ->where('language',$request->get("language"))
  138. ->where('word',$word['word'])
  139. ->groupby('meaning')
  140. ->orderby('word_count','desc')
  141. ->first();
  142. if($result){
  143. $hotMeaning[]=[
  144. 'word'=>$word['word'],
  145. 'meaning'=>$result['meaning'],
  146. 'language'=>$request->get("language"),
  147. 'owner'=>'',
  148. ];
  149. }
  150. }
  151. Cache::put($key, $hotMeaning, 3600);
  152. return $hotMeaning;
  153. }, env('CACHE_EXPIRE',3600*24));
  154. return $this->ok(["rows"=>$value,"count"=>count($value)]);
  155. break;
  156. default:
  157. # code...
  158. break;
  159. }
  160. $search = $request->get('search');
  161. if(!empty($search)){
  162. $table = $table->where(function($query) use($search){
  163. $query->where('word', 'like', $search."%")
  164. ->orWhere('word_en', 'like', $search."%")
  165. ->orWhere('meaning', 'like', "%".$search."%");
  166. });
  167. }
  168. $count = $table->count();
  169. $table = $table->orderBy($request->get('order','updated_at'),$request->get('dir','desc'));
  170. $table = $table->skip($request->get("offset",0))
  171. ->take($request->get('limit',1000));
  172. $result = $table->get();
  173. return $this->ok(["rows"=>TermResource::collection($result),"count"=>$count]);
  174. }
  175. /**
  176. * Store a newly created resource in storage.
  177. *
  178. * @param \Illuminate\Http\Request $request
  179. * @return \Illuminate\Http\Response
  180. */
  181. public function store(Request $request)
  182. {
  183. $user = AuthApi::current($request);
  184. if(!$user){
  185. return $this->error(__('auth.failed'));
  186. }
  187. $validated = $request->validate([
  188. 'word' => 'required',
  189. 'meaning' => 'required',
  190. 'language' => 'required'
  191. ]);
  192. #查询重复的
  193. /*
  194. 重复判定:
  195. 一个channel下面word+tag+language 唯一
  196. */
  197. $table = DhammaTerm::where('owner', $user["user_uid"])
  198. ->where('word',$request->get("word"))
  199. ->where('tag',$request->get("tag"));
  200. if($request->get("channel")){
  201. $isDoesntExist = $table->where('channel',$request->get("channel"))
  202. ->doesntExist();
  203. }else{
  204. $isDoesntExist = $table->where('language',$request->get("language"))
  205. ->doesntExist();
  206. }
  207. if($isDoesntExist){
  208. #不存在插入数据
  209. $term = new DhammaTerm;
  210. $term->id = app('snowflake')->id();
  211. $term->guid = Str::uuid();
  212. $term->word = $request->get("word");
  213. $term->word_en = Tools::getWordEn($request->get("word"));
  214. $term->meaning = $request->get("meaning");
  215. $term->other_meaning = $request->get("other_meaning");
  216. $term->note = $request->get("note");
  217. $term->tag = $request->get("tag");
  218. $term->channal = $request->get("channal");
  219. $term->language = $request->get("language");
  220. if($request->has("channal")){
  221. $channelInfo = ChannelApi::getById($request->get("channal"));
  222. if(!$channelInfo){
  223. return $this->error("channel id failed");
  224. }else{
  225. $term->owner = $channelInfo['studio_id'];
  226. $term->language = $channelInfo['lang'];
  227. }
  228. }else{
  229. if($request->has("studioId")){
  230. $studioId = $request->get("studioId");
  231. }else if($request->has("studioName")){
  232. $studioId = StudioApi::getIdByName($request->get("studioName"));
  233. }
  234. if(Str::isUuid($studioId)){
  235. $term->owner = $studioId;
  236. }else{
  237. return $this->error('not valid studioId');
  238. }
  239. }
  240. $term->editor_id = $user["user_id"];
  241. $term->create_time = time()*1000;
  242. $term->modify_time = time()*1000;
  243. $term->save();
  244. return $this->ok($term);
  245. }else{
  246. return $this->error("word existed",[],200);
  247. }
  248. }
  249. /**
  250. * Display the specified resource.
  251. *
  252. * @param string $id
  253. * @return \Illuminate\Http\Response
  254. */
  255. public function show(Request $request,$id)
  256. {
  257. //
  258. $result = DhammaTerm::where('guid', $id)->first();
  259. if($result){
  260. return $this->ok(new TermResource($result));
  261. }else{
  262. return $this->error("没有查询到数据");
  263. }
  264. }
  265. /**
  266. * Update the specified resource in storage.
  267. *
  268. * @param \Illuminate\Http\Request $request
  269. * @param \App\Models\DhammaTerm $dhammaTerm
  270. * @return \Illuminate\Http\Response
  271. */
  272. public function update(Request $request, string $id)
  273. {
  274. //
  275. $user = AuthApi::current($request);
  276. if(!$user){
  277. return $this->error(__('auth.failed'),[],401);
  278. }
  279. $dhammaTerm = DhammaTerm::find($id);
  280. if(!$dhammaTerm){
  281. return $this->error('404');
  282. }
  283. if(empty($dhammaTerm->channal)){
  284. //查看有没有studio权限
  285. if($user['user_uid'] !== $dhammaTerm->owner){
  286. return $this->error(__('auth.failed'),[403],403);
  287. }
  288. }else{
  289. //查看有没有channel权限
  290. $power = ShareApi::getResPower($user["user_uid"],$dhammaTerm->channal,2);
  291. if($power < 20){
  292. return $this->error(__('auth.failed'),[403],403);
  293. }
  294. }
  295. $dhammaTerm->word = $request->get("word");
  296. $dhammaTerm->word_en = Tools::getWordEn($request->get("word"));
  297. $dhammaTerm->meaning = $request->get("meaning");
  298. $dhammaTerm->other_meaning = $request->get("other_meaning");
  299. $dhammaTerm->note = $request->get("note");
  300. $dhammaTerm->tag = $request->get("tag");
  301. $dhammaTerm->channal = $request->get("channal");
  302. $dhammaTerm->language = $request->get("language");
  303. if($request->has("channal") && Str::isUuid($request->get("channal"))){
  304. $channelInfo = ChannelApi::getById($request->get("channal"));
  305. if(!$channelInfo){
  306. return $this->error("channel id failed");
  307. }else{
  308. $dhammaTerm->owner = $channelInfo['studio_id'];
  309. }
  310. }
  311. if($request->has("studioName")){
  312. $dhammaTerm->owner = StudioApi::getIdByName($request->get("studioName"));
  313. }else if($request->has("studioId")){
  314. $dhammaTerm->owner = $request->get("studioId");
  315. }
  316. $dhammaTerm->editor_id = $user["user_id"];
  317. $dhammaTerm->create_time = time()*1000;
  318. $dhammaTerm->modify_time = time()*1000;
  319. $dhammaTerm->save();
  320. return $this->ok($dhammaTerm);
  321. }
  322. /**
  323. * Remove the specified resource from storage.
  324. *
  325. * @param \App\Models\DhammaTerm $dhammaTerm
  326. * @return \Illuminate\Http\Response
  327. */
  328. public function destroy(DhammaTerm $dhammaTerm,Request $request)
  329. {
  330. /**
  331. * 一次删除多个单词
  332. */
  333. $user = AuthApi::current($request);
  334. if(!$user){
  335. return $this->error(__('auth.failed'));
  336. }
  337. $count = 0;
  338. if($request->has("uuid")){
  339. //查看是否有删除权限
  340. foreach ($request->get("id") as $key => $uuid) {
  341. $term = DhammaTerm::find($uuid);
  342. if($term->owner !== $user['user_uid']){
  343. if(!empty($term->channal)){
  344. //看是否为协作
  345. $power = ShareApi::getResPower($user['user_uid'],$term->channal);
  346. if($power < 20){
  347. continue;
  348. }
  349. }else{
  350. continue;
  351. }
  352. }
  353. $count += $term->delete();
  354. }
  355. }else{
  356. $arrId = json_decode($request->get("id"),true) ;
  357. foreach ($arrId as $key => $id) {
  358. # code...
  359. $result = DhammaTerm::where('id', $id)
  360. ->where('owner', $user['user_uid'])
  361. ->delete();
  362. if($result){
  363. $count++;
  364. }
  365. }
  366. }
  367. return $this->ok($count);
  368. }
  369. public function export(Request $request){
  370. $user = AuthApi::current($request);
  371. if(!$user){
  372. return $this->error(__('auth.failed'));
  373. }
  374. //TODO 判断是否有导出权限
  375. switch ($request->get("view")) {
  376. case 'channel':
  377. # code...
  378. $rows = DhammaTerm::where('channal',$request->get("id"))->cursor();
  379. break;
  380. case 'studio':
  381. # code...
  382. $studioId = StudioApi::getIdByName($request->get("name"));
  383. $rows = DhammaTerm::where('owner',$studioId)->cursor();
  384. break;
  385. default:
  386. $this->error('no view');
  387. break;
  388. }
  389. $spreadsheet = new Spreadsheet();
  390. $activeWorksheet = $spreadsheet->getActiveSheet();
  391. $activeWorksheet->setCellValue('A1', 'id');
  392. $activeWorksheet->setCellValue('B1', 'word');
  393. $activeWorksheet->setCellValue('C1', 'meaning');
  394. $activeWorksheet->setCellValue('D1', 'other_meaning');
  395. $activeWorksheet->setCellValue('E1', 'note');
  396. $activeWorksheet->setCellValue('F1', 'tag');
  397. $activeWorksheet->setCellValue('G1', 'language');
  398. $activeWorksheet->setCellValue('H1', 'channel_id');
  399. $currLine = 2;
  400. foreach ($rows as $key => $row) {
  401. # code...
  402. $activeWorksheet->setCellValue("A{$currLine}", $row->guid);
  403. $activeWorksheet->setCellValue("B{$currLine}", $row->word);
  404. $activeWorksheet->setCellValue("C{$currLine}", $row->meaning);
  405. $activeWorksheet->setCellValue("D{$currLine}", $row->other_meaning);
  406. $activeWorksheet->setCellValue("E{$currLine}", $row->note);
  407. $activeWorksheet->setCellValue("F{$currLine}", $row->tag);
  408. $activeWorksheet->setCellValue("G{$currLine}", $row->language);
  409. $activeWorksheet->setCellValue("H{$currLine}", $row->channal);
  410. $currLine++;
  411. }
  412. $writer = new Xlsx($spreadsheet);
  413. $fId = Str::uuid();
  414. $filename = storage_path("app/tmp/{$fId}");
  415. $writer->save($filename);
  416. Cache::put("download/tmp/{$fId}",file_get_contents($filename),300);
  417. unlink($filename);
  418. return $this->ok(['uuid'=>$fId,'filename'=>"term.xlsx",'type'=>"application/vnd.ms-excel"]);
  419. }
  420. public function import(Request $request){
  421. $user = AuthApi::current($request);
  422. if(!$user){
  423. return $this->error(__('auth.failed'));
  424. }
  425. /**
  426. * 判断是否有权限
  427. */
  428. switch ($request->get('view')) {
  429. case 'channel':
  430. # 向channel里面导入,忽略源数据的channel id 和 owner 都设置为这个channel 的
  431. $channel = ChannelApi::getById($request->get('id'));
  432. $owner_id = $channel['studio_id'];
  433. if($owner_id !== $user["user_uid"]){
  434. //判断是否为协作
  435. $power = ShareApi::getResPower($user["user_uid"],$request->get('id'));
  436. if($power<20){
  437. return $this->error(__('auth.failed'),[],403);
  438. }
  439. }
  440. $language = $channel['lang'];
  441. break;
  442. case 'studio':
  443. # 向 studio 里面导入,忽略源数据的 owner 但是要检测 channel id 是否有权限
  444. $owner_id = StudioApi::getIdByName($request->get('name'));
  445. if(!$owner_id){
  446. return $this->error('no studio name',[],403);
  447. }
  448. break;
  449. }
  450. $message = "";
  451. $filename = $request->get('filename');
  452. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
  453. $reader->setReadDataOnly(true);
  454. $spreadsheet = $reader->load($filename);
  455. $activeWorksheet = $spreadsheet->getActiveSheet();
  456. $currLine = 2;
  457. $countFail = 0;
  458. do {
  459. # code...
  460. $id = $activeWorksheet->getCell("A{$currLine}")->getValue();
  461. $word = $activeWorksheet->getCell("B{$currLine}")->getValue();
  462. $meaning = $activeWorksheet->getCell("C{$currLine}")->getValue();
  463. $other_meaning = $activeWorksheet->getCell("D{$currLine}")->getValue();
  464. $note = $activeWorksheet->getCell("E{$currLine}")->getValue();
  465. $tag = $activeWorksheet->getCell("F{$currLine}")->getValue();
  466. $language = $activeWorksheet->getCell("G{$currLine}")->getValue();
  467. $channel_id = $activeWorksheet->getCell("H{$currLine}")->getValue();
  468. $query = ['word'=>$word,'tag'=>$tag];
  469. $channelId = null;
  470. switch ($request->get('view')) {
  471. case 'channel':
  472. # 向channel里面导入,忽略源数据的channel id 和 owner 都设置为这个channel 的
  473. $query['channal'] = $request->get('id');
  474. $channelId = $request->get('id');
  475. break;
  476. case 'studio':
  477. # 向 studio 里面导入,忽略源数据的owner 但是要检测 channel id 是否有权限
  478. $query['owner'] = $owner_id;
  479. if(!empty($channel_id)){
  480. //有channel 数据,查看是否在studio中
  481. $channel = ChannelApi::getById($channel_id);
  482. if($channel === false){
  483. $message .= "没有查到版本信息:{$channel_id} - {$word}\n";
  484. $currLine++;
  485. $countFail++;
  486. continue 2;
  487. }
  488. if($owner_id != $channel['studio_id']){
  489. $message .= "版本不在studio中:{$channel_id} - {$word}\n";
  490. $currLine++;
  491. $countFail++;
  492. continue 2;
  493. }
  494. $query['channal'] = $channel_id;
  495. $channelId = $channel_id;
  496. }
  497. # code...
  498. break;
  499. }
  500. if(empty($id) && empty($word)){
  501. break;
  502. }
  503. //查询此id是否有旧数据
  504. if(!empty($id)){
  505. $oldRow = DhammaTerm::find($id);
  506. //TODO 有 id 无 word 删除数据
  507. if(empty($word)){
  508. //查看权限
  509. if($oldRow->owner !== $user['user_uid']){
  510. if(!empty($oldRow->channal)){
  511. //看是否为协作
  512. $power = ShareApi::getResPower($user['user_uid'],$oldRow->channal);
  513. if($power < 20){
  514. $message .= "无删除权限:{$id} - {$word}\n";
  515. $currLine++;
  516. $countFail++;
  517. continue;
  518. }
  519. }else{
  520. $message .= "无删除权限:{$id} - {$word}\n";
  521. $currLine++;
  522. $countFail++;
  523. continue;
  524. }
  525. }
  526. //删除
  527. $oldRow->delete();
  528. $currLine++;
  529. continue;
  530. }
  531. }else{
  532. $oldRow = null;
  533. }
  534. //查询是否跟已有数据重复
  535. $row = DhammaTerm::where($query)->first();
  536. if(!$row){
  537. //不重复
  538. if(isset($oldRow) && $oldRow){
  539. //找到旧的记录-修改旧数据
  540. $row = $oldRow;
  541. }else{
  542. //没找到旧的记录-新建
  543. $row = new DhammaTerm();
  544. $row->id = app('snowflake')->id();
  545. $row->guid = Str::uuid();
  546. $row->word = $word;
  547. $row->create_time = time()*1000;
  548. }
  549. }else{
  550. //重复-如果与旧的id不同,报错
  551. if(isset($oldRow) && $oldRow && $row->guid !== $id){
  552. $message .= "重复的数据:{$id} - {$word}\n";
  553. $currLine++;
  554. $countFail++;
  555. continue;
  556. }
  557. }
  558. $row->word = $word;
  559. $row->word_en = Tools::getWordEn($word);
  560. $row->meaning = $meaning;
  561. $row->other_meaning = $other_meaning;
  562. $row->note = $note;
  563. $row->tag = $tag;
  564. $row->language = $language;
  565. $row->channal = $channelId;
  566. $row->editor_id = $user['user_id'];
  567. $row->owner = $owner_id;
  568. $row->modify_time = time()*1000;
  569. $row->save();
  570. $currLine++;
  571. } while (true);
  572. return $this->ok(["success"=>$currLine-2-$countFail,'fail'=>($countFail)],$message);
  573. }
  574. }