task.go 15 KB

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