DhammaTermController.php 24 KB

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