go语言写的人脸本地化程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

897 line
23 KiB

  1. package business
  2. /**
  3. * @Author: yk
  4. * @Date: 2024/01/30 15:04
  5. * @Desc: 外部接口实现,关于人员的接口
  6. */
  7. import (
  8. "bytes"
  9. "digimetastaffsync/common"
  10. "digimetastaffsync/mydatabase"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "mime/multipart"
  16. "net/http"
  17. "os"
  18. "sort"
  19. "strconv"
  20. "strings"
  21. "time"
  22. )
  23. var timeStep int
  24. func init() {
  25. common.LoadConfig()
  26. //初始化时间步长时间步长
  27. timeStep = common.ConfigData.Timer
  28. }
  29. type FeatureResp struct {
  30. Status int `json:"status"`
  31. Message string `json:"message"`
  32. Result []interface{} `json:"result"`
  33. }
  34. type Staff struct {
  35. ID string `json:"id"`
  36. Name string `json:"name"`
  37. NickName string `json:"nickName"`
  38. Phone string `json:"phone"`
  39. Type int `json:"type"`
  40. Url string `json:"Url"`
  41. Image string `json:"image"`
  42. }
  43. type Req struct {
  44. Code string `json:"code"`
  45. StaffName string `json:"staffName"`
  46. StaffType int `json:"staffType"`
  47. Gender int `json:"gender"`
  48. DevId string `json:"devId"`
  49. FaceFeature string `json:"faceFeature"`
  50. HireDate string `json:"hireDate"`
  51. Birthday string `json:"birthDate"`
  52. Phone string `json:"phone"`
  53. StaffBase64Img string `json:"staffBase64Img"`
  54. DelFlag int `json:"status"`
  55. Modified string `json:"modified"`
  56. }
  57. func RegStaff(param Req) (*common.Response, error) {
  58. url := common.ConfigData.PushDataUrl
  59. common.Info(common.GenLogLine()+"reg staff url:%s\n", url)
  60. method := "POST"
  61. param.DevId = common.ConfigData.DevId
  62. if len(param.StaffBase64Img) < 20000 {
  63. param.StaffBase64Img = ""
  64. }
  65. fmt.Printf("code:%s, staffName:%s, staffType:%d, gender:%d, devId:%s, faceFeature:%s, hireDate:%s, birthday:%s, phone:%s, DelFlag:%d, modified:%s\n",
  66. param.Code, param.StaffName, param.StaffType, param.Gender, param.DevId, param.FaceFeature, param.HireDate, param.Birthday, param.Phone, param.DelFlag, param.Modified)
  67. common.Info(common.GenLogLine()+"exec reg code:%s, staffName:%s, staffType:%d, gender:%d, devId:%s, faceFeature:%s, hireDate:%s, birthday:%s, phone:%s, DelFlag:%d, modified:%s\n",
  68. param.Code, param.StaffName, param.StaffType, param.Gender, param.DevId, param.FaceFeature, param.HireDate, param.Birthday, param.Phone, param.DelFlag, param.Modified)
  69. fmt.Println()
  70. jsonData, err := json.Marshal(param)
  71. if err != nil {
  72. fmt.Println("Error marshaling JSON:", err)
  73. }
  74. req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonData))
  75. if err != nil {
  76. fmt.Errorf(common.GenLogLine()+"%s", err)
  77. common.Error(common.GenLogLine()+"%s", err)
  78. return nil, err
  79. }
  80. req.Header.Add("Content-Type", "application/json")
  81. client := &http.Client{}
  82. res, err := client.Do(req)
  83. if err != nil {
  84. fmt.Errorf(common.GenLogLine()+"%s", err)
  85. common.Error(common.GenLogLine()+"%s", err)
  86. return nil, err
  87. }
  88. defer res.Body.Close()
  89. body, err := io.ReadAll(res.Body)
  90. if err != nil {
  91. fmt.Errorf(common.GenLogLine()+"%s", err)
  92. common.Error(common.GenLogLine()+"%s", err)
  93. return nil, err
  94. }
  95. var response *common.Response
  96. err = json.Unmarshal([]byte(string(body)), &response)
  97. if err != nil {
  98. fmt.Println("Error:", err)
  99. return nil, err
  100. }
  101. common.Error(common.GenLogLine()+"reg result %s", string(body))
  102. return response, nil
  103. }
  104. func RegOnlineStaff(param Req) error {
  105. url := common.ConfigData.PushDataUrl
  106. fmt.Printf("url:%s\n", url)
  107. method := "POST"
  108. param.DevId = common.ConfigData.DevId
  109. fmt.Printf("====param:%v\n", param)
  110. jsonData, err := json.Marshal(param)
  111. if err != nil {
  112. fmt.Println("Error marshaling JSON:", err)
  113. }
  114. req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonData))
  115. if err != nil {
  116. fmt.Errorf(common.GenLogLine()+"%s", err)
  117. common.Error(common.GenLogLine()+"%s", err)
  118. return err
  119. }
  120. req.Header.Add("Content-Type", "application/json")
  121. client := &http.Client{}
  122. res, err := client.Do(req)
  123. if err != nil {
  124. fmt.Errorf(common.GenLogLine()+"%s", err)
  125. common.Error(common.GenLogLine()+"%s", err)
  126. return err
  127. }
  128. defer res.Body.Close()
  129. body, err := io.ReadAll(res.Body)
  130. if err != nil {
  131. fmt.Errorf(common.GenLogLine()+"%s", err)
  132. common.Error(common.GenLogLine()+"%s", err)
  133. return err
  134. }
  135. fmt.Println(string(body))
  136. return nil
  137. }
  138. func HandleStaff(emp Req) error {
  139. if emp.StaffBase64Img != "" {
  140. //feature = FetchStaffFaceFeature(emp.StaffBase64Img)
  141. //emp.FaceFeature = LocalFetchStaffFaceFeature(emp.StaffBase64Img)
  142. }
  143. var sType int
  144. if emp.StaffType > 70 {
  145. sType = 4
  146. } else {
  147. sType = 5
  148. }
  149. emp.StaffType = sType
  150. var sDels = []int{5, 6, 7, 8}
  151. if common.AryContainInt(sDels, emp.DelFlag) {
  152. emp.DelFlag = 1
  153. } else {
  154. emp.DelFlag = 0
  155. }
  156. RegStaff(emp)
  157. return nil
  158. }
  159. // Fetch2 获取员工信息,模拟获取saas的人员数据
  160. func Fetch2() []Staff {
  161. _token, err := common.GetToken()
  162. if err != nil {
  163. fmt.Errorf(common.GenLogLine()+"%s", err)
  164. common.Error(common.GenLogLine()+"%s", err)
  165. return nil
  166. }
  167. url := common.ConfigData.FetchDataUrl
  168. method := "GET"
  169. payload := strings.NewReader(``)
  170. client := &http.Client{}
  171. req, err := http.NewRequest(method, url, payload)
  172. if err != nil {
  173. fmt.Errorf(common.GenLogLine()+"%s", err)
  174. common.Error(common.GenLogLine()+"%s", err)
  175. return nil
  176. }
  177. token := fmt.Sprintf(`Bearer %s`, _token)
  178. req.Header.Add("Authorization", token)
  179. res, err := client.Do(req)
  180. if err != nil {
  181. fmt.Errorf(common.GenLogLine()+"%s", err)
  182. common.Error(common.GenLogLine()+"%s", err)
  183. return nil
  184. }
  185. defer res.Body.Close()
  186. body, err := io.ReadAll(res.Body)
  187. if err != nil {
  188. fmt.Errorf(common.GenLogLine()+"%s", err)
  189. common.Error(common.GenLogLine()+"%s", err)
  190. return nil
  191. }
  192. var response *common.Response
  193. err = json.Unmarshal([]byte(string(body)), &response)
  194. if err != nil {
  195. fmt.Println("Error:", err)
  196. }
  197. var result []Staff
  198. switch v := response.Data["items"].(type) {
  199. case []interface{}:
  200. for _, item := range v {
  201. var s Staff
  202. //fmt.Println(item)
  203. if item.(map[string]interface{})["id"] != nil {
  204. s.ID = (item.(map[string]interface{})["id"]).(string)
  205. }
  206. if item.(map[string]interface{})["name"] != nil {
  207. s.Name = (item.(map[string]interface{})["name"]).(string)
  208. }
  209. if item.(map[string]interface{})["nickName"] != nil {
  210. s.NickName = (item.(map[string]interface{})["nickName"]).(string)
  211. }
  212. if item.(map[string]interface{})["phone"] != nil {
  213. s.Phone = (item.(map[string]interface{})["phone"]).(string)
  214. }
  215. if item.(map[string]interface{})["type"] != nil {
  216. s.Type = (item.(map[string]interface{})["type"]).(int)
  217. }
  218. if item.(map[string]interface{})["resource"] != nil {
  219. if item.(map[string]interface{})["resource"].(map[string]interface{})["url"] != nil {
  220. s.Url = (item.(map[string]interface{})["resource"].(map[string]interface{})["url"]).(string)
  221. }
  222. }
  223. result = append(result, s)
  224. }
  225. default:
  226. fmt.Println("无法解析的类型")
  227. }
  228. return result
  229. }
  230. // AbleSendCode 发送验证码
  231. func AbleSendCode(phone string) string {
  232. url := common.ConfigData.CheckSendCodeUrl + "/" + phone
  233. method := "GET"
  234. payload := strings.NewReader("")
  235. client := &http.Client{}
  236. req, err := http.NewRequest(method, url, payload)
  237. if err != nil {
  238. fmt.Errorf(common.GenLogLine()+"%s", err)
  239. common.Error(common.GenLogLine()+"%s", err)
  240. return err.Error()
  241. }
  242. res, err := client.Do(req)
  243. if err != nil {
  244. fmt.Errorf(common.GenLogLine()+"%s", err)
  245. common.Error(common.GenLogLine()+"%s", err)
  246. return err.Error()
  247. }
  248. defer res.Body.Close()
  249. body, err := io.ReadAll(res.Body)
  250. if err != nil {
  251. fmt.Errorf(common.GenLogLine()+"%s", err)
  252. common.Error(common.GenLogLine()+"%s", err)
  253. return err.Error()
  254. }
  255. fmt.Println("response Body:", string(body))
  256. return string(body)
  257. }
  258. func SendCode(phone string) string {
  259. ableSend := AbleSendCode(phone)
  260. fmt.Println("ableSend:", ableSend)
  261. url := common.ConfigData.SendCodeUrl
  262. method := "POST"
  263. payload := strings.NewReader(`{
  264. "phone":"` + phone + `"}`)
  265. client := &http.Client{}
  266. req, err := http.NewRequest(method, url, payload)
  267. if err != nil {
  268. fmt.Errorf(common.GenLogLine()+"%s", err)
  269. common.Error(common.GenLogLine()+"%s", err)
  270. return err.Error()
  271. }
  272. req.Header.Add("Content-Type", "application/json")
  273. res, err := client.Do(req)
  274. if err != nil {
  275. fmt.Errorf(common.GenLogLine()+"%s", err)
  276. common.Error(common.GenLogLine()+"%s", err)
  277. return err.Error()
  278. }
  279. defer res.Body.Close()
  280. body, err := io.ReadAll(res.Body)
  281. if err != nil {
  282. fmt.Errorf(common.GenLogLine()+"%s", err)
  283. common.Error(common.GenLogLine()+"%s", err)
  284. return err.Error()
  285. }
  286. fmt.Println("response Body:", string(body))
  287. var result map[string]interface{}
  288. err = json.Unmarshal([]byte(string(body)), &result)
  289. if err != nil {
  290. fmt.Println("解析JSON出错:", err)
  291. return err.Error()
  292. }
  293. return string(body)
  294. }
  295. func ValidCode(phone string, code string) (string, error) {
  296. ableSend := AbleSendCode(phone)
  297. fmt.Println("ableSend:", ableSend)
  298. url := common.ConfigData.ValidCodeUrl + phone + "/" + code
  299. method := "GET"
  300. payload := strings.NewReader(``)
  301. client := &http.Client{}
  302. req, err := http.NewRequest(method, url, payload)
  303. res, err := client.Do(req)
  304. if err != nil {
  305. fmt.Errorf(common.GenLogLine()+"%s", err)
  306. common.Error(common.GenLogLine()+"%s", err)
  307. return "", err
  308. }
  309. defer res.Body.Close()
  310. body, err := io.ReadAll(res.Body)
  311. if err != nil {
  312. fmt.Errorf(common.GenLogLine()+"%s", err)
  313. common.Error(common.GenLogLine()+"%s", err)
  314. return "", err
  315. }
  316. fmt.Println("response Body:", string(body))
  317. common.Error(common.GenLogLine()+"reg result %s", string(body))
  318. return string(body), nil
  319. }
  320. func StaffInfo(staffId string) (map[string]interface{}, error) {
  321. fmt.Println("staffId:", staffId)
  322. url := common.ConfigData.StaffInfoUrl
  323. method := "GET"
  324. token, err := common.GetToken()
  325. if err != nil {
  326. return nil, err
  327. }
  328. payload := &bytes.Buffer{}
  329. writer := multipart.NewWriter(payload)
  330. _ = writer.WriteField("id", staffId)
  331. err = writer.Close()
  332. if err != nil {
  333. fmt.Println(err)
  334. return nil, err
  335. }
  336. client := &http.Client{}
  337. req, err := http.NewRequest(method, url, payload)
  338. if err != nil {
  339. fmt.Println(err)
  340. return nil, err
  341. }
  342. req.Header.Add("Authorization", "Bearer "+token)
  343. req.Header.Set("Content-Type", writer.FormDataContentType())
  344. res, err := client.Do(req)
  345. if err != nil {
  346. fmt.Println(err)
  347. return nil, err
  348. }
  349. defer res.Body.Close()
  350. body, err := io.ReadAll(res.Body)
  351. if err != nil {
  352. fmt.Println(err)
  353. return nil, err
  354. }
  355. fmt.Println(string(body))
  356. var result map[string]interface{}
  357. err = json.Unmarshal([]byte(string(body)), &result)
  358. if err != nil {
  359. fmt.Println("解析JSON出错:", err)
  360. return nil, err
  361. }
  362. items, ok := result["data"].(map[string]interface{})["items"].([]interface{})
  363. if !ok {
  364. fmt.Println("无法获取items字段")
  365. return nil, err
  366. }
  367. if len(items) == 0 {
  368. return nil, errors.New("未找到员工信息")
  369. }
  370. firstItem := items[0].(map[string]interface{})
  371. common.Error(common.GenLogLine()+"info result %v", firstItem)
  372. return firstItem, nil
  373. }
  374. func MgrLogin(userName string, password string) string {
  375. url := common.ConfigData.MgrLoginUrl
  376. fmt.Println("url:", url)
  377. enterpriseName := common.ConfigData.EnterpriseName
  378. method := "POST"
  379. payload := strings.NewReader(`{
  380. "enterpriseName":"` + enterpriseName + `",
  381. "userName":"` + userName + `",
  382. "password":"` + password + `"}`)
  383. client := &http.Client{}
  384. req, err := http.NewRequest(method, url, payload)
  385. if err != nil {
  386. fmt.Errorf(common.GenLogLine()+"%s", err)
  387. common.Error(common.GenLogLine()+"%s", err)
  388. return err.Error()
  389. }
  390. req.Header.Add("Content-Type", "application/json")
  391. res, err := client.Do(req)
  392. if err != nil {
  393. fmt.Errorf(common.GenLogLine()+"%s", err)
  394. common.Error(common.GenLogLine()+"%s", err)
  395. return err.Error()
  396. }
  397. defer res.Body.Close()
  398. body, err := io.ReadAll(res.Body)
  399. if err != nil {
  400. fmt.Errorf(common.GenLogLine()+"%s", err)
  401. common.Error(common.GenLogLine()+"%s", err)
  402. return err.Error()
  403. }
  404. fmt.Println("response Body:", string(body))
  405. return string(body)
  406. }
  407. func PhoneLogin(phone string) (map[string]interface{}, error) {
  408. url := common.ConfigData.PhoneLoginUrl
  409. method := "POST"
  410. payload := strings.NewReader(`{
  411. "phone":"` + phone + `"}`)
  412. client := &http.Client{}
  413. req, _ := http.NewRequest(method, url, payload)
  414. req.Header.Add("Content-Type", "application/json")
  415. res, err := client.Do(req)
  416. if err != nil {
  417. fmt.Errorf(common.GenLogLine()+"%s", err)
  418. common.Error(common.GenLogLine()+"%s", err)
  419. return nil, err
  420. }
  421. defer res.Body.Close()
  422. body, err := io.ReadAll(res.Body)
  423. if err != nil {
  424. fmt.Errorf(common.GenLogLine()+"%s", err)
  425. common.Error(common.GenLogLine()+"%s", err)
  426. return nil, err
  427. }
  428. fmt.Println("response Body:", string(body))
  429. var result map[string]interface{}
  430. err = json.Unmarshal([]byte(string(body)), &result)
  431. if err != nil {
  432. fmt.Println("解析JSON出错:", err)
  433. return nil, err
  434. }
  435. return result, nil
  436. }
  437. func Fetch() []Req {
  438. url := common.ConfigData.FetchData2Url
  439. method := "POST"
  440. payload := strings.NewReader("appId=dfwycustomer2u8&ygbh")
  441. client := &http.Client{}
  442. req, err := http.NewRequest(method, url, payload)
  443. if err != nil {
  444. fmt.Errorf(common.GenLogLine()+"%s", err)
  445. common.Error(common.GenLogLine()+"%s", err)
  446. return nil
  447. }
  448. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  449. res, err := client.Do(req)
  450. if err != nil {
  451. fmt.Errorf(common.GenLogLine()+"%s", err)
  452. common.Error(common.GenLogLine()+"%s", err)
  453. return nil
  454. }
  455. defer res.Body.Close()
  456. body, err := io.ReadAll(res.Body)
  457. if err != nil {
  458. fmt.Errorf(common.GenLogLine()+"%s", err)
  459. common.Error(common.GenLogLine()+"%s", err)
  460. return nil
  461. }
  462. var response *common.Resp
  463. err = json.Unmarshal([]byte(string(body)), &response)
  464. if err != nil {
  465. fmt.Println("Error:", err)
  466. }
  467. var result []Req
  468. fmt.Printf("====%#v====datassss\n", response)
  469. for _, item := range response.Data {
  470. var s Req
  471. //fmt.Println(item)
  472. if item.(map[string]interface{})["workcode"] != nil {
  473. s.Code = (item.(map[string]interface{})["workcode"]).(string)
  474. }
  475. if item.(map[string]interface{})["name"] != nil {
  476. s.StaffName = (item.(map[string]interface{})["name"]).(string)
  477. }
  478. if item.(map[string]interface{})["mobile"] != nil {
  479. s.Phone = (item.(map[string]interface{})["mobile"]).(string)
  480. }
  481. if item.(map[string]interface{})["level"] != nil {
  482. s.StaffType, _ = strconv.Atoi((item.(map[string]interface{})["level"]).(string))
  483. }
  484. if item.(map[string]interface{})["birthday"] != nil {
  485. s.Birthday = (item.(map[string]interface{})["birthday"]).(string)
  486. }
  487. if item.(map[string]interface{})["companystartdate"] != nil {
  488. s.HireDate = (item.(map[string]interface{})["companystartdate"]).(string)
  489. }
  490. if item.(map[string]interface{})["status"] != nil {
  491. s.DelFlag, _ = strconv.Atoi((item.(map[string]interface{})["status"]).(string))
  492. }
  493. if item.(map[string]interface{})["image"] != nil {
  494. s.StaffBase64Img = (item.(map[string]interface{})["image"]).(string)
  495. }
  496. if item.(map[string]interface{})["modified"] != nil {
  497. s.Modified = (item.(map[string]interface{})["modified"]).(string)
  498. }
  499. result = append(result, s)
  500. }
  501. if len(result) > 0 {
  502. sort.Slice(result, func(i, j int) bool {
  503. a, err := time.Parse("2006-01-02 15:04:05", result[i].Modified)
  504. if err != nil {
  505. common.Error(common.GenLogLine() + err.Error())
  506. }
  507. b, err2 := time.Parse("2006-01-02 15:04:05", result[j].Modified)
  508. if err2 != nil {
  509. common.Error(common.GenLogLine() + err2.Error())
  510. }
  511. return b.Before(a)
  512. })
  513. }
  514. return result
  515. }
  516. func FetchStaffImage(ygbh string) string {
  517. url := common.ConfigData.FetchData2Url
  518. method := "POST"
  519. payload := strings.NewReader("appId=dfwycustomer2u8&ygbh=" + fmt.Sprintf("%s", ygbh))
  520. client := &http.Client{}
  521. req, err := http.NewRequest(method, url, payload)
  522. if err != nil {
  523. fmt.Errorf(common.GenLogLine()+"%s", err)
  524. common.Error(common.GenLogLine()+"%s", err)
  525. return ""
  526. }
  527. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  528. res, _ := client.Do(req)
  529. defer res.Body.Close()
  530. body, err := io.ReadAll(res.Body)
  531. if err != nil {
  532. fmt.Errorf(common.GenLogLine()+"%s", err)
  533. common.Error(common.GenLogLine()+"%s", err)
  534. return ""
  535. }
  536. var response *common.Resp
  537. err = json.Unmarshal([]byte(string(body)), &response)
  538. if err != nil {
  539. fmt.Println("Error:", err)
  540. }
  541. var result string = ""
  542. for _, item := range response.Data {
  543. var s string
  544. //fmt.Println(item)
  545. if item.(map[string]interface{})["image"] != nil {
  546. s = (item.(map[string]interface{})["image"]).(string)
  547. }
  548. result = s
  549. }
  550. return strings.Replace(result, "\n", "", -1)
  551. }
  552. func FetchStaffFaceFeature(base64 string) string {
  553. url := "http://39.105.51.226:5000/cv/feature-extraction-service/1.7"
  554. method := "POST"
  555. err := common.SaveBase64ImageToFile(base64, "images/"+fmt.Sprintf("%d", time.Now().Unix())+"test.jpg")
  556. fmt.Printf("%v\n", err)
  557. payload := strings.NewReader(`{
  558. "detect":true,
  559. "base64Data":"` + base64 + `"}`)
  560. client := &http.Client{}
  561. req, err := http.NewRequest(method, url, payload)
  562. if err != nil {
  563. fmt.Errorf(common.GenLogLine()+"%s", err)
  564. common.Error(common.GenLogLine()+"%s", err)
  565. return ""
  566. }
  567. req.Header.Add("Authorization", "Bearer ")
  568. req.Header.Add("Content-Type", "application/json")
  569. res, err := client.Do(req)
  570. if err != nil {
  571. fmt.Errorf(common.GenLogLine()+"%s", err)
  572. common.Error(common.GenLogLine()+"%s", err)
  573. return ""
  574. }
  575. defer res.Body.Close()
  576. body, err := io.ReadAll(res.Body)
  577. if err != nil {
  578. fmt.Errorf(common.GenLogLine()+"%s", err)
  579. common.Error(common.GenLogLine()+"%s", err)
  580. return ""
  581. }
  582. fmt.Println(string(body))
  583. var response *FeatureResp
  584. err = json.Unmarshal([]byte(string(body)), &response)
  585. if err != nil {
  586. fmt.Println("Error:", err)
  587. }
  588. var result string
  589. result, err = extractFeature(response.Result[0])
  590. fmt.Printf(" success data : %+v\n", result)
  591. return result
  592. }
  593. func extractFeature(data interface{}) (string, error) {
  594. // 将 interface{} 类型转换为 map[string]interface{}
  595. resultMap, ok := data.(map[string]interface{})
  596. if !ok {
  597. return "", fmt.Errorf("Invalid data format")
  598. }
  599. // 取出 "faces" 字段
  600. faces, ok := resultMap["faces"].([]interface{})
  601. if !ok || len(faces) == 0 {
  602. return "", fmt.Errorf("No faces found")
  603. }
  604. // 取出 "feature" 字段
  605. feature, ok := faces[0].(map[string]interface{})["feature"].([]interface{})
  606. if !ok || len(feature) == 0 {
  607. return "", fmt.Errorf("No feature found")
  608. }
  609. // 转换 feature 字段为 []float64 类型
  610. var featureValues []float64
  611. for _, value := range feature {
  612. if floatValue, ok := value.(float64); ok {
  613. featureValues = append(featureValues, floatValue)
  614. } else {
  615. return "", fmt.Errorf("Invalid feature value type")
  616. }
  617. }
  618. str := common.FloatSliceToString(featureValues)
  619. return str, nil
  620. }
  621. func LocalFetchStaffFaceFeature(base64 string) (string, string, error) {
  622. url := common.ConfigData.LocalDetectUrl
  623. method := "POST"
  624. imgName := "static/faces/" + fmt.Sprintf("%d", time.Now().Unix()) + "test.jpg"
  625. err := common.SaveBase64ImageToFile(base64, imgName)
  626. payload := strings.NewReader(`{
  627. "imgbase64":"` + base64 + `"}`)
  628. client := &http.Client{}
  629. req, _ := http.NewRequest(method, url, payload)
  630. //req.Header.Add("Authorization", "Bearer ")
  631. req.Header.Add("Content-Type", "application/json")
  632. res, err := client.Do(req)
  633. if err != nil {
  634. fmt.Errorf(common.GenLogLine()+"%s", err)
  635. common.Error(common.GenLogLine()+"%s", err)
  636. return "", imgName, err
  637. }
  638. defer res.Body.Close()
  639. body, err := io.ReadAll(res.Body)
  640. if err != nil {
  641. fmt.Errorf(common.GenLogLine()+"%s", err)
  642. common.Error(common.GenLogLine()+"%s", err)
  643. return "", imgName, err
  644. }
  645. fmt.Println(string(body))
  646. var response map[string]interface{}
  647. err = json.Unmarshal([]byte(string(body)), &response)
  648. if err != nil {
  649. fmt.Println("Error:", err)
  650. return "", imgName, err
  651. }
  652. faces, ok := response["data"].(map[string]interface{})
  653. if !ok {
  654. fmt.Errorf("No faces found")
  655. }
  656. feature, ok1 := faces["faceData"].(map[string]interface{})["theFeature"].([]interface{})
  657. if !ok1 || len(feature) == 0 {
  658. return "", imgName, err
  659. }
  660. // 转换 feature 字段为 []float64 类型
  661. var featureValues []float64
  662. for _, value := range feature {
  663. if floatValue, ok := value.(float64); ok {
  664. featureValues = append(featureValues, floatValue)
  665. } else {
  666. return "", imgName, err
  667. }
  668. }
  669. str := common.FloatSliceToString(featureValues)
  670. return str, imgName, nil
  671. }
  672. func GetMaxId(dataList []Staff) string {
  673. maxID := dataList[0].ID
  674. common.Info(common.GenLogLine()+"maxID:", maxID)
  675. for _, data := range dataList {
  676. if data.ID > maxID {
  677. maxID = data.ID
  678. common.Info(common.GenLogLine()+"maxID:%s", maxID)
  679. }
  680. }
  681. return maxID
  682. }
  683. func GetNewestModified(dataList []Req) string {
  684. if len(dataList) == 0 {
  685. return ""
  686. }
  687. maxID := dataList[0].Modified
  688. return maxID
  689. }
  690. func TimerHandle() {
  691. fmt.Printf("TimerHandle start %d\n", timeStep)
  692. ticker := time.NewTicker(time.Second * time.Duration(timeStep))
  693. defer ticker.Stop()
  694. for range ticker.C { //十秒执行一次
  695. common.Info(common.GenLogLine() + "=====执行timerHandle开始=====")
  696. now := time.Now()
  697. // 将时间设置为23点59分59秒
  698. t := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 55, 0, now.Location())
  699. common.Info(common.GenLogLine() + "--1,执行日志分割 START--")
  700. duration := t.Sub(now)
  701. isWithin10Seconds := duration > 0*time.Second && duration <= time.Duration(timeStep)*time.Second
  702. fmt.Fprintln(os.Stdout, isWithin10Seconds)
  703. if isWithin10Seconds {
  704. common.Info(common.GenLogLine() + "--1.1执行RenameLogFile--")
  705. common.RenameLogFile()
  706. }
  707. common.Info(common.GenLogLine() + "--1,执行日志分割 END--")
  708. common.Info(common.GenLogLine() + "--2,数据同步 START--")
  709. //获取接口数据
  710. staffs := Fetch()
  711. cachedTime := common.GetCache("maxTime")
  712. if len(staffs) == 0 {
  713. common.Info(common.GenLogLine() + "数据为空")
  714. } else {
  715. //获取最新更新时间
  716. maxTime := GetNewestModified(staffs)
  717. var t1 time.Time
  718. var t2 time.Time
  719. var t3 time.Time
  720. if cachedTime == "" {
  721. cachedTime = common.ReadFile("di.txt")
  722. common.SetCacheWithExpire("maxTime", cachedTime, 0)
  723. }
  724. t1, _ = time.Parse("2006-01-02 15:04:05", cachedTime)
  725. t2, _ = time.Parse("2006-01-02 15:04:05", maxTime)
  726. if !t2.After(t1) {
  727. common.Info(common.GenLogLine() + "--2.1, 数据已被同步")
  728. } else {
  729. common.SetCacheWithExpire("maxTime", maxTime, 0)
  730. for _, staff := range staffs {
  731. time.Sleep(1 * time.Second) // 暂停1秒
  732. t3, _ = time.Parse("2006-01-02 15:04:05", staff.Modified)
  733. if t3.After(t1) {
  734. staff.StaffBase64Img = FetchStaffImage(staff.Code)
  735. common.Info(common.GenLogLine()+"----%v", "" == staff.StaffBase64Img)
  736. str := HandleStaff(staff)
  737. common.Info(common.GenLogLine()+"--2.2注册人员 姓名:%s 编号:%s 更新时间:%s--\n", staff.StaffName, staff.Code, staff.Modified)
  738. //str := RegOnlineStaff(staff)
  739. ss := ""
  740. if str == nil {
  741. ss = "保存成功"
  742. } else {
  743. ss = str.Error()
  744. }
  745. fmt.Printf("注册人员:%v\n", ss)
  746. common.Info(common.GenLogLine()+"--2.3注册人员:%v--\n", ss)
  747. } else {
  748. break
  749. }
  750. }
  751. common.WriteFile("di.txt", maxTime)
  752. common.Info(common.GenLogLine()+"--2.4,数据同步,缓存数据maxID-- :%s", common.GetCache("maxTime"))
  753. }
  754. }
  755. common.Info(common.GenLogLine() + "--2,数据同步 END--")
  756. common.Info(common.GenLogLine() + "=====执行timerHandle结束=====")
  757. }
  758. }
  759. func EmpToReq(emp mydatabase.Emp) Req {
  760. var req Req
  761. req.StaffName = emp.Name
  762. req.StaffType = 5 //普通员工
  763. req.Phone = emp.Phone
  764. req.StaffBase64Img = emp.Avatar
  765. req.FaceFeature = emp.Features
  766. return req
  767. }