util.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. package util
  2. import (
  3. "bytes"
  4. "fmt"
  5. mgo "mongodb"
  6. qu "qfw/util"
  7. "regexp"
  8. "sort"
  9. sp "spiderutil"
  10. "strings"
  11. "time"
  12. "github.com/yuin/gopher-lua"
  13. )
  14. const Role_Admin, Role_Examine, Role_Dev = 3, 2, 1 //管理员,审核员,开发员
  15. var (
  16. //MgoE *mgo.MongodbSim //编辑器87
  17. MgoEB *mgo.MongodbSim //编辑器163
  18. MgoS *mgo.MongodbSim
  19. Province map[string][]string
  20. City map[string][]string
  21. DomainNameReg = regexp.MustCompile(`(http|https)[::]+`)
  22. DownLoadReg = regexp.MustCompile(`download\(.*?\)`)
  23. CodeTypeReg = regexp.MustCompile(`(utf8|utf-8|gbk)`)
  24. TitleFilterReg1 = regexp.MustCompile(`[\p{Han}]`)
  25. TitleFilterReg2 = regexp.MustCompile(`((上|下)一(页|篇)|阅读次数)`)
  26. DetailFilterReg1 = regexp.MustCompile(`((上|下)一(页|篇)|阅读次数|浏览次数|扫一扫|分享|区块链存证)`)
  27. Area []string //省份
  28. DomainReg = regexp.MustCompile(`(?://).+?(?:[::/])`)
  29. SymbolReg = regexp.MustCompile("[,,\\s\u3000\u2003\u00a0]+")
  30. ReplaceReg = regexp.MustCompile(`[]::/]+`)
  31. CheckText = `item["spidercode"]="%s";item["site"]="%s";item["channel"]="%s"`
  32. JsonDataMap = map[string]bool{ //jsondata
  33. "extweight": true,
  34. "projecthref": true,
  35. "sourcewebsite": true,
  36. "sourcehref": true,
  37. "area_city_district": true,
  38. "projectname": true,
  39. "projectcode": true,
  40. "approvalno": true,
  41. "projectscope": true,
  42. "item": true,
  43. "buyer": true,
  44. "agency": true,
  45. "budget": true,
  46. "buyer_info": true,
  47. "buyerperson": true,
  48. "buyertel": true,
  49. "buyeraddr": true,
  50. "projectaddr": true,
  51. "publishdept": true,
  52. "funds": true,
  53. "paymenttype": true,
  54. "projectscale": true,
  55. "bidmethod": true,
  56. "bidopentime": true,
  57. "agency_info": true,
  58. "agencyperson": true,
  59. "agencytel": true,
  60. "agencyaddr": true,
  61. "isppp": true,
  62. "winner": true,
  63. "winneraddr": true,
  64. "winnerperson": true,
  65. "winnertel": true,
  66. "bidamount": true,
  67. "currency": true,
  68. "experts": true,
  69. "bidamounttype": true,
  70. "contractname": true,
  71. "countryprojectcode": true,
  72. "contractnumber": true,
  73. "projectperiod": true,
  74. "signaturedate": true,
  75. "multipackage": true,
  76. "package": true,
  77. "supervisorrate": true,
  78. "jsoncontent": true,
  79. "purchasinglist": true,
  80. "toptype": true,
  81. "subtype": true,
  82. "winnerorder": true,
  83. "bidopendate": true,
  84. "bidtype": true,
  85. }
  86. Bu = "_bu" //创建采历史爬虫后缀
  87. )
  88. func InitMgo() {
  89. defer qu.Catch()
  90. //MgoE = &mgo.MongodbSim{
  91. // MongodbAddr: sp.Config.Dbaddr,
  92. // DbName: sp.Config.Dbname,
  93. // Size: 10,
  94. //}
  95. //MgoE.InitPool()
  96. MgoEB = &mgo.MongodbSim{
  97. MongodbAddr: sp.Config.BidEditor.Addr,
  98. DbName: sp.Config.BidEditor.Db,
  99. Size: sp.Config.BidEditor.Size,
  100. UserName: sp.Config.BidEditor.Username,
  101. Password: sp.Config.BidEditor.Password,
  102. }
  103. MgoEB.InitPool()
  104. MgoS = &mgo.MongodbSim{
  105. MongodbAddr: sp.Config.Dbaddr,
  106. DbName: sp.Config.Dbname2,
  107. Size: 10,
  108. }
  109. MgoS.InitPool()
  110. }
  111. // 初始化省市行政区划信息
  112. func InitAreaCity() {
  113. //qu.ReadConfig("areacity.json", &Province)
  114. //Area = append(Area, "全国")
  115. //for area, _ := range Province {
  116. // if area == "全国" {
  117. // continue
  118. // }
  119. // Area = append(Area, area)
  120. //}
  121. Province = map[string][]string{}
  122. City = map[string][]string{}
  123. Area = append(Area, "全国")
  124. list, _ := MgoEB.Find("address", nil, nil, nil, false, -1, -1)
  125. for _, tmp := range *list {
  126. province := qu.ObjToString(tmp["province"])
  127. city := qu.ObjToString(tmp["city"])
  128. district := qu.ObjToString(tmp["district"])
  129. if province != "" && city == "" && district == "" { //area
  130. Area = append(Area, province)
  131. } else if province != "" && city != "" && district == "" { //city
  132. cityArr := Province[province]
  133. cityArr = append(cityArr, city)
  134. Province[province] = cityArr
  135. } else if province != "" && city != "" && district != "" { //district
  136. districtArr := City[city]
  137. districtArr = append(districtArr, district)
  138. City[city] = districtArr
  139. }
  140. }
  141. }
  142. // 爬虫整体测试时校验爬虫代码
  143. func SpiderPassCheckLua(liststr, contentstr string, lua map[string]interface{}) (msg []string) {
  144. //校验含过滤方法stringFind但没有过滤注释“--关键词过滤”
  145. //if strings.Contains(liststr, "stringFind") && !strings.Contains(liststr, "--关键词过滤") {
  146. // msg = append(msg, "列表页代码有过滤方法stringFind但缺少注释:--关键词过滤")
  147. //}
  148. //if strings.Contains(contentstr, "--关键词过滤") && !strings.Contains(contentstr, "delete") {
  149. // msg = append(msg, `三级页代码有过滤方法但缺少data["delete"]="true"`)
  150. //}
  151. //if !strings.Contains(contentstr, "s_title") {
  152. // msg = append(msg, "三级页缺少s_title")
  153. //}
  154. if !strings.Contains(contentstr, "getFileAttachmentsArrayWithTag") && !strings.Contains(contentstr, "downloadFile") {
  155. msg = append(msg, "三级页缺少下载附件方法")
  156. }
  157. //1.检测spidercode、site、channel
  158. //if param, ok := lua["param_common"].([]interface{}); ok && len(param) >= 3 {
  159. // spidercode := qu.ObjToString(param[0])
  160. // site := qu.ObjToString(param[1])
  161. // channel := qu.ObjToString(param[2])
  162. // checkText := fmt.Sprintf(CheckText, spidercode, site, channel)
  163. // if strings.Contains(liststr, `item["spidercode"]`) && !strings.Contains(liststr, checkText) {
  164. // msg = append(msg, "检查代码spidercode、site、channel字段值")
  165. // }
  166. //}
  167. //2.检测https
  168. //isHttps := false
  169. //for _, text := range DomainNameReg.FindAllString(liststr, -1) {
  170. // if strings.Contains(text, "https") {
  171. // isHttps = true
  172. // }
  173. //}
  174. //if isHttps {
  175. // for tmpStr, tmpText := range map[string]string{"列表页": liststr, "三级页": contentstr} {
  176. // downLoadText := DownLoadReg.FindString(tmpText)
  177. // if downLoadText != "" {
  178. // textArr := strings.Split(downLoadText, ",")
  179. // if len(textArr) < 4 {
  180. // msg = append(msg, tmpStr+"download方法添加下载参数")
  181. // } else if len(textArr) == 4 {
  182. // if !CodeTypeReg.MatchString(textArr[0]) || (textArr[1] != "true" && textArr[1] != "false") {
  183. // msg = append(msg, tmpStr+"download方法添加下载参数")
  184. // }
  185. // }
  186. // }
  187. // }
  188. //}
  189. //3.检测title
  190. //if strings.Contains(liststr, `item["title"]="a"`) {
  191. // if !strings.Contains(contentstr, `data["title"]`) {
  192. // msg = append(msg, "检查代码title的完整性")
  193. // }
  194. //}
  195. // 4.检测sendListNum
  196. //if !strings.Contains(liststr, "sendListNum") {
  197. // msg = append(msg, "sendListNum方法缺失")
  198. //}
  199. return
  200. }
  201. // 爬虫整体测试时校验列表页和详情页内容
  202. func SpiderPassCheckListAndDetail(result map[int64][]map[string]interface{}, data map[string]interface{}) (msg []string) {
  203. msgMap := map[string]bool{}
  204. //校验列表页信息
  205. for _, list := range result {
  206. for _, l := range list {
  207. //校验title
  208. title := qu.ObjToString(l["title"])
  209. if !TitleFilterReg1.MatchString(title) {
  210. msgMap["列表页title中无汉字"] = true
  211. } else if TitleFilterReg2.MatchString(title) {
  212. msgMap["列表页title中含有上(下)一页"] = true
  213. }
  214. //校验发布时间
  215. publishtime := qu.ObjToString(l["publishtime"])
  216. if publishtime == "0" || publishtime == "" {
  217. msgMap["列表页publishtime取值异常"] = true
  218. } else {
  219. t, err := time.ParseInLocation(qu.Date_Full_Layout, publishtime, time.Local)
  220. if err != nil || t.Unix() <= 0 {
  221. msgMap["列表页publishtime取值异常"] = true
  222. }
  223. }
  224. }
  225. }
  226. if len(data) > 0 {
  227. //校验publishtime
  228. if l_np_publishtime, ok := data["l_np_publishtime"].(lua.LNumber); ok {
  229. if l_np_publishtime <= 0 || l_np_publishtime > 0 && l_np_publishtime < 1000000000 {
  230. msgMap["三级页publishtime取值异常"] = true
  231. }
  232. } else if l_np_publishtime, ok := data["l_np_publishtime"].(int64); ok {
  233. if l_np_publishtime <= 0 || l_np_publishtime > 0 && l_np_publishtime < 1000000000 {
  234. msgMap["三级页publishtime取值异常"] = true
  235. }
  236. } else {
  237. msgMap["三级页publishtime值类型异常"] = true
  238. }
  239. contenthtml := qu.ObjToString(data["contenthtml"])
  240. if strings.Contains(contenthtml, "img") {
  241. msgMap["contenthtml中含有img是否下载"] = true
  242. }
  243. if strings.Contains(contenthtml, "iframe") {
  244. msgMap["contenthtml中含有iframe是否下载"] = true
  245. }
  246. detail := qu.ObjToString(data["detail"])
  247. if DetailFilterReg1.MatchString(detail) {
  248. msgMap["三级页正文提取包含无效内容"] = true
  249. }
  250. //校验jsondata
  251. if jsondata, ok := data["jsondata"].(map[string]interface{}); ok && len(jsondata) > 0 {
  252. for field, _ := range jsondata {
  253. if !JsonDataMap[field] {
  254. msgMap["jsondata中"+field+"属性错误"] = true
  255. }
  256. }
  257. }
  258. }
  259. for text, _ := range msgMap {
  260. msg = append(msg, text)
  261. }
  262. return
  263. }
  264. // 爬虫整体测试时校验列表页和详情页内容
  265. func SpiderPassCheckListAndDetail_back(list []map[string]interface{}, data map[string]interface{}) (msg []string) {
  266. if len(list) > 0 {
  267. p_zero := 0
  268. h_flag := true
  269. n_flag := true
  270. l_flag := true
  271. for _, l := range list {
  272. //校验title
  273. title := qu.ObjToString(l["title"])
  274. if !TitleFilterReg1.MatchString(title) && h_flag {
  275. msg = append(msg, "列表页title中无汉字")
  276. h_flag = false
  277. } else if TitleFilterReg2.MatchString(title) && n_flag {
  278. msg = append(msg, "列表页title中含有上(下)一页")
  279. n_flag = false
  280. }
  281. publishtime := qu.ObjToString(l["publishtime"])
  282. if publishtime == "0" {
  283. p_zero++
  284. } else if l_flag {
  285. t, _ := time.ParseInLocation(qu.Date_Full_Layout, publishtime, time.Local)
  286. if t.Unix() <= 0 {
  287. msg = append(msg, "列表页数据发布时间异常")
  288. l_flag = false
  289. }
  290. }
  291. }
  292. if len(data) > 0 {
  293. //校验publishtime
  294. if l_np_publishtime := data["l_np_publishtime"].(lua.LNumber); l_np_publishtime <= 0 {
  295. msg = append(msg, "三级页发布时间小于0")
  296. } else if p_zero == len(list) && l_np_publishtime == 0 {
  297. msg = append(msg, "三级页发布时间异常")
  298. }
  299. contenthtml := qu.ObjToString(data["contenthtml"])
  300. if strings.Contains(contenthtml, "img") {
  301. msg = append(msg, "contenthtml中含有img是否下载")
  302. }
  303. detail := qu.ObjToString(data["detail"])
  304. if TitleFilterReg2.MatchString(detail) {
  305. msg = append(msg, "三级页正文提取异常")
  306. }
  307. //校验jsondata
  308. if jsondata, ok := data["jsondata"].(map[string]interface{}); ok && len(jsondata) > 0 {
  309. for field, _ := range jsondata {
  310. if !JsonDataMap[field] {
  311. msg = append(msg, "jsondata中"+field+"属性错误")
  312. }
  313. }
  314. }
  315. }
  316. }
  317. return
  318. }
  319. func GetLuasInfoBySite(site, area, city, district string) (domain, status, event, platform, infotype, specialtype string, remarktime int64) {
  320. shelveUp := 0
  321. eventMap, platformMap := map[int]interface{}{}, map[string]interface{}{}
  322. infoformatMap := map[int]bool{}
  323. eventArr, platformArr, infoformatArr := []string{}, []string{}, []string{}
  324. //areaMap := map[string]int{}
  325. //areaCityMap := map[string]map[string]int{}
  326. //cityDistrictMap := map[string]map[string]int{}
  327. domainMap := map[string]bool{}
  328. domainArr := []string{}
  329. remarktime = time.Now().Unix()
  330. //luas, _ := MgoE.Find("luaconfig", `{"param_common.1":"`+site+`"}`, ``, `{"model":1,"event":1,"state":1,"platform":1,"param_common":1,"comeintime":1}`, false, -1, -1)
  331. luas, _ := MgoEB.Find("luaconfig", `{"site":"`+site+`"}`, ``, `{"projecthref":1,"model":1,"event":1,"state":1,"platform":1,"param_common":1,"comeintime":1,"infoformat":1}`, false, -1, -1)
  332. arr := [][]map[string]interface{}{}
  333. for _, l := range *luas {
  334. update := []map[string]interface{}{}
  335. set := map[string]interface{}{}
  336. if b, ok := l["projecthref"].(bool); ok && b { //爬虫采集的数据是流程性信息
  337. specialtype = "含流程数据"
  338. }
  339. //更新爬虫area、city、district
  340. if area != "" {
  341. set["model.area"] = area
  342. }
  343. if area == "全国" {
  344. set["model.city"] = ""
  345. set["model.district"] = ""
  346. } else if area != "" {
  347. if city != "" {
  348. set["model.city"] = city
  349. }
  350. if district != "" {
  351. set["model.district"] = district
  352. }
  353. }
  354. if len(set) > 0 {
  355. update = append(update, map[string]interface{}{"_id": l["_id"]})
  356. update = append(update, map[string]interface{}{"$set": set})
  357. arr = append(arr, update)
  358. }
  359. //remarktime
  360. if comeintime := qu.Int64All(l["comeintime"]); comeintime != int64(0) && comeintime < remarktime {
  361. remarktime = comeintime
  362. }
  363. //domain
  364. paramCommon := l["param_common"].([]interface{})
  365. if len(paramCommon) >= 12 {
  366. href := qu.ObjToString(paramCommon[11])
  367. domain := DomainReg.FindString(href)
  368. if domain != "" {
  369. domain = ReplaceReg.ReplaceAllString(domain, "")
  370. if !domainMap[domain] {
  371. domainArr = append(domainArr, domain)
  372. domainMap[domain] = true
  373. }
  374. }
  375. }
  376. //state、event、platform
  377. state := qu.IntAll(l["state"])
  378. event := qu.IntAll(l["event"])
  379. platform := qu.ObjToString(l["platform"])
  380. if state == 5 || state == 11 { //5:lua已上架;11:python已上线
  381. shelveUp++
  382. }
  383. eventMap[event] = true
  384. platformMap[platform] = true
  385. //infoformat
  386. infoformat := qu.IntAll(l["infoformat"])
  387. infoformatMap[infoformat] = true
  388. //area、city、district
  389. //if model, ok := l["model"].(map[string]interface{}); ok && model != nil {
  390. // a := qu.ObjToString(model["area"])
  391. // c := qu.ObjToString(model["city"])
  392. // d := qu.ObjToString(model["district"])
  393. // if a != "" {
  394. // areaMap[a] = areaMap[a] + 1
  395. // if c != "" {
  396. // if cityNum := areaCityMap[a]; cityNum != nil {
  397. // cityNum[c] = cityNum[c] + 1
  398. // } else {
  399. // areaCityMap[a] = map[string]int{c: 1}
  400. // }
  401. // if d != "" {
  402. // if distrctNum := cityDistrictMap[c]; distrctNum != nil {
  403. // distrctNum[d] = distrctNum[d] + 1
  404. // } else {
  405. // cityDistrictMap[c] = map[string]int{d: 1}
  406. // }
  407. // }
  408. // }
  409. //
  410. // }
  411. //}
  412. }
  413. //domain
  414. domain = strings.Join(domainArr, ";")
  415. for e, _ := range eventMap {
  416. eventArr = append(eventArr, fmt.Sprint(e))
  417. }
  418. event = strings.Join(eventArr, ",")
  419. for p, _ := range platformMap {
  420. platformArr = append(platformArr, p)
  421. }
  422. sort.Strings(platformArr)
  423. platform = strings.Join(platformArr, ",")
  424. for infoformat, _ := range infoformatMap {
  425. text := "招标"
  426. if infoformat == 2 {
  427. text = "拟建/审批"
  428. } else if infoformat == 3 {
  429. text = "产权"
  430. } else if infoformat == 4 {
  431. text = "舆情"
  432. }
  433. infoformatArr = append(infoformatArr, text)
  434. }
  435. sort.Strings(infoformatArr)
  436. infotype = strings.Join(infoformatArr, ",")
  437. //
  438. status = fmt.Sprintf("%d%s%d", shelveUp, "/", len(*luas))
  439. //批量更新
  440. if len(arr) > 0 {
  441. MgoEB.UpdateBulk("luaconfig", arr...)
  442. arr = [][]map[string]interface{}{}
  443. }
  444. //an, cn, dn := 0, 0, 0
  445. //for at, num := range areaMap {
  446. // if num > an {
  447. // area = at
  448. // an = num
  449. // }
  450. //}
  451. //if area != "" {
  452. // for ct, num := range areaCityMap[area] {
  453. // if num > cn {
  454. // city = ct
  455. // cn = num
  456. // }
  457. // }
  458. //}
  459. //if city != "" {
  460. // for dt, num := range cityDistrictMap[city] {
  461. // if num > dn {
  462. // district = dt
  463. // dn = num
  464. // }
  465. // }
  466. //}
  467. return
  468. }
  469. type StringValSorter struct {
  470. Keys []string
  471. Vals []string
  472. }
  473. func MapStringValueSort(m map[string]string) *StringValSorter {
  474. vs := NewStringValSorter(m)
  475. vs.Sort()
  476. return vs
  477. }
  478. func NewStringValSorter(m map[string]string) *StringValSorter {
  479. vs := &StringValSorter{
  480. Keys: make([]string, 0, len(m)),
  481. Vals: make([]string, 0, len(m)),
  482. }
  483. for k, v := range m {
  484. vs.Keys = append(vs.Keys, k)
  485. vs.Vals = append(vs.Vals, v)
  486. }
  487. return vs
  488. }
  489. func (vs *StringValSorter) Sort() {
  490. sort.Sort(vs)
  491. }
  492. func (vs *StringValSorter) Len() int {
  493. return len(vs.Vals)
  494. }
  495. func (vs *StringValSorter) Less(i, j int) bool {
  496. return vs.Vals[i] < vs.Vals[j]
  497. }
  498. func (vs *StringValSorter) Swap(i, j int) {
  499. vs.Vals[i], vs.Vals[j] = vs.Vals[j], vs.Vals[i]
  500. vs.Keys[i], vs.Keys[j] = vs.Keys[j], vs.Keys[i]
  501. }
  502. type MyWrite struct {
  503. Byte *bytes.Buffer
  504. }
  505. func (m *MyWrite) Write(p []byte) (n int, err error) {
  506. n, err = m.Byte.Write(p)
  507. return
  508. }
  509. func (m *MyWrite) Reader(p []byte) (n int, err error) {
  510. n, err = m.Byte.Read(p)
  511. return
  512. }