task.go 14 KB

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