spider.go 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767
  1. package front
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "log"
  7. "mongodb"
  8. "regexp"
  9. "sort"
  10. "spider"
  11. "strconv"
  12. mu "mfw/util"
  13. qu "qfw/util"
  14. util "spiderutil"
  15. "strings"
  16. "time"
  17. u "util"
  18. )
  19. type Base struct {
  20. SpiderCode string
  21. SpiderCodeOld string
  22. SpiderName string
  23. SpiderChannel string
  24. SpiderDownDetailPage bool
  25. SpiderStartPage int
  26. SpiderMaxPage int
  27. SpiderRunRate int
  28. Spider2Collection string
  29. SpiderPageEncoding string
  30. SpiderStoreMode int //1,2
  31. SpiderStoreToMsgEvent int
  32. SpiderTargetChannelUrl string
  33. SpiderLastDownloadTime string
  34. SpiderIsHistoricalMend bool
  35. SpiderIsMustDownload bool
  36. }
  37. type Step1 struct {
  38. Address string
  39. ContentChooser string
  40. DateFormat string
  41. Expert string
  42. Types int
  43. }
  44. type Step2 struct {
  45. Listadd string
  46. Listadds string
  47. BlockChooser string
  48. AddressChooser string
  49. TitleChooser string
  50. DateChooser string
  51. DateFormat string
  52. Expert string
  53. Types int
  54. }
  55. type Step3 struct {
  56. ContentChooser string
  57. ElementChooser string
  58. T_title string
  59. T_href string
  60. T_date string
  61. Expert string
  62. Types int
  63. }
  64. type StepRe3 struct {
  65. Checked bool
  66. Expert string
  67. }
  68. type OtherBase struct {
  69. IsFlow int //爬虫所采集数据是否参与数据流程标识
  70. SpiderType string //爬虫类型:increment增量;history历史
  71. SpiderHistoryMaxPage int //采集历史数据时的采集最大页
  72. SpiderMoveEvent string //爬虫采集完历史后要转移到的节点 comm:队列模式、bid:高性能模式、7700
  73. }
  74. //加载某个爬虫
  75. func (f *Front) LoadSpider(codeTaskIdReState string) error {
  76. tmpStr := strings.Split(codeTaskIdReState, "__")
  77. code := tmpStr[0]
  78. taskId := tmpStr[1]
  79. auth := qu.IntAll(f.GetSession("auth"))
  80. restate := -1
  81. if taskId == "restate=1" { //重采编辑
  82. restate = 1
  83. } else if taskId == "restate=2" {
  84. restate = 2
  85. } else if taskId == "restate=3" {
  86. restate = 3
  87. } else {
  88. if auth == role_dev && qu.ObjToString(f.GetSession(taskId)) == "" {
  89. xgTime := time.Unix(time.Now().Unix(), 0).Format("2006-01-02 15:04:05")
  90. f.SetSession(taskId, xgTime)
  91. }
  92. }
  93. copy := f.GetString("copy")
  94. if f.Method() == "GET" {
  95. code := util.Se.Decode4Hex(code)
  96. f.T["actiontext"] = "编辑"
  97. //lua, _ := u.MgoE.FindOne("luaconfig", map[string]interface{}{"code": code})
  98. lua, _ := u.MgoEB.FindOne("luaconfig", map[string]interface{}{"code": code})
  99. auth := qu.IntAll(f.GetSession("auth"))
  100. if qu.ObjToString((*lua)["createuserid"]) == f.GetSession("userid").(string) || auth >= 1 {
  101. if len(*lua) > 0 {
  102. if copy != "" {
  103. //luacopy, _ := u.MgoE.FindOne("luaconfig", map[string]interface{}{"code": copy})
  104. luacopy, _ := u.MgoEB.FindOne("luaconfig", map[string]interface{}{"code": copy})
  105. if len(*luacopy) > 0 {
  106. (*lua)["model"] = (*luacopy)["model"]
  107. common_copy := (*luacopy)["param_common"].([]interface{})
  108. common := (*lua)["param_common"].([]interface{})
  109. common_copy[0] = common[0]
  110. common_copy[1] = common[1]
  111. common_copy[2] = common[2]
  112. common_copy[11] = common[11]
  113. (*lua)["param_common"] = (*luacopy)["param_common"]
  114. (*lua)["param_time"] = (*luacopy)["param_time"]
  115. (*lua)["param_list"] = (*luacopy)["param_list"]
  116. (*lua)["param_content"] = (*luacopy)["param_content"]
  117. (*lua)["str_list"] = (*luacopy)["str_list"]
  118. (*lua)["str_time"] = (*luacopy)["str_time"]
  119. (*lua)["str_content"] = (*luacopy)["str_content"]
  120. (*lua)["Thref"] = (*luacopy)["Thref"]
  121. (*lua)["Tpublishtime"] = (*luacopy)["Tpublishtime"]
  122. (*lua)["Ttitle"] = (*luacopy)["Ttitle"]
  123. (*lua)["Tdate"] = (*luacopy)["Tdate"]
  124. (*lua)["type_content"] = (*luacopy)["type_content"]
  125. (*lua)["type_list"] = (*luacopy)["type_list"]
  126. (*lua)["type_time"] = (*luacopy)["type_time"]
  127. }
  128. }
  129. if (*lua)["listcheck"] != nil {
  130. listcheck := (*lua)["listcheck"].(string)
  131. listcheck = strings.Replace(listcheck, "\\n", "\n", -1)
  132. listcheck = strings.Replace(listcheck, "\\", "", -1)
  133. (*lua)["listcheck"] = listcheck
  134. }
  135. if (*lua)["contentcheck"] != nil {
  136. contentcheck := (*lua)["contentcheck"].(string)
  137. contentcheck = strings.Replace(contentcheck, "\\n", "\n", -1)
  138. contentcheck = strings.Replace(contentcheck, "\\", "", -1)
  139. (*lua)["contentcheck"] = contentcheck
  140. }
  141. js, _ := json.MarshalIndent((*lua)["model"], "", " ")
  142. (*lua)["js"] = string(js)
  143. f.T["lua"] = lua
  144. f.T["taskId"] = taskId
  145. f.T["restate"] = restate
  146. f.T["isflow"] = (*lua)["isflow"]
  147. f.T["spidertype"] = (*lua)["spidertype"]
  148. f.T["spidermovevent"] = (*lua)["spidermovevent"]
  149. f.T["spiderhistorymaxpage"] = (*lua)["spiderhistorymaxpage"]
  150. events := []string{}
  151. for k, _ := range util.Config.Uploadevents {
  152. events = append(events, k)
  153. }
  154. sort.Strings(events)
  155. f.T["events"] = events
  156. if (*lua)["oldlua"] != nil {
  157. return f.Render("oldedit.html", &f.T)
  158. }
  159. return f.Render("spideredit.html", &f.T)
  160. }
  161. } else {
  162. f.Write("您没有编辑他人脚本的权限")
  163. }
  164. }
  165. return nil
  166. }
  167. //查看某个爬虫
  168. func (f *Front) ViewSpider(id string) error {
  169. auth := qu.IntAll(f.GetSession("auth"))
  170. if auth >= 1 {
  171. if f.Method() == "GET" {
  172. code := util.Se.Decode4Hex(id)
  173. f.T["actiontext"] = "编辑"
  174. //lua, _ := u.MgoE.FindOne("luaconfig", map[string]interface{}{"code": code})
  175. lua, _ := u.MgoEB.FindOne("luaconfig", map[string]interface{}{"code": code})
  176. if len(*lua) > 0 {
  177. if (*lua)["listcheck"] != nil {
  178. listcheck := (*lua)["listcheck"].(string)
  179. listcheck = strings.Replace(listcheck, "\\n", "\n", -1)
  180. listcheck = strings.Replace(listcheck, "\\", "", -1)
  181. (*lua)["listcheck"] = listcheck
  182. }
  183. if (*lua)["contentcheck"] != nil {
  184. contentcheck := (*lua)["contentcheck"].(string)
  185. contentcheck = strings.Replace(contentcheck, "\\n", "\n", -1)
  186. contentcheck = strings.Replace(contentcheck, "\\", "", -1)
  187. (*lua)["contentcheck"] = contentcheck
  188. }
  189. js, _ := json.MarshalIndent((*lua)["model"], "", " ")
  190. (*lua)["js"] = string(js)
  191. f.T["lua"] = lua
  192. f.T["isflow"] = (*lua)["isflow"]
  193. f.T["spidertype"] = (*lua)["spidertype"]
  194. f.T["spidermovevent"] = (*lua)["spidermovevent"]
  195. f.T["spiderhistorymaxpage"] = (*lua)["spiderhistorymaxpage"]
  196. events := []string{}
  197. for k, _ := range util.Config.Uploadevents {
  198. events = append(events, k)
  199. }
  200. sort.Strings(events)
  201. f.T["events"] = events
  202. if (*lua)["oldlua"] != nil {
  203. return f.Render("oldedit.html", &f.T)
  204. }
  205. return f.Render("spiderview.html", &f.T)
  206. } else {
  207. f.Write("没有对应记录!")
  208. return nil
  209. }
  210. }
  211. return f.Redirect("/center")
  212. } else {
  213. f.Write("您没有查看他人脚本的权限")
  214. return nil
  215. }
  216. }
  217. func (f *Front) LoadModel(id string) error {
  218. if f.Method() == "GET" {
  219. //lua, _ := u.MgoE.Find("luaconfig", map[string]interface{}{"code": id}, nil, map[string]interface{}{"model": 1}, true, -1, -1)
  220. lua, _ := u.MgoEB.Find("luaconfig", map[string]interface{}{"code": id}, nil, map[string]interface{}{"model": 1}, true, -1, -1)
  221. if len(*lua) > 0 {
  222. f.ServeJson((*lua)[0])
  223. }
  224. }
  225. return f.Redirect("/center")
  226. }
  227. func (f *Front) SaveStep() {
  228. userid, _ := f.GetSession("userid").(string)
  229. auth := qu.IntAll(f.GetSession("auth"))
  230. rep := map[string]interface{}{}
  231. if f.GetString("oldlua") != "" {
  232. id := f.GetString("code")
  233. //one, _ := u.MgoE.FindOne("luaconfig", map[string]interface{}{"code": id})
  234. one, _ := u.MgoEB.FindOne("luaconfig", map[string]interface{}{"code": id})
  235. id = qu.ObjToString((*one)["code"])
  236. script := f.GetStringComm("script")
  237. if strings.Index(script, id) == -1 {
  238. rep["msg"] = "code/名称都不能更改"
  239. f.ServeJson(rep)
  240. return
  241. } else {
  242. upset := map[string]interface{}{"luacontent": script}
  243. upset["modifytime"] = time.Now().Unix()
  244. //b := u.MgoE.Update("luaconfig", map[string]interface{}{"code": id}, map[string]interface{}{"$set": upset}, true, false)
  245. b := u.MgoEB.Update("luaconfig", map[string]interface{}{"code": id}, map[string]interface{}{"$set": upset}, true, false)
  246. if b {
  247. rep["msg"] = "保存成功"
  248. rep["code"] = util.Se.Encode2Hex(id)
  249. f.ServeJson(rep)
  250. return
  251. }
  252. }
  253. } else {
  254. if f.Base.SpiderName != "" && f.Base.SpiderCode != "" {
  255. code := f.Base.SpiderCode
  256. //one, _ := u.MgoE.FindOne("luaconfig", map[string]interface{}{"code": f.Base.SpiderCode})
  257. one, _ := u.MgoEB.FindOne("luaconfig", map[string]interface{}{"code": f.Base.SpiderCode})
  258. //记录上架操作前的第一次保存时的爬虫历史
  259. user := f.GetSession("username").(string)
  260. LuaSaveLog(f.Base.SpiderCode, user, one, 0)
  261. state := qu.IntAllDef((*one)["state"], 0)
  262. restate := qu.IntAll((*one)["restate"])
  263. comeintime := time.Now().Unix()
  264. if len((*one)) > 0 {
  265. comeintime = qu.Int64All((*one)["comeintime"])
  266. ouserid := qu.ObjToString((*one)["createuserid"])
  267. if ouserid != userid && auth == role_dev {
  268. f.Write("权限不够,不能修改他人脚本")
  269. return
  270. } else {
  271. code = qu.ObjToString((*one)["code"])
  272. f.Base.SpiderCode = code
  273. f.Base.SpiderName = ((*one)["param_common"].([]interface{}))[1].(string)
  274. }
  275. } else {
  276. if auth != role_admin {
  277. f.Write("不能新建爬虫,请联系管理员导入")
  278. return
  279. }
  280. }
  281. listcheck := f.GetString("listcheck")
  282. contentcheck := f.GetString("contentcheck")
  283. if auth == role_dev {
  284. //f.Base.SpiderStoreToMsgEvent = 4002
  285. }
  286. common := []interface{}{
  287. f.Base.SpiderCode,
  288. f.Base.SpiderName,
  289. f.Base.SpiderChannel,
  290. f.Base.SpiderDownDetailPage,
  291. f.Base.SpiderStartPage,
  292. f.Base.SpiderMaxPage,
  293. f.Base.SpiderRunRate,
  294. f.Base.Spider2Collection,
  295. f.Base.SpiderPageEncoding,
  296. f.Base.SpiderStoreMode,
  297. f.Base.SpiderStoreToMsgEvent,
  298. f.Base.SpiderTargetChannelUrl,
  299. f.Base.SpiderLastDownloadTime,
  300. f.Base.SpiderIsHistoricalMend,
  301. f.Base.SpiderIsMustDownload,
  302. }
  303. ptime := []interface{}{
  304. f.Step1.DateFormat,
  305. f.Step1.Address,
  306. f.Step1.ContentChooser,
  307. }
  308. list := []interface{}{
  309. f.Step2.Listadd,
  310. f.Step2.Listadds,
  311. f.Step2.BlockChooser,
  312. f.Step2.AddressChooser,
  313. f.Step2.TitleChooser,
  314. f.Step2.DateChooser,
  315. f.Step2.DateFormat,
  316. }
  317. content := []interface{}{
  318. f.Step3.ContentChooser,
  319. f.Step3.ElementChooser,
  320. }
  321. param := map[string]interface{}{}
  322. common[4] = 1
  323. param["param_common"] = common
  324. param["channel"] = f.Base.SpiderChannel
  325. //向导模式
  326. param["param_time"] = ptime
  327. param["param_list"] = list
  328. param["param_content"] = content
  329. param["type_time"] = f.Step1.Types
  330. param["type_list"] = f.Step2.Types
  331. param["type_content"] = f.Step3.Types
  332. //专家模式
  333. param["str_time"] = f.Step1.Expert
  334. param["str_list"] = f.Step2.Expert
  335. param["str_content"] = f.Step3.Expert
  336. param["comeintime"] = comeintime
  337. listcheck = strings.Replace(listcheck, "\n", "\\\\n", -1)
  338. param["listcheck"] = strings.Replace(listcheck, "\"", "\\\\\"", -1)
  339. contentcheck = strings.Replace(contentcheck, "\n", "\\\\n", -1)
  340. param["contentcheck"] = strings.Replace(contentcheck, "\"", "\\\\\"", -1)
  341. //补充模型
  342. s_model := f.GetString("model")
  343. configModel := util.Config.Model[s_model]
  344. model := map[string]interface{}{}
  345. for k, _ := range configModel {
  346. model[k] = f.GetString(k)
  347. }
  348. model["model"] = s_model
  349. param["code"] = f.Base.SpiderCode
  350. param["model"] = model
  351. if len((*one)) > 0 {
  352. param["createuser"] = (*one)["createuser"]
  353. param["createuserid"] = (*one)["createuserid"]
  354. param["code"] = (*one)["code"]
  355. //开发员关联任务修改爬虫状态
  356. state = qu.IntAll((*one)["state"])
  357. if auth == role_dev && state >= Sp_state_3 && restate != 1 { //开发员修改,已经审核通过(不包含已上架),状态重置为待完成(restate!=1判断,重采修改保存爬虫时不修改爬虫状态)
  358. param["state"] = 0
  359. } else {
  360. param["state"] = state
  361. }
  362. } else {
  363. param["createuser"] = f.GetSession("loginuser")
  364. param["createuserid"] = f.GetSession("userid")
  365. param["createuseremail"] = f.GetSession("email")
  366. param["next"] = f.GetSession("email")
  367. param["state"] = 0
  368. }
  369. if qu.ObjToString((*one)["modifyuser"]) == "" {
  370. param["modifyuser"] = param["createuser"]
  371. param["modifyuserid"] = param["createuserid"]
  372. }
  373. param["modifytime"] = time.Now().Unix()
  374. param["Ttitle"] = f.Step3.T_title
  375. param["Thref"] = f.Step3.T_href
  376. param["Tdate"] = f.Step3.T_date
  377. //其他信息
  378. param["isflow"] = f.OtherBase.IsFlow
  379. param["spidertype"] = f.OtherBase.SpiderType
  380. param["spiderhistorymaxpage"] = f.OtherBase.SpiderHistoryMaxPage
  381. qu.Debug(f.OtherBase.SpiderMoveEvent)
  382. tmpEvent, err := strconv.Atoi(f.OtherBase.SpiderMoveEvent) //f.OtherBase.SpiderMoveEvent此处SpiderMoveEvent已不表示comm、bid、7700,表示增量的节点
  383. if f.OtherBase.SpiderType == "history" { //爬虫类型是history的放到7000节点,并记录历史节点
  384. param["event"] = 7000
  385. if err == nil {
  386. param["incrementevent"] = tmpEvent //开发人员切换增量节点
  387. } else if event := qu.IntAll((*one)["event"]); event != 7000 { //默认增量节点
  388. param["incrementevent"] = event
  389. }
  390. } else if f.OtherBase.SpiderType == "increment" && err == nil { //增量
  391. param["event"] = tmpEvent //开发人员切换增量节点
  392. }
  393. if tmpEvent == 7700 {
  394. param["spidermovevent"] = "7700"
  395. } else if movevent, ok := util.Config.Uploadevents[f.OtherBase.SpiderMoveEvent].(string); ok && movevent != "" {
  396. param["spidermovevent"] = movevent
  397. }
  398. //开发人员修改爬虫节点后,在审核人员上架时,要在原来的节点下架,临时记录要下架的节点downevent
  399. if event := qu.IntAll((*one)["event"]); event != tmpEvent && event != 7000 {
  400. param["downevent"] = event
  401. }
  402. //三级页复制
  403. param["str_recontent"] = f.StepRe3.Expert
  404. param["iscopycontent"] = f.StepRe3.Checked
  405. //
  406. param["listisfilter"] = ListFilterReg.MatchString(f.Step2.Expert) //列表页校验是否含“--关键词过滤”
  407. matchLua, msg := LuaTextCheck(f.Step2.Expert, f.Step3.Expert, f.Step2.Types)
  408. if !matchLua {
  409. issave := spider.SaveSpider(code, param) //保存脚本
  410. if issave {
  411. for k, v := range *one {
  412. if k != "_id" && param[k] == nil {
  413. param[k] = v
  414. }
  415. }
  416. Wlog(f.Base.SpiderName, f.Base.SpiderCode, user, f.GetSession("userid").(string), "修改", param)
  417. rep["msg"] = "保存成功"
  418. } else {
  419. rep["msg"] = "保存失败"
  420. }
  421. } else {
  422. rep["msg"] = "保存失败," + msg
  423. }
  424. rep["code"] = util.Se.Encode2Hex(code)
  425. f.ServeJson(rep)
  426. }
  427. }
  428. }
  429. func (f *Front) SaveChannels() {
  430. code := f.GetString("code")
  431. channels := f.GetString("channels")
  432. channels = strings.ReplaceAll(channels, ",", ",")
  433. arr := strings.Split(channels, ",")
  434. ok := u.MgoEB.Update("luaconfig", map[string]interface{}{"code": code}, map[string]interface{}{
  435. "$addToSet": map[string]interface{}{
  436. "channels": map[string]interface{}{"$each": arr},
  437. },
  438. }, false, false)
  439. f.ServeJson(map[string]interface{}{"ok": ok})
  440. }
  441. func (f *Front) SaveJs() {
  442. //param_type := f.GetString("param_type")
  443. //return_type := f.GetString("return_type")
  444. js_name := f.GetString("js_name")
  445. js_alias := f.GetString("js_alias")
  446. jstext := f.GetString("jstext")
  447. step := f.GetString("step")
  448. code := f.GetString("code")
  449. update := map[string]interface{}{
  450. "runjs": true,
  451. }
  452. js := map[string]interface{}{
  453. "js_text": jstext,
  454. "js_name": js_name,
  455. "js_step": step,
  456. "js_alias": js_alias,
  457. "js_param": "string",
  458. "js_return": "string",
  459. }
  460. if step == "list" {
  461. update["js_list"] = js
  462. } else if step == "detail" {
  463. update["js_detail"] = js
  464. }
  465. u.MgoEB.Update("luaconfig", map[string]interface{}{"code": code}, map[string]interface{}{"$set": update}, false, false)
  466. f.ServeJson(map[string]interface{}{"ok": true})
  467. }
  468. func LuaSaveLog(code, user string, data *map[string]interface{}, stype int) {
  469. saveOne, _ := u.MgoEB.FindOne("luasavelog", map[string]interface{}{"state": 0, "code": code})
  470. if stype == 0 { //保存记录
  471. if len(*saveOne) == 0 && len(*data) > 0 { //重新记录
  472. delete(*data, "_id")
  473. save := map[string]interface{}{
  474. "code": code,
  475. "state": 0,
  476. "saveuser": user,
  477. "comeintime": time.Now().Unix(),
  478. "luaold": data,
  479. }
  480. u.MgoEB.Save("luasavelog", save)
  481. }
  482. } else if stype == 1 { //对比
  483. if len(*saveOne) > 0 {
  484. tmp := (*saveOne)["luaold"].(map[string]interface{})
  485. updateMap := map[string]interface{}{} //记录字段改变值
  486. for k, v := range *data {
  487. if k != "_id" && k != "state" && k != "modifytime" {
  488. if tmpV := tmp[k]; tmpV != nil { //历史记录存在字段
  489. tmpJson, _ := json.Marshal(tmpV)
  490. dataJson, _ := json.Marshal(v)
  491. if string(tmpJson) != string(dataJson) {
  492. updateMap[k] = v
  493. }
  494. delete(tmp, k) //删除对比过的字段
  495. } else { //历史记录不存在字段
  496. updateMap[k] = v
  497. }
  498. }
  499. }
  500. if len(tmp) > 0 {
  501. for k, _ := range tmp { //上架时爬虫较历史爬虫少的字段信息
  502. updateMap[k] = nil
  503. }
  504. }
  505. set := map[string]interface{}{"state": 1, "updatetime": time.Now().Unix(), "updateuser": user}
  506. if len(updateMap) > 0 { //有字段改变
  507. set["luaupdate"] = updateMap
  508. set["lusnew"] = data
  509. }
  510. u.MgoEB.UpdateById("luasavelog", (*saveOne)["_id"], map[string]interface{}{"$set": set})
  511. }
  512. }
  513. }
  514. //爬虫保存时,检查列表页和三级页代码中是否含lua原生方法
  515. func LuaTextCheck(list, detail string, type_list int) (b bool, msg string) {
  516. defer qu.Catch()
  517. if LuaReg.MatchString(list) || LuaReg.MatchString(detail) {
  518. b = true
  519. msg = "代码中含有lua原生方法;"
  520. }
  521. if ListFilterReg.MatchString(detail) && !strings.Contains(detail, "delete") { //三级页含过滤但是没有data["delete"]="true"
  522. b = true
  523. msg = `三级页缺少data["delete"]="true"`
  524. }
  525. sln_reg := regexp.MustCompile(`sendListNum\(k,list\)`)
  526. slnIndexArr := sln_reg.FindAllStringIndex(list, -1)
  527. if type_list != 0 && len(slnIndexArr) == 0 { //列表页专家模式且不含sendListNum
  528. b = true
  529. msg = "代码中缺少sendListNum(k,list)方法;" + msg
  530. } else if type_list == 1 && len(slnIndexArr) > 0 { //判断sendListNum方法的位置
  531. trim_reg := regexp.MustCompile("trim")
  532. insert_reg := regexp.MustCompile("insert")
  533. trIndexArr := trim_reg.FindAllStringIndex(list, -1)
  534. irIndexArr := insert_reg.FindAllStringIndex(list, -1)
  535. slIndex := slnIndexArr[len(slnIndexArr)-1] //sendListNum位置
  536. trIndex := trIndexArr[len(trIndexArr)-1] //com.trim位置
  537. irIndex := irIndexArr[len(irIndexArr)-1] //insert位置
  538. qu.Debug("sendListNum位置:", trIndex, slIndex, irIndex)
  539. if slIndex[1] < trIndex[0] || slIndex[0] > irIndex[1] { //sendListNum方法必须在com.trim方法后,table.insert方法前
  540. b = true
  541. msg = "sendListNum方法位置错误;" + msg
  542. }
  543. }
  544. return
  545. }
  546. //方法测试
  547. func (f *Front) RunStep() {
  548. imodal, _ := f.GetInteger("imodal")
  549. script, _ := f.GetBool("script")
  550. listcheck := f.GetString("listcheck")
  551. contentcheck := f.GetString("contentcheck")
  552. downloadnode := f.GetString("downloadnode") //下载节点
  553. common := []interface{}{
  554. f.Base.SpiderCode,
  555. f.Base.SpiderName,
  556. f.Base.SpiderChannel,
  557. f.Base.SpiderDownDetailPage,
  558. f.Base.SpiderStartPage,
  559. f.Base.SpiderMaxPage,
  560. f.Base.SpiderRunRate,
  561. f.Base.Spider2Collection,
  562. f.Base.SpiderPageEncoding,
  563. f.Base.SpiderStoreMode,
  564. f.Base.SpiderStoreToMsgEvent,
  565. f.Base.SpiderTargetChannelUrl,
  566. f.Base.SpiderLastDownloadTime,
  567. f.Base.SpiderIsHistoricalMend,
  568. f.Base.SpiderIsMustDownload,
  569. "",
  570. "",
  571. "",
  572. }
  573. if f.Method() == "POST" {
  574. switch f.GetString("step") {
  575. case "step1": //publishtime
  576. ptime := []interface{}{
  577. f.Step1.DateFormat,
  578. f.Step1.Address,
  579. f.Step1.ContentChooser,
  580. }
  581. if script {
  582. _, scripts := spider.GetLastPublishTime(common, ptime, f.Step1.Expert, downloadnode, imodal, 1)
  583. f.ServeJson(scripts)
  584. return
  585. }
  586. rs, err := spider.GetLastPublishTime(common, ptime, f.Step1.Expert, downloadnode, imodal)
  587. if err == nil {
  588. f.ServeJson(rs)
  589. }
  590. case "step2": //list
  591. addrs := strings.Split(f.Step2.Listadds, "\n")
  592. if len(addrs) > 0 {
  593. for k, v := range addrs {
  594. addrs[k] = "'" + v + "'"
  595. }
  596. f.Step2.Listadds = strings.Join(addrs, ",")
  597. } else if len(f.Step2.Listadds) > 5 {
  598. f.Step2.Listadds = "'" + f.Step2.Listadds + "'"
  599. } else {
  600. f.Step2.Listadds = ""
  601. }
  602. list := []interface{}{
  603. f.Step2.Listadd,
  604. f.Step2.Listadds,
  605. f.Step2.BlockChooser,
  606. f.Step2.AddressChooser,
  607. f.Step2.TitleChooser,
  608. f.Step2.DateChooser,
  609. f.Step2.DateFormat,
  610. }
  611. listcheck = strings.Replace(listcheck, "\n", "\\n", -1)
  612. listcheck = strings.Replace(listcheck, "\"", "\\\"", -1)
  613. s_model := f.GetString("model")
  614. configModel := util.Config.Model[s_model]
  615. model := map[string]interface{}{}
  616. for k, _ := range configModel {
  617. model[k] = f.GetString(k)
  618. }
  619. if script {
  620. _, script := spider.GetPageList(common, list, model, listcheck, f.Step2.Expert, downloadnode, imodal, 1)
  621. f.ServeJson(script)
  622. return
  623. }
  624. rs, err := spider.GetPageList(common, list, model, listcheck, f.Step2.Expert, downloadnode, imodal)
  625. if err == nil {
  626. f.ServeJson(rs)
  627. } else if err.(error).Error() == "no" {
  628. f.ServeJson(rs[0])
  629. }
  630. case "step3": //detail
  631. content := []interface{}{
  632. f.Step3.ContentChooser,
  633. f.Step3.ElementChooser,
  634. }
  635. contentcheck = strings.Replace(contentcheck, "\n", "\\n", -1)
  636. contentcheck = strings.Replace(contentcheck, "\"", "\\\"", -1)
  637. data := map[string]interface{}{}
  638. data["title"] = f.Step3.T_title
  639. data["href"] = f.Step3.T_href
  640. data["publishtime"] = f.Step3.T_date
  641. if script {
  642. _, script := spider.GetContentInfo(common, content, data, contentcheck, f.Step3.Expert, downloadnode, imodal, 1)
  643. f.ServeJson(script)
  644. return
  645. }
  646. rs, err := spider.GetContentInfo(common, content, data, contentcheck, f.Step3.Expert, downloadnode, imodal)
  647. if projectinfo, ok := rs["projectinfo"].(map[string]interface{}); ok && projectinfo != nil {
  648. if attachments, ok := projectinfo["attachments"].(map[string]interface{}); ok && attachments != nil {
  649. for _, tmp := range attachments {
  650. tmpMap := tmp.(map[string]interface{})
  651. if qu.ObjToString(tmpMap["filename"]) == "附件中含有乱码" {
  652. rs["msg"] = "附件中含有乱码"
  653. }
  654. }
  655. }
  656. }
  657. if err == nil {
  658. f.ServeJson(rs)
  659. } else {
  660. f.ServeJson(rs["no"])
  661. }
  662. }
  663. }
  664. }
  665. //爬虫测试数据json
  666. func (f *Front) GetJson() {
  667. code := f.GetString("code")
  668. username := f.GetSession("username").(string)
  669. if tr := TestResultMap[username+code]; tr != nil {
  670. task, _ := u.MgoEB.FindOne("task", map[string]interface{}{"code": code, "i_state": 3})
  671. comeintime := int64(0)
  672. if len(*task) > 0 {
  673. comeintime = qu.Int64All((*task)["l_comeintime"])
  674. tr.task_remark = "审核任务创建时间:" + qu.FormatDateByInt64(&comeintime, qu.Date_Short_Layout) + ";" + tr.task_remark
  675. }
  676. data := tr.dataInfo
  677. result := tr.listInfo
  678. if len(data) > 0 {
  679. data["contenthtml"] = ""
  680. }
  681. num := 0
  682. list_fir := []map[string]interface{}{}
  683. list_sec := []map[string]interface{}{}
  684. for page, list := range result {
  685. for k, v := range list {
  686. v["a_index"] = k + 1
  687. num++
  688. }
  689. if page == 1 {
  690. list_fir = list
  691. } else if page == 2 {
  692. list_sec = list
  693. }
  694. }
  695. f.T["list_fir"] = list_fir
  696. f.T["list_sec"] = list_sec
  697. f.T["data"] = data
  698. f.T["num"] = num
  699. f.T["descript"] = tr.task_descript
  700. f.T["remark"] = tr.task_remark
  701. f.T["rateremark"] = tr.task_rateremark
  702. f.T["reason"] = tr.reason
  703. f.T["msg"] = tr.msg
  704. f.T["comeintime"] = comeintime
  705. delete(TestResultMap, username+code)
  706. }
  707. f.Render("jsonInfo.html", &f.T)
  708. }
  709. var TestResultMap = map[string]*TestResult{} //username+code
  710. //某个爬虫整体测试结果
  711. type TestResult struct {
  712. task_remark string
  713. task_rateremark []string
  714. task_descript string
  715. reason string
  716. msg string
  717. listInfo map[int64][]map[string]interface{}
  718. dataInfo map[string]interface{}
  719. }
  720. //整体测试
  721. func (f *Front) SpiderPass() {
  722. defer mu.Catch()
  723. tr := &TestResult{}
  724. result := map[int64][]map[string]interface{}{}
  725. data := map[string]interface{}{}
  726. msgArr := []string{}
  727. code := f.GetString("code")
  728. downloadnode := f.GetString("node")
  729. //根据code查询待确认任务
  730. query := map[string]interface{}{
  731. "s_code": code,
  732. "i_state": 3,
  733. }
  734. task, _ := u.MgoEB.FindOne("task", query)
  735. descript := "null"
  736. remark := "null"
  737. remarktmp := []string{}
  738. rateremarktmp := []string{}
  739. if len(*task) > 0 {
  740. descript = (*task)["s_descript"].(string)
  741. if mrecord, ok := (*task)["a_mrecord"].([]interface{}); ok {
  742. for _, m := range mrecord {
  743. remarkInfo := m.(map[string]interface{})
  744. if remark := qu.ObjToString(remarkInfo["s_mrecord_remark"]); remark != "" {
  745. remarktmp = append(remarktmp, remark+";")
  746. }
  747. if rateremark := qu.ObjToString(remarkInfo["s_mrecord_rateremark"]); rateremark != "" {
  748. rateremarktmp = append(rateremarktmp, rateremark+";")
  749. }
  750. }
  751. }
  752. }
  753. if len(remarktmp) > 0 {
  754. remark = ""
  755. remark = strings.Join(remarktmp, "")
  756. }
  757. tr.task_remark = remark
  758. tr.task_rateremark = rateremarktmp
  759. tr.task_descript = descript
  760. //基本信息、方法一(发布时间)、方法二(列表页)、方法三(详情页)、总请求次数、go方法一、go方法二、go方法三、列表页条数
  761. steps := []interface{}{false, false, false, false, 0, 0, 0, 0, 0}
  762. one, _ := u.MgoEB.FindOne("luaconfig", map[string]interface{}{"code": code})
  763. reason, _ := (*one)["reason"].(string)
  764. tr.reason = reason
  765. if len(*one) > 0 && (*one)["oldlua"] == nil {
  766. common := (*one)["param_common"].([]interface{})
  767. if len(common) < 13 {
  768. f.ServeJson(steps)
  769. return
  770. } else {
  771. steps[0] = true
  772. }
  773. } else {
  774. steps[0] = true
  775. }
  776. script, liststr, contentstr := "", "", ""
  777. if (*one)["oldlua"] == nil {
  778. script, liststr, contentstr = spider.GetScript(code)
  779. } else {
  780. script = (*one)["luacontent"].(string)
  781. }
  782. if liststr != "" && contentstr != "" {
  783. msgArr = u.SpiderPassCheckLua(liststr, contentstr, (*one)) //校验
  784. }
  785. s := spider.CreateSpider(downloadnode, script)
  786. s.SpiderMaxPage = 2 //采集列表页总页数
  787. s.Timeout = 60
  788. timestr, timeerr := s.GetLastPublishTime()
  789. if timeerr == nil && len(timestr) > 4 {
  790. steps[1] = true //发布时间获取成功
  791. downloadNum := 0
  792. result, downloadNum, _ = s.DownListPageItem() //列表页采集结果
  793. if downloadNum == 0 {
  794. f.ServeJson(steps)
  795. return
  796. }
  797. steps[2] = true //列表页获取成功
  798. steps[8] = downloadNum //下载量
  799. tr.listInfo = result
  800. if s.DownDetail {
  801. onePageList := result[1] //第一页数据
  802. if onePageDataNum := len(onePageList); onePageDataNum > 0 {
  803. index := onePageDataNum / 2 //取一条数据下载三级页
  804. param := map[string]string{}
  805. for k, v := range onePageList[index] {
  806. param[k] = qu.ObjToString(v)
  807. }
  808. data = map[string]interface{}{}
  809. s.DownloadDetailPage(param, data)
  810. tr.dataInfo = data
  811. if len(data) == 0 || qu.ObjToString(data["detail"]) == "" {
  812. steps[3] = false //详情页获取失败
  813. } else {
  814. steps[3] = true //详情页获取成功
  815. }
  816. }
  817. } else {
  818. steps[3] = true //详情页获取成功
  819. }
  820. //list, _ = s.DownListPageItem()
  821. //for _, l := range list {
  822. // if publishtime := qu.ObjToString(l["publishtime"]); publishtime == "0" || publishtime == "" {
  823. // msgArr = append(msgArr, "列表页publishtime取值异常")
  824. // break
  825. // } else {
  826. // t, err := time.ParseInLocation(qu.Date_Full_Layout, publishtime, time.Local)
  827. // if err != nil || t.Unix() <= 0 {
  828. // msgArr = append(msgArr, "列表页publishtime取值异常")
  829. // break
  830. // }
  831. // }
  832. //}
  833. //if len(list) > 0 {
  834. // tr.listInfo = list
  835. // listone := list[0]
  836. // if len(qu.ObjToString(listone["href"])) < 7 ||
  837. // (qu.ObjToString(listone["publishtime"]) != "0" && len(qu.ObjToString(listone["publishtime"])) < 5) ||
  838. // len(qu.ObjToString(listone["title"])) < 3 {
  839. // f.ServeJson(steps)
  840. // return
  841. // } else {
  842. // steps[2] = true
  843. // if s.DownDetail {
  844. // param := map[string]string{}
  845. // index := 0
  846. // if len(list) > 0 {
  847. // steps[8] = len(list)
  848. // index = len(list) / 2
  849. // for k, v := range list[index] {
  850. // param[k] = qu.ObjToString(v)
  851. // }
  852. // data = map[string]interface{}{}
  853. // s.DownloadDetailPage(param, data)
  854. // if len(data) > 0 {
  855. // tr.dataInfo = data
  856. // }
  857. // if len(data) == 0 || data["detail"].(string) == "" {
  858. // steps[3] = false
  859. // } else {
  860. // steps[3] = true
  861. // }
  862. // }
  863. // } else {
  864. // steps[3] = true
  865. // }
  866. // }
  867. //}
  868. }
  869. //关闭laustate
  870. s.L.Close()
  871. steps[4] = s.Test_luareqcount
  872. steps[5] = s.Test_goreqtime
  873. steps[6] = s.Test_goreqlist
  874. steps[7] = s.Test_goreqcon
  875. //校验
  876. msg := u.SpiderPassCheckListAndDetail(result, data)
  877. msgArr = append(msgArr, msg...)
  878. username := f.GetSession("username").(string)
  879. tr.msg = strings.Join(msgArr, ";")
  880. TestResultMap[username+code] = tr
  881. f.ServeJson(steps)
  882. }
  883. func (f *Front) DownSpider(code string) {
  884. auth := qu.IntAll(f.GetSession("auth"))
  885. user := f.GetSession("loginuser")
  886. success := false
  887. script := ""
  888. if auth > role_dev {
  889. success = true
  890. //one, _ := u.MgoE.FindOne("luaconfig", map[string]interface{}{"code": code})
  891. one, _ := u.MgoEB.FindOne("luaconfig", map[string]interface{}{"code": code})
  892. createuserid := qu.ObjToString((*one)["createuserid"])
  893. filename := code + ".lua"
  894. if len(*one) > 0 {
  895. if (*one)["oldlua"] != nil {
  896. if (*one)["luacontent"] != nil {
  897. script = (*one)["luacontent"].(string)
  898. }
  899. } else {
  900. user, _ := u.MgoEB.FindById("user", createuserid, nil)
  901. name := (*one)["createuser"]
  902. email := (*user)["s_email"]
  903. upload := time.Now().Format("2006-01-02 15:04:05")
  904. script, _, _ = spider.GetScript(code, name, email, upload)
  905. }
  906. }
  907. f.ResponseWriter.Header().Del("Content-Type")
  908. f.ResponseWriter.Header().Add("Content-Type", "application/x-download")
  909. f.ResponseWriter.Header().Add("Content-Disposition", "attachment;filename=spider_"+filename)
  910. f.WriteBytes([]byte(script))
  911. } else {
  912. f.Write("您没有权限")
  913. }
  914. //记录日志
  915. downlogs := map[string]interface{}{
  916. "code": code,
  917. "user": user,
  918. "auth": auth,
  919. "time": time.Now().Unix(),
  920. "success": success,
  921. "script": script,
  922. }
  923. u.MgoEB.Save("luadownlogs", downlogs)
  924. }
  925. //下架删除心跳
  926. func DelSpiderHeart(code string) bool {
  927. return u.MgoS.Update("spider_heart", map[string]interface{}{"code": code}, map[string]interface{}{"$set": map[string]interface{}{"del": true}}, false, true)
  928. }
  929. //下架删除download数据
  930. //func delDownloadData(code string) bool {
  931. // return mgu.Del("download", "spider", "spider", `{"code":"`+code+`"}`)
  932. //}
  933. //批量作废删除download数据
  934. //func disableDelDownloadData(code []string) {
  935. // for _, v := range code {
  936. // flag := delDownloadData(v)
  937. // log.Println(code, "---批量删除download数据:", flag)
  938. // }
  939. //}
  940. //爬虫核对
  941. func (f *Front) Checktime() {
  942. code := f.GetString("code")
  943. auth := qu.IntAll(f.GetSession("auth"))
  944. if auth != role_admin {
  945. f.ServeJson(false)
  946. } else {
  947. //b := u.MgoE.Update("luaconfig", map[string]interface{}{"code": code}, map[string]interface{}{"$set": map[string]interface{}{
  948. // "l_checktime": time.Now().Unix(),
  949. //}}, true, false)
  950. b := u.MgoEB.Update("luaconfig", map[string]interface{}{"code": code}, map[string]interface{}{"$set": map[string]interface{}{
  951. "l_checktime": time.Now().Unix(),
  952. }}, true, false)
  953. f.ServeJson(b)
  954. }
  955. }
  956. //批量作废
  957. func (f *Front) Disables() error {
  958. auth := qu.IntAll(f.GetSession("auth"))
  959. names := strings.Split(f.GetString("names"), ",")
  960. ids := strings.Split(f.GetString("ids"), ",")
  961. codes := strings.Split(f.GetString("codes"), ",")
  962. disablereason := f.GetString("disablereason")
  963. res := ""
  964. if IsHasUpState(auth, Sp_state_4) {
  965. for k, id := range ids {
  966. b, err := UpStateAndUpSpider("", id, disablereason, "", Sp_state_4)
  967. if b { //作废成功
  968. //修改任务状态
  969. UpTaskState(codes, 4, "", int64(0))
  970. //删除download表数据
  971. //go disableDelDownloadData(codes)
  972. if err != nil {
  973. res = res + names[k] + ",ok" + qu.ObjToString(err.Error()) + ";"
  974. } else {
  975. res = res + names[k] + ",ok" + ";"
  976. }
  977. } else {
  978. res = res + names[k] + "," + qu.ObjToString(err.Error()) + ";"
  979. }
  980. }
  981. } else {
  982. res = "没有权限"
  983. }
  984. f.ServeJson(res)
  985. return nil
  986. }
  987. //批量上下架
  988. func (f *Front) BatchShelves() {
  989. codes := strings.Split(f.GetString("codes"), ",")
  990. state, _ := f.GetInteger("state")
  991. auth := qu.IntAll(f.GetSession("auth"))
  992. errCode := []string{}
  993. var err error
  994. b := false
  995. if IsHasUpState(auth, Sp_state_5) {
  996. if state == 5 { //批量上架
  997. for _, code := range codes {
  998. _, err = UpStateAndUpSpider(code, "", "", "", Sp_state_5)
  999. if err != nil {
  1000. errCode = append(errCode, code)
  1001. }
  1002. }
  1003. } else { //批量下架
  1004. for _, code := range codes {
  1005. b, err = UpStateAndUpSpider(code, "", "", "", Sp_state_6)
  1006. if !b || err != nil {
  1007. errCode = append(errCode, code)
  1008. }
  1009. //下架删除download数据
  1010. //if b {
  1011. // flag := delDownloadData(code)
  1012. // log.Println(code, "---删除download数据:", flag)
  1013. //}
  1014. }
  1015. }
  1016. } else {
  1017. errCode = append(errCode, "没有权限")
  1018. }
  1019. f.ServeJson(errCode)
  1020. }
  1021. //更新爬虫状态
  1022. func (f *Front) UpState() error {
  1023. username := f.GetSession("username").(string)
  1024. code := f.GetString("code")
  1025. state, _ := f.GetInt("state")
  1026. id := f.GetString("taskId")
  1027. reason := f.GetString("reason")
  1028. auth := qu.IntAll(f.GetSession("auth"))
  1029. var codeArr = []string{code}
  1030. var taskid []string
  1031. //修改任务状态
  1032. istotask := false
  1033. res := map[string]interface{}{
  1034. "istotask": istotask,
  1035. "err": "没有权限",
  1036. "code": util.Se.Encode2Hex(code),
  1037. "taskid": taskid,
  1038. }
  1039. var xgTime int64
  1040. if f.GetSession(id) == nil || f.GetSession(id) == "" {
  1041. xgTime = time.Now().Unix()
  1042. } else {
  1043. xgTimeStr := qu.ObjToString(f.GetSession(id))
  1044. xgTimeTmp, _ := time.ParseInLocation("2006-01-02 15:04:05", xgTimeStr, time.Local)
  1045. xgTime = xgTimeTmp.Unix()
  1046. }
  1047. f.DelSession(id)
  1048. if IsHasUpState(auth, int(state)) {
  1049. b, err := UpStateAndUpSpider(code, "", reason, username, int(state)) //更新爬虫状态
  1050. if b && state == Sp_state_1 { //提交审核
  1051. //有对应任务跳转提交记录页
  1052. taskid = checkTask(codeArr, 1)
  1053. if len(taskid) > 0 {
  1054. res["istotask"] = true
  1055. res["taskid"] = taskid[0]
  1056. }
  1057. } else if b && state == Sp_state_2 { //打回
  1058. taskid = checkTask(codeArr, 2)
  1059. if len(taskid) > 0 {
  1060. //UpTaskState([]string{taskid}, 2) //修改状态
  1061. UpTaskState(taskid, 2, "", int64(0)) //修改任务状态
  1062. SaveRemark(taskid, reason, username) //保存记录信息
  1063. }
  1064. } else if b && state == Sp_state_3 { //审核通过
  1065. taskid = checkTask(codeArr, 3)
  1066. if len(taskid) > 0 {
  1067. //UpTaskState([]string{taskid}, 3)
  1068. UpTaskState(taskid, 3, "", int64(0))
  1069. SaveRemark(taskid, "", username)
  1070. }
  1071. } else if b && state == Sp_state_6 { //下架
  1072. //下架成功删除心跳数据
  1073. flag := DelSpiderHeart(code)
  1074. log.Println(code, "---下架删除download数据:", flag)
  1075. } else if b && state == Sp_state_7 { //反馈
  1076. taskid = checkTask(codeArr, 7)
  1077. if len(taskid) > 0 {
  1078. UpTaskState(taskid, 7, reason, xgTime)
  1079. }
  1080. }
  1081. if err != nil {
  1082. res["err"] = err.Error()
  1083. f.ServeJson(res)
  1084. } else {
  1085. res["err"] = ""
  1086. f.ServeJson(res)
  1087. }
  1088. } else {
  1089. f.ServeJson(res)
  1090. }
  1091. return nil
  1092. }
  1093. func (f *Front) Assort() {
  1094. state, _ := f.GetInteger("state")
  1095. code := f.GetString("code")
  1096. codes := u.SymbolReg.Split(code, -1)
  1097. success := true
  1098. msg := ""
  1099. for _, code := range codes {
  1100. query := map[string]interface{}{
  1101. "code": code,
  1102. }
  1103. //下架爬虫
  1104. //lua, _ := u.MgoE.FindOne("luaconfig", query)
  1105. lua, _ := u.MgoEB.FindOne("luaconfig", query)
  1106. upresult, err := spider.UpdateSpiderByCodeState(code, "6", qu.IntAll((*lua)["event"]))
  1107. qu.Debug("下架爬虫:", code, upresult, err)
  1108. if upresult && err == nil {
  1109. //更新爬虫状态
  1110. update := map[string]interface{}{
  1111. "$set": map[string]interface{}{
  1112. "state": state,
  1113. //"modifytime": time.Now().Unix(),
  1114. "l_uploadtime": time.Now().Unix(),
  1115. },
  1116. }
  1117. //u.MgoE.Update("luaconfig", query, update, false, false)
  1118. u.MgoEB.Update("luaconfig", query, update, false, false)
  1119. //关闭任务
  1120. query = map[string]interface{}{
  1121. "s_code": code,
  1122. }
  1123. update = map[string]interface{}{
  1124. "$set": map[string]interface{}{
  1125. "i_state": 6,
  1126. },
  1127. }
  1128. u.MgoEB.Update("task", query, update, false, true)
  1129. //删除心跳
  1130. DelSpiderHeart(code)
  1131. } else {
  1132. success = false
  1133. msg += code + ";"
  1134. }
  1135. }
  1136. f.ServeJson(map[string]interface{}{"success": success, "msg": msg})
  1137. }
  1138. //更新爬虫状态,并判断是否更新节点爬虫
  1139. func UpStateAndUpSpider(code, id, reason, username string, state int) (bool, error) {
  1140. upresult := false
  1141. var err error
  1142. one := &map[string]interface{}{}
  1143. if code != "" {
  1144. //one, _ = u.MgoE.FindOne("luaconfig", map[string]interface{}{"code": code})
  1145. one, _ = u.MgoEB.FindOne("luaconfig", map[string]interface{}{"code": code})
  1146. } else {
  1147. //one, _ = u.MgoE.FindById("luaconfig", id, nil)
  1148. one, _ = u.MgoEB.FindById("luaconfig", id, nil)
  1149. code = qu.ObjToString((*one)["code"])
  1150. }
  1151. if len(*one) > 0 {
  1152. var event int
  1153. unset := map[string]interface{}{}
  1154. if (*one)["event"] != nil {
  1155. event = qu.IntAll((*one)["event"])
  1156. } else {
  1157. for k, _ := range util.Config.Uploadevents { //?
  1158. event = qu.IntAll(k)
  1159. break
  1160. }
  1161. //r := rand.New(rand.NewSource(time.Now().UnixNano()))
  1162. //event = util.Config.Uploadevents[r.Intn(len(util.Config.Uploadevents))]
  1163. }
  1164. //oldstate := qu.IntAll(one["state"])
  1165. switch state {
  1166. case Sp_state_4, Sp_state_6: //作废、下架
  1167. // if oldstate == Sp_state_5 {
  1168. // upresult = false
  1169. // err = errors.New("已上架不允许作废")
  1170. // } else {
  1171. // upresult = true
  1172. // }
  1173. upresult, err = spider.UpdateSpiderByCodeState(code, fmt.Sprint(state), event) //下架
  1174. qu.Debug("下架:", upresult, code)
  1175. case Sp_state_5: //上架(爬虫端在更新上架的时候为了更新内存中字段,采用先下架上架)
  1176. if downevent := qu.IntAll((*one)["downevent"]); downevent != 0 { //爬虫开发修改爬虫节点,审核人员上架爬虫时,原来爬虫所在节点下架
  1177. upresult, err = spider.UpdateSpiderByCodeState(code, "6", downevent)
  1178. if upresult && err == nil {
  1179. unset = map[string]interface{}{"downevent": ""}
  1180. }
  1181. }
  1182. upresult, err = spider.UpdateSpiderByCodeState(code, "6", event)
  1183. qu.Debug("下架:", upresult, code)
  1184. if upresult && err == nil {
  1185. upresult, err = spider.UpdateSpiderByCodeState(code, fmt.Sprint(state), event)
  1186. qu.Debug("上架:", upresult, code)
  1187. }
  1188. default:
  1189. upresult = true
  1190. err = nil
  1191. }
  1192. if err != nil && strings.Contains(err.Error(), "timeout") {
  1193. err = errors.New("连接节点" + fmt.Sprint(event) + "超时")
  1194. upresult = true
  1195. }
  1196. if upresult && err == nil {
  1197. upset := map[string]interface{}{"state": state} //修改状态
  1198. if (*one)["oldlua"] != nil { //老脚本上传
  1199. //upresult = u.MgoE.Update("luaconfig", map[string]interface{}{"code": code}, map[string]interface{}{"$set": upset}, true, false)
  1200. up := map[string]interface{}{
  1201. "$set": upset,
  1202. }
  1203. if len(unset) > 0 {
  1204. up["$unset"] = unset
  1205. }
  1206. upresult = u.MgoEB.Update("luaconfig", map[string]interface{}{"code": code}, up, true, false)
  1207. } else {
  1208. if state == Sp_state_1 { //提交审核
  1209. upset["l_complete"] = time.Now().Unix()
  1210. upset["report"] = ""
  1211. } else if state == Sp_state_7 { //反馈问题
  1212. upset["report"] = reason
  1213. upset["state"] = 1 //反馈后爬虫改为待审核
  1214. upset["l_complete"] = time.Now().Unix()
  1215. } else if state == Sp_state_3 { //审核通过
  1216. if (*one)["event"] == nil {
  1217. upset["event"] = event
  1218. //upset["modifytime"] = time.Now().Unix()
  1219. }
  1220. upset["frequencyerrtimes"] = 0 //爬虫审核通过,重置采集频率异常次数
  1221. upset["l_uploadtime"] = time.Now().Unix()
  1222. } else if state == Sp_state_2 { //打回原因
  1223. upset["reason"] = reason
  1224. } else if state == Sp_state_5 { //上架,核对时间重置
  1225. upset["l_checktime"] = 0
  1226. LuaSaveLog(code, username, one, 1)
  1227. } else if state == Sp_state_4 { //作废,作废原因
  1228. upset["disablereason"] = reason
  1229. //upset["modifytime"] = time.Now().Unix()
  1230. upset["l_uploadtime"] = time.Now().Unix() //l_complete爬虫完成时间
  1231. }
  1232. up := map[string]interface{}{
  1233. "$set": upset,
  1234. }
  1235. if len(unset) > 0 {
  1236. up["$unset"] = unset
  1237. }
  1238. //upresult = u.MgoE.Update("luaconfig", map[string]interface{}{"code": code}, map[string]interface{}{"$set": upset}, false, false)
  1239. upresult = u.MgoEB.Update("luaconfig", map[string]interface{}{"code": code}, up, false, false)
  1240. qu.Debug("提交日志:", code, upset, upresult)
  1241. if upresult && (state == Sp_state_2 || state == Sp_state_3) { //打回、审核记录日志
  1242. types := "打回"
  1243. if state == Sp_state_3 {
  1244. types = "审核"
  1245. }
  1246. obj := map[string]interface{}{
  1247. "code": code,
  1248. "auditor": username,
  1249. "types": types,
  1250. "comeintime": time.Now().Unix(),
  1251. "reason": reason,
  1252. "spideruser": (*one)["createuser"],
  1253. "modifytime": (*one)["modifytime"],
  1254. "event": (*one)["event"],
  1255. "site": (*one)["site"],
  1256. "channel": (*one)["channel"],
  1257. }
  1258. if !strings.HasSuffix(code, u.Bu) { //凡是以_bu结尾的爬虫一律不计入审核记录
  1259. //新爬虫审核记录表
  1260. if state == Sp_state_3 || state == Sp_state_2 {
  1261. count := u.MgoEB.Count("lua_logs_auditor", map[string]interface{}{"code": code, "types": types})
  1262. if count == 0 { //新爬虫审核记录
  1263. u.MgoEB.Save("lua_logs_auditor_new", obj)
  1264. }
  1265. }
  1266. u.MgoEB.Save("lua_logs_auditor", obj) //历史维护爬虫审核记录
  1267. }
  1268. }
  1269. }
  1270. }
  1271. }
  1272. return upresult, err
  1273. }
  1274. //保存记录信息
  1275. func SaveRemark(taskid []string, reason, username string) {
  1276. timeNow := time.Now().Unix()
  1277. if reason == "" {
  1278. reason = "审核通过"
  1279. }
  1280. for _, id := range taskid {
  1281. task, _ := u.MgoEB.FindById("task", id, nil)
  1282. if task != nil && len(*task) > 0 {
  1283. checkData := (*task)["a_check"]
  1284. var checkArr []map[string]interface{}
  1285. newData := make(map[string]interface{})
  1286. newData["s_check_checkUser"] = username
  1287. newData["l_check_checkTime"] = timeNow
  1288. newData["s_check_checkRemark"] = reason
  1289. if checkData != nil {
  1290. myArr := qu.ObjArrToMapArr(checkData.([]interface{}))
  1291. if myArr != nil && len(myArr) > 0 {
  1292. for _, v := range myArr {
  1293. checkArr = append(checkArr, v)
  1294. }
  1295. }
  1296. }
  1297. checkArr = append(checkArr, newData)
  1298. (*task)["a_check"] = checkArr
  1299. u.MgoEB.UpdateById("task", id, map[string]interface{}{"$set": &task})
  1300. }
  1301. }
  1302. }
  1303. //修改任务状态
  1304. func UpTaskState(code []string, num int, reason string, startTime int64) {
  1305. query := map[string]interface{}{}
  1306. update := map[string]interface{}{}
  1307. for _, v := range code {
  1308. if num == 1 || num == 2 || num == 3 || num == 7 { //id
  1309. query = map[string]interface{}{
  1310. "_id": mongodb.StringTOBsonId(v),
  1311. }
  1312. } else {
  1313. query = map[string]interface{}{ //code
  1314. "s_code": v,
  1315. }
  1316. }
  1317. if num == 1 { //提交审核
  1318. update = map[string]interface{}{
  1319. "$set": map[string]interface{}{
  1320. "i_state": 3,
  1321. },
  1322. }
  1323. } else if num == 2 { //打回 -->未通过
  1324. update = map[string]interface{}{
  1325. "$set": map[string]interface{}{
  1326. "i_state": 5,
  1327. "l_updatetime": time.Now().Unix(),
  1328. },
  1329. }
  1330. } else if num == 3 { //发布(审核通过) -->审核通过
  1331. update = map[string]interface{}{
  1332. "$set": map[string]interface{}{
  1333. "i_state": 4,
  1334. "l_updatetime": time.Now().Unix(),
  1335. "l_uploadtime": time.Now().Unix(),
  1336. },
  1337. }
  1338. } else if num == 4 { //批量作废 -->关闭
  1339. update = map[string]interface{}{
  1340. "$set": map[string]interface{}{
  1341. "i_state": 6,
  1342. "l_complete": time.Now().Unix(),
  1343. "l_updatetime": time.Now().Unix(),
  1344. },
  1345. }
  1346. } else if num == 7 { //反馈信息 -->待审核
  1347. newData := map[string]interface{}{
  1348. "l_mrecord_comeintime": startTime,
  1349. "l_mrecord_complete": time.Now().Unix(),
  1350. "s_mrecord_remark": reason,
  1351. }
  1352. mrecord := []interface{}{}
  1353. mrecord = append(mrecord, newData)
  1354. update = map[string]interface{}{
  1355. "$set": map[string]interface{}{
  1356. "i_state": 3,
  1357. "l_complete": time.Now().Unix(),
  1358. "a_mrecord": mrecord,
  1359. "l_updatetime": time.Now().Unix(),
  1360. },
  1361. }
  1362. }
  1363. flag := u.MgoEB.Update("task", query, update, false, true)
  1364. log.Println("codeOrId:", query, " 修改任务状态:", flag)
  1365. }
  1366. }
  1367. //更新节点
  1368. func (f *Front) ChangeEvent() {
  1369. auth := qu.IntAll(f.GetSession("auth"))
  1370. if auth != role_admin {
  1371. f.ServeJson("没有权限")
  1372. }
  1373. code := f.GetString("code")
  1374. event, _ := f.GetInt("event")
  1375. eventok := false
  1376. for k, _ := range util.Config.Uploadevents {
  1377. if event == qu.Int64All(k) {
  1378. eventok = true
  1379. break
  1380. }
  1381. }
  1382. if !eventok {
  1383. f.ServeJson("没有对应节点")
  1384. return
  1385. }
  1386. //info, _ := u.MgoE.FindOne("luaconfig", map[string]interface{}{"code": code})
  1387. info, _ := u.MgoEB.FindOne("luaconfig", map[string]interface{}{"code": code})
  1388. if len(*info) > 0 {
  1389. oldevent := qu.IntAll((*info)["event"])
  1390. if qu.IntAll((*info)["state"]) == Sp_state_5 {
  1391. //源节点下架
  1392. _, err := spider.UpdateSpiderByCodeState(code, fmt.Sprint(Sp_state_6), oldevent)
  1393. set := map[string]interface{}{
  1394. "$set": map[string]interface{}{
  1395. "event": qu.IntAll(event),
  1396. "state": Sp_state_6,
  1397. },
  1398. }
  1399. //u.MgoE.Update("luaconfig", map[string]interface{}{"code": code}, set, true, false)
  1400. u.MgoEB.Update("luaconfig", map[string]interface{}{"code": code}, set, true, false)
  1401. if err != nil && strings.Contains(err.Error(), "timeout") {
  1402. f.ServeJson("连接节点" + fmt.Sprint(oldevent) + "超时")
  1403. } else {
  1404. f.ServeJson(err.Error())
  1405. }
  1406. } else {
  1407. set := map[string]interface{}{
  1408. "$set": map[string]interface{}{
  1409. "event": qu.IntAll(event),
  1410. },
  1411. }
  1412. //u.MgoE.Update("luaconfig", map[string]interface{}{"code": code}, set, true, false)
  1413. u.MgoEB.Update("luaconfig", map[string]interface{}{"code": code}, set, true, false)
  1414. }
  1415. } else {
  1416. f.ServeJson("没有对应记录")
  1417. }
  1418. }
  1419. //验证用户是否有更改状态权限
  1420. func IsHasUpState(auth, state int) bool {
  1421. rep := false
  1422. switch auth {
  1423. case role_dev:
  1424. if state == Sp_state_1 || state == Sp_state_7 {
  1425. rep = true
  1426. }
  1427. case role_examine:
  1428. if state == Sp_state_2 || state == Sp_state_3 {
  1429. rep = true
  1430. }
  1431. case role_admin:
  1432. rep = true
  1433. default:
  1434. }
  1435. return rep
  1436. }
  1437. var list_fields = `{"_id":1,"code":1,"createuser":1,"modifyuser":1,"modifytime":1,"l_uploadtime":1,"l_checktime":1,"state":1,"param_common":1,"event":1,"urgency":1,"platform":1,"pendstate":1}`
  1438. //脚本管理,结合爬虫运行信息
  1439. func (f *Front) LuaList() {
  1440. auth := qu.IntAll(f.GetSession("auth"))
  1441. if auth != role_admin {
  1442. f.ServeJson("没有权限!")
  1443. return
  1444. }
  1445. if f.Method() == "POST" {
  1446. state, _ := f.GetInteger("state")
  1447. event, _ := f.GetInteger("event")
  1448. start, _ := f.GetInteger("start")
  1449. limit, _ := f.GetInteger("length")
  1450. draw, _ := f.GetInteger("draw")
  1451. searchStr := f.GetString("search[value]")
  1452. //search := strings.Replace(searchStr, " ", "", -1)
  1453. search := strings.TrimSpace(searchStr)
  1454. platform := f.GetString("platform")
  1455. query := map[string]interface{}{}
  1456. queryArr := []interface{}{}
  1457. //搜索条件
  1458. if search != "" {
  1459. q1 := map[string]interface{}{}
  1460. q1["$or"] = []interface{}{
  1461. map[string]interface{}{"code": map[string]interface{}{"$regex": search}},
  1462. map[string]interface{}{"createuser": map[string]interface{}{"$regex": search}},
  1463. map[string]interface{}{"param_common.1": map[string]interface{}{"$regex": search}},
  1464. }
  1465. queryArr = append(queryArr, q1)
  1466. }
  1467. //爬虫状态
  1468. q2 := map[string]interface{}{}
  1469. if state > -1 {
  1470. q2 = map[string]interface{}{"state": state}
  1471. } else {
  1472. q2 = map[string]interface{}{
  1473. "state": map[string]interface{}{
  1474. "$in": []int{Sp_state_3, Sp_state_5, Sp_state_6},
  1475. },
  1476. }
  1477. }
  1478. queryArr = append(queryArr, q2)
  1479. //爬虫节点
  1480. q3 := map[string]interface{}{}
  1481. if event > -1 {
  1482. q3 = map[string]interface{}{"event": event}
  1483. queryArr = append(queryArr, q3)
  1484. }
  1485. //爬虫平台
  1486. q4 := map[string]interface{}{}
  1487. if platform != "-1" {
  1488. q4 = map[string]interface{}{"platform": platform}
  1489. queryArr = append(queryArr, q4)
  1490. }
  1491. query["$and"] = queryArr
  1492. sort := `{"%s":%d}`
  1493. orderIndex := f.GetString("order[0][column]")
  1494. orderName := f.GetString(fmt.Sprintf("columns[%s][data]", orderIndex))
  1495. orderType := 1
  1496. if f.GetString("order[0][dir]") != "asc" {
  1497. orderType = -1
  1498. }
  1499. sort = fmt.Sprintf(sort, orderName, orderType)
  1500. page := start / 10
  1501. //luas, _ := u.MgoE.Find("luaconfig", query, sort, list_fields, false, start, limit)
  1502. //count := u.MgoE.Count("luaconfig", query)
  1503. luas, _ := u.MgoEB.Find("luaconfig", query, sort, list_fields, false, start, limit)
  1504. count := u.MgoEB.Count("luaconfig", query)
  1505. qu.Debug("query:", query, start, limit, count, len(*luas))
  1506. for k, v := range *luas {
  1507. v["num"] = k + 1 + page*10
  1508. l_uploadtime := qu.Int64All(v["l_uploadtime"])
  1509. v["l_uploadtime"] = qu.FormatDateByInt64(&l_uploadtime, qu.Date_Full_Layout)
  1510. l_checktime := qu.Int64All(v["l_checktime"])
  1511. v["l_checktime"] = qu.FormatDateByInt64(&l_checktime, qu.Date_Full_Layout)
  1512. if l_checktime > 0 { //核对
  1513. v["is_check"] = true
  1514. } else { //未核对
  1515. v["is_check"] = false
  1516. }
  1517. if tmp, ok := spinfos.Load(v["code"]); ok {
  1518. info := tmp.(*spinfo)
  1519. v["modifytime"] = info.lastHeartbeat
  1520. v["yesterday"] = fmt.Sprint(info.yesterdayDowncount) + "/" + fmt.Sprint(info.yestoDayRequestNum)
  1521. v["terday"] = fmt.Sprint(info.todayDowncount) + "/" + fmt.Sprint(info.toDayRequestNum)
  1522. v["lastdowncount"] = info.lastDowncount
  1523. v["lstate"] = info.lstate
  1524. } else {
  1525. v["modifytime"] = ""
  1526. v["yesterday"] = ""
  1527. v["terday"] = ""
  1528. v["lastdowncount"] = 0
  1529. v["lstate"] = ""
  1530. }
  1531. }
  1532. f.ServeJson(map[string]interface{}{"draw": draw, "data": luas, "recordsFiltered": count, "recordsTotal": count})
  1533. } else {
  1534. events := []string{}
  1535. for k, _ := range util.Config.Uploadevents {
  1536. events = append(events, k)
  1537. }
  1538. sort.Strings(events)
  1539. f.T["events"] = events
  1540. f.Render("lualist.html", &f.T)
  1541. }
  1542. }
  1543. //心跳监控
  1544. func (f *Front) Heart() {
  1545. if f.Method() == "POST" {
  1546. event, _ := f.GetInteger("event")
  1547. start, _ := f.GetInteger("start")
  1548. limit, _ := f.GetInteger("length")
  1549. draw, _ := f.GetInteger("draw")
  1550. searchStr := f.GetString("search[value]")
  1551. search := strings.TrimSpace(searchStr) //只能搜索code
  1552. //qu.Debug("search:", search, "start:", start, "limit:", limit, "draw:", draw)
  1553. query := map[string]interface{}{
  1554. "del": false,
  1555. }
  1556. if event > -1 {
  1557. query["event"] = event
  1558. }
  1559. if search != "" {
  1560. query["code"] = search
  1561. }
  1562. sort := `{"%s":%d}`
  1563. orderIndex := f.GetString("order[0][column]")
  1564. orderName := f.GetString(fmt.Sprintf("columns[%s][data]", orderIndex))
  1565. orderType := 1
  1566. if f.GetString("order[0][dir]") != "asc" {
  1567. orderType = -1
  1568. }
  1569. sort = fmt.Sprintf(sort, orderName, orderType)
  1570. qu.Debug("query:", query, "sort:", sort)
  1571. list, _ := u.MgoS.Find("spider_heart", query, sort, nil, false, start, limit)
  1572. count := u.MgoS.Count("spider_heart", query)
  1573. for _, l := range *list {
  1574. code := qu.ObjToString(l["code"])
  1575. qu.Debug(code)
  1576. //d, _ := u.MgoE.FindOneByField("luaconfig", map[string]interface{}{"code": code}, map[string]interface{}{"state": 1, "param_common": 1, "str_list": 1, "type_list": 1})
  1577. d, _ := u.MgoEB.FindOneByField("luaconfig", map[string]interface{}{"code": code}, map[string]interface{}{"state": 1, "param_common": 1, "str_list": 1, "type_list": 1})
  1578. l["state"] = (*d)["state"]
  1579. l["param_common"] = (*d)["param_common"]
  1580. if lt := qu.Int64All(l["list"]); lt != 0 {
  1581. l["list"] = qu.FormatDateByInt64(&lt, qu.Date_Full_Layout)
  1582. } else {
  1583. l["list"] = 0
  1584. }
  1585. if dt := qu.Int64All(l["detail"]); dt != 0 {
  1586. l["detail"] = qu.FormatDateByInt64(&dt, qu.Date_Full_Layout)
  1587. } else {
  1588. l["detail"] = 0
  1589. }
  1590. if det := qu.Int64All(l["detailexecute"]); det != 0 {
  1591. l["detailexecute"] = qu.FormatDateByInt64(&det, qu.Date_Full_Layout)
  1592. } else {
  1593. l["detailexecute"] = 0
  1594. }
  1595. if ft := qu.Int64All(l["findlist"]); ft != 0 {
  1596. l["findlist"] = qu.FormatDateByInt64(&ft, qu.Date_Full_Layout)
  1597. } else {
  1598. l["findlist"] = 0
  1599. }
  1600. ut := qu.Int64All(l["updatetime"])
  1601. l["updatetime"] = qu.FormatDateByInt64(&ut, qu.Date_Full_Layout)
  1602. //l["isfindlist"] = "否"
  1603. //typeList := qu.IntAll((*d)["type_list"])
  1604. //strList := qu.ObjToString((*d)["str_list"])
  1605. //if typeList == 1 && strings.Contains(strList, "findListHtml") {
  1606. // l["isfindlist"] = "是"
  1607. //}
  1608. }
  1609. f.ServeJson(map[string]interface{}{"draw": draw, "data": list, "recordsFiltered": count, "recordsTotal": count})
  1610. } else {
  1611. events := []string{}
  1612. for k, _ := range util.Config.Uploadevents {
  1613. events = append(events, k)
  1614. }
  1615. sort.Strings(events)
  1616. f.T["events"] = events
  1617. f.Render("heart.html", &f.T)
  1618. }
  1619. }
  1620. //爬虫信息
  1621. type spinfo struct {
  1622. code string
  1623. todayDowncount, toDayRequestNum int
  1624. yesterdayDowncount, yestoDayRequestNum int
  1625. totalDowncount, totalRequestNum int
  1626. errorNum, roundCount, runRate int
  1627. lastDowncount int
  1628. lastHeartbeat string
  1629. lstate string
  1630. }
  1631. //爬虫信息
  1632. func SpiderInfo(data string) {
  1633. data = util.Se.DecodeString(data)
  1634. infos := []map[string]interface{}{}
  1635. err := json.Unmarshal([]byte(data), &infos)
  1636. if err != nil {
  1637. return
  1638. }
  1639. for _, tmp := range infos {
  1640. lastHeartbeat := qu.Int64All(tmp["lastHeartbeat"])
  1641. info := &spinfo{
  1642. code: fmt.Sprint(tmp["code"]),
  1643. todayDowncount: qu.IntAll(tmp["todayDowncount"]),
  1644. toDayRequestNum: qu.IntAll(tmp["toDayRequestNum"]),
  1645. yesterdayDowncount: qu.IntAll(tmp["yesterdayDowncount"]),
  1646. yestoDayRequestNum: qu.IntAll(tmp["yestoDayRequestNum"]),
  1647. totalDowncount: qu.IntAll(tmp["totalDowncount"]),
  1648. totalRequestNum: qu.IntAll(tmp["totalRequestNum"]),
  1649. errorNum: qu.IntAll(tmp["errorNum"]),
  1650. roundCount: qu.IntAll(tmp["roundCount"]),
  1651. runRate: qu.IntAll(tmp["runRate"]),
  1652. lastHeartbeat: qu.FormatDateByInt64(&lastHeartbeat, qu.Date_Full_Layout),
  1653. lastDowncount: qu.IntAll(tmp["lastDowncount"]),
  1654. lstate: fmt.Sprint(tmp["lstate"]),
  1655. }
  1656. spinfos.Store(info.code, info)
  1657. //log.Println(info)
  1658. }
  1659. }
  1660. //接受维护任务信息
  1661. func SpiderModifyTask(data string) {
  1662. data = util.Se.DecodeString(data)
  1663. mtasks := []map[string]interface{}{}
  1664. err := json.Unmarshal([]byte(data), &mtasks)
  1665. if err != nil {
  1666. return
  1667. }
  1668. for k, tmp := range mtasks {
  1669. log.Println(k, tmp)
  1670. }
  1671. }
  1672. //查看是否有该任务
  1673. func checkTask(codes []string, num int) []string {
  1674. // var id string = ""
  1675. query := map[string]interface{}{}
  1676. var idArr []string
  1677. if len(codes) > 0 {
  1678. for _, v := range codes {
  1679. if num == 1 {
  1680. query = map[string]interface{}{
  1681. "s_code": v,
  1682. "i_state": map[string]interface{}{
  1683. "$in": []int{1, 2, 5},
  1684. },
  1685. }
  1686. } else if num == 2 { //打回时查询待审核的任务
  1687. query = map[string]interface{}{
  1688. "s_code": v,
  1689. "i_state": 3,
  1690. }
  1691. } else if num == 3 { //审核通过时查询待处理、处理中、待审核、未通过的任务
  1692. query = map[string]interface{}{
  1693. "s_code": v,
  1694. "i_state": map[string]interface{}{
  1695. "$in": []int{1, 2, 3, 5},
  1696. },
  1697. }
  1698. } else if num == 7 {
  1699. query = map[string]interface{}{
  1700. "s_code": v,
  1701. "i_state": map[string]interface{}{
  1702. "$in": []int{2, 5},
  1703. },
  1704. }
  1705. }
  1706. task, _ := u.MgoEB.Find("task", query, nil, nil, false, -1, -1)
  1707. if task != nil {
  1708. for _, t := range *task {
  1709. idArr = append(idArr, mongodb.BsonIdToSId(t["_id"]))
  1710. }
  1711. }
  1712. return idArr
  1713. }
  1714. }
  1715. return idArr
  1716. }