task.go 13 KB

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