task.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. package tool
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "encoding/json"
  6. "fmt"
  7. "go.mongodb.org/mongo-driver/bson/primitive"
  8. "google.golang.org/grpc"
  9. "gopkg.in/mgo.v2/bson"
  10. "jy_publishing/Logger"
  11. jypb "jy_publishing/proto/common"
  12. pb "jy_publishing/proto/proto"
  13. "jygit.jydev.jianyu360.cn/BP/servicerd/proto"
  14. util "jygit.jydev.jianyu360.cn/data_processing/common_utils"
  15. "jygit.jydev.jianyu360.cn/data_processing/common_utils/mongodb"
  16. "jygit.jydev.jianyu360.cn/data_processing/common_utils/udp"
  17. "log"
  18. "net"
  19. "regexp"
  20. "strconv"
  21. "strings"
  22. "time"
  23. )
  24. var (
  25. JyUrl = "https://www.jianyu360.cn/article/content/%s.html"
  26. InfoFields = []string{"title", "project_code", "province", "city", "industry", "buyer", "budget", "winner", "amount",
  27. "detail", "attch", "contact_person", "contact_phone", "attach", "discern_attach", "type", "recommended_service", "deliveryAddress"}
  28. )
  29. var SaveFields = map[string]string{
  30. "title": "title",
  31. "project_code": "projectcode",
  32. "province": "area",
  33. "city": "city",
  34. "buyer": "buyer",
  35. "budget": "budget",
  36. "winner": "s_winner",
  37. "amount": "bidamount",
  38. "detail": "detail",
  39. "contact_phone": "buyertel",
  40. "contact_person": "buyerperson",
  41. "discern_attach": "attach_text",
  42. "type": "type", // 消息类型
  43. "recommended_service": "recommended_service", // 供应商推荐服务
  44. "deliveryAddress": "deliveryAddress",
  45. //"attch": "",
  46. //"industry": "",
  47. //"contract_overt": "",
  48. }
  49. var InfoType = map[int]string{
  50. 1: "招标信息",
  51. 2: "采购信息",
  52. 4: "招标公告",
  53. 5: "采购意向",
  54. 6: "招标预告",
  55. 7: "招标结果",
  56. 8: "直采-采购信息",
  57. }
  58. // @Description 信息处理(信息发布和附件识别)
  59. // 1、敏感词处理,2、信息发布,3、信息删除
  60. // @Author J 2022/4/9 11:47 AM
  61. func TaskInfo(obj interface{}) {
  62. info, _ := obj.(map[string]interface{})
  63. if util.ObjToString(info["action"]) == "1" {
  64. // 敏感词处理
  65. Sensitive(info)
  66. } else if util.ObjToString(info["action"]) == "2" {
  67. // 数据处理
  68. InfoPub(info)
  69. } else if util.ObjToString(info["action"]) == "3" {
  70. //id := util.ObjToString(info["id"])
  71. tmp := info["appendInfo"].(map[string]interface{})
  72. DelMethod(util.IntAll(tmp["type"]), util.ObjToString(tmp["publish_id"]))
  73. }
  74. }
  75. // @Description 敏感词处理(title, content, attachment)
  76. // @Author J 2022/4/11 9:36 AM
  77. func Sensitive(info map[string]interface{}) {
  78. tmp := info["appendInfo"].(map[string]interface{})
  79. tArr := WordsIdentify(util.ObjToString(tmp["title"]))
  80. dArr := WordsIdentify(util.ObjToString(tmp["detail"]))
  81. if attsMap, ok := tmp["attach"].(map[string]interface{}); ok && len(attsMap) > 0 {
  82. other := map[string]interface{}{
  83. "id": info["id"],
  84. "action": info["action"],
  85. "msgType": info["msgType"],
  86. "title": tArr,
  87. "detail": dArr,
  88. }
  89. otherJson, _ := json.Marshal(other)
  90. var attsArr []*pb.Request
  91. for _, m := range attsMap {
  92. m1 := m.(map[string]interface{})
  93. attsArr = append(attsArr, &pb.Request{
  94. FileUrl: util.ObjToString(m1["fid"]),
  95. FileName: util.ObjToString(m1["filename"]),
  96. FileType: util.ObjToString(m1["ftype"]),
  97. //ReturnType: 0, // 不传
  98. ExtractType: 0,
  99. })
  100. }
  101. msginfo := &pb.FileRequest{
  102. Message: attsArr,
  103. Other: string(otherJson),
  104. Topic: FileTopicResult,
  105. }
  106. Logger.Debug("file extract send nsq: " + fmt.Sprint(msginfo))
  107. _ = MProducer.Publish(msginfo)
  108. } else {
  109. // 没有附件
  110. Logger.Debug("title sensitive array: " + fmt.Sprint(tArr))
  111. Logger.Debug("detail sensitive array: " + fmt.Sprint(dArr))
  112. req := &jypb.SensitiveRequest{
  113. Id: util.ObjToString(info["id"]),
  114. MsgType: util.ObjToString(info["msgType"]),
  115. Title: tArr,
  116. Detail: dArr,
  117. }
  118. Logger.Debug("JyRpcSensitive request: " + fmt.Sprint(req))
  119. JyRpcSensitive(req)
  120. }
  121. //atts := tmp["attachment"].(map[string]interface{})
  122. //resultAtts := make(map[string]interface{})
  123. //resultAttach := make(map[string]interface{})
  124. //for k, v := range atts {
  125. // attach := make(map[string]interface{}) // attach_text字段
  126. // resp, err := AttsMethod(v.(map[string]interface{}))
  127. // if err != nil {
  128. // return nil
  129. // }
  130. // for i, r := range resp.Result {
  131. // if w := WordsIdentify(r.TextContent); w != nil {
  132. // resultAtts[k] = w
  133. // }
  134. // attach[strconv.Itoa(i)] = map[string]interface{}{"file_name": r.FileName, "attach_url": r.TextUrl}
  135. // }
  136. // resultAttach[k] = attach
  137. //}
  138. //resultMap["attach_text"] = resultAttach
  139. //resultMap["attachment"] = resultAtts
  140. }
  141. // @Description 敏感词识别
  142. // @Author J 2022/4/12 1:33 PM
  143. func WordsIdentify(str string) []string {
  144. if str == "" {
  145. return nil
  146. }
  147. ret := Ms.Discern(str, 2)
  148. if len(ret) > 0 {
  149. var words []string
  150. for _, r := range ret {
  151. words = append(words, r.MatchRule)
  152. }
  153. return words
  154. }
  155. return []string{}
  156. }
  157. // @Description 附件调用gRpc接口处理
  158. // @Author J 2022/4/12 10:02 AM
  159. // Deprecated
  160. func AttsMethod(att map[string]interface{}) (*pb.FileResponse, error) {
  161. reqs := &pb.FileRequest{
  162. Message: []*pb.Request{{
  163. FileName: "",
  164. FileType: "",
  165. FileUrl: ""}},
  166. Other: "",
  167. }
  168. // 1.调用gRPC接口
  169. conn, err := grpc.Dial(ClientAddr, grpc.WithInsecure())
  170. if err != nil {
  171. return nil, err
  172. }
  173. var client proto.ServiceClient
  174. client = proto.NewServiceClient(conn)
  175. repl, err := client.Apply(context.Background(), &proto.ApplyReqData{Name: "extract_service", Balance: 0})
  176. if err != nil {
  177. return nil, err
  178. }
  179. //2.业务调用
  180. addr := fmt.Sprintf("%s:%d", repl.Ip, repl.Port)
  181. conn_b, err := grpc.Dial(addr, grpc.WithInsecure())
  182. if err != nil {
  183. return nil, err
  184. }
  185. defer func(conn_b *grpc.ClientConn) {
  186. _ = conn_b.Close()
  187. }(conn_b)
  188. pc := pb.NewFileExtractClient(conn_b)
  189. rep, err := pc.FileExtract(context.Background(), reqs)
  190. if err != nil {
  191. return nil, err
  192. }
  193. return rep, nil
  194. }
  195. type DeliveryAddress struct {
  196. Area string `json:"area"`
  197. City string `json:"city"`
  198. Districts string `json:"districts"`
  199. DetailsAddr string `json:"detailsAddr"`
  200. }
  201. // @Description 信息发布
  202. // @Author J 2022/4/12 1:57 PM
  203. func InfoPub(info map[string]interface{}) {
  204. tmp := info["appendInfo"].(map[string]interface{})
  205. saveMap := make(map[string]interface{})
  206. jyMap := make(map[string]interface{})
  207. extractType := 0
  208. for _, f := range InfoFields {
  209. if tmp[f] == nil {
  210. continue
  211. }
  212. //交付地址
  213. if f == "deliveryAddress" {
  214. daStr := util.ObjToString(tmp[f])
  215. var da = DeliveryAddress{}
  216. err := json.Unmarshal([]byte(daStr), &da)
  217. if err == nil && da.Area != "" {
  218. saveMap["deliver_area"] = da.Area
  219. saveMap["deliver_city"] = da.City
  220. saveMap["deliver_district"] = da.Districts
  221. saveMap["deliver_detail"] = da.DetailsAddr
  222. }
  223. } else if f == "budget" || f == "amount" {
  224. saveMap[SaveFields[f]] = util.Float64All(tmp[f])
  225. jyMap[f] = util.Float64All(tmp[f])
  226. } else if f == "industry" {
  227. // topscopeclass/subcopeclass
  228. //if s := util.ObjToString(tmp[f]); s != "" {
  229. //
  230. // for _, s2 := range strings.Split(s, ",") {
  231. // arr := strings.Split(s2, "_")
  232. // // todo
  233. // }
  234. //}
  235. } else if f == "winner" {
  236. if s := util.ObjToString(tmp[f]); s != "" {
  237. s = strings.ReplaceAll(s, ",", ",") //中文变英文
  238. saveMap[SaveFields[f]] = s
  239. saveMap[f] = s
  240. jyMap[f] = s
  241. jyMap[SaveFields[f]] = s
  242. }
  243. } else if f == "attach" {
  244. s := util.ObjToString(tmp[f])
  245. if s != "" {
  246. atts := map[string]interface{}{}
  247. if err := json.Unmarshal([]byte(s), &atts); err != nil {
  248. Logger.Error("data Unmarshal Failed:", Logger.Field("error", err))
  249. }
  250. for _, i := range atts {
  251. i2 := i.(map[string]interface{})
  252. //delete(i2, "uid")
  253. delete(i2, "ossurl")
  254. i2["url"] = "oss"
  255. }
  256. saveMap["projectinfo"] = map[string]interface{}{"attachments": atts}
  257. saveMap["isValidFile"] = true
  258. }
  259. } else if f == "discern_attach" {
  260. if s := util.ObjToString(tmp[f]); s != "" {
  261. atts_txt := map[string]interface{}{}
  262. if err := json.Unmarshal([]byte(s), &atts_txt); err != nil {
  263. Logger.Error("data Unmarshal Failed:", Logger.Field("error", err))
  264. }
  265. for k, v := range atts_txt {
  266. atts_txt[k] = map[string]interface{}{k: v}
  267. }
  268. saveMap[SaveFields[f]] = atts_txt
  269. }
  270. } else if f == "type" {
  271. jyMap[f] = InfoType[0]
  272. it := util.IntAll(tmp[f])
  273. infoType := InfoType[it]
  274. if infoType != "" {
  275. jyMap[f] = infoType
  276. }
  277. if len(InfoCodes) >= it {
  278. if infoType == "" {
  279. jyMap[f] = InfoCodes[it-1].Name
  280. }
  281. saveMap["infoattribute"] = InfoCodes[it-1].Code
  282. saveMap["ispublic"] = InfoCodes[it-1].IsPublic //是否公开
  283. extractType = InfoCodes[it-1].ExtractType
  284. }
  285. } else if f == "recommended_service" {
  286. saveMap[SaveFields[f]] = util.IntAll(tmp[f])
  287. } else {
  288. if s := util.ObjToString(tmp[f]); s != "" {
  289. saveMap[SaveFields[f]] = s
  290. if SaveFields[f] == "buyer" || SaveFields[f] == "buyerperson" || SaveFields[f] == "buyertel" ||
  291. SaveFields[f] == "area" || SaveFields[f] == "city" {
  292. jyMap[SaveFields[f]] = s
  293. }
  294. }
  295. }
  296. }
  297. now := time.Now()
  298. saveMap["comeintime"] = now.Unix()
  299. saveMap["publishtime"] = now.Unix()
  300. saveMap["contenthtml"] = tmp["detail"]
  301. cut := util.NewCut().ClearHtml(util.ObjToString(tmp["detail"]))
  302. tmp["detail"] = cut
  303. saveMap["s_sha"] = Sha(cut)
  304. saveMap["site"] = "剑鱼信息发布平台"
  305. saveMap["channel"] = "公告"
  306. saveMap["spidercode"] = "a_jyxxfbpt_gg"
  307. saveMap["extracttype"] = extractType
  308. saveMap["areaval"] = 0
  309. saveMap["detail_isvalidity"] = 1
  310. saveMap["infoformat"] = 1
  311. saveMap["dataging"] = 0
  312. saveMap["buyerhint"] = util.IntAll(tmp["contact_overt"])
  313. _id := primitive.NewObjectID()
  314. saveMap["_id"] = _id
  315. saveMap["href"] = fmt.Sprintf(JyUrl, util.CommonEncodeArticle("content", mongodb.BsonIdToSId(_id)))
  316. saveMap["competehref"] = "#"
  317. saveMap["jyfb_data"] = jyMap
  318. saveMap["jyfb_id"] = util.ObjToString(info["id"])
  319. saveMap["public_type"] = "用户发布"
  320. Logger.Debug("InfoPub mgo save: " + fmt.Sprint(saveMap))
  321. MgoBid.SaveByOriID(BidColl, saveMap)
  322. }
  323. type AttsResponse struct {
  324. Other AttsOther `json:"other"`
  325. Result []*AttsResult `json:"result"`
  326. }
  327. type AttsOther struct {
  328. Id string `json:"id"`
  329. Action string `json:"action"`
  330. MsgType string `json:"msgType"`
  331. Detail []string `json:"detail"`
  332. Title []string `json:"title"`
  333. }
  334. type AttsResult struct {
  335. FileName string `json:"fileName"`
  336. TextUrl string `json:"textUrl"`
  337. TextContent string `json:"textContent"`
  338. FilePath string `json:"filePath"`
  339. ErrorState string `json:"errorState"`
  340. }
  341. // @Description 附件处理完成队列
  342. // @Author J 2022/4/13 3:29 PM
  343. func TaskAtts(obj map[string]interface{}) {
  344. atts := make(map[string]interface{})
  345. atts_text := make(map[string]interface{})
  346. for i, r := range obj["result"].([]interface{}) {
  347. r1 := r.(map[string]interface{})
  348. at := make(map[string]interface{})
  349. text := make(map[string]interface{})
  350. at["state"] = r1["errorState"].(string)
  351. if r1["errorState"].(string) == "200" {
  352. textContent := OssGetObject(util.ObjToString(r1["textUrl"]))
  353. at["sensitive"] = WordsIdentify(textContent)
  354. text["file_name"] = r1["fileName"].(string)
  355. text["attach_url"] = r1["textUrl"].(string)
  356. }
  357. atts[strconv.Itoa(i)] = at
  358. if len(text) > 0 {
  359. atts_text[strconv.Itoa(i)] = text
  360. }
  361. }
  362. attsJson, _ := json.Marshal(atts)
  363. attsTextJson, _ := json.Marshal(atts_text)
  364. // 直接调用剑鱼接口
  365. var other map[string]interface{}
  366. _ = json.Unmarshal([]byte(util.ObjToString(obj["other"])), &other)
  367. req := &jypb.SensitiveRequest{
  368. Id: util.ObjToString(other["id"]),
  369. MsgType: util.ObjToString(other["msgType"]),
  370. //Action: util.ObjToString(obj.Other.Action),
  371. Title: util.ObjArrToStringArr(other["title"].([]interface{})),
  372. Detail: util.ObjArrToStringArr(other["detail"].([]interface{})),
  373. Attachments: string(attsJson),
  374. AttachTxt: string(attsTextJson),
  375. }
  376. Logger.Debug("JyRpcSensitive request: " + fmt.Sprint(req))
  377. JyRpcSensitive(req)
  378. }
  379. // @Description 敏感词识别完成调用剑鱼接口
  380. // @Author J 2022/4/13 11:16 AM
  381. func JyRpcSensitive(req *jypb.SensitiveRequest) {
  382. conn := JyRpcClient.Conn()
  383. jyIntf := jypb.NewCommonInfoClient(conn)
  384. resp, err := jyIntf.SensitiveMethod(context.Background(), req)
  385. if err != nil {
  386. Logger.Error(err.Error())
  387. InitEtcd()
  388. resp, err = jyIntf.SensitiveMethod(context.Background(), req)
  389. if err != nil {
  390. Logger.Error(err.Error())
  391. }
  392. }
  393. Logger.Info("JyRpcSensitive response: " + resp.String())
  394. }
  395. // @Description 信息删除(es、bidding、extract、project)
  396. // @Author J 2022/4/8 4:37 PM:00
  397. func DelMethod(mold int, res string) {
  398. if !bson.IsObjectIdHex(res) {
  399. Logger.Error(" bidding del fail, id err" + res)
  400. return
  401. }
  402. q := map[string]interface{}{"_id": mongodb.StringTOBsonId(res)}
  403. b := MgoBid.Del(BidColl, q)
  404. if !b {
  405. Logger.Error(" bidding del fail...")
  406. }
  407. b = MgoExt.Del(ExtColl, q)
  408. if !b {
  409. Logger.Error(" extract del fail...")
  410. }
  411. switch mold {
  412. case 8:
  413. Index = "bidding_yg" //直采-采购信息
  414. var (
  415. ok bool
  416. id string
  417. )
  418. data := Es.Get(Index, `{"query": {"bool": {"must": [{"terms": {"source_id": ["`+res+`"]}}]}},"from": 0,"size": 1}`)
  419. if data != nil && len(*data) > 0 {
  420. one := (*data)[0]
  421. id = util.ObjToString(one["id"])
  422. if id != "" {
  423. ok = Es.DelById(Index, id)
  424. } else {
  425. ok = Es.DelById(Index, res)
  426. }
  427. }
  428. if !ok {
  429. log.Println(id, "用户删除发布信息后 删除索引信息失败:", data, "----", res)
  430. }
  431. default:
  432. Es.DelById(Index, res)
  433. }
  434. //Es.DelById(IndexAll, Itype, res)
  435. project := Sysconfig["project"].(map[string]interface{})
  436. by, _ := json.Marshal(map[string]interface{}{
  437. "infoid": res,
  438. "stype": "deleteInfo",
  439. })
  440. addr := &net.UDPAddr{
  441. IP: net.ParseIP(project["addr"].(string)),
  442. Port: util.IntAll(project["port"]),
  443. }
  444. Logger.Debug(string(by))
  445. _ = UdpClient.WriteUdp(by, udp.OP_TYPE_DATA, addr)
  446. }
  447. // @Description 数据处理完成调用jy接口
  448. // @Author J 2022/4/9 11:41 AM
  449. func JyRpcDataFin(_id string) {
  450. info, _ := MgoBid.FindById(BidColl, _id, `{"jyfb_id": 1}`)
  451. if len(*info) == 0 {
  452. Logger.Error("JyRpcDataFin mgo not find, id: " + _id)
  453. return
  454. }
  455. conn := JyRpcClient.Conn()
  456. req := &jypb.StateRequest{
  457. Id: util.ObjToString((*info)["jyfb_id"]),
  458. PublishId: _id,
  459. }
  460. jyIntf := jypb.NewCommonInfoClient(conn)
  461. Logger.Info("JyRpcDataFin request: " + req.String())
  462. resp, err := jyIntf.StateMethod(context.Background(), req)
  463. if err != nil {
  464. Logger.Error(err.Error())
  465. InitEtcd()
  466. resp, err = jyIntf.StateMethod(context.Background(), req)
  467. if err != nil {
  468. Logger.Error(err.Error())
  469. }
  470. }
  471. Logger.Info("JyRpcDataFin response: " + resp.String())
  472. }
  473. var reg = regexp.MustCompile("[^0-9A-Za-z\u4e00-\u9fa5]+")
  474. var Filter = regexp.MustCompile("<[^>]*?>|[\\s\u3000\u2003\u00a0]")
  475. func Sha(con string) string {
  476. h := sha256.New()
  477. con = reg.ReplaceAllString(Filter.ReplaceAllString(con, ""), "")
  478. h.Write([]byte(con))
  479. return fmt.Sprintf("%x", h.Sum(nil))
  480. }