util.go 17 KB

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