Forráskód Böngészése

Merge branch 'laravel' into laravel

visuddhinanda 3 éve
szülő
commit
a1dbc7ad78

+ 66 - 0
app/Console/Commands/TestRedis.php

@@ -0,0 +1,66 @@
+<?php
+
+namespace App\Console\Commands;
+
+use Illuminate\Console\Command;
+use Illuminate\Support\Facades\Redis;
+use Illuminate\Support\Facades\Cache;
+
+class TestRedis extends Command
+{
+    /**
+     * The name and signature of the console command.
+     *
+     * @var string
+     */
+    protected $signature = 'test:redis';
+
+    /**
+     * The console command description.
+     *
+     * @var string
+     */
+    protected $description = 'testing redis';
+
+    /**
+     * Create a new command instance.
+     *
+     * @return void
+     */
+    public function __construct()
+    {
+        parent::__construct();
+    }
+
+    /**
+     * Execute the console command.
+     *
+     * @return int
+     */
+    public function handle()
+    {
+		$this->info("test redis");
+		Redis::set("test-redis",'this is a test');
+		$this->info("redis get:".Redis::get("test-redis"));
+
+		Redis::hSet("test-redis-hash",'hash','this is a test hash');
+		$this->info("redis hash get:".Redis::hGet("test-redis-hash",'hash'));
+
+		$this->info("test cache");
+		Cache::put('cache-key','cache value',10);
+		$this->info('catche test: ',Cache::get('cache-key'));
+		cache(["cache-key-2"=>'cache value 2']);
+		$this->info('cache() test',cache("cache-key-2"));
+		$value = Cache::get('cache-key-3',function(){
+			return 'cache-value-3';
+		});
+		if(Cache::has('cache-key-3')){
+			$this->info("cache-key-3 exist");
+		}else{
+			$this->info("cache-key-3 no");
+		}
+
+
+        return 0;
+    }
+}

+ 17 - 32
app/Http/Controllers/SentPrController.php

@@ -70,7 +70,6 @@ class SentPrController extends Controller
 			$new->save();			
 		}
 
-		
 		$robotMessageOk=false;
 		$webHookMessage="";
 		if(app()->isLocal()==false)
@@ -91,22 +90,20 @@ class SentPrController extends Controller
 			book65 par:829-1306
 			book67 par:759-1152
 			*/
-			$userinfo = new \UserInfo();
 
