script.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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. S.Push(ret)
  227. return 1
  228. }))
  229. // s.L.SetGlobal("findMgoData", s.L.NewFunction(func(S *lua.LState) int {
  230. // update := [][]map[string]interface{}{}
  231. // query := map[string]interface{}{"state": 0}
  232. // data, _ := Mgo.Find(util.Config.TmpCollName, query, `{"_id":-1}`, nil, false, 0, 10)
  233. // pageList := []interface{}{}
  234. // for _, d := range *data {
  235. // tmpMap := map[string]string{}
  236. // tmpMap["title"] = qu.ObjToString(d["title"])
  237. // tmpMap["detail"] = qu.ObjToString(d["detail"])
  238. // tmpMap["href"] = qu.ObjToString(d["href"])
  239. // publishtime := qu.Int64All(d["publishtime"])
  240. // tmpMap["publishtime"] = qu.FormatDateByInt64(&publishtime, qu.Date_Full_Layout)
  241. // tmpMap["_id"] = qu.BsonIdToSId(d["_id"])
  242. // pageList = append(pageList, tmpMap)
  243. // update = append(update, []map[string]interface{}{
  244. // map[string]interface{}{"_id": d["_id"]},
  245. // map[string]interface{}{"$set": map[string]interface{}{"state": 1}},
  246. // })
  247. // }
  248. // ret := util.MapToTable(s.L, pageList)
  249. // S.Push(ret)
  250. // if len(update) > 0 {
  251. // Mgo.UpdateBulk(util.Config.TmpCollName, update...)
  252. // }
  253. // return 1
  254. // }))
  255. s.L.SetGlobal("findMap", s.L.NewFunction(func(S *lua.LState) int {
  256. qmap := S.ToTable(-2)
  257. content := S.ToString(-1)
  258. ret := s.L.NewTable()
  259. util.FindMap(qmap, content, ret)
  260. S.Push(ret)
  261. return 1
  262. }))
  263. //公示暴露方式
  264. s.L.SetGlobal("getEcpsCode", s.L.NewFunction(func(S *lua.LState) int {
  265. area := strings.ToUpper(S.ToString(-2))
  266. content := S.ToString(-1)
  267. code, state := util.GetEcpsCode(area, []byte(content))
  268. if state == "wx" {
  269. code, _ = GetCodeByWx([]byte(content))
  270. }
  271. S.Push(lua.LString(code))
  272. return 1
  273. }))
  274. //调用jsvm
  275. s.L.SetGlobal("jsvm", s.L.NewFunction(func(S *lua.LState) int {
  276. js := S.ToString(-1)
  277. ret := s.L.NewTable()
  278. if js == "" {
  279. ret.RawSet(lua.LString("val"), lua.LString(""))
  280. ret.RawSet(lua.LString("err"), lua.LString("js is null"))
  281. } else {
  282. rep := util.JsVmPost(util.Config.JsVmUrl, js)
  283. ret.RawSet(lua.LString("val"), lua.LString(qu.ObjToString(rep["val"])))
  284. ret.RawSet(lua.LString("err"), lua.LString(qu.ObjToString(rep["err"])))
  285. }
  286. S.Push(ret)
  287. return 1
  288. }))
  289. //指定下载器
  290. s.L.SetGlobal("changeDownloader", s.L.NewFunction(func(S *lua.LState) int {
  291. s.Downloader = GetOneDownloader()
  292. S.Push(lua.LString(s.Downloader))
  293. return 1
  294. }))
  295. //指定下载器file
  296. s.L.SetGlobal("changeDownloaderFile", s.L.NewFunction(func(S *lua.LState) int {
  297. s.Downloader = GetOneDownloaderFile()
  298. S.Push(lua.LString(s.Downloader))
  299. return 1
  300. }))
  301. //手工延时
  302. s.L.SetGlobal("timeSleep", s.L.NewFunction(func(S *lua.LState) int {
  303. // if workTime {
  304. // util.TimeSleepFunc(time.Duration(S.ToInt(-1))*time.Second, TimeSleepChan)
  305. // } else {
  306. // util.TimeSleepFunc(1*time.Second, TimeSleepChan)
  307. // }
  308. util.TimeSleepFunc(time.Second*2, TimeSleepChan)
  309. return 0
  310. }))
  311. //编码解码
  312. s.L.SetGlobal("transCode", s.L.NewFunction(func(S *lua.LState) int {
  313. codeType := strings.ToLower(S.ToString(-2))
  314. str := S.CheckString(-1)
  315. switch codeType {
  316. case "unicode":
  317. str = transUnic(str)
  318. case "urlencode_gbk":
  319. data, _ := ioutil.ReadAll(transform.NewReader(bytes.NewReader([]byte(str)), simplifiedchinese.GBK.NewEncoder()))
  320. l, _ := url.Parse("http://a.com/?" + string(data))
  321. tmpstr := l.Query().Encode()
  322. if len(tmpstr) > 1 {
  323. str = tmpstr[0 : len(tmpstr)-1]
  324. } else {
  325. str = ""
  326. }
  327. case "urlencode_utf8":
  328. l, _ := url.Parse("http://a.com/?" + str)
  329. tmpstr := l.Query().Encode()
  330. if len(tmpstr) > 1 {
  331. str = tmpstr[0 : len(tmpstr)-1]
  332. } else {
  333. str = ""
  334. }
  335. case "urldecode_utf8":
  336. str, _ = url.QueryUnescape(str)
  337. case "decode64":
  338. str = util.DecodeB64(str)
  339. case "encodemd5":
  340. str = qu.GetMd5String(str)
  341. case "htmldecode": //html实体码
  342. //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>`
  343. str = S.ToString(-1)
  344. reg, _ := regexp.Compile("&#\\d+;")
  345. str = reg.ReplaceAllStringFunc(str, func(src string) string {
  346. v, _ := strconv.Atoi(src[2 : len(src)-1])
  347. return string(rune(v))
  348. })
  349. }
  350. S.Push(lua.LString(str))
  351. return 1
  352. }))
  353. //如果服务端返回的html是gzip压缩过格式的 这里需要转一下
  354. s.L.SetGlobal("unGzip", s.L.NewFunction(func(S *lua.LState) int {
  355. html := S.ToString(-1)
  356. bs := []byte(html)
  357. gzipreader, _ := gzip.NewReader(bytes.NewReader(bs))
  358. bs, _ = ioutil.ReadAll(gzipreader)
  359. S.Push(lua.LString(bs))
  360. return 1
  361. }))
  362. //luamaker提供的分析列表页url地址 获取列表数据公用方法
  363. s.L.SetGlobal("getSimpleListPage", s.L.NewFunction(func(S *lua.LState) int {
  364. html := S.ToString(-3)
  365. date_pattern := S.ToString(-2)
  366. pageListUrl := S.ToString(-1) //列表页url
  367. bs := []byte(html)
  368. tmparr := []string{}
  369. tmpret := []int{}
  370. re, _ := regexp.Compile(`采购|招标|公示|公告|意见|结果|通知|工程`)
  371. doc, _ := gq.NewDocumentFromReader(bytes.NewReader(bs))
  372. doc.Find("a").Each(func(i int, sq *gq.Selection) {
  373. text := sq.Text()
  374. if len(text) < 30 {
  375. return
  376. }
  377. tmparr = append(tmparr, text)
  378. if re.MatchString(text) {
  379. tmpret = append(tmpret, 1)
  380. //logger.Debug(text)
  381. } else {
  382. tmpret = append(tmpret, 0)
  383. }
  384. })
  385. logger.Debug(tmpret)
  386. //线性分析,算周边,只算周围5步的点
  387. tmplen, thepos, themax := len(tmpret), -1, 0
  388. for i := 0; i < tmplen; i++ {
  389. if tmpret[i] == 0 {
  390. continue
  391. }
  392. start, end := i-MAX_STEP, i+MAX_STEP
  393. if start < 0 {
  394. start = 0
  395. }
  396. if end > tmplen {
  397. end = tmplen
  398. }
  399. tmp := 0
  400. //从当前位置往左,往右找连续点
  401. for j := i; j > start; j-- {
  402. if tmpret[j] == 1 {
  403. tmp++
  404. } else {
  405. break
  406. }
  407. }
  408. for j := i; j < end; j++ {
  409. if tmpret[j] == 1 {
  410. tmp++
  411. } else {
  412. break
  413. }
  414. }
  415. if tmp > themax {
  416. themax = tmp
  417. thepos = i
  418. }
  419. } //end of for...
  420. //logger.Debug("找位置完成")
  421. //验证
  422. if thepos == -1 {
  423. logger.Error("完蛋,找不到")
  424. panic("不支持啊,失败啊")
  425. }
  426. //下边是找父容器
  427. var thelink *gq.Selection
  428. doc.Find("a").Each(func(i int, sq *gq.Selection) {
  429. if sq.Text() == tmparr[thepos] {
  430. thelink = sq
  431. }
  432. })
  433. isfind := false
  434. //同样Path向上找,不超过5步
  435. for i := 0; i < MAX_STEP; i++ {
  436. thelink = thelink.Parent()
  437. clen := getChildrenLen(thelink)
  438. if clen >= themax-1 {
  439. isfind = true
  440. break
  441. }
  442. //logger.Debug("TAG:::", thelink.Nodes[0].Data, clen)
  443. }
  444. //找到列表
  445. pageList := []interface{}{}
  446. if isfind {
  447. thelink.Children().Each(func(i int, sq *gq.Selection) {
  448. page := map[string]string{}
  449. link_sq := sq.Find("a")
  450. href := link_sq.AttrOr("href", "")
  451. text := link_sq.Text()
  452. page["title"] = text
  453. page["href"] = dealHref(pageListUrl, href)
  454. page["publishtime"] = dealPublishTime(strings.TrimSpace(sq.Text()), date_pattern)
  455. //logger.Debug(i)
  456. pageList = append(pageList, page)
  457. })
  458. } else {
  459. logger.Error("完蛋,找父亲节点失败啊")
  460. //panic("不支持啊,失败啊")
  461. }
  462. ret := util.MapToTable(s.L, pageList)
  463. S.Push(ret)
  464. return 1
  465. }))
  466. //招投标信息标题判重
  467. s.L.SetGlobal("titleRepeatJudgement", s.L.NewFunction(func(S *lua.LState) int {
  468. S.Push(lua.LBool(false))
  469. return 1
  470. }))
  471. //招标信息判重新方法 2016-12-14 wanghuidong
  472. s.L.SetGlobal("urlRepeatJudgement", s.L.NewFunction(func(S *lua.LState) int {
  473. S.Push(lua.LBool(false))
  474. return 1
  475. }))
  476. //将url放入内存缓存 2016-12-14 wanghuidong
  477. s.L.SetGlobal("putUrl2Redis", s.L.NewFunction(func(S *lua.LState) int {
  478. //url := S.ToString(-1)
  479. return 1
  480. }))
  481. //解析附件中的word、pdf
  482. s.L.SetGlobal("officeAnalysis", s.L.NewFunction(func(S *lua.LState) int {
  483. ext := map[string]byte{"pdf": byte(0), "doc": byte(1), "docx": byte(2)}
  484. str := S.ToString(-2)
  485. extension := S.ToString(-1)
  486. bs, _ := base64.StdEncoding.DecodeString(str)
  487. bs = append([]byte{ext[extension]}, bs...)
  488. msgid := mu.UUID(8)
  489. Msclient.Call("", msgid, mu.SERVICE_OFFICE_ANALYSIS, mu.SENDTO_TYPE_ALL_RECIVER, bs, 60)
  490. return 1
  491. }))
  492. //下载附件download(url,method,param,head,cookie,fileName)
  493. s.L.SetGlobal("downloadFile", s.L.NewFunction(func(S *lua.LState) int {
  494. if s.FileLastThreeTimes == nil {
  495. s.FileLastThreeTimes = make([]time.Duration, 4)
  496. }
  497. if util.Config.IsDelay {
  498. SleepTime(3, s.FileLastThreeTimes) //睡眠时间
  499. }
  500. start := time.Now() //起始时间
  501. cookie := S.ToString(-1)
  502. head := S.ToTable(-2)
  503. param := S.ToTable(-3)
  504. method := S.ToString(-4)
  505. url := S.ToString(-5)
  506. fileName := S.ToString(-6)
  507. ishttps := strings.Contains(url, "https")
  508. var mycookie []*http.Cookie
  509. if cookie != "{}" {
  510. json.Unmarshal([]byte(cookie), &mycookie)
  511. } else {
  512. mycookie = make([]*http.Cookie, 0)
  513. }
  514. fileName = strings.TrimSpace(fileName)
  515. url = strings.TrimSpace(url)
  516. ret := DownloadFile(s.Downloader, url, method, util.GetTable(param), util.GetTable(head), mycookie, s.Encoding, s.Userproxy, ishttps, s.SCode, s.Timeout)
  517. url, name, size, ftype, fid := util.UploadFile(s.SCode, fileName, url, ret)
  518. if strings.TrimSpace(ftype) == "" {
  519. if len(path.Ext(name)) > 0 {
  520. ftype = path.Ext(name)[1:]
  521. }
  522. }
  523. S.Push(lua.LString(url))
  524. S.Push(lua.LString(name))
  525. S.Push(lua.LString(size))
  526. S.Push(lua.LString(ftype))
  527. S.Push(lua.LString(fid))
  528. atomic.AddInt32(&s.ToDayRequestNum, 1)
  529. atomic.AddInt32(&s.TotalRequestNum, 1)
  530. end := time.Since(start)
  531. if len(s.FileLastThreeTimes) >= 4 {
  532. s.FileLastThreeTimes = s.FileLastThreeTimes[1:]
  533. }
  534. s.FileLastThreeTimes = append(s.FileLastThreeTimes, end)
  535. return 5
  536. }))
  537. s.L.SetGlobal("clearMemoeryCache", s.L.NewFunction(func(S *lua.LState) int {
  538. /*title := S.ToString(-1)
  539. isExist, _ := redis.Exists("title_repeat_judgement", "title_repeat_"+title)
  540. if isExist {
  541. redis.Del("title_repeat_judgement", "title_repeat_"+title)
  542. }*/
  543. return 1
  544. }))
  545. //支持正则,提取
  546. s.L.SetGlobal("regexp", s.L.NewFunction(func(S *lua.LState) int {
  547. index := int(S.ToNumber(-1))
  548. regstr := S.ToString(-2)
  549. text := S.ToString(-3)
  550. reg := regexp.MustCompile(regstr)
  551. reps := reg.FindAllStringSubmatchIndex(text, -1)
  552. ret := s.L.NewTable()
  553. number := 0
  554. for _, v := range reps {
  555. number++
  556. ret.Insert(number, lua.LString(text[v[index]:v[index+1]]))
  557. }
  558. S.Push(ret)
  559. return 1
  560. }))
  561. //支持替换
  562. s.L.SetGlobal("replace", s.L.NewFunction(func(S *lua.LState) int {
  563. text := S.ToString(-3)
  564. old := S.ToString(-2)
  565. repl := S.ToString(-1)
  566. text = strings.Replace(text, old, repl, -1)
  567. S.Push(lua.LString(text))
  568. return 1
  569. }))
  570. //标题的关键词、排除词过滤
  571. s.L.SetGlobal("pagefilterword", s.L.NewFunction(func(S *lua.LState) int {
  572. keyWordReg := regexp.MustCompile(util.Config.Word["keyword"])
  573. notKeyWordReg := regexp.MustCompile(util.Config.Word["notkeyword"])
  574. data := S.ToTable(-1)
  575. dataMap := util.TableToMap(data)
  576. ret := s.L.NewTable()
  577. num := 1
  578. for _, v := range dataMap {
  579. tmp := v.(map[string]interface{})
  580. isOk := false
  581. if title := qu.ObjToString(tmp["title"]); title != "" {
  582. if keyWordReg.MatchString(title) && !notKeyWordReg.MatchString(title) {
  583. isOk = true
  584. }
  585. }
  586. if isOk {
  587. ret.Insert(num, util.MapToLuaTable(S, tmp))
  588. num++
  589. }
  590. }
  591. S.Push(ret)
  592. return 1
  593. }))
  594. //标题的关键词、排除词过滤
  595. s.L.SetGlobal("detailfilterword", s.L.NewFunction(func(S *lua.LState) int {
  596. keyWordReg := regexp.MustCompile(util.Config.Word["keyword"])
  597. notKeyWordReg := regexp.MustCompile(util.Config.Word["notkeyword"])
  598. data := S.ToTable(-1)
  599. dataMap := util.TableToMap(data)
  600. if title := qu.ObjToString(dataMap["title"]); title != "" {
  601. if keyWordReg.MatchString(title) && !notKeyWordReg.MatchString(title) {
  602. S.Push(lua.LBool(true))
  603. return 1
  604. } else {
  605. qu.Debug(s.SCode, dataMap["href"], " title error")
  606. }
  607. } else {
  608. qu.Debug(s.SCode, dataMap["href"], " title error")
  609. }
  610. S.Push(lua.LBool(false))
  611. return 1
  612. }))
  613. //detail过滤
  614. s.L.SetGlobal("filterdetail", s.L.NewFunction(func(S *lua.LState) int {
  615. /*
  616. 1.长度判断 (特殊处理:详情请访问原网页!;详见原网页;见原网页;无;无相关内容;无正文内容)
  617. 2.是否含汉字
  618. */
  619. reg1 := regexp.MustCompile("(原网页|无|无相关内容|无正文内容|见附件|详见附件)")
  620. reg2 := regexp.MustCompile("[\u4e00-\u9fa5]")
  621. detail := S.ToString(-1)
  622. if reg1.MatchString(detail) {
  623. S.Push(lua.LBool(true))
  624. return 1
  625. }
  626. if len([]rune(detail)) < 50 || !reg2.MatchString(detail) {
  627. S.Push(lua.LBool(false))
  628. return 1
  629. }
  630. S.Push(lua.LBool(false))
  631. return 1
  632. }))
  633. //匹配汉字
  634. s.L.SetGlobal("matchan", s.L.NewFunction(func(S *lua.LState) int {
  635. reg1 := regexp.MustCompile("(见附件|详见附件)")
  636. reg2 := regexp.MustCompile("[\u4e00-\u9fa5]")
  637. detail := S.ToString(-1)
  638. detail = reg1.ReplaceAllString(detail, "")
  639. ok := reg2.MatchString(detail)
  640. S.Push(lua.LBool(ok))
  641. return 1
  642. }))
  643. //aes ecb模式加密
  644. s.L.SetGlobal("aesEncryptECB", s.L.NewFunction(func(S *lua.LState) int {
  645. origData := S.ToString(-2)
  646. key := S.ToString(-1)
  647. bytekey := []byte(key)
  648. byteorigData := []byte(origData)
  649. cipher, _ := aes.NewCipher(generateKey([]byte(bytekey)))
  650. length := (len(byteorigData) + aes.BlockSize) / aes.BlockSize
  651. plain := make([]byte, length*aes.BlockSize)
  652. copy(plain, byteorigData)
  653. pad := byte(len(plain) - len(byteorigData))
  654. for i := len(byteorigData); i < len(plain); i++ {
  655. plain[i] = pad
  656. }
  657. encrypted := make([]byte, len(plain))
  658. // 分组分块加密
  659. for bs, be := 0, cipher.BlockSize(); bs <= len(byteorigData); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
  660. cipher.Encrypt(encrypted[bs:be], plain[bs:be])
  661. }
  662. result := base64.StdEncoding.EncodeToString(encrypted)
  663. S.Push(lua.LString(result))
  664. return 1
  665. }))
  666. //根据正文获取发布时间
  667. s.L.SetGlobal("getPublishtime", s.L.NewFunction(func(S *lua.LState) int {
  668. detail := S.ToString(-2)
  669. contenthtml := S.ToString(-1)
  670. publishtime := util.GetPublishtime([]string{contenthtml, detail})
  671. S.Push(lua.LString(publishtime))
  672. return 1
  673. }))
  674. //匹配
  675. s.L.SetGlobal("stringFind", s.L.NewFunction(func(S *lua.LState) int {
  676. regstr := S.ToString(-1)
  677. text := S.ToString(-2)
  678. reg := regexp.MustCompile(regstr)
  679. result := reg.FindString(text)
  680. isMatch := false
  681. if result != "" {
  682. isMatch = true
  683. }
  684. S.Push(lua.LString(result))
  685. S.Push(lua.LBool(isMatch))
  686. return 2
  687. }))
  688. //去除特殊标签中间内容
  689. s.L.SetGlobal("getPureContent", s.L.NewFunction(func(S *lua.LState) int {
  690. con := S.ToString(-1)
  691. reg := regexp.MustCompile("(?s)<!%-%-.*?%-%->")
  692. con = reg.ReplaceAllString(con, "")
  693. // indexArr := reg.FindAllStringIndex(con, -1)
  694. // for i := len(indexArr) - 1; i >= 0; i-- {
  695. // if index := indexArr[i]; len(index) == 2 {
  696. // con = con[:index[0]] + con[index[1]:]
  697. // }
  698. // }
  699. S.Push(lua.LString(con))
  700. return 1
  701. }))
  702. return ""
  703. }
  704. func dealHref(pageListUrl, href string) string {
  705. returnUrl := ""
  706. if href != "" {
  707. r, _ := regexp.Compile("^./")
  708. match := r.MatchString(href)
  709. if match {
  710. url2 := r.ReplaceAllString(href, "")
  711. returnUrl = pageListUrl + url2
  712. }
  713. r2, _ := regexp.Compile("^/")
  714. match2 := r2.MatchString(href)
  715. if match2 {
  716. r3, _ := regexp.Compile("http://[^/]*/")
  717. domain := r3.FindString(pageListUrl)
  718. //fmt.Println(domain)
  719. url2 := r2.ReplaceAllString(href, "")
  720. returnUrl = domain + url2
  721. }
  722. }
  723. return returnUrl
  724. }
  725. func dealPublishTime(content string, pattern string) string {
  726. publishTime := ""
  727. if pattern == "yyyy-MM-dd HH:mm:ss" {
  728. r, _ := regexp.Compile("\\d{4}-\\d{2}-\\d{2}\\s*\\d{2}:\\d{2}:\\d{2}")
  729. publishTime = r.FindString(content)
  730. } else if pattern == "yyyy-MM-dd" {
  731. r, _ := regexp.Compile("\\d{4}-\\d{2}-\\d{2}")
  732. publishTime = r.FindString(content)
  733. } else if pattern == "MM-dd" {
  734. r, _ := regexp.Compile("\\d{2}-\\d{2}")
  735. publishTime = r.FindString(content)
  736. }
  737. return publishTime
  738. }
  739. func getChildrenLen(sq *gq.Selection) (ret int) {
  740. sq.Children().Each(func(i int, sq2 *gq.Selection) {
  741. ret = i
  742. })
  743. return
  744. }
  745. //
  746. func (s *Script) Reload() {
  747. s.L.Close()
  748. s.LoadScript(s.SCode, s.ScriptFile, false)
  749. }
  750. //unicode转码
  751. func transUnic(str string) string {
  752. buf := bytes.NewBuffer(nil)
  753. i, j := 0, len(str)
  754. for i < j {
  755. x := i + 6
  756. if x > j {
  757. buf.WriteString(str[i:])
  758. break
  759. }
  760. if str[i] == '\\' && str[i+1] == 'u' {
  761. hex := str[i+2 : x]
  762. r, err := strconv.ParseUint(hex, 16, 64)
  763. if err == nil {
  764. buf.WriteRune(rune(r))
  765. } else {
  766. logger.Warn(err.Error())
  767. buf.WriteString(str[i:x])
  768. }
  769. i = x
  770. } else {
  771. buf.WriteByte(str[i])
  772. i++
  773. }
  774. }
  775. return buf.String()
  776. }
  777. //取得变量
  778. func (s *Script) GetVar(key string) string {
  779. return s.L.GetGlobal(key).String()
  780. }
  781. //
  782. func (s *Script) GetIntVar(key string) int {
  783. lv := s.L.GetGlobal(key)
  784. if v, ok := lv.(lua.LNumber); ok {
  785. return int(v)
  786. }
  787. return -1
  788. }
  789. //
  790. func (s *Script) GetBoolVar(key string) bool {
  791. lv := s.L.GetGlobal(key)
  792. if v, ok := lv.(lua.LBool); ok {
  793. return bool(v)
  794. }
  795. return false
  796. }
  797. func isWorkTime() {
  798. workTime = util.IsWorkTime()
  799. util.TimeAfterFunc(10*time.Minute, isWorkTime, TimeChan)
  800. }
  801. //设置睡眠时间
  802. func SleepTime(basetime int, times []time.Duration) {
  803. st := 0 //记录最后睡眠时长
  804. base := float64(basetime * 60)
  805. if times[3].Seconds() > base { //最后一次大于 basetime*60秒
  806. if times[2].Seconds() > base {
  807. n := 0
  808. if times[0].Seconds() > base {
  809. n++
  810. }
  811. if times[1].Seconds() > base {
  812. n++
  813. }
  814. st = n + 1
  815. } else if times[2].Seconds() < base && times[0].Seconds() > base && times[1].Seconds() > base {
  816. st = 1
  817. }
  818. }
  819. if st > 0 {
  820. time.Sleep(time.Duration(st) * time.Minute)
  821. }
  822. }
  823. func generateKey(key []byte) (genKey []byte) {
  824. genKey = make([]byte, 16)
  825. copy(genKey, key)
  826. for i := 16; i < len(key); {
  827. for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
  828. genKey[j] ^= key[i]
  829. }
  830. }
  831. return genKey
  832. }