task.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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].Name
  259. }
  260. saveMap["infoAttribute"] = InfoCodes[it-1].Code
  261. saveMap["isPublic"] = InfoCodes[it-1].IsPublic //是否公开
  262. }
  263. } else if f == "recommended_service" {
  264. saveMap[SaveFields[f]] = util.IntAll(tmp[f])
  265. } else {
  266. if s := util.ObjToString(tmp[f]); s != "" {
  267. saveMap[SaveFields[f]] = s
  268. if SaveFields[f] == "buyer" || SaveFields[f] == "buyerperson" || SaveFields[f] == "buyertel" ||
  269. SaveFields[f] == "area" || SaveFields[f] == "city" {
  270. jyMap[SaveFields[f]] = s
  271. }
  272. }
  273. }
  274. }
  275. now := time.Now()
  276. saveMap["comeintime"] = now.Unix()
  277. saveMap["publishtime"] = now.Unix()
  278. saveMap["contenthtml"] = tmp["detail"]
  279. cut := util.NewCut().ClearHtml(util.ObjToString(tmp["detail"]))
  280. tmp["detail"] = cut
  281. saveMap["s_sha"] = Sha(cut)
  282. saveMap["site"] = "剑鱼信息发布平台"
  283. saveMap["channel"] = "公告"
  284. saveMap["spidercode"] = "a_jyxxfbpt_gg"
  285. saveMap["extracttype"] = 0
  286. saveMap["areaval"] = 0
  287. saveMap["detail_isvalidity"] = 1
  288. saveMap["infoformat"] = 1
  289. saveMap["dataging"] = 0
  290. saveMap["buyerhint"] = util.IntAll(tmp["contact_overt"])
  291. _id := primitive.NewObjectID()
  292. saveMap["_id"] = _id
  293. saveMap["href"] = fmt.Sprintf(JyUrl, util.CommonEncodeArticle("content", mongodb.BsonIdToSId(_id)))
  294. saveMap["competehref"] = "#"
  295. saveMap["jyfb_data"] = jyMap
  296. saveMap["jyfb_id"] = util.ObjToString(info["id"])
  297. Logger.Debug("InfoPub mgo save: " + fmt.Sprint(saveMap))
  298. MgoBid.SaveByOriID(BidColl, saveMap)
  299. }
  300. type AttsResponse struct {
  301. Other AttsOther `json:"other"`
  302. Result []*AttsResult `json:"result"`
  303. }
  304. type AttsOther struct {
  305. Id string `json:"id"`
  306. Action string `json:"action"`
  307. MsgType string `json:"msgType"`
  308. Detail []string `json:"detail"`
  309. Title []string `json:"title"`
  310. }
  311. type AttsResult struct {
  312. FileName string `json:"fileName"`
  313. TextUrl string `json:"textUrl"`
  314. TextContent string `json:"textContent"`
  315. FilePath string `json:"filePath"`
  316. ErrorState string `json:"errorState"`
  317. }
  318. // @Description 附件处理完成队列
  319. // @Author J 2022/4/13 3:29 PM
  320. func taskAtts(obj map[string]interface{}) {
  321. atts := make(map[string]interface{})
  322. atts_text := make(map[string]interface{})
  323. for i, r := range obj["result"].([]interface{}) {
  324. r1 := r.(map[string]interface{})
  325. at := make(map[string]interface{})
  326. text := make(map[string]interface{})
  327. at["state"] = r1["errorState"].(string)
  328. if r1["errorState"].(string) == "200" {
  329. textContent := OssGetObject(util.ObjToString(r1["textUrl"]))
  330. at["sensitive"] = WordsIdentify(textContent)
  331. text["file_name"] = r1["fileName"].(string)
  332. text["attach_url"] = r1["textUrl"].(string)
  333. }
  334. atts[strconv.Itoa(i)] = at
  335. if len(text) > 0 {
  336. atts_text[strconv.Itoa(i)] = text
  337. }
  338. }
  339. attsJson, _ := json.Marshal(atts)
  340. attsTextJson, _ := json.Marshal(atts_text)
  341. // 直接调用剑鱼接口
  342. var other map[string]interface{}
  343. _ = json.Unmarshal([]byte(util.ObjToString(obj["other"])), &other)
  344. req := &jypb.SensitiveRequest{
  345. Id: util.ObjToString(other["id"]),
  346. MsgType: util.ObjToString(other["msgType"]),
  347. //Action: util.ObjToString(obj.Other.Action),
  348. Title: util.ObjArrToStringArr(other["title"].([]interface{})),
  349. Detail: util.ObjArrToStringArr(other["detail"].([]interface{})),
  350. Attachments: string(attsJson),
  351. AttachTxt: string(attsTextJson),
  352. }
  353. Logger.Debug("JyRpcSensitive request: " + fmt.Sprint(req))
  354. JyRpcSensitive(req)
  355. }
  356. // @Description 敏感词识别完成调用剑鱼接口
  357. // @Author J 2022/4/13 11:16 AM
  358. func JyRpcSensitive(req *jypb.SensitiveRequest) {
  359. conn := JyRpcClient.Conn()
  360. jyIntf := jypb.NewCommonInfoClient(conn)
  361. resp, err := jyIntf.SensitiveMethod(context.Background(), req)
  362. if err != nil {
  363. Logger.Error(err.Error())
  364. initEtcd()
  365. resp, err = jyIntf.SensitiveMethod(context.Background(), req)
  366. if err != nil {
  367. Logger.Error(err.Error())
  368. }
  369. }
  370. Logger.Info("JyRpcSensitive response: " + resp.String())
  371. }
  372. // @Description 信息删除(es、bidding、extract、project)
  373. // @Author J 2022/4/8 4:37 PM:00
  374. func DelMethod(res string) {
  375. if !bson.IsObjectIdHex(res) {
  376. Logger.Error(" bidding del fail, id err" + res)
  377. return
  378. }
  379. q := map[string]interface{}{"_id": mongodb.StringTOBsonId(res)}
  380. b := MgoBid.Del(BidColl, q)
  381. if !b {
  382. Logger.Error(" bidding del fail...")
  383. }
  384. b = MgoExt.Del(ExtColl, q)
  385. if !b {
  386. Logger.Error(" extract del fail...")
  387. }
  388. Es.DelById(Index, res)
  389. //Es.DelById(IndexAll, Itype, res)
  390. project := Sysconfig["project"].(map[string]interface{})
  391. by, _ := json.Marshal(map[string]interface{}{
  392. "infoid": res,
  393. "stype": "deleteInfo",
  394. })
  395. addr := &net.UDPAddr{
  396. IP: net.ParseIP(project["addr"].(string)),
  397. Port: util.IntAll(project["port"]),
  398. }
  399. Logger.Debug(string(by))
  400. _ = UdpClient.WriteUdp(by, udp.OP_TYPE_DATA, addr)
  401. }
  402. // @Description 数据处理完成调用jy接口
  403. // @Author J 2022/4/9 11:41 AM
  404. func JyRpcDataFin(_id string) {
  405. info, _ := MgoBid.FindById(BidColl, _id, `{"jyfb_id": 1}`)
  406. if len(*info) == 0 {
  407. Logger.Error("JyRpcDataFin mgo not find, id: " + _id)
  408. return
  409. }
  410. conn := JyRpcClient.Conn()
  411. req := &jypb.StateRequest{
  412. Id: util.ObjToString((*info)["jyfb_id"]),
  413. PublishId: _id,
  414. }
  415. jyIntf := jypb.NewCommonInfoClient(conn)
  416. Logger.Info("JyRpcDataFin request: " + req.String())
  417. resp, err := jyIntf.StateMethod(context.Background(), req)
  418. if err != nil {
  419. Logger.Error(err.Error())
  420. initEtcd()
  421. resp, err = jyIntf.StateMethod(context.Background(), req)
  422. if err != nil {
  423. Logger.Error(err.Error())
  424. }
  425. }
  426. Logger.Info("JyRpcDataFin response: " + resp.String())
  427. }
  428. var reg = regexp.MustCompile("[^0-9A-Za-z\u4e00-\u9fa5]+")
  429. var Filter = regexp.MustCompile("<[^>]*?>|[\\s\u3000\u2003\u00a0]")
  430. func Sha(con string) string {
  431. h := sha256.New()
  432. con = reg.ReplaceAllString(Filter.ReplaceAllString(con, ""), "")
  433. h.Write([]byte(con))
  434. return fmt.Sprintf("%x", h.Sum(nil))
  435. }