task.go 14 KB

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