front.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. package spider
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. mu "mfw/util"
  7. "os"
  8. "qfw/util"
  9. "sort"
  10. lu "spiderutil"
  11. "strings"
  12. "sync/atomic"
  13. "time"
  14. "github.com/go-xweb/xweb"
  15. "github.com/tealeg/xlsx"
  16. )
  17. type Front struct {
  18. *xweb.Action
  19. login xweb.Mapper `xweb:"/"` //登录
  20. loadIndex xweb.Mapper `xweb:"/front"` //控制中心
  21. start xweb.Mapper `xweb:"/front/start"`
  22. stop xweb.Mapper `xweb:"/front/stop"`
  23. pass xweb.Mapper `xweb:"/front/pass"`
  24. resume xweb.Mapper `xweb:"/front/resume"`
  25. reloadlua xweb.Mapper `xweb:"/front/reloadlua"`
  26. addSpider xweb.Mapper `xweb:"/front/addSpider"`
  27. delSpider xweb.Mapper `xweb:"/front/delSpider/([^.]*).html"`
  28. addJob xweb.Mapper `xweb:"/front/addJob"`
  29. searchJob xweb.Mapper `xweb:"/front/searchJob"`
  30. clearErr xweb.Mapper `xweb:"/front/clearErr"`
  31. viewErrIndex xweb.Mapper `xweb:"/front/viewErrIndex/([^.]*).html"`
  32. viewErrDetail xweb.Mapper `xweb:"/front/viewErrDetail"`
  33. updateDownLimit xweb.Mapper `xweb:"/front/updateDownLimit"`
  34. fastStartOrStop xweb.Mapper `xweb:"/front/fastStartOrStop"`
  35. getscript xweb.Mapper `xweb:"/front/getscript"`
  36. sendinfo xweb.Mapper `xweb:"/front/sendinfo"`
  37. getAllSpider xweb.Mapper `xweb:"/front/getAllSpider"`
  38. }
  39. const (
  40. PageSize = 10
  41. )
  42. //调用保存信息接口
  43. func (i *Front) Sendinfo() error {
  44. id := i.GetString("id")
  45. info, _ := MgoS.FindById("data_bak", id, nil)
  46. delete(*info, "_id")
  47. tmp, _ := json.Marshal([]interface{}{"title", []interface{}{&info}})
  48. bs, err := Msclient.Call("", mu.UUID(8), 4002, mu.SENDTO_TYPE_ALL_RECIVER, tmp, 30)
  49. log.Println(string(bs))
  50. log.Println(err)
  51. reps := ""
  52. if err == nil && strings.ToLower(string(bs)) == "true" {
  53. reps = "send success"
  54. } else {
  55. reps = "send fail"
  56. }
  57. i.ServeJson(reps)
  58. return nil
  59. }
  60. func (i *Front) Getscript() error {
  61. code := i.GetString("code")
  62. var script = ""
  63. if v, ok := Allspiders.Load(code); ok {
  64. sp := v.(*Spider)
  65. script = sp.ScriptFile
  66. }
  67. log.Println("----------------------------")
  68. log.Println(script)
  69. log.Println("----------------------------")
  70. i.ServeJson(script)
  71. return nil
  72. }
  73. func (i *Front) Login() error {
  74. name := i.GetString("s_name")
  75. pass := i.GetString("s_pwd")
  76. if name != "" && pass != "" {
  77. tmp, _ := MgoS.FindOne("spider_admin", map[string]interface{}{"loginname": name, "password": util.GetMd5String(pass)})
  78. if len(*tmp) > 0 {
  79. i.SetSession("loginuser", *tmp)
  80. }
  81. return i.Redirect("/front")
  82. } else {
  83. i.T["login"] = false
  84. return i.Render("login.html", &i.T)
  85. }
  86. }
  87. //加载首页
  88. func (i *Front) LoadIndex() error {
  89. qcode := i.GetString("qcode")
  90. currPage, _ := i.GetInt("currPage")
  91. state := i.GetString("state")
  92. if currPage < 1 {
  93. currPage = 1
  94. }
  95. var spRunTotal, todayDownTotal, yesdayDownTotal,
  96. errTotal, todayRequest, yestoDayRequest, allspidersLen int32
  97. Allspiders.Range(func(key, value interface{}) bool {
  98. v := value.(*Spider)
  99. errTotal = errTotal + v.ErrorNum
  100. todayDownTotal = todayDownTotal + v.TodayDowncount
  101. yesdayDownTotal = yesdayDownTotal + v.YesterdayDowncount
  102. if !v.Stop && !v.Pass {
  103. spRunTotal = spRunTotal + 1
  104. }
  105. todayRequest = todayRequest + v.ToDayRequestNum
  106. yestoDayRequest = yestoDayRequest + v.YestoDayRequestNum
  107. allspidersLen = allspidersLen + 1
  108. return true
  109. })
  110. i.T["spTotal"] = allspidersLen
  111. i.T["spRunTotal"] = spRunTotal
  112. i.T["todayDownTotal"] = todayDownTotal
  113. i.T["yesdayDownTotal"] = yesdayDownTotal
  114. i.T["errTotal"] = errTotal
  115. i.T["todayRequest"] = todayRequest
  116. i.T["yestoDayRequest"] = yestoDayRequest
  117. i.T["qcode"] = qcode
  118. totalPage := int64((allspidersLen + PageSize - 1) / PageSize)
  119. if currPage > totalPage {
  120. currPage = totalPage
  121. }
  122. i.T["totalPage"] = totalPage
  123. i.T["currPage"] = currPage
  124. if lu.Config.Working == 1 { //排队模式
  125. length := 0
  126. LoopListPath.Range(func(k, v interface{}) bool {
  127. if v != nil {
  128. length++
  129. }
  130. return true
  131. })
  132. i.T["listnum"] = length
  133. } else {
  134. i.T["listnum"] = ""
  135. }
  136. i.T["spiders"] = getSpiders(qcode, state, currPage)
  137. return i.Render("index.html", &i.T)
  138. }
  139. /*
  140. //一键加载
  141. func (i *Front) FastStartOrStop() error {
  142. if lu.Config.Working == 1 {
  143. i.ServeJson("fail")
  144. return nil
  145. }
  146. flag := i.GetString("flag")
  147. Allspiders.Range(func(key, value interface{}) bool {
  148. v := value.(*Spider)
  149. lu.TimeSleepFunc(50*time.Millisecond, TimeSleepChan)
  150. switch flag {
  151. case "start":
  152. v.Stop = false
  153. v.StartJob()
  154. case "stop":
  155. v.Stop = true
  156. SaveDownCount(v.Code, false, v.TodayDowncount, v.ToDayRequestNum, v.YesterdayDowncount, v.YestoDayRequestNum)
  157. }
  158. return true
  159. })
  160. i.ServeJson("ok")
  161. return nil
  162. }
  163. //开启爬虫
  164. func (i *Front) Start() error {
  165. if lu.Config.Working == 1 {
  166. return nil
  167. }
  168. qcode := i.GetString("qcode")
  169. code := i.GetString("code")
  170. currPage, _ := i.GetInt("currPage")
  171. state := i.GetString("state")
  172. if currPage < 1 {
  173. currPage = 1
  174. }
  175. if value, ok := Allspiders.Load(code); ok {
  176. v := value.(*Spider)
  177. v.Stop = false
  178. v.StartJob()
  179. }
  180. res := make(map[string]interface{})
  181. res["qcode"] = qcode
  182. allspidersLen := 0
  183. Allspiders.Range(func(key, value interface{}) bool {
  184. allspidersLen += 1
  185. return true
  186. })
  187. totalPage := int64((allspidersLen + PageSize - 1) / PageSize)
  188. if currPage > totalPage {
  189. currPage = totalPage
  190. }
  191. res["totalPage"] = totalPage
  192. res["currPage"] = currPage
  193. res["spiders"] = getSpiders(qcode, state, currPage)
  194. i.ServeJson(&res)
  195. return nil
  196. }
  197. //停止爬虫
  198. func (i *Front) Stop() error {
  199. if lu.Config.Working == 1 {
  200. return nil
  201. }
  202. code := i.GetString("code")
  203. qcode := i.GetString("qcode")
  204. currPage, _ := i.GetInt("currPage")
  205. state := i.GetString("state")
  206. if currPage < 1 {
  207. currPage = 1
  208. }
  209. if value, ok := Allspiders.Load(code); ok {
  210. v := value.(*Spider)
  211. v.Stop = true
  212. SaveDownCount(v.Code, false, v.TodayDowncount, v.ToDayRequestNum, v.YesterdayDowncount, v.YestoDayRequestNum)
  213. }
  214. res := make(map[string]interface{})
  215. res["qcode"] = qcode
  216. allspidersLen := 0
  217. Allspiders.Range(func(key, value interface{}) bool {
  218. allspidersLen += 1
  219. return true
  220. })
  221. totalPage := int64((allspidersLen + PageSize - 1) / PageSize)
  222. if currPage > totalPage {
  223. currPage = totalPage
  224. }
  225. res["totalPage"] = totalPage
  226. res["currPage"] = currPage
  227. res["spiders"] = getSpiders(qcode, state, currPage)
  228. i.ServeJson(&res)
  229. return nil
  230. }
  231. //暂停爬虫
  232. func (i *Front) Pass() error {
  233. if lu.Config.Working == 1 {
  234. return nil
  235. }
  236. code := i.GetString("code")
  237. qcode := i.GetString("qcode")
  238. currPage, _ := i.GetInt("currPage")
  239. state := i.GetString("state")
  240. if currPage < 1 {
  241. currPage = 1
  242. }
  243. if value, ok := Allspiders.Load(code); ok {
  244. v := value.(*Spider)
  245. v.Pass = true
  246. }
  247. res := make(map[string]interface{})
  248. res["qcode"] = qcode
  249. allspidersLen := 0
  250. Allspiders.Range(func(key, value interface{}) bool {
  251. allspidersLen += 1
  252. return true
  253. })
  254. totalPage := int64((allspidersLen + PageSize - 1) / PageSize)
  255. if currPage > totalPage {
  256. currPage = totalPage
  257. }
  258. res["totalPage"] = totalPage
  259. res["currPage"] = currPage
  260. res["spiders"] = getSpiders(qcode, state, currPage)
  261. i.ServeJson(&res)
  262. return nil
  263. }
  264. //唤醒爬虫
  265. func (i *Front) Resume() error {
  266. if lu.Config.Working == 1 {
  267. return nil
  268. }
  269. code := i.GetString("code")
  270. qcode := i.GetString("qcode")
  271. currPage, _ := i.GetInt("currPage")
  272. state := i.GetString("state")
  273. if currPage < 1 {
  274. currPage = 1
  275. }
  276. if value, ok := Allspiders.Load(code); ok {
  277. v := value.(*Spider)
  278. v.Pass = false
  279. }
  280. res := make(map[string]interface{})
  281. res["qcode"] = qcode
  282. allspidersLen := 0
  283. Allspiders.Range(func(key, value interface{}) bool {
  284. allspidersLen += 1
  285. return true
  286. })
  287. totalPage := int64((allspidersLen + PageSize - 1) / PageSize)
  288. if currPage > totalPage {
  289. currPage = totalPage
  290. }
  291. res["totalPage"] = totalPage
  292. res["currPage"] = currPage
  293. res["spiders"] = getSpiders(qcode, state, currPage)
  294. i.ServeJson(&res)
  295. return nil
  296. }
  297. //重新加载lua脚本
  298. func (i *Front) Reloadlua() error {
  299. if lu.Config.Working == 1 {
  300. i.ServeJson("排队模式不需要重载!")
  301. return nil
  302. }
  303. code := i.GetString("code")
  304. qcode := i.GetString("qcode")
  305. currPage, _ := i.GetInt("currPage")
  306. state := i.GetString("state")
  307. if currPage < 1 {
  308. currPage = 1
  309. }
  310. info := ""
  311. if value, ok := Allspiders.Load(code); ok {
  312. spider := value.(*Spider)
  313. spider.Reload()
  314. spider.LoadScript(code, spider.ScriptFile, false)
  315. spider.DownDetail = spider.GetBoolVar("spiderDownDetailPage")
  316. spider.Collection = spider.GetVar("spider2Collection")
  317. spider.SpiderRunRate = int64(spider.GetIntVar("spiderRunRate"))
  318. spider.StoreToMsgEvent = spider.GetIntVar("spiderStoreToMsgEvent")
  319. spider.StoreMode = spider.GetIntVar("spiderStoreMode")
  320. spider.CoverAttr = spider.GetVar("spiderCoverAttr")
  321. spiderSleepBase := spider.GetIntVar("spiderSleepBase")
  322. if spiderSleepBase == -1 {
  323. spider.SleepBase = 1000
  324. } else {
  325. spider.SleepBase = spiderSleepBase
  326. }
  327. spiderSleepRand := spider.GetIntVar("spiderSleepRand")
  328. if spiderSleepRand == -1 {
  329. spider.SleepRand = 1000
  330. } else {
  331. spider.SleepRand = spiderSleepRand
  332. }
  333. spiderTimeout := spider.GetIntVar("spiderTimeout")
  334. if spiderTimeout == -1 {
  335. spider.Timeout = 60
  336. } else {
  337. spider.Timeout = int64(spiderTimeout)
  338. }
  339. spider.TargetChannelUrl = spider.GetVar("spiderTargetChannelUrl")
  340. spider.UserName = spider.GetVar("spiderUserName")
  341. spider.UserEmail = spider.GetVar("spiderUserEmail")
  342. spider.UploadTime = spider.GetVar("spiderUploadTime")
  343. info = "已重新加载"
  344. }
  345. res := make(map[string]interface{})
  346. res["qcode"] = qcode
  347. allspidersLen := 0
  348. Allspiders.Range(func(key, value interface{}) bool {
  349. allspidersLen += 1
  350. return true
  351. })
  352. totalPage := int64((allspidersLen + PageSize - 1) / PageSize)
  353. if currPage > totalPage {
  354. currPage = totalPage
  355. }
  356. res["totalPage"] = totalPage
  357. res["currPage"] = currPage
  358. res["spiders"] = getSpiders(qcode, state, currPage)
  359. res["info"] = info
  360. i.ServeJson(&res)
  361. return nil
  362. }
  363. //添加爬虫
  364. func (i *Front) AddSpider() error {
  365. i.ServeJson("添加任务已作废!")
  366. return nil
  367. res := "添加任务失败,请输入正确的lua脚本路径!"
  368. filename := i.GetString("filename")
  369. f, err := os.Open("./" + filename)
  370. if err != nil {
  371. res = err.Error()
  372. } else {
  373. for _, v := range Allspiders {
  374. if v.Script.ScriptFile == filename {
  375. res = v.Script.ScriptFile + ",任务已经存在,请不要重复添加"
  376. i.ServeJson(&res)
  377. return nil
  378. }
  379. }
  380. if strings.Contains(f.Name(), "spider_") &&
  381. strings.HasSuffix(f.Name(), ".lua") {
  382. sp := NewSpider(filename)
  383. Allspiders[sp.Code] = sp
  384. go sp.StartJob()
  385. res = "添加任务成功!"
  386. } else {
  387. res = "请输入正确的lua脚本名称(spider_test.lua)!"
  388. }
  389. }
  390. i.ServeJson(&res)
  391. return nil
  392. }
  393. //删除爬虫
  394. func (i *Front) DelSpider(code string) error {
  395. flag := "fail"
  396. msg := "del " + code
  397. Allspiders.Range(func(k, value interface{}) bool {
  398. v := value.(*Spider)
  399. if lu.Config.Working == 0 {
  400. if k == code {
  401. v.Stop = true
  402. v.L.Close()
  403. os.Remove(v.ScriptFile)
  404. Allspiders.Delete(k)
  405. flag = "ok"
  406. return false
  407. }
  408. } else {
  409. }
  410. return true
  411. })
  412. res := map[string]string{"msg": msg, "flag": flag}
  413. i.ServeJson(&res)
  414. return nil
  415. }
  416. //添加任务
  417. func (i *Front) AddJob() error {
  418. res := ""
  419. succ, fail := 0, 0
  420. jobs := i.GetString("jobs")
  421. list := []interface{}{}
  422. json.Unmarshal([]byte(jobs), &list)
  423. if len(list) < 1 {
  424. res = "数据格式不正确!"
  425. i.ServeJson(&res)
  426. return nil
  427. }
  428. listJob := []interface{}{}
  429. var sp *Spider
  430. for _, v := range list {
  431. tmp := v.(map[string]interface{})
  432. code, ok1 := tmp["code"].(string)
  433. _, ok2 := tmp["href"].(string)
  434. _, ok3 := tmp["title"].(string)
  435. if !ok1 || !ok2 || !ok3 {
  436. fail++
  437. continue
  438. }
  439. if s, ok := Allspiders.Load(code); ok {
  440. sp = s.(*Spider)
  441. p := make(map[string]string)
  442. for key, value := range tmp {
  443. p[key] = util.ObjToString(value)
  444. }
  445. p["publishtime"] = fmt.Sprint(time.Now().Unix())
  446. listJob = append(listJob, p)
  447. succ++
  448. } else {
  449. fail++
  450. }
  451. }
  452. if succ > 0 {
  453. go mu.NewGoThread(int(sp.Thread)).Run(sp.DownloadDetailByNames, listJob...)
  454. res += "添加成功:" + fmt.Sprint(succ) + "条任务!"
  455. }
  456. if fail > 0 {
  457. res += "添加失败:" + fmt.Sprint(fail) + "条任务!"
  458. }
  459. i.ServeJson(&res)
  460. return nil
  461. }
  462. */
  463. //searchJob
  464. func (i *Front) SearchJob() error {
  465. qcode := i.GetString("qcode")
  466. currPage, _ := i.GetInt("currPage")
  467. state := i.GetString("state")
  468. if currPage < 1 {
  469. currPage = 1
  470. }
  471. res := make(map[string]interface{})
  472. res["qcode"] = qcode
  473. allspidersLen := 0
  474. Allspiders.Range(func(key, value interface{}) bool {
  475. allspidersLen += 1
  476. return true
  477. })
  478. totalPage := int64((allspidersLen + PageSize - 1) / PageSize)
  479. if currPage > totalPage {
  480. currPage = totalPage
  481. }
  482. res["totalPage"] = totalPage
  483. res["currPage"] = currPage
  484. res["spiders"] = getSpiders(qcode, state, currPage)
  485. i.ServeJson(&res)
  486. return nil
  487. }
  488. //错误查看
  489. func (i *Front) ViewErrIndex(code string) error {
  490. i.T["code"] = code
  491. tmp, _ := MgoS.FindOne("spider_ldtime", map[string]interface{}{"code": code})
  492. if len(*tmp) > 1 {
  493. i.T["lastpubtime"] = (*tmp)["lastpubtimestr"]
  494. }
  495. return i.Render("viewErr.html", &i.T)
  496. }
  497. //错误信息
  498. func (i *Front) ViewErrDetail() error {
  499. code := i.GetString("code")
  500. res := make(map[string]interface{})
  501. if value, ok := Allspiders.Load(code); ok {
  502. v := value.(*Spider)
  503. res["name"] = v.Name
  504. res["errorNum"] = v.ErrorNum
  505. res["lastDowncount"] = v.LastDowncount
  506. res["lastExecTime"] = time.Unix(util.Int64All(v.LastExecTime), 0).Format(util.Date_Full_Layout)
  507. //res["totalDowncount"] = v.TotalDowncount
  508. res["todayDowncount"] = v.TodayDowncount
  509. res["yestoDayDowncount"] = v.YesterdayDowncount
  510. res["todayRequest"] = v.ToDayRequestNum
  511. //res["totalRequest"] = v.TotalRequestNum
  512. res["yestoDayRequest"] = v.YestoDayRequestNum
  513. res["lowlimit"] = v.LowerLimit
  514. res["uplimit"] = v.UpperLimit
  515. }
  516. list, _ := MgoS.Find("spider_errlog", map[string]interface{}{"code": code}, map[string]interface{}{"comeintime": -1}, map[string]interface{}{"comeintime": 1, "url": 1, "content": 1}, false, -1, -1)
  517. for _, v := range *list {
  518. v["comeintime"] = time.Unix(util.Int64All(v["comeintime"]), 0).Format(util.Date_Full_Layout)
  519. if v["url"] == nil {
  520. v["url"] = "监控错误日志"
  521. }
  522. }
  523. res["list"] = *list
  524. i.ServeJson(&res)
  525. return nil
  526. }
  527. //错误清零
  528. func (i *Front) ClearErr() error {
  529. code := i.GetString("code")
  530. qcode := i.GetString("qcode")
  531. state := i.GetString("state")
  532. currPage, _ := i.GetInt("currPage")
  533. if value, ok := Allspiders.Load(code); ok {
  534. v := value.(*Spider)
  535. atomic.StoreInt32(&v.ErrorNum, 0)
  536. MgoS.Del("spider_errlog", map[string]interface{}{"code": code})
  537. }
  538. res := make(map[string]interface{})
  539. res["qcode"] = qcode
  540. allspidersLen := 0
  541. Allspiders.Range(func(key, value interface{}) bool {
  542. allspidersLen += 1
  543. return true
  544. })
  545. totalPage := int64((allspidersLen + PageSize - 1) / PageSize)
  546. if currPage > totalPage {
  547. currPage = totalPage
  548. }
  549. res["totalPage"] = totalPage
  550. res["currPage"] = currPage
  551. res["spiders"] = getSpiders(qcode, state, currPage)
  552. i.ServeJson(&res)
  553. return nil
  554. }
  555. //修改正常下载数的上下限
  556. func (i *Front) UpdateDownLimit() error {
  557. code := i.GetString("code")
  558. uplimit, _ := i.GetInt("uplimit")
  559. lowlimit, _ := i.GetInt("lowlimit")
  560. lastpubtime := i.GetString("lastpubtime")
  561. var updata map[string]interface{}
  562. if lastpubtime == "" {
  563. updata = map[string]interface{}{"$set": map[string]interface{}{"uplimit": uplimit, "lowlimit": lowlimit}}
  564. } else {
  565. time, _ := time.ParseInLocation(util.Date_Full_Layout, lastpubtime, time.Local)
  566. updata = map[string]interface{}{"$set": map[string]interface{}{"uplimit": uplimit, "lowlimit": lowlimit, "lastpubtime": time.Unix(), "lastpubtimestr": lastpubtime}}
  567. }
  568. b := MgoS.Update("spider_ldtime", map[string]interface{}{"code": code}, updata, true, false)
  569. if b {
  570. if value, ok := Allspiders.Load(code); ok {
  571. v := value.(*Spider)
  572. v.UpperLimit = int(uplimit)
  573. v.LowerLimit = int(lowlimit)
  574. }
  575. }
  576. i.ServeJson(b)
  577. return nil
  578. }
  579. func getSpiders(code, state string, currPage int64) []interface{} {
  580. spiders := []interface{}{}
  581. Allspiders.Range(func(key, value interface{}) bool {
  582. v := value.(*Spider)
  583. if code != "" && !strings.Contains(fmt.Sprint(key), code) && !strings.Contains(v.Name, code) {
  584. return true
  585. }
  586. if state == "stop" {
  587. if !v.Stop {
  588. return true
  589. }
  590. }
  591. if state == "pass" {
  592. if !v.Pass {
  593. return true
  594. }
  595. }
  596. if state == "run" {
  597. if v.Stop || v.Pass {
  598. return true
  599. }
  600. }
  601. spider := make(map[string]interface{})
  602. spider["code"] = fmt.Sprint(key)
  603. spider["name"] = v.Name
  604. spider["stop"] = v.Stop
  605. spider["pass"] = v.Pass
  606. spider["filepath"] = v.ScriptFile
  607. spider["errnum"] = v.Script.ErrorNum
  608. spider["lstate"] = v.L.Status(v.L)
  609. if v.ExecuteOkTime == 0 {
  610. spider["lastTime"] = "开始时间:" + fmt.Sprint(time.Unix(v.LastExecTime, 0).Format(util.Date_Full_Layout)) + ",结束时间:0"
  611. } else {
  612. spider["lastTime"] = "开始时间:" + fmt.Sprint(time.Unix(v.LastExecTime, 0).Format(util.Date_Full_Layout)) + ",结束时间:" + fmt.Sprint(time.Unix(v.ExecuteOkTime, 0).Format(util.Date_Full_Layout))
  613. }
  614. spider["lastTimeShort"] = time.Unix(v.LastExecTime, 0).Format("15:04:05")
  615. spider["lastDownNum"] = v.LastDowncount
  616. spider["todayDownNum"] = v.TodayDowncount
  617. spider["yesterdayDownNum"] = v.YesterdayDowncount
  618. spider["totalDowncount"] = v.TotalDowncount
  619. spider["totalRequest"] = v.TotalRequestNum
  620. spider["todayRequest"] = v.ToDayRequestNum
  621. spider["yestoDayRequest"] = v.YestoDayRequestNum
  622. spider["noDownloadNum"] = v.NoDownloadNum
  623. spider["lastHeartbeat"] = time.Unix(v.LastHeartbeat, 0).Format(util.Date_Full_Layout)
  624. spider["targetChannelUrl"] = v.TargetChannelUrl
  625. spider["lowlimit"] = v.LowerLimit
  626. spider["uplimit"] = v.UpperLimit
  627. spider["userName"] = v.UserName
  628. if state == "abnormal" {
  629. if v.YesterdayDowncount == 0 {
  630. if !v.Stop {
  631. spiders = append(spiders, spider)
  632. }
  633. } else {
  634. if v.YestoDayRequestNum/v.YesterdayDowncount > 200 {
  635. spiders = append(spiders, spider)
  636. }
  637. }
  638. } else if state == "norequest" {
  639. if v.ToDayRequestNum == 0 {
  640. spiders = append(spiders, spider)
  641. }
  642. } else {
  643. spiders = append(spiders, spider)
  644. }
  645. return true
  646. })
  647. insertSort(spiders, "code")
  648. insertSort(spiders, "errnum")
  649. arrs := []interface{}{}
  650. num := int64(0)
  651. for _, v := range spiders {
  652. num = num + 1
  653. if num > (currPage-1)*PageSize && num <= currPage*PageSize {
  654. arrs = append(arrs, v)
  655. }
  656. }
  657. return arrs
  658. }
  659. //插入排序
  660. func insertSort(list []interface{}, index string) {
  661. for i := 1; i < len(list); i++ {
  662. tmp1 := list[i].(map[string]interface{})
  663. tmp2 := list[i-1].(map[string]interface{})
  664. if _, ok := tmp1[index].(int32); ok {
  665. if util.IntAll(tmp1[index]) > util.IntAll(tmp2[index]) {
  666. j := i - 1
  667. temp := list[i].(map[string]interface{})
  668. for j >= 0 && util.IntAll(list[j].(map[string]interface{})[index]) < util.IntAll(temp[index]) {
  669. list[j+1] = list[j]
  670. j--
  671. }
  672. list[j+1] = temp
  673. }
  674. } else if _, ok := tmp1[index].(string); ok {
  675. if tmp1[index].(string) < tmp2[index].(string) {
  676. j := i - 1
  677. temp := list[i].(map[string]interface{})
  678. for j >= 0 && list[j].(map[string]interface{})[index].(string) > temp[index].(string) {
  679. list[j+1] = list[j]
  680. j--
  681. }
  682. list[j+1] = temp
  683. }
  684. }
  685. }
  686. }
  687. //获取所有内存中的爬虫
  688. func (i *Front) GetAllSpider() {
  689. defer util.Catch()
  690. //Allspiders
  691. allspidersLen, spidersLen_ok := 0, 0
  692. AllspiderCodes := []string{}
  693. Allspiders.Range(func(key, value interface{}) bool {
  694. allspidersLen++
  695. if value != nil {
  696. spidersLen_ok++
  697. v := value.(*Spider)
  698. AllspiderCodes = append(AllspiderCodes, v.Code)
  699. }
  700. return true
  701. })
  702. sort.Strings(AllspiderCodes)
  703. //LoopListPath
  704. size_all, size_ok, size_no := 0, 0, 0
  705. //size_no_index := []string{}
  706. LoopListPathCodes := []string{}
  707. LoopListPath.Range(func(k, v interface{}) bool {
  708. size_all++
  709. if v != nil {
  710. size_ok++
  711. info, _ := v.(map[string]string)
  712. code := info["code"]
  713. LoopListPathCodes = append(LoopListPathCodes, code)
  714. } else {
  715. //size_no_index = append(size_no_index, fmt.Sprint(k))
  716. size_no++
  717. }
  718. return true
  719. })
  720. sort.Strings(LoopListPathCodes)
  721. //excle
  722. xf, err := xlsx.OpenFile("res/spidercodes.xlsx")
  723. if err != nil {
  724. log.Println("spidercodes file not foud", err.Error())
  725. return
  726. }
  727. //sheet 统计
  728. sh0 := xf.Sheets[0]
  729. row := sh0.AddRow()
  730. row.AddCell().SetValue(size_all)
  731. row.AddCell().SetValue(size_ok)
  732. row.AddCell().SetValue(size_no)
  733. //row.AddCell().SetValue(strings.Join(size_no_index, ","))
  734. row.AddCell().SetValue(allspidersLen)
  735. row.AddCell().SetValue(spidersLen_ok)
  736. //sheet codes
  737. sh1 := xf.Sheets[1]
  738. LoopLen := len(LoopListPathCodes)
  739. tmpLen := LoopLen
  740. allLen := len(AllspiderCodes)
  741. if tmpLen < allLen {
  742. tmpLen = allLen
  743. }
  744. for j := 0; j < tmpLen; j++ {
  745. row := sh1.AddRow()
  746. cell1 := ""
  747. cell2 := ""
  748. if j < LoopLen {
  749. cell1 = LoopListPathCodes[j]
  750. }
  751. if j < allLen {
  752. cell2 = AllspiderCodes[j]
  753. }
  754. row.AddCell().SetValue(cell1)
  755. row.AddCell().SetValue(cell2)
  756. }
  757. fname := fmt.Sprintf("res/爬虫代码%d.xlsx", time.Now().Unix())
  758. xf.Save(fname)
  759. arr := strings.Split(fname, "/")
  760. i.ResponseWriter.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", arr[1]))
  761. i.ServeFile(fname)
  762. go func(path string) {
  763. time.Sleep(time.Second * 30)
  764. os.Remove(fname)
  765. }(fname)
  766. }