script.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. package script
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "github.com/yuin/gopher-lua/parse"
  7. qu "jygit.jydev.jianyu360.cn/data_processing/common_utils"
  8. "net/url"
  9. "os"
  10. "path/filepath"
  11. "spider_creator/backend"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/chromedp/cdproto/browser"
  16. "github.com/chromedp/cdproto/network"
  17. "github.com/chromedp/cdproto/page"
  18. "github.com/chromedp/chromedp"
  19. "github.com/yuin/gopher-lua"
  20. be "spider_creator/backend"
  21. )
  22. const (
  23. selector_type_id = 0
  24. selector_type_query = 1
  25. selector_type_search = 2
  26. selector_type_jspath = 3
  27. selector_type_query_all = 4
  28. execute_return_type_string = 0
  29. execute_return_type_list = 1
  30. execute_return_type_table = 2
  31. qlm_list_lua = "/qlm_list.lua"
  32. qlm_detail_lua = "/qlm_detail.lua"
  33. )
  34. var (
  35. DataCache = make(chan map[string]interface{}, 2000)
  36. Datas []map[string]interface{}
  37. )
  38. type GLVm struct {
  39. ScriptDir string
  40. LogsDir string
  41. LogsFile *os.File
  42. Dnf backend.EventNotifyFace
  43. Headless bool
  44. ShowImage bool
  45. ProxyServer bool
  46. ProxyAddr string
  47. B *GLBrowser
  48. ScriptRunning bool //控制一次只能执行一个脚本
  49. DataSaveOver chan bool
  50. }
  51. type GLBrowser struct {
  52. Ctx context.Context
  53. CancelFn context.CancelFunc
  54. }
  55. func NewGLVM(scriptDir, logsDir string, dnf be.EventNotifyFace) *GLVm {
  56. return &GLVm{
  57. ScriptDir: scriptDir,
  58. LogsDir: logsDir,
  59. Dnf: dnf,
  60. DataSaveOver: make(chan bool, 1),
  61. }
  62. }
  63. // LoadScript 加载脚本
  64. func (glvm *GLVm) LoadScript(page string) string {
  65. var path string
  66. if page == "list" {
  67. path = glvm.ScriptDir + qlm_list_lua
  68. } else if page == "detail" {
  69. path = glvm.ScriptDir + qlm_detail_lua
  70. }
  71. bs, err := os.ReadFile(path)
  72. if err != nil {
  73. qu.Debug(path, "脚本加载失败...")
  74. }
  75. return string(bs)
  76. }
  77. // RunScript 执行lua代码
  78. func (glvm *GLVm) RunScript(script, recordId string) error {
  79. defer qu.Catch()
  80. var s *lua.LState = lua.NewState()
  81. defer s.Close()
  82. //日志文件
  83. now := time.Now()
  84. path := glvm.LogsDir + fmt.Sprintf("/%s.log", qu.FormatDate(&now, qu.Date_Short_Layout))
  85. qu.Debug("log path:", path)
  86. file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
  87. if err != nil {
  88. qu.Debug("日志创建失败:", err)
  89. return err
  90. }
  91. glvm.LogsFile = file
  92. defer glvm.LogsFile.Close()
  93. //方法绑定
  94. glvm.ResetBrowser() //先创建浏览器对象
  95. glvm.BindLuaState(s) //绑定虚拟机函数
  96. glvm.B.BindLuaState(s, recordId)
  97. defer func() {
  98. if b := glvm.B; b != nil {
  99. b.CancelFn()
  100. b.Ctx = nil
  101. b.CancelFn = nil
  102. b = nil
  103. }
  104. }()
  105. reader := strings.NewReader(script)
  106. chunk, err := parse.Parse(reader, "code")
  107. if err != nil {
  108. return err
  109. }
  110. proto, err := lua.Compile(chunk, script)
  111. if err != nil {
  112. return err
  113. }
  114. lfunc := s.NewFunctionFromProto(proto)
  115. s.Push(lfunc)
  116. s.Call(0, 0)
  117. return nil
  118. }
  119. // ResetBrowser 重置浏览器
  120. func (glvm *GLVm) ResetBrowser() {
  121. if glvm.B != nil && glvm.B.CancelFn != nil {
  122. glvm.B.CancelFn()
  123. glvm.B.Ctx = nil
  124. glvm.B.CancelFn = nil
  125. }
  126. _, _, _, _, ctx, incCancelFn := backend.NewBrowser(glvm.Headless, glvm.ShowImage, glvm.ProxyServer, "http://")
  127. b := &GLBrowser{
  128. Ctx: ctx,
  129. CancelFn: incCancelFn,
  130. }
  131. if glvm.B == nil {
  132. glvm.B = b
  133. } else {
  134. glvm.B.Ctx, glvm.B.CancelFn = b.Ctx, b.CancelFn
  135. }
  136. }
  137. // BindLuaState 绑定虚拟机函数
  138. func (glvm *GLVm) BindLuaState(s *lua.LState) {
  139. s.SetGlobal("browser_reset", s.NewFunction(func(l *lua.LState) int {
  140. glvm.ResetBrowser()
  141. return 0
  142. }))
  143. s.SetGlobal("browser_savelog", s.NewFunction(func(l *lua.LState) int {
  144. text := l.ToString(-1)
  145. qu.Debug("log:", text)
  146. now := time.Now()
  147. glvm.LogsFile.Write([]byte(fmt.Sprintf("%s%s%s%s", qu.FormatDate(&now, qu.Date_Full_Layout), "---", text, "\n")))
  148. return 0
  149. }))
  150. }
  151. func (glvm *GLVm) CloseTabs() {
  152. if glvm.B != nil && glvm.B.CancelFn != nil {
  153. glvm.B.CancelFn()
  154. glvm.B.Ctx = nil
  155. glvm.B.CancelFn = nil
  156. glvm.B = nil
  157. }
  158. }
  159. // findTab 根据标题、url找tab
  160. func (b *GLBrowser) findTabContext(tabTitle, tabUrl string, timeoutInt64 int64) (ctx context.Context, err error) {
  161. if b.Ctx != nil {
  162. if timeoutInt64 == 0 {
  163. timeoutInt64 = 5000
  164. }
  165. timeout := time.Duration(timeoutInt64) * time.Millisecond
  166. if tabTitle == "" && tabUrl == "" {
  167. ctx, _ = context.WithTimeout(b.Ctx, timeout)
  168. return ctx, nil
  169. } else {
  170. ts, err := chromedp.Targets(b.Ctx)
  171. if err != nil {
  172. return nil, err
  173. }
  174. for _, t := range ts {
  175. if (tabTitle != "" && strings.Contains(t.Title, tabTitle)) || (tabUrl != "" && strings.Contains(t.URL, tabUrl)) {
  176. // log.Printf("find tab param<title,url>: %s %s found %s %s", tabTitle, tabUrl,
  177. // t.Title, t.URL)
  178. newCtx, _ := chromedp.NewContext(b.Ctx, chromedp.WithTargetID(t.TargetID))
  179. ctx, _ = context.WithTimeout(newCtx, timeout)
  180. return ctx, nil
  181. }
  182. }
  183. }
  184. return nil, errors.New("can't find tab")
  185. }
  186. return nil, errors.New("context is error")
  187. }
  188. // CloseTabs 关闭页面
  189. func (b *GLBrowser) CloseTabs(tabTitle, tabUrl string, timeoutInt64 int64) (err error) {
  190. if timeoutInt64 == 0 {
  191. timeoutInt64 = 5
  192. }
  193. timeout := time.Duration(timeoutInt64) * time.Millisecond
  194. ts, err := chromedp.Targets(b.Ctx)
  195. if err != nil {
  196. return err
  197. }
  198. for _, t := range ts {
  199. if (tabTitle != "" && strings.Contains(t.Title, tabTitle)) || (tabUrl != "" && strings.Contains(t.URL, tabUrl)) {
  200. newCtx, _ := chromedp.NewContext(b.Ctx, chromedp.WithTargetID(t.TargetID))
  201. ctx, _ := context.WithTimeout(newCtx, timeout)
  202. chromedp.Run(
  203. ctx,
  204. page.Close(),
  205. )
  206. }
  207. }
  208. return nil
  209. }
  210. // Navigate 导航到指定网址
  211. func (b *GLBrowser) Navigate(tabTitle string, tabUrl string, isNewTab bool, targetUrl string, timeout int64) (err error) {
  212. ctx, err := b.findTabContext(tabTitle, tabUrl, timeout)
  213. if err != nil {
  214. return err
  215. }
  216. //新标签页
  217. if isNewTab {
  218. ctx, _ = chromedp.NewContext(ctx)
  219. }
  220. //
  221. return chromedp.Run(ctx,
  222. chromedp.Navigate(targetUrl))
  223. }
  224. // Navigate 导航到指定网址,并保存请求资源,如图片等
  225. func (b *GLBrowser) NavigateAndSaveRes(tabTitle string, tabUrl string, timeout int64, isNewTab bool, targetUrl string, saveFileTypeList, save2dir string) (err error) {
  226. ctx, err := b.findTabContext(tabTitle, tabUrl, timeout)
  227. if err != nil {
  228. return err
  229. }
  230. //新标签页
  231. if isNewTab {
  232. ctx, _ = chromedp.NewContext(ctx)
  233. }
  234. //
  235. saveFileType := strings.Split(saveFileTypeList, " ")
  236. isNeedRes := func(fileType string) bool {
  237. for _, v := range saveFileType {
  238. if strings.Contains(fileType, v) {
  239. return true
  240. }
  241. }
  242. return false
  243. }
  244. fnURL2FileName := func(requestURL string) string {
  245. u, err := url.Parse(requestURL)
  246. if err != nil {
  247. return ""
  248. }
  249. _, filename := filepath.Split(u.Path)
  250. return filename
  251. }
  252. var cache = map[network.RequestID]string{}
  253. chromedp.ListenTarget(ctx, func(v interface{}) {
  254. switch ev := v.(type) {
  255. case *network.EventRequestWillBeSent: //准备下载
  256. cache[ev.RequestID] = ev.Request.URL
  257. case *network.EventResponseReceived: //检查回应头的contenttype
  258. contentType, _ := ev.Response.Headers["Content-Type"].(string)
  259. fmt.Println(contentType)
  260. if !isNeedRes(contentType) {
  261. delete(cache, ev.RequestID)
  262. }
  263. case *network.EventLoadingFinished: //下载完成
  264. if uri, ok := cache[ev.RequestID]; ok {
  265. filename := fnURL2FileName(uri)
  266. fmt.Println("save2file", filename)
  267. if filename != "" {
  268. filePath := filepath.Join(save2dir, filename)
  269. var buf []byte
  270. if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
  271. var err error
  272. buf, err = network.GetResponseBody(ev.RequestID).Do(ctx)
  273. return err
  274. })); err == nil {
  275. os.WriteFile(filePath, buf, 0777)
  276. } else {
  277. fmt.Println(err.Error())
  278. }
  279. }
  280. }
  281. }
  282. })
  283. //
  284. err = chromedp.Run(ctx,
  285. chromedp.Navigate(targetUrl))
  286. //下载存储
  287. return err
  288. }
  289. // ExecuteJS 执行脚本
  290. func (b *GLBrowser) ExecuteJS(tabTitle, tabUrl, script string, ret interface{}, timeout int64) (err error) {
  291. ctx, err := b.findTabContext(tabTitle, tabUrl, timeout)
  292. if err != nil {
  293. return err
  294. }
  295. return chromedp.Run(ctx,
  296. chromedp.Evaluate(script, ret))
  297. }
  298. // Click 点击
  299. func (b *GLBrowser) Click(tabTitle, tabUrl, selector string, selectorType int, timeout int64) (err error) {
  300. ctx, err := b.findTabContext(tabTitle, tabUrl, timeout)
  301. if err != nil {
  302. return err
  303. }
  304. var act chromedp.QueryAction
  305. switch selectorType {
  306. case selector_type_id:
  307. act = chromedp.Click(selector, chromedp.ByID)
  308. case selector_type_query:
  309. act = chromedp.Click(selector, chromedp.ByQuery)
  310. case selector_type_search:
  311. act = chromedp.Click(selector, chromedp.BySearch)
  312. case selector_type_jspath:
  313. act = chromedp.Click(selector, chromedp.ByJSPath)
  314. default:
  315. act = chromedp.Click(selector, chromedp.ByQueryAll)
  316. }
  317. err = chromedp.Run(ctx,
  318. act)
  319. return err
  320. }
  321. // KeySend 键盘输入
  322. func (b *GLBrowser) KeySend(tabTitle, tabUrl, selector, sendStr string, selectorType int, timeout int64) (err error) {
  323. ctx, err := b.findTabContext(tabTitle, tabUrl, timeout)
  324. if err != nil {
  325. return err
  326. }
  327. var act chromedp.QueryAction
  328. switch selectorType {
  329. case selector_type_id:
  330. act = chromedp.SendKeys(selector, sendStr, chromedp.ByID)
  331. case selector_type_query:
  332. act = chromedp.SendKeys(selector, sendStr, chromedp.ByQuery)
  333. case selector_type_search:
  334. act = chromedp.SendKeys(selector, sendStr, chromedp.BySearch)
  335. case selector_type_jspath:
  336. act = chromedp.SendKeys(selector, sendStr, chromedp.ByJSPath)
  337. default:
  338. act = chromedp.SendKeys(selector, sendStr, chromedp.ByQueryAll)
  339. }
  340. return chromedp.Run(ctx,
  341. act)
  342. }
  343. // WaitVisible 等待元素可见
  344. func (b *GLBrowser) WaitVisible(tabTitle, tabUrl, selector string, selectorType int, timeout int64) error {
  345. ctx, err := b.findTabContext(tabTitle, tabUrl, timeout)
  346. if err != nil {
  347. return err
  348. }
  349. var act chromedp.QueryAction
  350. switch selectorType {
  351. case selector_type_id:
  352. act = chromedp.WaitVisible(selector, chromedp.ByID)
  353. case selector_type_query:
  354. act = chromedp.WaitVisible(selector, chromedp.ByQuery)
  355. case selector_type_search:
  356. act = chromedp.WaitVisible(selector, chromedp.BySearch)
  357. case selector_type_jspath:
  358. act = chromedp.WaitVisible(selector, chromedp.ByJSPath)
  359. default:
  360. act = chromedp.WaitVisible(selector, chromedp.ByQueryAll)
  361. }
  362. return chromedp.Run(ctx,
  363. act)
  364. }
  365. // 重置浏览器
  366. func (b *GLBrowser) Reset() {
  367. }
  368. // DownloadFile 只有在非headless模式下有效,与click方法其实是一致的
  369. func (b *GLBrowser) DownloadFile(tabTitle, tabUrl string, timeout int64, selector string, selectorType int, save2dir string) error {
  370. ctx, err := b.findTabContext(tabTitle, tabUrl, timeout)
  371. if err != nil {
  372. return err
  373. }
  374. var act chromedp.QueryAction
  375. switch selectorType {
  376. case selector_type_id:
  377. act = chromedp.Click(selector, chromedp.ByID)
  378. case selector_type_query:
  379. act = chromedp.Click(selector, chromedp.ByQuery)
  380. case selector_type_search:
  381. act = chromedp.Click(selector, chromedp.BySearch)
  382. case selector_type_jspath:
  383. act = chromedp.Click(selector, chromedp.ByJSPath)
  384. default:
  385. act = chromedp.Click(selector, chromedp.ByQueryAll)
  386. }
  387. return chromedp.Run(ctx,
  388. browser.SetDownloadBehavior(browser.SetDownloadBehaviorBehaviorAllowAndName).WithDownloadPath(save2dir).WithEventsEnabled(true),
  389. act)
  390. }
  391. // BindLuaState
  392. func (b *GLBrowser) BindLuaState(s *lua.LState, recordId string) {
  393. //执行暂停
  394. s.SetGlobal("browser_sleep", s.NewFunction(func(l *lua.LState) int {
  395. fmt.Println("---browser_sleep---")
  396. timeout := l.ToInt64(-1)
  397. if timeout == 0 {
  398. timeout = 5
  399. }
  400. time.Sleep(time.Duration(timeout) * time.Millisecond)
  401. return 0
  402. }))
  403. //关闭tabl页
  404. s.SetGlobal("browser_closetabs", s.NewFunction(func(l *lua.LState) int {
  405. fmt.Println("---browser_closetabs---")
  406. timeout := l.ToInt64(-3)
  407. tabTitle := l.ToString(-2)
  408. tabUrl := l.ToString(-1)
  409. if timeout == 0 {
  410. timeout = 5
  411. }
  412. b.CloseTabs(tabTitle, tabUrl, timeout)
  413. return 0
  414. }))
  415. //注册打开地址
  416. s.SetGlobal("browser_navagite", s.NewFunction(func(l *lua.LState) int {
  417. fmt.Println("---browser_navagite---")
  418. tabTitle := l.ToString(-5) //指定标签页title
  419. tabUrl := l.ToString(-4) //指定标签页url
  420. isNewTab := l.ToBool(-3) //是否打开新的标签页
  421. timeout := l.ToInt64(-2) //网页打开的超时时间
  422. targetUrl := l.ToString(-1) //打开网页的链接
  423. if err := b.Navigate(tabTitle, tabUrl, isNewTab, targetUrl, timeout); err != nil {
  424. l.Push(lua.LString(err.Error()))
  425. } else {
  426. l.Push(lua.LString("ok"))
  427. }
  428. return 1
  429. }))
  430. //执行浏览器端js
  431. s.SetGlobal("browser_executejs", s.NewFunction(func(l *lua.LState) int {
  432. fmt.Println("---browser_executejs---")
  433. tabTitle := l.ToString(-5)
  434. tabUrl := l.ToString(-4)
  435. timeout := l.ToInt64(-3)
  436. returnType := l.ToInt(-2) //返回数据类型
  437. script := l.ToString(-1) //执行的js
  438. switch returnType {
  439. case execute_return_type_string: //返回string
  440. var ret string
  441. if err := b.ExecuteJS(tabTitle, tabUrl, script, &ret, timeout); err == nil {
  442. l.Push(lua.LString("ok"))
  443. l.Push(lua.LString(ret))
  444. } else {
  445. l.Push(lua.LString("err"))
  446. l.Push(lua.LString(err.Error()))
  447. }
  448. case execute_return_type_list: //返回list
  449. var ret = make([]interface{}, 0, 0)
  450. var tmp = make(map[string]interface{})
  451. if err := b.ExecuteJS(tabTitle, tabUrl, script, &ret, timeout); err == nil {
  452. for i, v := range ret {
  453. tmp[strconv.Itoa(i)] = v
  454. }
  455. l.Push(lua.LString("ok"))
  456. l.Push(MapToTable(tmp))
  457. } else {
  458. l.Push(lua.LString("err"))
  459. l.Push(lua.LString(err.Error()))
  460. }
  461. case execute_return_type_table: //返回table
  462. var ret = make(map[string]interface{})
  463. if err := b.ExecuteJS(tabTitle, tabUrl, script, &ret, timeout); err == nil {
  464. l.Push(lua.LString("ok"))
  465. l.Push(MapToTable(ret))
  466. } else {
  467. l.Push(lua.LString("err"))
  468. l.Push(lua.LString(err.Error()))
  469. }
  470. }
  471. return 2
  472. }))
  473. //按键
  474. s.SetGlobal("browser_keysend", s.NewFunction(func(l *lua.LState) int {
  475. fmt.Println("---browser_keysend---")
  476. tabTitle := l.ToString(-6)
  477. tabUrl := l.ToString(-5)
  478. timeout := l.ToInt64(-4)
  479. words := l.ToString(-3)
  480. selectorType := l.ToInt(-2)
  481. selector := l.ToString(-1)
  482. fmt.Println(selector, words, selectorType, timeout)
  483. err := b.KeySend(tabTitle, tabUrl, selector, words, selectorType, timeout)
  484. if err != nil {
  485. l.Push(lua.LString(err.Error()))
  486. } else {
  487. l.Push(lua.LString("ok"))
  488. }
  489. return 1
  490. }))
  491. //点击
  492. s.SetGlobal("browser_click", s.NewFunction(func(l *lua.LState) int {
  493. fmt.Println("---browser_click---")
  494. tabTitle := l.ToString(-5)
  495. tabUrl := l.ToString(-4)
  496. timeout := l.ToInt64(-3)
  497. selectorType := l.ToInt(-2)
  498. selector := l.ToString(-1)
  499. err := b.Click(tabTitle, tabUrl, selector, selectorType, timeout)
  500. if err != nil {
  501. l.Push(lua.LString(err.Error()))
  502. } else {
  503. l.Push(lua.LString("ok"))
  504. }
  505. return 1
  506. }))
  507. //等待元素加载
  508. s.SetGlobal("browser_waitvisible", s.NewFunction(func(l *lua.LState) int {
  509. fmt.Println("---browser_waitvisible---")
  510. tabTitle := l.ToString(-5)
  511. tabUrl := l.ToString(-4)
  512. timeout := l.ToInt64(-3)
  513. selectorType := l.ToInt(-2) //选择器类型
  514. selector := l.ToString(-1) //选择器
  515. err := b.WaitVisible(tabTitle, tabUrl, selector, selectorType, timeout)
  516. if err != nil {
  517. l.Push(lua.LString(err.Error()))
  518. } else {
  519. l.Push(lua.LString("ok"))
  520. }
  521. return 1
  522. }))
  523. //下载附件
  524. s.SetGlobal("browser_downloadfile", s.NewFunction(func(l *lua.LState) int {
  525. tabTitle := l.ToString(-6)
  526. tabUrl := l.ToString(-5)
  527. timeout := l.ToInt64(-4)
  528. selectorType := l.ToInt(-3)
  529. selector := l.ToString(-2)
  530. save2dir := l.ToString(-1)
  531. err := b.DownloadFile(tabTitle, tabUrl, timeout, selector, selectorType, save2dir)
  532. if err != nil {
  533. l.Push(lua.LString(err.Error()))
  534. } else {
  535. l.Push(lua.LString("ok"))
  536. }
  537. return 1
  538. }))
  539. //注册打开地址
  540. s.SetGlobal("browser_navagite_download_res", s.NewFunction(func(l *lua.LState) int {
  541. tabTitle := l.ToString(-7)
  542. tabUrl := l.ToString(-6)
  543. timeout := l.ToInt64(-5)
  544. isNewTab := l.ToBool(-4)
  545. targetUrl := l.ToString(-3)
  546. saveFileTypeList := l.ToString(-2)
  547. savedir := l.ToString(-1)
  548. if err := b.NavigateAndSaveRes(tabTitle, tabUrl, timeout, isNewTab, targetUrl, saveFileTypeList, savedir); err != nil {
  549. l.Push(lua.LString(err.Error()))
  550. } else {
  551. l.Push(lua.LString("ok"))
  552. }
  553. return 1
  554. }))
  555. //发布时间格式化
  556. s.SetGlobal("browser_publishtime", s.NewFunction(func(l *lua.LState) int {
  557. text := l.ToString(-1)
  558. publishtime := getPublitime(text)
  559. l.Push(lua.LString(publishtime))
  560. return 1
  561. }))
  562. //保存数据
  563. s.SetGlobal("browser_savedata", s.NewFunction(func(l *lua.LState) int {
  564. //fmt.Println("---browser_savedata---")
  565. page := l.ToString(-2)
  566. data := l.ToTable(-1)
  567. result := TableToMap(data)
  568. if page == "list" {
  569. result["recordid"] = recordId
  570. }
  571. DataCache <- result
  572. return 1
  573. }))
  574. //获取数据
  575. s.SetGlobal("browser_getdata", s.NewFunction(func(l *lua.LState) int {
  576. fmt.Println("---browser_getdata---")
  577. num := l.ToInt(-1) //获取多少条数据
  578. count := len(Datas)
  579. if count == 0 {
  580. l.Push(lua.LString("err"))
  581. l.Push(lua.LString("当前可下载量为0"))
  582. } else {
  583. if count < num {
  584. num = count
  585. }
  586. data := Datas[:num]
  587. Datas = Datas[num:]
  588. tMap := MapToTable(map[string]interface{}{"data": data})
  589. l.Push(lua.LString("ok"))
  590. l.Push(tMap.RawGetString("data"))
  591. }
  592. return 2
  593. }))
  594. }