script.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. /**
  2. 脚本加载+调用 封装,
  3. 前期走文件系统加载
  4. 后期走数据库配置,
  5. LUA中公共的方法需要抽出来,主脚本文件加载LUA公共文件
  6. */
  7. package spider
  8. import (
  9. "bytes"
  10. "compress/gzip"
  11. "crypto/aes"
  12. "encoding/base64"
  13. "encoding/json"
  14. "io/ioutil"
  15. mu "mfw/util"
  16. "net/http"
  17. "net/url"
  18. "path"
  19. qu "qfw/util"
  20. _ "qfw/util/redis"
  21. "regexp"
  22. util "spiderutil"
  23. "strconv"
  24. "strings"
  25. "sync/atomic"
  26. "time"
  27. gq "github.com/PuerkitoBio/goquery"
  28. "github.com/cjoudrey/gluahttp"
  29. "github.com/donnie4w/go-logger/logger"
  30. lujson "github.com/yuin/gopher-json"
  31. "github.com/yuin/gopher-lua"
  32. "golang.org/x/text/encoding/simplifiedchinese"
  33. "golang.org/x/text/transform"
  34. )
  35. //脚本
  36. type Script struct {
  37. SCode, ScriptFile string
  38. Encoding string
  39. Userproxy bool
  40. //Ishttps bool
  41. ErrorNum int32 //错误数
  42. Downloader string //下载器
  43. TotalRequestNum int32 //总请求次数
  44. ToDayRequestNum int32 //今日请求次数
  45. YestoDayRequestNum int32 //昨日请求次数
  46. Timeout int64 //超时时间秒
  47. L *lua.LState
  48. NoDownloadNum int32 //未成功下载数
  49. LastThreeTimes []time.Duration //单条信息流程完成的时间,最后三次
  50. FileLastThreeTimes []time.Duration //附件下载单条信息流程完成的时间,最后三次
  51. }
  52. const (
  53. MAX_STEP = 5 //计算时的最大步长
  54. )
  55. var workTime = true
  56. //
  57. func init() {
  58. go isWorkTime()
  59. }
  60. var TimeSleepChan = make(chan bool, 1)
  61. //加载文件
  62. func (s *Script) LoadScript(code, script_file string, newstate bool) string {
  63. defer mu.Catch()
  64. s.SCode = code
  65. s.ScriptFile = script_file
  66. if util.Config.Working == 0 {
  67. if newstate {
  68. s.L = lua.NewState(lua.Options{
  69. RegistrySize: 256 * 20,
  70. CallStackSize: 256,
  71. IncludeGoStackTrace: false,
  72. })
  73. }
  74. } else { //节能模式从CC池中获取lua.LState
  75. if newstate { //队列模式的newstate主要区分是列表页爬虫CC还是三级页爬虫CC2
  76. lState := <-CC2
  77. s.L = lState
  78. } else {
  79. lState := <-CC
  80. s.L = lState
  81. }
  82. //logger.Debug("获取CC资源", script_file)
  83. }
  84. s.L.PreloadModule("http", gluahttp.NewHttpModule(&http.Client{}).Loader)
  85. s.L.PreloadModule("json", lujson.Loader)
  86. if err := s.L.DoString(script_file); err != nil {
  87. logger.Debug(code + ",加载lua脚本错误:" + err.Error())
  88. return "加载lua脚本错误:" + err.Error()
  89. //panic(code + ",加载lua脚本错误:" + err.Error())
  90. }
  91. s.Encoding = s.GetVar("spiderPageEncoding")
  92. s.Userproxy = s.GetBoolVar("spiderUserProxy")
  93. //暴露go方法
  94. //download(url,head) 普通下载
  95. s.L.SetGlobal("download", s.L.NewFunction(func(S *lua.LState) int {
  96. if s.LastThreeTimes == nil {
  97. s.LastThreeTimes = make([]time.Duration, 4)
  98. }
  99. if util.Config.IsDelay {
  100. SleepTime(1, s.LastThreeTimes) //睡眠时间
  101. }
  102. start := time.Now() //起始时间
  103. head := S.ToTable(-1)
  104. url := S.ToString(-2)
  105. ishttps := S.ToBool(-3)
  106. charset := S.ToString(-4)
  107. if charset == "" {
  108. charset = s.Encoding
  109. }
  110. ret := Download(s.Downloader, url, "get", util.GetTable(head), charset, s.Userproxy, ishttps, s.SCode, s.Timeout)
  111. S.Push(lua.LString(ret))
  112. atomic.AddInt32(&s.ToDayRequestNum, 1)
  113. atomic.AddInt32(&s.TotalRequestNum, 1)
  114. end := time.Since(start)
  115. if len(s.LastThreeTimes) >= 4 {
  116. s.LastThreeTimes = s.LastThreeTimes[1:]
  117. }
  118. s.LastThreeTimes = append(s.LastThreeTimes, end)
  119. return 1
  120. }))
  121. //高级下载downloadAdv(url,method,param,head,cookie)
  122. s.L.SetGlobal("downloadAdv", s.L.NewFunction(func(S *lua.LState) int {
  123. if s.LastThreeTimes == nil {
  124. s.LastThreeTimes = make([]time.Duration, 4)
  125. }
  126. if util.Config.IsDelay {
  127. SleepTime(1, s.LastThreeTimes) //睡眠时间
  128. }
  129. start := time.Now() //起始时间
  130. cookie := S.ToString(-1)
  131. head := S.ToTable(-2)
  132. param := S.ToTable(-3)
  133. method := S.ToString(-4)
  134. url := S.ToString(-5)
  135. ishttps := S.ToBool(-6)
  136. charset := S.ToString(-7)
  137. if charset == "" {
  138. charset = s.Encoding
  139. }
  140. var mycookie []*http.Cookie
  141. json.Unmarshal([]byte(cookie), &mycookie)
  142. var ret string
  143. var retcookie []*http.Cookie
  144. if param == nil {
  145. ptext := map[string]interface{}{"text": S.ToString(-3)}
  146. ret, retcookie = DownloadAdv(s.Downloader, url, method, ptext, util.GetTable(head), mycookie, charset, s.Userproxy, ishttps, s.SCode, s.Timeout)
  147. } else {
  148. ret, retcookie = DownloadAdv(s.Downloader, url, method, util.GetTable(param), util.GetTable(head), mycookie, charset, s.Userproxy, ishttps, s.SCode, s.Timeout)
  149. }
  150. S.Push(lua.LString(ret))
  151. scookie, _ := json.Marshal(retcookie)
  152. S.Push(lua.LString(scookie))
  153. atomic.AddInt32(&s.ToDayRequestNum, 1)
  154. atomic.AddInt32(&s.TotalRequestNum, 1)
  155. end := time.Since(start)
  156. if len(s.LastThreeTimes) >= 4 {
  157. s.LastThreeTimes = s.LastThreeTimes[1:]
  158. }
  159. s.LastThreeTimes = append(s.LastThreeTimes, end)
  160. return 2
  161. }))
  162. //保存验证错误日志
  163. s.L.SetGlobal("saveErrLog", s.L.NewFunction(func(S *lua.LState) int {
  164. code := S.ToString(-4)
  165. name := S.ToString(-3)
  166. url := S.ToString(-2)
  167. content := S.ToString(-1)
  168. saveVerificationLog(code, name, url, content)
  169. atomic.AddInt32(&s.ErrorNum, 1)
  170. atomic.AddInt32(&s.NoDownloadNum, 1)
  171. //防止恶意增加日志
  172. util.TimeSleepFunc(5*time.Second, TimeSleepChan)
  173. return 0
  174. }))
  175. //添加改版日志
  176. s.L.SetGlobal("saveRevisionLog", s.L.NewFunction(func(S *lua.LState) int {
  177. url := S.ToString(-2)
  178. str := S.ToString(-1)
  179. logger.Error(s.SCode, url, str)
  180. return 0
  181. }))
  182. //查找信息是否存在(作废)
  183. s.L.SetGlobal("findHasExit", s.L.NewFunction(func(S *lua.LState) int {
  184. //c := S.ToString(-2)
  185. //q := S.ToString(-1)
  186. //b := findHasExit(c, q)
  187. S.Push(lua.LBool(false))
  188. return 1
  189. }))
  190. s.L.SetGlobal("findOneText", s.L.NewFunction(func(S *lua.LState) int {
  191. nodetype := S.ToString(-3)
  192. gpath := S.ToString(-2)
  193. content := S.ToString(-1)
  194. ret := util.FindOneText(gpath, content, nodetype)
  195. S.Push(ret)
  196. return 1
  197. }))
  198. s.L.SetGlobal("findContentText", s.L.NewFunction(func(S *lua.LState) int {
  199. gpath := S.ToString(-2)
  200. content := S.ToString(-1)
  201. ret := util.FindContentText(gpath, content)
  202. S.Push(ret)
  203. return 1
  204. }))
  205. s.L.SetGlobal("findOneHtml", s.L.NewFunction(func(S *lua.LState) int {
  206. nodetype := S.ToString(-3)
  207. gpath := S.ToString(-2)
  208. content := S.ToString(-1)
  209. ret := util.FindOneHtml(gpath, content, nodetype)
  210. S.Push(ret)
  211. return 1
  212. }))
  213. s.L.SetGlobal("findListText", s.L.NewFunction(func(S *lua.LState) int {
  214. gpath := S.ToString(-2)
  215. content := S.ToString(-1)
  216. ret := s.L.NewTable()
  217. util.FindListText(gpath, content, ret)
  218. S.Push(ret)
  219. return 1
  220. }))
  221. s.L.SetGlobal("findListHtml", s.L.NewFunction(func(S *lua.LState) int {
  222. gpath := S.ToString(-2)
  223. content := S.ToString(-1)
  224. ret := s.L.NewTable()
  225. util.FindListHtml(gpath, content, ret)
  226. if ret.Len() > 0 {
  227. UpdateHeart("", "", code, "", "findlist") //记录列表页实际采集数据量心跳
  228. }
  229. S.Push(ret)
  230. return 1
  231. }))
  232. // s.L.SetGlobal("findMgoData", s.L.NewFunction(func(S *lua.LState) int {
  233. // update := [][]map[string]interface{}{}
  234. // query := map[string]interface{}{"state": 0}
  235. // data, _ := Mgo.Find(util.Config.TmpCollName, query, `{"_id":-1}`, nil, false, 0, 10)
  236. // pageList := []interface{}{}
  237. // for _, d := range *data {
  238. // tmpMap := map[string]string{}
  239. // tmpMap["title"] = qu.ObjToString(d["title"])
  240. // tmpMap["detail"] = qu.ObjToString(d["detail"])
  241. // tmpMap["href"] = qu.ObjToString(d["href"])
  242. // publishtime := qu.Int64All(d["publishtime"])
  243. // tmpMap["publishtime"] = qu.FormatDateByInt64(&publishtime, qu.Date_Full_Layout)
  244. // tmpMap["_id"] = qu.BsonIdToSId(d["_id"])
  245. // pageList = append(pageList, tmpMap)
  246. // update = append(update, []map[string]interface{}{
  247. // map[string]interface{}{"_id": d["_id"]},
  248. // map[string]interface{}{"$set": map[string]interface{}{"state": 1}},
  249. // })
  250. // }
  251. // ret := util.MapToTable(s.L, pageList)
  252. // S.Push(ret)
  253. // if len(update) > 0 {
  254. // Mgo.UpdateBulk(util.Config.TmpCollName, update...)
  255. // }
  256. // return 1
  257. // }))
  258. s.L.SetGlobal("findMap", s.L.NewFunction(func(S *lua.LState) int {
  259. qmap := S.ToTable(-2)
  260. content := S.ToString(-1)
  261. ret := s.L.NewTable()
  262. util.FindMap(qmap, content, ret)
  263. S.Push(ret)
  264. return 1
  265. }))
  266. //公示暴露方式
  267. s.L.SetGlobal("getEcpsCode", s.L.NewFunction(func(S *lua.LState) int {
  268. area := strings.ToUpper(S.ToString(-2))
  269. content := S.ToString(-1)
  270. code, state := util.GetEcpsCode(area, []byte(content))
  271. if state == "wx" {
  272. code, _ = GetCodeByWx([]byte(content))
  273. }
  274. S.Push(lua.LString(code))
  275. return 1
  276. }))
  277. //调用jsvm
  278. s.L.SetGlobal("jsvm", s.L.NewFunction(func(S *lua.LState) int {
  279. js := S.ToString(-1)
  280. ret := s.L.NewTable()
  281. if js == "" {
  282. ret.RawSet(lua.LString("val"), lua.LString(""))
  283. ret.RawSet(lua.LString("err"), lua.LString("js is null"))
  284. } else {
  285. rep := util.JsVmPost(util.Config.JsVmUrl, js)
  286. ret.RawSet(lua.LString("val"), lua.LString(qu.ObjToString(rep["val"])))
  287. ret.RawSet(lua.LString("err"), lua.LString(qu.ObjToString(rep["err"])))
  288. }
  289. S.Push(ret)
  290. return 1
  291. }))
  292. //指定下载器
  293. s.L.SetGlobal("changeDownloader", s.L.NewFunction(func(S *lua.LState) int {
  294. s.Downloader = GetOneDownloader()
  295. S.Push(lua.LString(s.Downloader))
  296. return 1
  297. }))
  298. //指定下载器file
  299. s.L.SetGlobal("changeDownloaderFile", s.L.NewFunction(func(S *lua.LState) int {
  300. s.Downloader = GetOneDownloaderFile()
  301. S.Push(lua.LString(s.Downloader))
  302. return 1
  303. }))
  304. //手工延时
  305. s.L.SetGlobal("timeSleep", s.L.NewFunction(func(S *lua.LState) int {
  306. // if workTime {
  307. // util.TimeSleepFunc(time.Duration(S.ToInt(-1))*time.Second, TimeSleepChan)
  308. // } else {
  309. // util.TimeSleepFunc(1*time.Second, TimeSleepChan)
  310. // }
  311. util.TimeSleepFunc(time.Second*2, TimeSleepChan)
  312. return 0
  313. }))
  314. //编码解码
  315. s.L.SetGlobal("transCode", s.L.NewFunction(func(S *lua.LState) int {
  316. codeType := strings.ToLower(S.ToString(-2))
  317. str := S.CheckString(-1)
  318. switch codeType {
  319. case "unicode":
  320. str = transUnic(str)
  321. case "urlencode_gbk":
  322. data, _ := ioutil.ReadAll(transform.NewReader(bytes.NewReader([]byte(str)), simplifiedchinese.GBK.NewEncoder()))
  323. l, _ := url.Parse("http://a.com/?" + string(data))
  324. tmpstr := l.Query().Encode()
  325. if len(tmpstr) > 1 {
  326. str = tmpstr[0 : len(tmpstr)-1]
  327. } else {
  328. str = ""
  329. }
  330. case "urlencode_utf8":
  331. l, _ := url.Parse("http://a.com/?" + str)
  332. tmpstr := l.Query().Encode()
  333. if len(tmpstr) > 1 {
  334. str = tmpstr[0 : len(tmpstr)-1]
  335. } else {
  336. str = ""
  337. }
  338. case "urldecode_utf8":
  339. str, _ = url.QueryUnescape(str)
  340. case "decode64":
  341. str = util.DecodeB64(str)
  342. case "encodemd5":
  343. str = qu.GetMd5String(str)
  344. case "htmldecode": //html实体码
  345. //txt := `<div align="left" style="margin-left: 0pt;"><span style='font-family:; font-size:13px; color:#000000'>&#22826;&#38451;&#23707;&#29305;&#21220;&#28040;&#38450;&#31449;&#12289;&#26494;&#28006;&#29305;&#21220;&#28040;&#38450;&#31449;&#24314;&#35774;&#39033;&#30446;&#35774;&#35745;&#20013;&#26631;&#20844;&#31034;</span></div>`
  346. str = S.ToString(-1)
  347. reg, _ := regexp.Compile("&#\\d+;")
  348. str = reg.ReplaceAllStringFunc(str, func(src string) string {
  349. v, _ := strconv.Atoi(src[2 : len(src)-1])
  350. return string(rune(v))
  351. })
  352. }
  353. S.Push(lua.LString(str))
  354. return 1
  355. }))
  356. //如果服务端返回的html是gzip压缩过格式的 这里需要转一下
  357. s.L.SetGlobal("unGzip", s.L.NewFunction(func(S *lua.LState) int {
  358. html := S.ToString(-1)
  359. bs := []byte(html)
  360. gzipreader, _ := gzip.NewReader(bytes.NewReader(bs))
  361. bs, _ = ioutil.ReadAll(gzipreader)
  362. S.Push(lua.LString(bs))
  363. return 1
  364. }))
  365. //luamaker提供的分析列表页url地址 获取列表数据公用方法
  366. s.L.SetGlobal("getSimpleListPage", s.L.NewFunction(func(S *lua.LState) int {
  367. html := S.ToString(-3)
  368. date_pattern := S.ToString(-2)
  369. pageListUrl := S.ToString(-1) //列表页url
  370. bs := []byte(html)
  371. tmparr := []string{}
  372. tmpret := []int{}
  373. re, _ := regexp.Compile(`采购|招标|公示|公告|意见|结果|通知|工程`)
  374. doc, _ := gq.NewDocumentFromReader(bytes.NewReader(bs))
  375. doc.Find("a").Each(func(i int, sq *gq.Selection) {
  376. text := sq.Text()
  377. if len(text) < 30 {
  378. return
  379. }
  380. tmparr = append(tmparr, text)
  381. if re.MatchString(text) {
  382. tmpret = append(tmpret, 1)
  383. //logger.Debug(text)
  384. } else {
  385. tmpret = append(tmpret, 0)
  386. }
  387. })
  388. logger.Debug(tmpret)
  389. //线性分析,算周边,只算周围5步的点
  390. tmplen, thepos, themax := len(tmpret), -1, 0
  391. for i := 0; i < tmplen; i++ {
  392. if tmpret[i] == 0 {
  393. continue
  394. }
  395. start, end := i-MAX_STEP, i+MAX_STEP
  396. if start < 0 {
  397. start = 0
  398. }
  399. if end > tmplen {
  400. end = tmplen
  401. }
  402. tmp := 0
  403. //从当前位置往左,往右找连续点
  404. for j := i; j > start; j-- {
  405. if tmpret[j] == 1 {
  406. tmp++
  407. } else {
  408. break
  409. }
  410. }
  411. for j := i; j < end; j++ {
  412. if tmpret[j] == 1 {
  413. tmp++
  414. } else {
  415. break
  416. }
  417. }
  418. if tmp > themax {
  419. themax = tmp
  420. thepos = i
  421. }
  422. } //end of for...
  423. //logger.Debug("找位置完成")
  424. //验证
  425. if thepos == -1 {
  426. logger.Error("完蛋,找不到")
  427. panic("不支持啊,失败啊")
  428. }
  429. //下边是找父容器
  430. var thelink *gq.Selection
  431. doc.Find("a").Each(func(i int, sq *gq.Selection) {
  432. if sq.Text() == tmparr[thepos] {
  433. thelink = sq
  434. }
  435. })
  436. isfind := false
  437. //同样Path向上找,不超过5步
  438. for i := 0; i < MAX_STEP; i++ {
  439. thelink = thelink.Parent()
  440. clen := getChildrenLen(thelink)
  441. if clen >= themax-1 {
  442. isfind = true
  443. break
  444. }
  445. //logger.Debug("TAG:::", thelink.Nodes[0].Data, clen)
  446. }
  447. //找到列表
  448. pageList := []interface{}{}
  449. if isfind {
  450. thelink.Children().Each(func(i int, sq *gq.Selection) {
  451. page := map[string]string{}
  452. link_sq := sq.Find("a")
  453. href := link_sq.AttrOr("href", "")
  454. text := link_sq.Text()
  455. page["title"] = text
  456. page["href"] = dealHref(pageListUrl, href)
  457. page["publishtime"] = dealPublishTime(strings.TrimSpace(sq.Text()), date_pattern)
  458. //logger.Debug(i)
  459. pageList = append(pageList, page)
  460. })
  461. } else {
  462. logger.Error("完蛋,找父亲节点失败啊")
  463. //panic("不支持啊,失败啊")
  464. }
  465. ret := util.MapToTable(s.L, pageList)
  466. S.Push(ret)
  467. return 1
  468. }))
  469. //招投标信息标题判重
  470. s.L.SetGlobal("titleRepeatJudgement", s.L.NewFunction(func(S *lua.LState) int {
  471. S.Push(lua.LBool(false))
  472. return 1
  473. }))
  474. //招标信息判重新方法 2016-12-14 wanghuidong
  475. s.L.SetGlobal("urlRepeatJudgement", s.L.NewFunction(func(S *lua.LState) int {
  476. S.Push(lua.LBool(false))
  477. return 1
  478. }))
  479. //将url放入内存缓存 2016-12-14 wanghuidong
  480. s.L.SetGlobal("putUrl2Redis", s.L.NewFunction(func(S *lua.LState) int {
  481. //url := S.ToString(-1)
  482. return 1
  483. }))
  484. //解析附件中的word、pdf
  485. s.L.SetGlobal("officeAnalysis", s.L.NewFunction(func(S *lua.LState) int {
  486. ext := map[string]byte{"pdf": byte(0), "doc": byte(1), "docx": byte(2)}
  487. str := S.ToString(-2)
  488. extension := S.ToString(-1)
  489. bs, _ := base64.StdEncoding.DecodeString(str)
  490. bs = append([]byte{ext[extension]}, bs...)
  491. msgid := mu.UUID(8)
  492. Msclient.Call("", msgid, mu.SERVICE_OFFICE_ANALYSIS, mu.SENDTO_TYPE_ALL_RECIVER, bs, 60)
  493. return 1
  494. }))
  495. //下载附件download(url,method,param,head,cookie,fileName)
  496. s.L.SetGlobal("downloadFile", s.L.NewFunction(func(S *lua.LState) int {
  497. if s.FileLastThreeTimes == nil {
  498. s.FileLastThreeTimes = make([]time.Duration, 4)
  499. }
  500. if util.Config.IsDelay {
  501. SleepTime(3, s.FileLastThreeTimes) //睡眠时间
  502. }
  503. start := time.Now() //起始时间
  504. cookie := S.ToString(-1)
  505. head := S.ToTable(-2)
  506. param := S.ToTable(-3)
  507. method := S.ToString(-4)
  508. url := S.ToString(-5)
  509. fileName := S.ToString(-6)
  510. ishttps := strings.Contains(url, "https")
  511. var mycookie []*http.Cookie
  512. if cookie != "{}" {
  513. json.Unmarshal([]byte(cookie), &mycookie)
  514. } else {
  515. mycookie = make([]*http.Cookie, 0)
  516. }
  517. fileName = strings.TrimSpace(fileName)
  518. url = strings.TrimSpace(url)
  519. ret := DownloadFile(s.Downloader, url, method, util.GetTable(param), util.GetTable(head), mycookie, s.Encoding, s.Userproxy, ishttps, s.SCode, s.Timeout)
  520. url, name, size, ftype, fid := util.UploadFile(s.SCode, fileName, url, ret)
  521. if strings.TrimSpace(ftype) == "" {
  522. if len(path.Ext(name)) > 0 {
  523. ftype = path.Ext(name)[1:]
  524. }
  525. }
  526. S.Push(lua.LString(url))
  527. S.Push(lua.LString(name))
  528. S.Push(lua.LString(size))
  529. S.Push(lua.LString(ftype))
  530. S.Push(lua.LString(fid))
  531. atomic.AddInt32(&s.ToDayRequestNum, 1)
  532. atomic.AddInt32(&s.TotalRequestNum, 1)
  533. end := time.Since(start)
  534. if len(s.FileLastThreeTimes) >= 4 {
  535. s.FileLastThreeTimes = s.FileLastThreeTimes[1:]
  536. }
  537. s.FileLastThreeTimes = append(s.FileLastThreeTimes, end)
  538. return 5
  539. }))
  540. s.L.SetGlobal("clearMemoeryCache", s.L.NewFunction(func(S *lua.LState) int {
  541. /*title := S.ToString(-1)
  542. isExist, _ := redis.Exists("title_repeat_judgement", "title_repeat_"+title)
  543. if isExist {
  544. redis.Del("title_repeat_judgement", "title_repeat_"+title)
  545. }*/
  546. return 1
  547. }))
  548. //支持正则,提取
  549. s.L.SetGlobal("regexp", s.L.NewFunction(func(S *lua.LState) int {
  550. index := int(S.ToNumber(-1))
  551. regstr := S.ToString(-2)
  552. text := S.ToString(-3)
  553. reg := regexp.MustCompile(regstr)
  554. reps := reg.FindAllStringSubmatchIndex(text, -1)
  555. ret := s.L.NewTable()
  556. number := 0
  557. for _, v := range reps {
  558. number++
  559. ret.Insert(number, lua.LString(text[v[index]:v[index+1]]))
  560. }
  561. S.Push(ret)
  562. return 1
  563. }))
  564. //支持替换
  565. s.L.SetGlobal("replace", s.L.NewFunction(func(S *lua.LState) int {
  566. text := S.ToString(-3)
  567. old := S.ToString(-2)
  568. repl := S.ToString(-1)
  569. text = strings.Replace(text, old, repl, -1)
  570. S.Push(lua.LString(text))
  571. return 1
  572. }))
  573. //标题的关键词、排除词过滤
  574. s.L.SetGlobal("pagefilterword", s.L.NewFunction(func(S *lua.LState) int {
  575. keyWordReg := regexp.MustCompile(util.Config.Word["keyword"])
  576. notKeyWordReg := regexp.MustCompile(util.Config.Word["notkeyword"])
  577. data := S.ToTable(-1)
  578. dataMap := util.TableToMap(data)
  579. ret := s.L.NewTable()
  580. num := 1
  581. for _, v := range dataMap {
  582. tmp := v.(map[string]interface{})
  583. isOk := false
  584. if title := qu.ObjToString(tmp["title"]); title != "" {
  585. if keyWordReg.MatchString(title) && !notKeyWordReg.MatchString(title) {
  586. isOk = true
  587. }
  588. }
  589. if isOk {
  590. ret.Insert(num, util.MapToLuaTable(S, tmp))
  591. num++
  592. }
  593. }
  594. S.Push(ret)
  595. return 1
  596. }))
  597. //标题的关键词、排除词过滤
  598. s.L.SetGlobal("detailfilterword", s.L.NewFunction(func(S *lua.LState) int {
  599. keyWordReg := regexp.MustCompile(util.Config.Word["keyword"])
  600. notKeyWordReg := regexp.MustCompile(util.Config.Word["notkeyword"])
  601. data := S.ToTable(-1)
  602. dataMap := util.TableToMap(data)
  603. if title := qu.ObjToString(dataMap["title"]); title != "" {
  604. if keyWordReg.MatchString(title) && !notKeyWordReg.MatchString(title) {
  605. S.Push(lua.LBool(true))
  606. return 1
  607. } else {
  608. qu.Debug(s.SCode, dataMap["href"], " title error")
  609. }
  610. } else {
  611. qu.Debug(s.SCode, dataMap["href"], " title error")
  612. }
  613. S.Push(lua.LBool(false))
  614. return 1
  615. }))
  616. //detail过滤
  617. s.L.SetGlobal("filterdetail", s.L.NewFunction(func(S *lua.LState) int {
  618. /*
  619. 1.长度判断 (特殊处理:详情请访问原网页!;详见原网页;见原网页;无;无相关内容;无正文内容)
  620. 2.是否含汉字
  621. */
  622. reg1 := regexp.MustCompile("(原网页|无|无相关内容|无正文内容|见附件|详见附件)")
  623. reg2 := regexp.MustCompile("[\u4e00-\u9fa5]")
  624. detail := S.ToString(-1)
  625. if reg1.MatchString(detail) {
  626. S.Push(lua.LBool(true))
  627. return 1
  628. }
  629. if len([]rune(detail)) < 50 || !reg2.MatchString(detail) {
  630. S.Push(lua.LBool(false))
  631. return 1
  632. }
  633. S.Push(lua.LBool(false))
  634. return 1
  635. }))
  636. //匹配汉字
  637. s.L.SetGlobal("matchan", s.L.NewFunction(func(S *lua.LState) int {
  638. reg1 := regexp.MustCompile("(见附件|详见附件)")
  639. reg2 := regexp.MustCompile("[\u4e00-\u9fa5]")
  640. detail := S.ToString(-1)
  641. detail = reg1.ReplaceAllString(detail, "")
  642. ok := reg2.MatchString(detail)
  643. S.Push(lua.LBool(ok))
  644. return 1
  645. }))
  646. //aes ecb模式加密
  647. s.L.SetGlobal("aesEncryptECB", s.L.NewFunction(func(S *lua.LState) int {
  648. origData := S.ToString(-2)
  649. key := S.ToString(-1)
  650. bytekey := []byte(key)
  651. byteorigData := []byte(origData)
  652. cipher, _ := aes.NewCipher(generateKey([]byte(bytekey)))
  653. length := (len(byteorigData) + aes.BlockSize) / aes.BlockSize
  654. plain := make([]byte, length*aes.BlockSize)
  655. copy(plain, byteorigData)
  656. pad := byte(len(plain) - len(byteorigData))
  657. for i := len(byteorigData); i < len(plain); i++ {
  658. plain[i] = pad
  659. }
  660. encrypted := make([]byte, len(plain))
  661. // 分组分块加密
  662. for bs, be := 0, cipher.BlockSize(); bs <= len(byteorigData); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
  663. cipher.Encrypt(encrypted[bs:be], plain[bs:be])
  664. }
  665. result := base64.StdEncoding.EncodeToString(encrypted)
  666. S.Push(lua.LString(result))
  667. return 1
  668. }))
  669. //根据正文获取发布时间
  670. s.L.SetGlobal("getPublishtime", s.L.NewFunction(func(S *lua.LState) int {
  671. detail := S.ToString(-2)
  672. contenthtml := S.ToString(-1)
  673. publishtime := util.GetPublishtime([]string{contenthtml, detail})
  674. S.Push(lua.LString(publishtime))
  675. return 1
  676. }))
  677. //匹配
  678. s.L.SetGlobal("stringFind", s.L.NewFunction(func(S *lua.LState) int {
  679. regstr := S.ToString(-1)
  680. text := S.ToString(-2)
  681. reg := regexp.MustCompile(regstr)
  682. result := reg.FindString(text)
  683. isMatch := false
  684. if result != "" {
  685. isMatch = true
  686. }
  687. S.Push(lua.LString(result))
  688. S.Push(lua.LBool(isMatch))
  689. return 2
  690. }))
  691. //截取
  692. s.L.SetGlobal("stringSub", s.L.NewFunction(func(S *lua.LState) int {
  693. text := S.ToString(-3)
  694. start := S.ToInt(-2)
  695. end := S.ToInt(-1)
  696. result := ""
  697. if len(text) > 0 {
  698. textRune := []rune(text)
  699. textLen := len(textRune)
  700. if end < 0 {
  701. if start > 0 { //正向截取到倒数第end位
  702. result = string(textRune[start-1 : textLen+1+end])
  703. } else if start < 0 { //反向截取 从倒数第start位截取到倒数第end位
  704. result = string(textRune[textLen+start : textLen+1+end])
  705. }
  706. } else if start > 0 && end >= start && end <= textLen { //从第start个截取到第end个
  707. result = string(textRune[start-1 : end])
  708. }
  709. // if end == -1 {
  710. // if start >= 1 { //正向截取到结尾
  711. // result = string(textRune[start-1:])
  712. // } else if start < 0 && textLen+start >= 0 { //反向截取后缀
  713. // result = string(textRune[textLen+start:])
  714. // }
  715. // } else if start >= 1 && end <= textLen { //从第start个截取到第end个
  716. // result = string(textRune[start-1 : end])
  717. // }
  718. }
  719. S.Push(lua.LString(result))
  720. return 1
  721. }))
  722. //base64加密
  723. s.L.SetGlobal("encodeBase64", s.L.NewFunction(func(S *lua.LState) int {
  724. text := S.ToString(-1)
  725. base64Text := base64.StdEncoding.EncodeToString([]byte(text))
  726. S.Push(lua.LString(base64Text))
  727. return 1
  728. }))
  729. //长度
  730. s.L.SetGlobal("stringLen", s.L.NewFunction(func(S *lua.LState) int {
  731. text := S.ToString(-1)
  732. textLen := len([]rune(text))
  733. S.Push(lua.LNumber(textLen))
  734. return 1
  735. }))
  736. //去除特殊标签中间内容
  737. s.L.SetGlobal("getPureContent", s.L.NewFunction(func(S *lua.LState) int {
  738. con := S.ToString(-1)
  739. reg := regexp.MustCompile("(?s)<(!%-%-|!--|style).*?(%-%-|--|style)>") //注释 css
  740. con = reg.ReplaceAllString(con, "")
  741. // indexArr := reg.FindAllStringIndex(con, -1)
  742. // for i := len(indexArr) - 1; i >= 0; i-- {
  743. // if index := indexArr[i]; len(index) == 2 {
  744. // con = con[:index[0]] + con[index[1]:]
  745. // }
  746. // }
  747. S.Push(lua.LString(con))
  748. return 1
  749. }))
  750. return ""
  751. }
  752. func dealHref(pageListUrl, href string) string {
  753. returnUrl := ""
  754. if href != "" {
  755. r, _ := regexp.Compile("^./")
  756. match := r.MatchString(href)
  757. if match {
  758. url2 := r.ReplaceAllString(href, "")
  759. returnUrl = pageListUrl + url2
  760. }
  761. r2, _ := regexp.Compile("^/")
  762. match2 := r2.MatchString(href)
  763. if match2 {
  764. r3, _ := regexp.Compile("http://[^/]*/")
  765. domain := r3.FindString(pageListUrl)
  766. //fmt.Println(domain)
  767. url2 := r2.ReplaceAllString(href, "")
  768. returnUrl = domain + url2
  769. }
  770. }
  771. return returnUrl
  772. }
  773. func dealPublishTime(content string, pattern string) string {
  774. publishTime := ""
  775. if pattern == "yyyy-MM-dd HH:mm:ss" {
  776. r, _ := regexp.Compile("\\d{4}-\\d{2}-\\d{2}\\s*\\d{2}:\\d{2}:\\d{2}")
  777. publishTime = r.FindString(content)
  778. } else if pattern == "yyyy-MM-dd" {
  779. r, _ := regexp.Compile("\\d{4}-\\d{2}-\\d{2}")
  780. publishTime = r.FindString(content)
  781. } else if pattern == "MM-dd" {
  782. r, _ := regexp.Compile("\\d{2}-\\d{2}")
  783. publishTime = r.FindString(content)
  784. }
  785. return publishTime
  786. }
  787. func getChildrenLen(sq *gq.Selection) (ret int) {
  788. sq.Children().Each(func(i int, sq2 *gq.Selection) {
  789. ret = i
  790. })
  791. return
  792. }
  793. //
  794. //func (s *Script) Reload() {
  795. // s.L.Close()
  796. // s.LoadScript(s.SCode, s.ScriptFile, false)
  797. //}
  798. //unicode转码
  799. func transUnic(str string) string {
  800. buf := bytes.NewBuffer(nil)
  801. i, j := 0, len(str)
  802. for i < j {
  803. x := i + 6
  804. if x > j {
  805. buf.WriteString(str[i:])
  806. break
  807. }
  808. if str[i] == '\\' && str[i+1] == 'u' {
  809. hex := str[i+2 : x]
  810. r, err := strconv.ParseUint(hex, 16, 64)
  811. if err == nil {
  812. buf.WriteRune(rune(r))
  813. } else {
  814. logger.Warn(err.Error())
  815. buf.WriteString(str[i:x])
  816. }
  817. i = x
  818. } else {
  819. buf.WriteByte(str[i])
  820. i++
  821. }
  822. }
  823. return buf.String()
  824. }
  825. //取得变量
  826. func (s *Script) GetVar(key string) string {
  827. return s.L.GetGlobal(key).String()
  828. }
  829. //
  830. func (s *Script) GetIntVar(key string) int {
  831. lv := s.L.GetGlobal(key)
  832. if v, ok := lv.(lua.LNumber); ok {
  833. return int(v)
  834. }
  835. return -1
  836. }
  837. //
  838. func (s *Script) GetBoolVar(key string) bool {
  839. lv := s.L.GetGlobal(key)
  840. if v, ok := lv.(lua.LBool); ok {
  841. return bool(v)
  842. }
  843. return false
  844. }
  845. func isWorkTime() {
  846. workTime = util.IsWorkTime()
  847. util.TimeAfterFunc(10*time.Minute, isWorkTime, TimeChan)
  848. }
  849. //设置睡眠时间
  850. func SleepTime(basetime int, times []time.Duration) {
  851. st := 0 //记录最后睡眠时长
  852. base := float64(basetime * 60)
  853. if times[3].Seconds() > base { //最后一次大于 basetime*60秒
  854. if times[2].Seconds() > base {
  855. n := 0
  856. if times[0].Seconds() > base {
  857. n++
  858. }
  859. if times[1].Seconds() > base {
  860. n++
  861. }
  862. st = n + 1
  863. } else if times[2].Seconds() < base && times[0].Seconds() > base && times[1].Seconds() > base {
  864. st = 1
  865. }
  866. }
  867. if st > 0 {
  868. time.Sleep(time.Duration(st) * time.Minute)
  869. }
  870. }
  871. func generateKey(key []byte) (genKey []byte) {
  872. genKey = make([]byte, 16)
  873. copy(genKey, key)
  874. for i := 16; i < len(key); {
  875. for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
  876. genKey[j] ^= key[i]
  877. }
  878. }
  879. return genKey
  880. }