task.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. package main
  2. import (
  3. "app.yhyue.com/BP/servicerd/proto"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "google.golang.org/grpc"
  8. "gopkg.in/mgo.v2/bson"
  9. jypb "jy_publishing/proto/common"
  10. pb "jy_publishing/proto/proto"
  11. "net"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "utils"
  16. . "utils/log"
  17. "utils/mongodb"
  18. )
  19. var (
  20. JyUrl = "https://www.jianyu360.cn/article/content/%s.html"
  21. InfoFields = []string{"title", "project_code", "province", "city", "industry", "buyer", "budget", "winner", "amount",
  22. "detail", "attch", "contract_person", "contract_phone", "attach", "discern_attach"}
  23. )
  24. var SaveFields = map[string]string{
  25. "title": "title",
  26. "project_code": "projectcode",
  27. "province": "area",
  28. "city": "city",
  29. "buyer": "buyer",
  30. "budget": "budget",
  31. "winner": "s_winner",
  32. "amount": "bidamount",
  33. "detail": "detail",
  34. "contract_person": "buyerperson",
  35. "contract_phone": "buyertel",
  36. "discern_attach": "attach_text",
  37. //"attch": "",
  38. //"industry": "",
  39. //"contract_overt": "",
  40. }
  41. // @Description 信息处理(信息发布和附件识别)
  42. // 1、敏感词处理,2、信息发布,3、信息删除
  43. // @Author J 2022/4/9 11:47 AM
  44. func taskInfo(obj interface{}) {
  45. info, _ := obj.(map[string]interface{})
  46. if util.ObjToString(info["action"]) == "1" {
  47. // 敏感词处理
  48. Sensitive(info)
  49. } else if util.ObjToString(info["action"]) == "2" {
  50. // 数据处理
  51. InfoPub(info)
  52. } else if util.ObjToString(info["action"]) == "3" {
  53. //id := util.ObjToString(info["id"])
  54. tmp := info["appendInfo"].(map[string]interface{})
  55. DelMethod(util.ObjToString(tmp["publish_id"]))
  56. }
  57. }
  58. // @Description 敏感词处理(title, content, attachment)
  59. // @Author J 2022/4/11 9:36 AM
  60. func Sensitive(info map[string]interface{}) {
  61. tmp := info["appendInfo"].(map[string]interface{})
  62. tArr := WordsIdentify(util.ObjToString(tmp["title"]))
  63. dArr := WordsIdentify(util.ObjToString(tmp["detail"]))
  64. Logger.Debug("" + fmt.Sprintln(tmp))
  65. if attsMap, ok := tmp["attach"].(map[string]interface{}); ok && len(attsMap) > 0 {
  66. other := map[string]interface{}{
  67. "id": info["id"],
  68. "action": info["action"],
  69. "msgType": info["msgType"],
  70. "title": tArr,
  71. "detail": dArr,
  72. }
  73. otherJson, _ := json.Marshal(other)
  74. var attsArr []*pb.Request
  75. for _, m := range attsMap {
  76. m1 := m.(map[string]interface{})
  77. attsArr = append(attsArr, &pb.Request{
  78. FileUrl: util.ObjToString(m1["fid"]),
  79. FileName: util.ObjToString(m1["filename"]),
  80. FileType: util.ObjToString(m1["ftype"]),
  81. ReturnType: 1,
  82. ExtractType: 0,
  83. })
  84. }
  85. msginfo := &pb.FileRequest{
  86. Message: attsArr,
  87. Other: string(otherJson),
  88. Topic: FileTopicResult,
  89. }
  90. Logger.Debug("file extract send nsq: " + fmt.Sprint(msginfo))
  91. _ = MProducer.Publish(msginfo)
  92. } else {
  93. // 没有附件
  94. Logger.Debug("title sensitive array: " + fmt.Sprint(tArr))
  95. Logger.Debug("detail sensitive array: " + fmt.Sprint(dArr))
  96. req := &jypb.SensitiveRequest{
  97. Id: util.ObjToString(info["id"]),
  98. MsgType: util.ObjToString(info["msgType"]),
  99. Title: tArr,
  100. Detail: dArr,
  101. }
  102. Logger.Debug("JyRpcSensitive request: " + fmt.Sprint(req))
  103. JyRpcSensitive(req)
  104. }
  105. //atts := tmp["attachment"].(map[string]interface{})
  106. //resultAtts := make(map[string]interface{})
  107. //resultAttach := make(map[string]interface{})
  108. //for k, v := range atts {
  109. // attach := make(map[string]interface{}) // attach_text字段
  110. // resp, err := AttsMethod(v.(map[string]interface{}))
  111. // if err != nil {
  112. // return nil
  113. // }
  114. // for i, r := range resp.Result {
  115. // if w := WordsIdentify(r.TextContent); w != nil {
  116. // resultAtts[k] = w
  117. // }
  118. // attach[strconv.Itoa(i)] = map[string]interface{}{"file_name": r.FileName, "attach_url": r.TextUrl}
  119. // }
  120. // resultAttach[k] = attach
  121. //}
  122. //resultMap["attach_text"] = resultAttach
  123. //resultMap["attachment"] = resultAtts
  124. }
  125. // @Description 敏感词识别
  126. // @Author J 2022/4/12 1:33 PM
  127. func WordsIdentify(str string) []string {
  128. if str == "" {
  129. return nil
  130. }
  131. ret := Ms.Discern(str, 2)
  132. if len(ret) > 0 {
  133. var words []string
  134. for _, r := range ret {
  135. words = append(words, r.MatchRule)
  136. }
  137. return words
  138. }
  139. return []string{}
  140. }
  141. // @Description 附件调用gRpc接口处理
  142. // @Author J 2022/4/12 10:02 AM
  143. // Deprecated
  144. func AttsMethod(att map[string]interface{}) (*pb.FileResponse, error) {
  145. reqs := &pb.FileRequest{
  146. Message: []*pb.Request{{
  147. FileName: "",
  148. FileType: "",
  149. FileUrl: ""}},
  150. Other: "",
  151. }
  152. // 1.调用gRPC接口
  153. conn, err := grpc.Dial(ClientAddr, grpc.WithInsecure())
  154. if err != nil {
  155. return nil, err
  156. }
  157. var client proto.ServiceClient
  158. client = proto.NewServiceClient(conn)
  159. repl, err := client.Apply(context.Background(), &proto.ApplyReqData{Name: "extract_service", Balance: 0})
  160. if err != nil {
  161. return nil, err
  162. }
  163. //2.业务调用
  164. addr := fmt.Sprintf("%s:%d", repl.Ip, repl.Port)
  165. conn_b, err := grpc.Dial(addr, grpc.WithInsecure())
  166. if err != nil {
  167. return nil, err
  168. }
  169. defer func(conn_b *grpc.ClientConn) {
  170. _ = conn_b.Close()
  171. }(conn_b)
  172. pc := pb.NewFileExtractClient(conn_b)
  173. rep, err := pc.FileExtract(context.Background(), reqs)
  174. if err != nil {
  175. return nil, err
  176. }
  177. return rep, nil
  178. }
  179. // @Description 信息发布
  180. // @Author J 2022/4/12 1:57 PM
  181. func InfoPub(info map[string]interface{}) {
  182. tmp := info["appendInfo"].(map[string]interface{})
  183. saveMap := make(map[string]interface{})
  184. jyMap := make(map[string]interface{})
  185. for _, f := range InfoFields {
  186. if tmp[f] == nil {
  187. continue
  188. }
  189. if f == "budget" || f == "amount" {
  190. saveMap[SaveFields[f]] = util.Float64All(tmp[f])
  191. jyMap[f] = util.Float64All(tmp[f])
  192. } else if f == "industry" {
  193. // topscopeclass/subcopeclass
  194. //if s := util.ObjToString(tmp[f]); s != "" {
  195. //
  196. // for _, s2 := range strings.Split(s, ",") {
  197. // arr := strings.Split(s2, "_")
  198. // // todo
  199. // }
  200. //}
  201. } else if f == "winner" {
  202. if s := util.ObjToString(tmp[f]); s != "" {
  203. s = strings.ReplaceAll(s, ",", ",") //中文变英文
  204. saveMap[SaveFields[f]] = s
  205. saveMap[f] = s
  206. jyMap[f] = s
  207. jyMap[SaveFields[f]] = s
  208. }
  209. } else if f == "attach" {
  210. s := util.ObjToString(tmp[f])
  211. if s != "" {
  212. atts := map[string]interface{}{}
  213. if err := json.Unmarshal([]byte(s), &atts); err != nil {
  214. Logger.Error("data Unmarshal Failed:", Field("error", err))
  215. }
  216. saveMap["projectinfo"] = map[string]interface{}{"attachments": atts}
  217. }
  218. } else if f == "discern_attach" {
  219. if s := util.ObjToString(tmp[f]); s != "" {
  220. atts := map[string]interface{}{}
  221. if err := json.Unmarshal([]byte(s), &atts); err != nil {
  222. Logger.Error("data Unmarshal Failed:", Field("error", err))
  223. }
  224. saveMap[SaveFields[f]] = atts
  225. }
  226. } else {
  227. if s := util.ObjToString(tmp[f]); s != "" {
  228. saveMap[SaveFields[f]] = s
  229. if SaveFields[f] == "buyer" || SaveFields[f] == "buyerperson" || SaveFields[f] == "buyertel" ||
  230. SaveFields[f] == "area" || SaveFields[f] == "city" {
  231. jyMap[SaveFields[f]] = s
  232. }
  233. }
  234. }
  235. }
  236. now := time.Now()
  237. saveMap["comeintime"] = now.Unix()
  238. saveMap["publishtime"] = now.Unix()
  239. saveMap["contenthtml"] = tmp["detail"]
  240. cut := util.NewCut().ClearHtml(util.ObjToString(tmp["detail"]))
  241. tmp["detail"] = cut
  242. saveMap["site"] = "剑鱼信息发布平台"
  243. saveMap["channel"] = "公告"
  244. saveMap["spidercode"] = "a_jyxxfbpt_gg"
  245. saveMap["extracttype"] = 0
  246. saveMap["areaval"] = 0
  247. saveMap["infoformat"] = 1
  248. saveMap["dataging"] = 0
  249. saveMap["buyerhint"] = util.IntAll(tmp["contact_overt"])
  250. _id := bson.NewObjectIdWithTime(now)
  251. saveMap["href"] = fmt.Sprintf(JyUrl, util.CommonEncodeArticle("content", mongodb.BsonIdToSId(_id)))
  252. saveMap["competehref"] = "#"
  253. saveMap["jyfb_data"] = jyMap
  254. saveMap["jyfb_id"] = util.ObjToString(info["id"])
  255. Logger.Debug("InfoPub mgo save: " + fmt.Sprint(saveMap))
  256. MgoBid.SaveByOriID(BidColl, saveMap)
  257. }
  258. type AttsResponse struct {
  259. Other AttsOther `json:"other"`
  260. Result []*AttsResult `json:"result"`
  261. }
  262. type AttsOther struct {
  263. Id string `json:"id"`
  264. Action string `json:"action"`
  265. MsgType string `json:"msgType"`
  266. Detail []string `json:"detail"`
  267. Title []string `json:"title"`
  268. }
  269. type AttsResult struct {
  270. FileName string `json:"fileName"`
  271. TextUrl string `json:"textUrl"`
  272. TextContent string `json:"textContent"`
  273. FilePath string `json:"filePath"`
  274. ErrorState string `json:"errorState"`
  275. }
  276. // @Description 附件处理完成队列
  277. // @Author J 2022/4/13 3:29 PM
  278. func taskAtts(obj map[string]interface{}) {
  279. atts := make(map[string]interface{})
  280. atts_text := make(map[string]interface{})
  281. for i, r := range obj["result"].([]interface{}) {
  282. r1 := r.(map[string]interface{})
  283. at := make(map[string]interface{})
  284. text := make(map[string]interface{})
  285. at["state"] = r1["errorState"].(string)
  286. if r1["errorState"].(string) == "200" {
  287. at["sensitive"] = WordsIdentify(r1["textContent"].(string))
  288. text["file_name"] = r1["fileName"].(string)
  289. text["attach_url"] = r1["textUrl"].(string)
  290. }
  291. atts[strconv.Itoa(i)] = at
  292. if len(text) > 0 {
  293. atts_text[strconv.Itoa(i)] = text
  294. }
  295. }
  296. attsJson, _ := json.Marshal(atts)
  297. attsTextJson, _ := json.Marshal(atts_text)
  298. // 直接调用剑鱼接口
  299. var other map[string]interface{}
  300. _ = json.Unmarshal([]byte(util.ObjToString(obj["other"])), &other)
  301. req := &jypb.SensitiveRequest{
  302. Id: util.ObjToString(other["id"]),
  303. MsgType: util.ObjToString(other["msgType"]),
  304. //Action: util.ObjToString(obj.Other.Action),
  305. Title: util.ObjArrToStringArr(other["title"].([]interface{})),
  306. Detail: util.ObjArrToStringArr(other["detail"].([]interface{})),
  307. Attachments: string(attsJson),
  308. AttachTxt: string(attsTextJson),
  309. }
  310. Logger.Debug("JyRpcSensitive request: " + fmt.Sprint(req))
  311. JyRpcSensitive(req)
  312. }
  313. // @Description 敏感词识别完成调用剑鱼接口
  314. // @Author J 2022/4/13 11:16 AM
  315. func JyRpcSensitive(req *jypb.SensitiveRequest) {
  316. conn := JyRpcClient.Conn()
  317. jyIntf := jypb.NewCommonInfoClient(conn)
  318. resp, err := jyIntf.SensitiveMethod(context.Background(), req)
  319. if err != nil {
  320. Logger.Error(err.Error())
  321. initEtcd()
  322. resp, err = jyIntf.SensitiveMethod(context.Background(), req)
  323. if err != nil {
  324. Logger.Error(err.Error())
  325. }
  326. }
  327. Logger.Info("JyRpcSensitive response: " + resp.String())
  328. }
  329. // @Description 信息删除(es、bidding、extract、project)
  330. // @Author J 2022/4/8 4:37 PM:00
  331. func DelMethod(res string) {
  332. q := map[string]interface{}{"_id": mongodb.StringTOBsonId(res)}
  333. b := MgoBid.Del(BidColl, q)
  334. if !b {
  335. Logger.Error(" bidding del fail...")
  336. }
  337. b = MgoExt.Del(ExtColl, q)
  338. if !b {
  339. Logger.Error(" extract del fail...")
  340. }
  341. Es.DelById(Index, Itype, res)
  342. Es.DelById(IndexAll, Itype, res)
  343. project := Sysconfig["project"].(map[string]interface{})
  344. by, _ := json.Marshal(map[string]interface{}{
  345. "infoid": res,
  346. "stype": "deleteInfo",
  347. })
  348. addr := &net.UDPAddr{
  349. IP: net.ParseIP(project["addr"].(string)),
  350. Port: util.IntAll(project["port"]),
  351. }
  352. Logger.Debug(string(by))
  353. _ = UdpClient.WriteUdp(by, util.OP_TYPE_DATA, addr)
  354. }
  355. // @Description 数据处理完成调用jy接口
  356. // @Author J 2022/4/9 11:41 AM
  357. func JyRpcDataFin(_id string) {
  358. info, _ := MgoBid.FindById(BidColl, _id, `{"jyfb_id": 1}`)
  359. if len(*info) == 0 {
  360. Logger.Error("JyRpcDataFin mgo not find, id: " + _id)
  361. return
  362. }
  363. conn := JyRpcClient.Conn()
  364. req := &jypb.StateRequest{
  365. Id: util.ObjToString((*info)["jyfb_id"]),
  366. PublishId: _id,
  367. }
  368. jyIntf := jypb.NewCommonInfoClient(conn)
  369. Logger.Info("JyRpcDataFin request: " + req.String())
  370. resp, err := jyIntf.StateMethod(context.Background(), req)
  371. if err != nil {
  372. Logger.Error(err.Error())
  373. initEtcd()
  374. resp, err = jyIntf.StateMethod(context.Background(), req)
  375. if err != nil {
  376. Logger.Error(err.Error())
  377. }
  378. }
  379. Logger.Info("JyRpcDataFin response: " + resp.String())
  380. }