From 6d09d7170c99f8d16acdbcb0a2280ccab950c84c Mon Sep 17 00:00:00 2001
From: 554325746@qq.com <554325746@qq.com>
Date: 星期六, 01 八月 2020 10:33:00 +0800
Subject: [PATCH] add systemd service

---
 esutil/EsClient.go |  481 ++++++++++++++++++++++++----------------------------
 1 files changed, 223 insertions(+), 258 deletions(-)

diff --git a/esutil/EsClient.go b/esutil/EsClient.go
index 38f4405..f0239fc 100644
--- a/esutil/EsClient.go
+++ b/esutil/EsClient.go
@@ -12,12 +12,40 @@
 	"strings"
 	"time"
 
-	log "github.com/long/test/log"
+	log "andriodServer/log"
 )
 
-func GetEsDataReq(url string, parama string, picurl string, isSource bool) (error, map[string]interface{}) {
-	//log.Log.Infoln("es 鏌ヨ璇锋眰璺緞" + url) //  閰嶇疆淇℃伅 鑾峰彇
-	req, err := http.NewRequest("POST", url, strings.NewReader(parama))
+func EsReq(method string, url string, parama []byte) (buf []byte, err error) {
+	//defer elapsed("page")()
+	timeout := time.Duration(100 * time.Second)
+	client := http.Client{
+		Timeout: timeout,
+	}
+	request, err := http.NewRequest(method, url, bytes.NewBuffer(parama))
+	request.Header.Set("Content-type", "application/json")
+
+	if err != nil {
+		fmt.Println("build request fail !")
+		return nil, err
+	}
+
+	resp, err := client.Do(request)
+	if err != nil {
+		fmt.Println("request error: ", err)
+		return nil, err
+	}
+
+	defer resp.Body.Close()
+	body, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		fmt.Println(err)
+		return nil, err
+	}
+	return body, nil
+}
+
+func GetEsDataReq(url string, param string, isSource bool) (error, map[string]interface{}) {
+	req, err := http.NewRequest("POST", url, strings.NewReader(param))
 
 	if err != nil {
 		return err, nil
@@ -29,7 +57,7 @@
 	resp, err := client.Do(req)
 
 	if err != nil {
-		return err, nil
+        return err, nil
 	}
 
 	defer resp.Body.Close()
@@ -49,7 +77,7 @@
 	}
 	// 鏄惁闇�瑕� 瑙f瀽 es 杩斿洖鐨� source
 	if isSource {
-		dat, ok := dat["hits"].(map[string]interface{})
+        dat, ok := dat["hits"].(map[string]interface{})
 		if !ok {
 			return errors.New("data is not type of  map[string]interface{}"), nil
 		}
@@ -58,67 +86,91 @@
 		data["total"] = dat["total"]
 		sources := []interface{}{}
 		for _, value := range dat["hits"].([]interface{}) {
+			d := make(map[string]interface{})
 			source, ok := value.(map[string]interface{})["_source"].(map[string]interface{})
 			if !ok {
 				return errors.New("value is not type of map[string]interface{}"), nil
 			}
 
-			source["id"] = value.(map[string]interface{})["_id"]
-
-			sdkType := source["sdkType"]
-			if sdkType != nil {
-				sdk, err := strconv.Atoi(sdkType.(string))
-				if err != nil {
-					return err, nil
+			d["id"] = value.(map[string]interface{})["_id"]
+			d["picDate"] = source["picDate"]
+			pmax, exist := source["picMaxUrl"]
+			if !exist {
+				continue
+			}
+			alarmRules, exist := source["alarmRules"]
+			if exist {
+				if alarmB,ae := json.Marshal(alarmRules);ae ==nil {
+					var alarmRArr []AlarmRule
+					if ae = json.Unmarshal(alarmB, &alarmRArr);ae ==nil && len(alarmRArr) >0 {
+						d["alarmLevel"] = alarmRArr[0].AlarmLevel
+					}
 				}
+			} else {
+				d["alarmLevel"] = ""
+			}
+			pmArr := pmax.([]interface{})
+			if len(pmArr) > 0 {
+				d["picMaxUrl"] = pmArr[0]
+			} else {
+				d["picMaxUrl"] = ""
+			}
+			d["picAddress"] = source["cameraAddr"]
 
-				source["sdkType"] = sdkTypeToValue(sdk)
+			tB, err := json.Marshal(source["targetInfo"])
+			if err != nil {
+			    log.Log.Infoln("err:", err)
+                continue
 			}
 
-			pmax, exist := source["picMaxUrl"].(string)
-			//fmt.Println("picMaxUrl: ",pmax)
-			if !exist {
-				return errors.New("picMaxurl is not string"), nil
+			tiArr := []TargetInfo{}
+			err = json.Unmarshal(tB, &tiArr)
+			if err !=nil {
+			    log.Log.Infoln("err:", err)
+				continue
+			}
+			if len(tiArr) > 0 {
+				ti := tiArr[0]
+				d["picSmUrl"] = ti.PicSmUrl
+				d["targetType"] = ti.TargetType
+				if ti.TargetType == "FaceDetect" {
+					sLabelStr, ok := source["showLabels"]
+					if ok {
+						//labelArr := strings.Split(sLabelStr.(string), "/")
+						//if len(labelArr) == 3 {
+						//	d["gender"] = labelArr[0]
+						//	d["ageDescription"] = labelArr[1]
+						//	d["race"] = labelArr[2]
+						//}
+						d["showLabels"] = sLabelStr
+					} else {
+						d["showLabels"] = ""
+					}
+
+
+					if bInfos,ok := source["baseInfo"]; ok && bInfos != nil {
+						bd := getSourceBaseInfo(bInfos)
+						d["baseInfo"] = bd //姣斿鍒扮殑搴曞簱鐨勪汉
+					} else {
+						d["baseInfo"] = []interface{}{}
+					}
+					d["sdkType"] = source["taskName"]
+				} else {
+					d["sdkType"] = source["taskName"]
+					d["picSmUrl"] = d["picMaxUrl"]
+				}
+			} else {
+				d["picSmUrl"] = d["picMaxUrl"]
 			}
 
-			if !strings.HasPrefix(pmax, "http") {
-				source["picMaxUrl"] = picurl + pmax
-
+			vUri := source["videoUrl"]
+			if vUri != nil && vUri.(string) != "" {
+				d["videoNum"] = "http://"+vUri.(string)
+			} else {
+				d["videoNum"] = ""
 			}
 
-			psm, exist := source["picSmUrl"].(string)
-			if !exist {
-				return errors.New("picSmUrl is not string"), nil
-			}
-
-			if !strings.HasPrefix(psm, "http") {
-				source["picSmUrl"] = picurl + psm
-			}
-
-			prace, exist := source["Race"]
-			if exist {
-				source["race"] = prace
-			}
-
-			pGender, exist := source["Gender"]
-			if exist {
-				source["gender"] = pGender
-			}
-
-			source["ageDescription"] = getAgeDesc(source["Age"])
-
-			source["videoNum"] = getVideoUrl(source)
-			picDate := source["picDate"].(string)
-			lastIdx := strings.LastIndex(picDate,":")
-			picDateStr := picDate[:lastIdx]
-			if err == nil {
-				source["picDate"] = picDateStr
-			}
-
-			baseInfo := getSourceBaseInfo(source)
-			source["baseInfo"] = baseInfo
-
-			sources = append(sources, source)
+			sources = append(sources, d)
 		}
 		data["datalist"] = sources
 		return nil, data
@@ -127,226 +179,139 @@
 	}
 }
 
-func getAgeDesc(age interface{})(ageDesc string) {
-	if age !=nil {
-		ageInt := age.(float64)
-		if ageInt >0 && ageInt<7 {
-			ageDesc = "绔ュ勾"
-		} else if ageInt >=7 && ageInt<18 {
-			ageDesc = "灏戝勾"
-		} else if ageInt >=18 && ageInt<40 {
-			ageDesc = "闈掑勾"
-		} else if ageInt >=40 && ageInt<65 {
-			ageDesc = "涓勾"
-		} else if ageInt >=65 {
-			ageDesc = "鑰佸勾"
-		} else {
-			ageDesc = ""
-		}
-	}
-	return ageDesc
+type AlarmRule struct {
+	GroupId 			string 			`json:"groupId"`
+	AlarmLevel 			string 			`json:"alarmLevel"`
+}
+
+type TargetInfo struct {
+	TargetId 		string  		`json:"targetId"`
+	TargetType 		string 			`json:"targetType"`
+	PicSmUrl 		string 			`json:"picSmUrl"`
+	TargetScore 	float32 		`json:"targetScore"`
 }
 
 type BaseInfo struct {
-	TaskId string `json:"taskId"`
-	TaskName string `json:"taskName"`
-	LikePer string `json:"likePer"`
-	TableId string `json:"tableId"`
-	TableName string `json:"tableName"`
-	PersonId string `json:"personId"`
-	PersonPicUrl string `json:"personPicUrl"`
-	PersonName string `json:"personName"`
-	Gender string `json:"gender"`
-	PhoneNum string `json:"phoneNum"`
-	IDCard string `json:"IDCard"`
-	MonitorLevel string `json:"monitorLevel"`
-	Content string `json:"content"`
+	TaskId 			string 		`json:"taskId"`
+	TaskName 		string 		`json:"taskName"`
+	LikePer 		float32 	`json:"likePer"`
+	TableId 		string 		`json:"tableId"`
+	TableName 		string 		`json:"tableName"`
+	PersonId 		string 		`json:"personId"`
+	PersonPicUrl 	string 		`json:"personPicUrl"`
+	PersonName 		string 		`json:"personName"`
+	Gender 			string 		`json:"gender"`
+	PhoneNum 		string 		`json:"phoneNum"`
+	IDCard 			string 		`json:"IDCard"`
+	MonitorLevel 	string 		`json:"monitorLevel"`
+	Content 		string 		`json:"content"`
 }
 
-func getSourceBaseInfo(source map[string]interface{}) []BaseInfo {
-	sdkType := source["sdkType"].(string)
-	baseInfoArr := make([]BaseInfo,0)
-	if sdkType == "浜鸿劯" {
-		likePer,baseName,personId,idCard,personPicUrl,gender,content :="","","","","","",""
-		if source["likePer"] !=nil {
-			likePer = source["likePer"].(string)
-		}
-		if source["BaseName"] !=nil {
-			baseName = source["BaseName"].(string)
-		}
-		if source["personId"] !=nil {
-			personId = source["personId"].(string)
-		}
-		if source["idcard"] !=nil {
-			idCard = source["idcard"].(string)
-		}
-		if source["personPicUrl"] !=nil {
-			personPicUrl = source["personPicUrl"].(string)
-		}
-		if source["Gender"] !=nil {
-			gender = source["Gender"].(string)
-		}
-		if source["content"] !=nil {
-			content = source["content"].(string)
-		}
-		var baseInfo = BaseInfo{
-			TaskId:"",//2.0鏂板瓧娈�
-			TaskName:"",//2.0鏂板瓧娈�
-			LikePer:likePer,
-			TableId:"",//2.0鏂板瓧娈�
-			TableName:baseName,
-			PersonId:personId,
-			PersonName:idCard,//浜哄憳濮撳悕锛屼粠绠$悊骞冲彴鑾峰彇
-			PersonPicUrl:personPicUrl,
-			Gender:gender,
-			PhoneNum:"",//鎵嬫満鍙凤紝浠庣鐞嗗钩鍙拌幏鍙�
-			IDCard:idCard,
-			MonitorLevel:"",//2.0鏂板瓧娈�
-			Content:content,
-		}
+type TI struct {
+	BwType       	string  	`json:"bwType"`
+	TargetPicUrl 	string 		`json:"targetPicUrl"`
+	TargetName 		string 		`json:"targetName"`
+	TargetId 		string 		`json:"targetId"`
+	TableId 		string 		`json:"tableId"`
+	CompareScore 	float32 	`json:"compareScore"`
+	MonitorLevel 	string 		`json:"monitorLevel"`
+	Content 		string 		`json:"content"`
+	TableName 		string 		`json:"tableName"`
+	Labels 			string 		`json:"labels"`
+}
 
-		baseInfoArr = append(baseInfoArr, baseInfo)
-		//bytes, err := json.Marshal(baseInfoArr)
-		//if err !=nil {
-		//	return ""
-		//}
+func getSourceBaseInfo(bInfos interface{}) []BaseInfo {
+	baseInfoArr := make([]BaseInfo,0)
+
+	b, err := json.Marshal(bInfos)
+	if err == nil {
+		var targetArr []TI
+		if err = json.Unmarshal(b, &targetArr); err == nil && len(targetArr) >0 {
+			for _,t := range targetArr {
+				idCard,sex := "",""
+				if t.Labels != "" {
+					arr := strings.Split(t.Labels, "/")
+					if len(arr) > 0 {
+						for _,str := range arr {
+							if str == "鐢�" || str == "濂�" {
+								sex = str
+								break
+							}
+						}
+						for _,str := range arr {
+							if len(str) == 18 {
+								idCard = str
+								break
+							}
+						}
+					}
+				}
+				baseInfoArr = append(baseInfoArr, BaseInfo{
+					TaskId: "",//2.0鏂板瓧娈�
+					TaskName: "",//2.0鏂板瓧娈�
+					LikePer: t.CompareScore,
+					TableId: "",//2.0鏂板瓧娈�
+					TableName: t.TableName,
+					PersonId: t.TargetId,
+					PersonName: t.TargetName,//浜哄憳濮撳悕锛屼粠绠$悊骞冲彴鑾峰彇
+					PersonPicUrl: t.TargetPicUrl,
+					Gender: sex,
+					PhoneNum: "",//鎵嬫満鍙凤紝浠庣鐞嗗钩鍙拌幏鍙�
+					IDCard: idCard,
+					MonitorLevel: t.MonitorLevel,//2.0鏂板瓧娈�
+					Content: t.Content,
+				})
+			}
+		} else {
+			fmt.Println("unmarshal bInfos err:", err)
+		}
+	} else {
+		fmt.Println("marshal bInfos err:", err)
 	}
+
 	return baseInfoArr
 }
 
-func getVideoUrl(source map[string]interface{}) (videoUrl string){
-	imgKey := source["imgKey"].(string)
-	picDate := source["picDate"].(string)//鎶撴媿鏃ユ湡
-	cameraId := source["videoReqNum"].(string)//鎽勫儚鏈篿d
-	indeviceId := source["indeviceid"].(string)//鍒嗘瀽璁惧id
-	deviceMap := make(map[string]string,0)
-	deviceMap["DSVAD010120181119"] = "http://172.17.50.241:11111/getRecordVideoPath"
-	deviceMap["DSVAD010220181119"] = "http://172.17.50.242:11111/getRecordVideoPath"
-	deviceMap["DSVAD010320181119"] = "http://172.17.50.243:11111/getRecordVideoPath"
-	deviceMap["DSVAD010420181119"] = "http://172.17.50.244:11111/getRecordVideoPath"
-
-	ngxMap := make(map[string]string,0)
-	ngxMap["DSVAD010120181119"] = "http://58.118.225.79:44180/videosource"
-	ngxMap["DSVAD010220181119"] = "http://58.118.225.79:44280/videosource"
-	ngxMap["DSVAD010320181119"] = "http://58.118.225.79:44380/videosource"
-	ngxMap["DSVAD010420181119"] = "http://58.118.225.79:44480/videosource"
-
-
-	reqUrl := deviceMap[indeviceId]
-	paramMap := make(map[string]interface{},0)
-	paramMap["imgKey"] = imgKey
-	paramMap["picDate"] = picDate
-	paramMap["videoNum"] = cameraId
-
-	respBytes, err := doPostRequest(reqUrl, "application/json", paramMap, nil, nil)
-	if err !=nil{
-		return ""
-	}
-
-	var resp RespVideo
-	err = json.Unmarshal(respBytes, &resp)
-	if err !=nil {
-		return ""
-	}
-
-	filePath := resp.FilePath
-	videoUrl = ""
-	if !strings.Contains(filePath, "/cut"){
-		videoUrl = ""
-		fmt.Printf("videoReqUrl:%s ,imgKey:%s ,picDate:%s ,cameraId:%s ,filePath:%s \n ",reqUrl,imgKey,picDate,cameraId,filePath)
-	} else {
-		strArr := strings.Split(filePath, "/cut")
-		ngxUrl := ngxMap[indeviceId]
-		if ngxUrl !="" && len(strArr) >0 {
-			videoUrl = ngxUrl + strArr[1]
-		}
-	}
-	if videoUrl == ""{
-		respMap := make(map[string]interface{},0)
-		err := json.Unmarshal(respBytes, &respMap)
-		if err !=nil {
-			fmt.Println("resp UnmarshalToMap err: ",err)
-		}
-		fmt.Println("resp: ",respMap)
-	}
-	return videoUrl
-}
-
-type RespVideo struct{
-	FilePath string `json:"file_path"`
-}
-func doPostRequest(url string, contentType string, body map[string]interface{}, params map[string]string, headers map[string]string) ([]byte, error) {
-	var resultBytes []byte
-	var bodyJson []byte
-	if body != nil {
-		var err error
-		bodyJson, err = json.Marshal(body)
-		if err != nil {
-			log.Log.Errorln("doPostRequestMarshal err:",err)
-			return resultBytes, err
-		}
-	}
-	request, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyJson))
-	if err != nil {
-		log.Log.Errorln("NewRequest ERR:",err)
-		return resultBytes, err
-	}
-	request.Header.Set("Content-type", contentType)
-	//add params
-	q := request.URL.Query()
-	if params != nil {
-		for key, val := range params {
-			q.Add(key, val)
-		}
-		request.URL.RawQuery = q.Encode()
-	}
-	// add headers
-	if headers != nil {
-		for key, val := range headers {
-			request.Header.Add(key, val)
-		}
-	}
-	timeOut:= time.Duration(8*time.Second)//set request timeout
-	client := &http.Client{
-		Timeout:timeOut,
-	}
-	resp, err := client.Do(request)
-	if err != nil {
-		log.Log.Errorln("DoRequest ERR:",err)
-		return resultBytes, err
-	}
-	defer resp.Body.Close()
-	resultBytes, err = ioutil.ReadAll(resp.Body)
-	if err != nil {
-		log.Log.Errorln("ReadAll ERR:",err)
-		return resultBytes, err
-	}
-	return resultBytes, nil
-}
-
-//sdk绫诲瀷
-func sdkTypeToValue(i int) string {
-	value := []string{"浜鸿劯", "杞﹁締", "浜轰綋", "鍏ヤ镜", "鎷ユ尋", "闈犲彸琛�", "浜哄憳寮傚父", "涓綋闈欐"}
-
-	return value[i-1]
-}
-
-func PostAction(sec int, Eurl string, picurl string) []byte {
-	index := "videopersons,personaction"
+func PostAction(sec int, Eurl string, ishub string, size int, lastT time.Time, curTime time.Time) []byte {
+	index := "ai_ocean"
 	url := fmt.Sprintf("%s%s%s", Eurl, index, "/_search")
 
-	seccond := strconv.Itoa(sec)
-	preSec := ""
-	if sec > 40 {
-		preSec = "-40s"
+	sizeStr :=""
+	if size <=0 {
+		sizeStr = "1000"
+	} else {
+		sizeStr = strconv.Itoa(size)
 	}
-	prama := "{\"query\":{\"bool\":{\"filter\":[{\"range\":{\"picDate\":{\"gte\":\"now+8h-" + seccond + "s\",\"lt\":\"now+8h"+preSec+"\"}}}]}},\"size\":\"1000\",\"sort\":[{\"picDate\":{\"order\":\"desc\"}}]," +
-		"\"_source\":[\"baseInfo\",\"Gender\",\"BaseName\",\"Age\",\"personId\",\"personPicUrl\",\"indeviceName\",\"imgKey\",\"sdkType\",\"ageDescription\",\"indeviceid\",\"content\",\"Id\",\"picAddress\",\"picMaxUrl\",\"picDate\",\"Race\",\"videoNum\",\"picSmUrl\",\"taskName\",\"personIsHub\",\"idcard\",\"videoIp\",\"videoReqNum\"]" +
+	preSec := "10"
+	if sec <=0 {
+		preSec = "10"
+	} else {
+		preSec = strconv.Itoa(sec)
+	}
+	var filterArr []string
+	var mustNotArr []string
+	//鏄惁鏌ユ姤璀︽暟鎹�
+	if ishub == "hub" {
+		mustNotArr = append(mustNotArr,"{\"term\":{\"alarmRules.alarmLevel.raw\":\"浜旂骇\"}}")
+	}
+
+	filterArr = append(filterArr, "{\"range\":{\"picDate\":{\"gte\":\"now+8h-"+preSec+"s\",\"lt\":\"now+8h\"}}}")
+
+	filterStr := ""
+	mustNotStr := ""
+	if len(filterArr) >0 {
+		filterStr = strings.Join(filterArr, ",")
+	}
+	if len(mustNotArr) > 0 {
+		mustNotStr = strings.Join(mustNotArr, ",")
+	}
+	param := "{\"query\":{\"bool\":{\"filter\":["+filterStr+"],\"must_not\":["+mustNotStr+"]}},\"size\":\""+sizeStr+"\",\"sort\":[{\"picDate\":{\"order\":\"desc\"}}]," +
+		"\"_source\":{\"includes\":[\"cameraAddr\",\"baseInfo\",\"targetInfo\",\"content\",\"id\",\"picMaxUrl\",\"picDate\",\"showLabels\",\"taskName\",\"sdkName\",\"videoUrl\",\"alarmRules\"],\"excludes\":[\"*.feature\",\"*.attachTarget\",\"*.targetLocation\"]}" +
 		"}"
-	err, tokenRes := GetEsDataReq(url, prama, picurl, true)
+	err, tokenRes := GetEsDataReq(url, param, true)
 
 	if err != nil {
-		log.Log.Errorln(err)
+		log.Log.Errorln("GetEsDataReq err:", err)
 		return nil
 	}
 	jsonstring, _ := json.Marshal(tokenRes)

--
Gitblit v1.8.0