-			$username = $userinfo->getName($user_uid)['nickname'];
-			$palitext = PaliSentence::where('book',$data['book'])
-									->where('paragraph',$data['para'])
-									->where('word_begin',$data['begin'])
-									->where('word_end',$data['end'])
-									->value('text');
-			$palitext = mb_substr($palitext,0,20,"UTF-8");
-			$sent_num = $data['book']."-".$data['para']."-".$data['begin']."-".$data['end'];
-			$prtext = mb_substr($data['text'],0,140,"UTF-8");
-			$link = "https://www-hk.wikipali.org/app/article/index.php?view=para&book={$data['book']}&par={$data['para']}&begin={$data['begin']}&end={$data['end']}&mode=edit";
-			Log::info("palitext:{$palitext} prtext = {$prtext} link={$link}");
-			//$palitext = str_replace("{","**",$palitext);
-			//$palitext = str_replace("}","**",$palitext);
-					if(($data['book']==65 && $data['para']>=829 && $data['para']<=1306) || ($data['book']== 67 && $data['para'] >= 759 && $data['para'] <= 1152)){
+			if(($data['book']==65 && $data['para']>=829 && $data['para']<=1306) || ($data['book']== 67 && $data['para'] >= 759 && $data['para'] <= 1152)){
+				$userinfo = new \UserInfo();
+
+				$username = $userinfo->getName($user_uid)['nickname'];
+				$palitext = PaliSentence::where('book',$data['book'])
+										->where('paragraph',$data['para'])
+										->where('word_begin',$data['begin'])
+										->where('word_end',$data['end'])
+										->value('text');
+				$palitext = mb_substr($palitext,0,20,"UTF-8");
+				$prtext = mb_substr($data['text'],0,20,"UTF-8");
+				$link = "https://www-hk.wikipali.org/app/article/index.php?view=para&book={$data['book']}&par={$data['para']}&begin={$data['begin']}&end={$data['end']}&channel={$data['channel']}&mode=edit";
+				Log::info("palitext:{$palitext} prtext = {$prtext} link={$link}");
 				switch ($data['channel']) {
 					//测试
 					//case '3b0cb0aa-ea88-4ce5-b67d-00a3e76220cc':
@@ -134,23 +131,11 @@ class SentPrController extends Controller
 						break;
 				}		
 				$url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=25dbd74f-c89c-40e5-8cbc-48b1ef7710b8";
-				/*
-				$param = [
-				"actionCard"=> [
-					"title"=> "修改建议", 
-					"text"=> " wikipali: 来自{$_COOKIE['user_uid']}的修改建议:{$data['text']}", 
-					"btnOrientation"=> "0", 
-					"singleTitle" => "详情",
-					"singleURL"=>"https://staging.wikipali.org/app/article/index.php?view=para&book={$data['book']}&par={$data['para']}&channal={$data['channel']}&display=sent&mode=edit"
-				], 
-				"msgtype"=>"actionCard"
-				];
-				*/
 				$param = [
-					"msgtype"=>"markdown",
-					"markdown"=> [
-						"content"=> $strMessage, 
-					], 
+						"msgtype"=>"markdown",
+						"markdown"=> [
+							"content"=> $strMessage, 
+						], 
 					];
 				Log::info("message:{$strMessage}");
 				if(!empty($strMessage)){

+ 329 - 0
app/Http/Controllers/UserDictController.php

@@ -0,0 +1,329 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use App\Models\UserDict;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Redis;
+use Illuminate\Support\Facades\Log;
+
+class UserDictController extends Controller
+{
+    /**
+     * Display a listing of the resource.
+     *
+     * @return \Illuminate\Http\Response
+     */
+    public function index(Request $request)
+    {
+        //
+		$result=false;
+		$indexCol = ['id','word','type','grammar','mean','factors','confidence','updated_at','creator_id'];
+		switch ($request->get('view')) {
+			case 'user':
+				# code...
+				$table = UserDict::select($indexCol)
+									->where('creator_id', $_COOKIE["user_id"])
+									->where('source', '<>', "_SYS_USER_WBW_");
+				if(isset($_GET["search"])){
+					$table->where('word', 'like', $_GET["search"]."%");
+				}
+				if(isset($_GET["order"]) && isset($_GET["dir"])){
+					$table->orderBy($_GET["order"],$_GET["dir"]);
+				}else{
+					$table->orderBy('updated_at','desc');
+				}
+				$count = $table->count();
+				if(isset($_GET["limit"])){
+					$offset = 0;
+					if(isset($_GET["offset"])){
+						$offset = $_GET["offset"];
+					}
+					$table->skip($offset)->take($_GET["limit"]);
+				}			
+				$result = $table->get();
+				break;
+			case 'word':
+				$result = UserDict::select($indexCol)
+									->where('word', $_GET["word"])
+									->orderBy('created_at','desc')
+									->get();				
+				break;
+			default:
+				# code...
+				break;
+		}
+		if($result){
+			return $this->ok(["rows"=>$result,"count"=>$count]);
+		}else{
+			return $this->error("没有查询到数据");
+		}
+    }
+
+    /**
+     * Store a newly created resource in storage.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @return \Illuminate\Http\Response
+     */
+    public function store(Request $request)
+    {
+        //
+		if(!isset($_COOKIE["user_id"])){
+			$this->error("not login");
+		}
+        $snowflake = new SnowFlakeId();
+
+		$_data = json_decode($_POST["data"],true);
+		switch($request->get('view')){
+			case "wbw":
+				#查询用户重复的数据
+				$iOk = 0;
+				$updateOk=0;
+				foreach ($_data as $key => $word) {
+					# code...
+					$isDoesntExist = UserDict::where('creator_id', $_COOKIE["user_id"])
+										->where('word',$word["word"])
+										->where('type',$word["type"])
+										->where('grammar',$word["grammar"])
+										->where('parent',$word["parent"])
+										->where('mean',$word["mean"])
+										->where('factors',$word["factors"])
+										->where('factormean',$word["factormean"])
+										->where('source','_USER_WBW_')
+										->doesntExist();
+					
+					if($isDoesntExist){
+						#不存在插入数据
+						$word["id"]=app('snowflake')->id();
+						$word["source"]='_USER_WBW_';
+						$word["create_time"]=mTime();
+						$word["creator_id"]=$_COOKIE["user_id"];
+						$id = UserDict::insert($word);
+						$updateOk = $this->update_sys_wbw($word);
+						$this->update_redis($word);
+						$iOk++;
+					}
+				}
+				$this->ok([$iOk,$updateOk]);
+				break;
+			case "dict":
+				break;
+		}
+    }
+
+    /**
+     * Display the specified resource.
+     *
+     * @param  int  $id
+     * @return \Illuminate\Http\Response
+     */
+    public function show($id)
+    {
+        //
+		$result = UserDict::find($id);
+		if($result){
+			$this->ok($result);
+		}else{
+			$this->error("没有查询到数据");
+		}
+    }
+
+    /**
+     * Update the specified resource in storage.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @param  int  $id
+     * @return \Illuminate\Http\Response
+     */
+    public function update(Request $request, $id)
+    {
+        //
+		$newData = $request->all();
+		$result = UserDict::where('id', $id)
+				->update($newData);
+		if($result){
+			$updateOk = $this->update_sys_wbw($newData);
+			$this->update_redis($newData);
+			$this->ok([$result,$updateOk]);
+		}else{
+		$this->error("没有查询到数据");
+		}
+    }
+
+    /**
+     * Remove the specified resource from storage.
+     * @param  \Illuminate\Http\Request  $request
+     * @param  int  $id
+     * @return \Illuminate\Http\Response
+     */
+    public function destroy(Request $request,$id)
+    {
+        //
+		Log::info("userDictController->destroy start");
+		Log::info("userDictController->destroy id= {$id}");
+		$arrId = json_decode($request->get("id"),true) ;
+		$count = 0;
+		foreach ($arrId as $key => $id) {
+			# 找到对应数据
+			$data = UserDict::find($id);
+			//查看是否有权限删除
+			if($data->creator_id == $_COOKIE["user_id"]){
+				$result = UserDict::where('id', $id)
+								->delete();
+				$count += $result;
+				$updateOk = $this->update_sys_wbw($data);
+				$this->update_redis($data);
+			}
+		}
+		return $this->ok([$count,$updateOk]);
+    }
+	public function delete(Request $request){
+		Log::info("userDictController->destroy start");
+		$arrId = json_decode($request->get("id"),true) ;
+		Log::info("id=".$request->get("id"));
+		$count = 0;
+		$updateOk = false;
+		foreach ($arrId as $key => $id) {
+			# 找到对应数据
+			$data = UserDict::where('id',$id)->first();
+			Log::info('creator_id:'.$data->creator_id);
+			$param = [
+				"id"=>$id,
+				'creator_id'=>$_COOKIE["user_id"]
+			];
+			Log::info($param);
+			$del = UserDict::where($param)->delete();
+			$count += $del;
+			$updateOk = $this->update_sys_wbw($data);
+			$this->update_redis($data);
+
+		}
+		Log::info("delete:".$count);
+		return $this->ok(['deleted'=>$count]);
+	}
+
+	/*
+	更新系统wbw汇总表
+	*/
+	private function update_sys_wbw($data){
+
+		#查询用户重复的数据
+		$count = UserDict::where('word',$data["word"])
+		->where('type',$data["type"])
+		->where('grammar',$data["grammar"])
+		->where('parent',$data["parent"])
+		->where('mean',$data["mean"])
+		->where('factors',$data["factors"])
+		->where('factormean',$data["factormean"])
+		->where('source','_USER_WBW_')
+		->count();
+
+		if($count==0){
+            # 没有任何用户有这个数据
+			#删除数据
+			$result = UserDict::where('word',$data["word"])
+			->where('type',$data["type"])
+			->where('grammar',$data["grammar"])
+			->where('parent',$data["parent"])
+			->where('mean',$data["mean"])
+			->where('factors',$data["factors"])
+			->where('factormean',$data["factormean"])
+			->where('source','_SYS_USER_WBW_')
+			->delete();
+			return($result);
+
+		}else{
+            #更新或新增
+			#查询最早上传这个数据的用户
+			$creator_id = UserDict::where('word',$data["word"])
+							->where('type',$data["type"])
+							->where('grammar',$data["grammar"])
+							->where('parent',$data["parent"])
+							->where('mean',$data["mean"])
+							->where('factors',$data["factors"])
+							->where('factormean',$data["factormean"])
+							->where('source','_USER_WBW_')
+							->orderby("created_at",'asc')
+							->value("creator_id");
+
+            $count = UserDict::where('word',$data["word"])
+                        ->where('type',$data["type"])
+                        ->where('grammar',$data["grammar"])
+                        ->where('parent',$data["parent"])
+                        ->where('mean',$data["mean"])
+                        ->where('factors',$data["factors"])
+                        ->where('factormean',$data["factormean"])
+                        ->where('source','_SYS_USER_WBW_')
+                        ->count();
+            if($count==0){
+                #系统字典没有 新增
+                $result = UserDict::insert(
+				[
+                    'id' =>$snowflake->id(),
+					'word'=>$data["word"],
+					'type'=>$data["type"],
+					'grammar'=>$data["grammar"],
+					'parent'=>$data["parent"],
+					'mean'=>$data["mean"],
+					'factors'=>$data["factors"],
+					'factormean'=>$data["factormean"],
+					'source'=>"_SYS_USER_WBW_",
+                    'creator_id' => $creator_id,
+					'ref_counter' => 1,
+                    "create_time"=>time()*1000
+                    ]);
+            }else{
+                #有,更新
+                $result = UserDict::where('word',$data["word"])
+                        ->where('type',$data["type"])
+                        ->where('grammar',$data["grammar"])
+                        ->where('parent',$data["parent"])
+                        ->where('mean',$data["mean"])
+                        ->where('factors',$data["factors"])
+                        ->where('factormean',$data["factormean"])
+                        ->where('source','_SYS_USER_WBW_')
+                        ->update(
+                    [
+                        'creator_id'=>$creator_id,
+                        'ref_counter'=>$count
+                    ]);
+            }
+			return($result);
+		}
+	}
+
+	private function update_redis($word){
+		#更新 redis
+
+		//if ($this->redis != false) 
+		{
+			{
+				$Fetch = UserDict::where(['word'=>$word['word'],"source"=>"_SYS_USER_WBW_"])->get();
+				$redisWord=array();
+				foreach ($Fetch as  $one) {
+					# code...
+					$redisWord[] = array(
+									$one["id"],
+									$one["word"],
+									$one["type"],
+									$one["grammar"],
+									$one["parent"],
+									$one["mean"],
+									$one["note"],
+									$one["factors"],
+									$one["factormean"],
+									$one["status"],
+									$one["confidence"],
+									$one["creator_id"],
+									$one["source"],
+									$one["language"]
+									);
+				}
+				Redis::hSet("dict://user",$word['word'],json_encode($redisWord,JSON_UNESCAPED_UNICODE));			
+			}
+		}
+		#更新redis结束
+	}
+
+}

+ 3 - 0
app/Models/UserDict.php

@@ -8,4 +8,7 @@ use Illuminate\Database\Eloquent\Model;
 class UserDict extends Model
 {
     use HasFactory;
+	protected $casts = [
+		'id' => 'string'
+	];
 }

+ 22 - 12
public/app/udict/my_dict_list.js

@@ -76,7 +76,7 @@ const grid = new gridjs.Grid({
       	}
 	],
 	server: {
-		url: '../api/user_dicts.php?op=index&view=user',
+		url: '/api/v2/userdict?view=user',
 		then: data => data.data.rows.map(card => [null,card.id,card.word, card.type, card.grammar, card.mean, card.factors, card.confidence, card.updated_at,null]),
 		total: data => data.data.count
 	  },
@@ -101,18 +101,28 @@ const grid = new gridjs.Grid({
 document.querySelector("#to_recycle").onclick = function(){
 	if(_rowSelected.length>0){
 		if(confirm(`删除${_rowSelected.length}个单词,此操作不能恢复。`)){
-			$.getJSON("../api/user_dicts.php",
-			{
-				op:'delete',
+			let deleteId = JSON.stringify({
 				id:JSON.stringify(_rowSelected)
-			},
-			function(data){
-				if(data.ok){
-					grid.forceRender();
-					alert(`delete ok `);
-				}
-			});			
+			});
+			console.log("delete id:",deleteId);
+		fetch('/api/v2/userdict',{
+				method: 'DELETE',
+				credentials: 'include',
+				headers: {
+					'Content-Type': 'application/json'
+				},
+				body: deleteId
+			})
+		  .then(response => response.json())
+		  .then(function(data){
+			  console.log(data);
+			  if(data.ok){
+				_rowSelected = new Array();
+				grid.forceRender();
+				alert(`delete ok `+data.data.deleted);
+			}
+		  });
+		
 		}
-
 	}
 }

+ 3 - 0
routes/api.php

@@ -14,6 +14,7 @@ use App\Http\Controllers\LikeController;
 use App\Http\Controllers\SentHistoryController;
 use App\Http\Controllers\PaliTextController;
 use App\Http\Controllers\ChannelController;
+use App\Http\Controllers\UserDictController;
 
 
 /*
@@ -45,5 +46,7 @@ Route::group(['prefix' => 'v2'],function(){
     Route::apiResource('sent_history',SentHistoryController::class);
     Route::apiResource('palitext',PaliTextController::class);
     Route::apiResource('channel',ChannelController::class);
+    Route::delete('userdict', [UserDictController::class, 'delete']);
+    Route::apiResource('userdict',UserDictController::class);
 
 });