task.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. "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", "deliveryAddress"}
  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. "deliveryAddress": "deliveryAddress",
  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. //交付地址
  212. if f == "deliveryAddress" {
  213. daStr := util.ObjToString(tmp[f])
  214. var da = DeliveryAddress{}
  215. err := json.Unmarshal([]byte(daStr), &da)
  216. if err == nil && da.Area != "" {
  217. saveMap["deliver_area"] = da.Area
  218. saveMap["deliver_city"] = da.City
  219. saveMap["deliver_district"] = da.Districts
  220. saveMap["deliver_detail"] = da.DetailsAddr
  221. }
  222. } else if f == "budget" || f == "amount" {
  223. saveMap[SaveFields[f]] = util.Float64All(tmp[f])
  224. jyMap[f] = util.Float64All(tmp[f])
  225. } else if f == "industry" {
  226. // topscopeclass/subcopeclass
  227. //if s := util.ObjToString(tmp[f]); s != "" {
  228. //
  229. // for _, s2 := range strings.Split(s, ",") {
  230. // arr := strings.Split(s2, "_")
  231. // // todo
  232. // }
  233. //}
  234. } else if f == "winner" {
  235. if s := util.ObjToString(tmp[f]); s != "" {
  236. s = strings.ReplaceAll(s, ",", ",") //中文变英文
  237. saveMap[SaveFields[f]] = s
  238. saveMap[f] = s
  239. jyMap[f] = s
  240. jyMap[SaveFields[f]] = s
  241. }
  242. } else if f == "attach" {
  243. s := util.ObjToString(tmp[f])
  244. if s != "" {
  245. atts := map[string]interface{}{}
  246. if err := json.Unmarshal([]byte(s), &atts); err != nil {
  247. Logger.Error("data Unmarshal Failed:", Logger.Field("error", err))
  248. }
  249. for _, i := range atts {
  250. i2 := i.(map[string]interface{})
  251. //delete(i2, "uid")
  252. delete(i2, "ossurl")
  253. i2["url"] = "oss"
  254. }
  255. saveMap["projectinfo"] = map[string]interface{}{"attachments": atts}
  256. }
  257. } else if f == "discern_attach" {
  258. if s := util.ObjToString(tmp[f]); s != "" {
  259. atts_txt := map[string]interface{}{}
  260. if err := json.Unmarshal([]byte(s), &atts_txt); err != nil {
  261. Logger.Error("data Unmarshal Failed:", Logger.Field("error", err))
  262. }
  263. for k, v := range atts_txt {
  264. atts_txt[k] = map[string]interface{}{k: v}
  265. }
  266. saveMap[SaveFields[f]] = atts_txt
  267. }
  268. } else if f == "type" {
  269. jyMap[f] = InfoType[0]
  270. it := util.IntAll(tmp[f])
  271. infoType := InfoType[it]
  272. if infoType != "" {
  273. jyMap[f] = infoType
  274. }
  275. if len(InfoCodes) >= it {
  276. if infoType == "" {
  277. jyMap[f] = InfoCodes[it-1].Name
  278. }
  279. saveMap["infoattribute"] = InfoCodes[it-1].Code
  280. saveMap["ispublic"] = InfoCodes[it-1].IsPublic //是否公开
  281. extractType = InfoCodes[it-1].ExtractType
  282. }
  283. } else if f == "recommended_service" {
  284. saveMap[SaveFields[f]] = util.IntAll(tmp[f])
  285. } else {
  286. if s := util.ObjToString(tmp[f]); s != "" {
  287. saveMap[SaveFields[f]] = s
  288. if SaveFields[f] == "buyer" || SaveFields[f] == "buyerperson" || SaveFields[f] == "buyertel" ||
  289. SaveFields[f] == "area" || SaveFields[f] == "city" {
  290. jyMap[SaveFields[f]] = s
  291. }
  292. }
  293. }
  294. }
  295. now := time.Now()
  296. saveMap["comeintime"] = now.Unix()
  297. saveMap["publishtime"] = now.Unix()
  298. saveMap["contenthtml"] = tmp["detail"]
  299. cut := util.NewCut().ClearHtml(util.ObjToString(tmp["detail"]))
  300. tmp["detail"] = cut
  301. saveMap["s_sha"] = Sha(cut)
  302. saveMap["site"] = "剑鱼信息发布平台"
  303. saveMap["channel"] = "公告"
  304. saveMap["spidercode"] = "a_jyxxfbpt_gg"
  305. saveMap["extracttype"] = extractType
  306. saveMap["areaval"] = 0
  307. saveMap["detail_isvalidity"] = 1
  308. saveMap["infoformat"] = 1
  309. saveMap["dataging"] = 0
  310. saveMap["buyerhint"] = util.IntAll(tmp["contact_overt"])
  311. _id := primitive.NewObjectID()
  312. saveMap["_id"] = _id
  313. saveMap["href"] = fmt.Sprintf(JyUrl, util.CommonEncodeArticle("content", mongodb.BsonIdToSId(_id)))
  314. saveMap["competehref"] = "#"
  315. saveMap["jyfb_data"] = jyMap
  316. saveMap["jyfb_id"] = util.ObjToString(info["id"])
  317. saveMap["public_type"] = "用户发布"
  318. Logger.Debug("InfoPub mgo save: " + fmt.Sprint(saveMap))
  319. MgoBid.SaveByOriID(BidColl, saveMap)
  320. }
  321. type AttsResponse struct {
  322. Other AttsOther `json:"other"`
  323. Result []*AttsResult `json:"result"`
  324. }
  325. type AttsOther struct {
  326. Id string `json:"id"`
  327. Action string `json:"action"`
  328. MsgType string `json:"msgType"`
  329. Detail []string `json:"detail"`
  330. Title []string `json:"title"`
  331. }
  332. type AttsResult struct {
  333. FileName string `json:"fileName"`
  334. TextUrl string `json:"textUrl"`
  335. TextContent string `json:"textContent"`
  336. FilePath string `json:"filePath"`
  337. ErrorState string `json:"errorState"`
  338. }
  339. // @Description 附件处理完成队列
  340. // @Author J 2022/4/13 3:29 PM
  341. func TaskAtts(obj map[string]interface{}) {
  342. atts := make(map[string]interface{})
  343. atts_text := make(map[string]interface{})
  344. for i, r := range obj["result"].([]interface{}) {
  345. r1 := r.(map[string]interface{})
  346. at := make(map[string]interface{})
  347. text := make(map[string]interface{})
  348. at["state"] = r1["errorState"].(string)
  349. if r1["errorState"].(string) == "200" {
  350. textContent := OssGetObject(util.ObjToString(r1["textUrl"]))
  351. at["sensitive"] = WordsIdentify(textContent)
  352. text["file_name"] = r1["fileName"].(string)
  353. text["attach_url"] = r1["textUrl"].(string)
  354. }
  355. atts[strconv.Itoa(i)] = at
  356. if len(text) > 0 {
  357. atts_text[strconv.Itoa(i)] = text
  358. }
  359. }
  360. attsJson, _ := json.Marshal(atts)
  361. attsTextJson, _ := json.Marshal(atts_text)
  362. // 直接调用剑鱼接口
  363. var other map[string]interface{}
  364. _ = json.Unmarshal([]byte(util.ObjToString(obj["other"])), &other)
  365. req := &jypb.SensitiveRequest{
  366. Id: util.ObjToString(other["id"]),
  367. MsgType: util.ObjToString(other["msgType"]),
  368. //Action: util.ObjToString(obj.Other.Action),
  369. Title: util.ObjArrToStringArr(other["title"].([]interface{})),
  370. Detail: util.ObjArrToStringArr(other["detail"].([]interface{})),
  371. Attachments: string(attsJson),
  372. AttachTxt: string(attsTextJson),
  373. }
  374. Logger.Debug("JyRpcSensitive request: " + fmt.Sprint(req))
  375. JyRpcSensitive(req)
  376. }
  377. // @Description 敏感词识别完成调用剑鱼接口
  378. // @Author J 2022/4/13 11:16 AM
  379. func JyRpcSensitive(req *jypb.SensitiveRequest) {
  380. conn := JyRpcClient.Conn()
  381. jyIntf := jypb.NewCommonInfoClient(conn)
  382. resp, err := jyIntf.SensitiveMethod(context.Background(), req)
  383. if err != nil {
  384. Logger.Error(err.Error())
  385. InitEtcd()
  386. resp, err = jyIntf.SensitiveMethod(context.Background(), req)
  387. if err != nil {
  388. Logger.Error(err.Error())
  389. }
  390. }
  391. Logger.Info("JyRpcSensitive response: " + resp.String())
  392. }
  393. // @Description 信息删除(es、bidding、extract、project)
  394. // @Author J 2022/4/8 4:37 PM:00
  395. func DelMethod(res string) {
  396. if !bson.IsObjectIdHex(res) {
  397. Logger.Error(" bidding del fail, id err" + res)
  398. return
  399. }
  400. q := map[string]interface{}{"_id": mongodb.StringTOBsonId(res)}
  401. b := MgoBid.Del(BidColl, q)
  402. if !b {
  403. Logger.Error(" bidding del fail...")
  404. }
  405. b = MgoExt.Del(ExtColl, q)
  406. if !b {
  407. Logger.Error(" extract del fail...")
  408. }
  409. Es.DelById(Index, res)
  410. //Es.DelById(IndexAll, Itype, res)
  411. project := Sysconfig["project"].(map[string]interface{})
  412. by, _ := json.Marshal(map[string]interface{}{
  413. "infoid": res,
  414. "stype": "deleteInfo",
  415. })
  416. addr := &net.UDPAddr{
  417. IP: net.ParseIP(project["addr"].(string)),
  418. Port: util.IntAll(project["port"]),
  419. }
  420. Logger.Debug(string(by))
  421. _ = UdpClient.WriteUdp(by, udp.OP_TYPE_DATA, addr)
  422. }
  423. // @Description 数据处理完成调用jy接口
  424. // @Author J 2022/4/9 11:41 AM
  425. func JyRpcDataFin(_id string) {
  426. info, _ := MgoBid.FindById(BidColl, _id, `{"jyfb_id": 1}`)
  427. if len(*info) == 0 {
  428. Logger.Error("JyRpcDataFin mgo not find, id: " + _id)
  429. return
  430. }
  431. conn := JyRpcClient.Conn()
  432. req := &jypb.StateRequest{
  433. Id: util.ObjToString((*info)["jyfb_id"]),
  434. PublishId: _id,
  435. }
  436. jyIntf := jypb.NewCommonInfoClient(conn)
  437. Logger.Info("JyRpcDataFin request: " + req.String())
  438. resp, err := jyIntf.StateMethod(context.Background(), req)
  439. if err != nil {
  440. Logger.Error(err.Error())
  441. InitEtcd()
  442. resp, err = jyIntf.StateMethod(context.Background(), req)
  443. if err != nil {
  444. Logger.Error(err.Error())
  445. }
  446. }
  447. Logger.Info("JyRpcDataFin response: " + resp.String())
  448. }
  449. var reg = regexp.MustCompile("[^0-9A-Za-z\u4e00-\u9fa5]+")
  450. var Filter = regexp.MustCompile("<[^>]*?>|[\\s\u3000\u2003\u00a0]")
  451. func Sha(con string) string {
  452. h := sha256.New()
  453. con = reg.ReplaceAllString(Filter.ReplaceAllString(con, ""), "")
  454. h.Write([]byte(con))
  455. return fmt.Sprintf("%x", h.Sum(nil))
  456. }