front.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  1. // front
  2. package front
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "mongodb"
  8. qu "qfw/util"
  9. "qfw/util/redis"
  10. "regexp"
  11. "sort"
  12. "spider"
  13. util "spiderutil"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "time"
  18. u "util"
  19. "github.com/go-xweb/httpsession"
  20. "github.com/go-xweb/xweb"
  21. "github.com/lauyoume/gopinyin"
  22. "github.com/tealeg/xlsx"
  23. )
  24. type Front struct {
  25. *xweb.Action
  26. login xweb.Mapper `xweb:"/"`
  27. logout xweb.Mapper `xweb:"/center/logout"` //退出
  28. loadIndex xweb.Mapper `xweb:"/center"` //控制中心
  29. spidernew xweb.Mapper `xweb:"/center/spider"` //爬虫新建
  30. reg xweb.Mapper `xweb:"/center/reg"` //爬虫注册
  31. assign xweb.Mapper `xweb:"/center/user/assign"` //分配爬虫
  32. loadSpider xweb.Mapper `xweb:"/center/spider/edit/(.*)"` //爬虫加载
  33. viewSpider xweb.Mapper `xweb:"/center/spider/view/(.*)"` //爬虫查看
  34. downSpider xweb.Mapper `xweb:"/center/spider/download/(.*)"` //爬虫下载
  35. upState xweb.Mapper `xweb:"/center/spider/upstate"` //爬虫状态更新
  36. assort xweb.Mapper `xweb:"/center/spider/assort"` //审核人员分类(无发布、需登录、无法处理、需删除)
  37. batchShelves xweb.Mapper `xweb:"/center/spider/batchShelves"` //批量上下架
  38. checktime xweb.Mapper `xweb:"/center/spider/checktime"` //爬虫核对
  39. disables xweb.Mapper `xweb:"/center/spider/disable"` //批量作废
  40. changeEvent xweb.Mapper `xweb:"/center/changeEvent"` //节点更新
  41. getJson xweb.Mapper `xweb:"/center/spider/json"` //
  42. delRedis xweb.Mapper `xweb:"/center/spider/delRedis"` //清理Redis
  43. updateESP xweb.Mapper `xweb:"/center/spider/updateesp"` //修改爬虫的节点/状态/平台
  44. updatePendState xweb.Mapper `xweb:"/center/spider/updatePendState"` //更新爬虫挂起状态
  45. tagCode xweb.Mapper `xweb:"/center/spider/tagcode"` //标记爬虫
  46. spiderModel xweb.Mapper `xweb:"/center/model"` //获取补充模型
  47. runStep xweb.Mapper `xweb:"/center/run"` //方法测试
  48. spiderPass xweb.Mapper `xweb:"/center/spider/pass"` //整体测试
  49. runPinYin xweb.Mapper `xweb:"/center/runpy"` //获取拼音
  50. saveStep xweb.Mapper `xweb:"/center/save"` //脚本保存
  51. loadModel xweb.Mapper `xweb:"/center/gmodel/(.*)"` //加载模型
  52. importdata xweb.Mapper `xweb:"/center/importdata"` //导入脚本
  53. importfile xweb.Mapper `xweb:"/center/importfile"` //批量导入爬虫
  54. oldedit xweb.Mapper `xweb:"/center/oldedit"` //老文件编辑
  55. findName xweb.Mapper `xweb:"/center/findname"` //即时查询名称
  56. checkrepeat xweb.Mapper `xweb:"/center/spider/isrepeat"` //脚本代码判重
  57. heart xweb.Mapper `xweb:"/center/heart"` //心跳监控
  58. spiderCopy xweb.Mapper `xweb:"/center/spider/copy"` //复制爬虫
  59. Base Base
  60. OtherBase OtherBase
  61. Step1 Step1
  62. Step2 Step2
  63. Step3 Step3
  64. StepRe3 StepRe3
  65. U U
  66. luaList xweb.Mapper `xweb:"/center/lualist.html"` //脚本管理
  67. user xweb.Mapper `xweb:"/center/user.html"` //用户管理
  68. delUser xweb.Mapper `xweb:"/center/user/del"` //删除用户
  69. updateUser xweb.Mapper `xweb:"/center/user/updateUser"` //修改用户信息
  70. checkUsenamer xweb.Mapper `xweb:"/center/user/checkUsenamer"` //校验用户名的唯一性
  71. checkEmail xweb.Mapper `xweb:"/center/user/checkEmail"` //校验邮箱的唯一性
  72. saveNewUser xweb.Mapper `xweb:"/center/user/saveNewUser"` //添加用户
  73. getCity xweb.Mapper `xweb:"/center/getCity"` //获取城市
  74. }
  75. const role_admin, role_examine, role_dev = 3, 2, 1 //管理员,审核员,开发员
  76. const Sp_state_0, Sp_state_1, Sp_state_2, Sp_state_3, Sp_state_4, Sp_state_5, Sp_state_6, Sp_state_7 = 0, 1, 2, 3, 4, 5, 6, 7 //0待完成,1待审核,2打回,3发布,4作废,5已上架,6已下架,7其他
  77. var LuaReg = regexp.MustCompile(`(:(find|match)|string\.|com\.getPureContent)`)
  78. var spinfos sync.Map = sync.Map{}
  79. var SessMap map[string]*httpsession.Session
  80. var AutoTpl map[string]interface{}
  81. var Mails *util.Mail
  82. var Reg = regexp.MustCompile(`(http|https)://([\w]+\.)+[\w]+`)
  83. var ListFilterReg = regexp.MustCompile("关键词过滤")
  84. var Transfercode map[string]interface{}
  85. var LuaStateMap = map[int]string{
  86. 0: "待完成",
  87. 1: "待审核",
  88. 2: "未通过",
  89. 3: "已通过",
  90. 4: "已作废",
  91. 5: "已上架",
  92. 6: "已下架",
  93. 7: "无发布",
  94. 8: "需登录",
  95. 9: "转python",
  96. 10: "已删除",
  97. }
  98. func (f *Front) Login() error {
  99. username := f.GetString("username")
  100. password := f.GetString("password")
  101. f.SetSession("password", password)
  102. password = util.Se.EncodeString(password)
  103. query := map[string]interface{}{
  104. "s_name": username,
  105. "s_pass": password,
  106. }
  107. user, _ := u.MgoEB.FindOne("user", query)
  108. if user != nil && len(*user) > 0 && qu.IntAll((*user)["i_delete"]) == 0 {
  109. f.SetSession("userid", mongodb.BsonIdToSId((*user)["_id"]))
  110. f.SetSession("username", (*user)["s_fullname"])
  111. f.SetSession("loginuser", (*user)["s_name"])
  112. f.SetSession("email", (*user)["s_email"])
  113. f.SetSession("auth", (*user)["i_auth"])
  114. f.SetSession("platform", (*user)["s_platform"])
  115. comeintime := time.Unix((*user)["l_comeintime"].(int64), 0).Format("2006-01-02")
  116. f.SetSession("comeintime", comeintime)
  117. if qu.IntAll((*user)["i_auth"]) > role_admin {
  118. return f.Redirect("/center/user.html")
  119. } else if qu.IntAll((*user)["i_auth"]) == role_dev {
  120. return f.Redirect("/center/mytask")
  121. } else {
  122. return f.Redirect("/center")
  123. }
  124. } else {
  125. if username != "" {
  126. f.T["fail"] = "fail"
  127. }
  128. return f.Render("login.html", &f.T)
  129. }
  130. }
  131. //用户管理
  132. func (f *Front) User() {
  133. if f.Method() == "POST" {
  134. auth := qu.IntAll(f.GetSession("auth"))
  135. if auth > role_admin {
  136. start, _ := f.GetInteger("start")
  137. limit, _ := f.GetInteger("length")
  138. draw, _ := f.GetInteger("draw")
  139. query := map[string]interface{}{
  140. "i_delete": 0, //可用用户
  141. "i_auth": map[string]interface{}{
  142. "$lt": auth,
  143. },
  144. }
  145. user, _ := u.MgoEB.Find("user", query, nil, nil, false, start, limit)
  146. count := u.MgoEB.Count("user", query)
  147. page := start / 10
  148. for k, v := range *user {
  149. v["num"] = k + 1 + page*10
  150. v["l_comeintime"] = time.Unix(v["l_comeintime"].(int64), 0).Format("2006-01-02")
  151. v["s_pass"] = util.Se.DecodeString(v["s_pass"].(string))
  152. v["userid"] = mongodb.BsonIdToSId(v["_id"])
  153. }
  154. f.ServeJson(map[string]interface{}{
  155. "draw": draw,
  156. "data": user,
  157. "recordsFiltered": count,
  158. "recordsTotal": count,
  159. })
  160. }
  161. } else {
  162. f.Render("user.html")
  163. }
  164. }
  165. //删除用户
  166. func (f *Front) DelUser() {
  167. userid := f.GetString("userid")
  168. auth := qu.IntAll(f.GetSession("auth"))
  169. if auth > role_admin {
  170. query := map[string]interface{}{
  171. "_id": mongodb.StringTOBsonId(userid),
  172. }
  173. update := map[string]interface{}{
  174. "$set": map[string]interface{}{
  175. "i_delete": 1,
  176. },
  177. }
  178. ok := u.MgoEB.Update("user", query, update, false, false)
  179. if ok {
  180. f.ServeJson(map[string]interface{}{
  181. "status": "y",
  182. })
  183. } else {
  184. f.ServeJson(map[string]interface{}{
  185. "status": "n",
  186. })
  187. }
  188. } else {
  189. f.ServeJson(map[string]interface{}{
  190. "status": "e",
  191. })
  192. }
  193. }
  194. //修改用户
  195. func (f *Front) UpdateUser() {
  196. // username := f.GetString("username")
  197. password := f.GetString("password")
  198. userid := f.GetString("userid")
  199. f.SetSession("password", password)
  200. userAuth := f.GetString("userAuth")
  201. auth := qu.IntAll(f.GetSession("auth"))
  202. self := f.GetString("self")
  203. //log.Println("userid----:", userid, "username----:", username, "password----:", password, "auth----:", auth, "self----:", self)
  204. query := map[string]interface{}{
  205. "_id": mongodb.StringTOBsonId(userid),
  206. }
  207. update := map[string]interface{}{}
  208. if "y" == self { //修改个人信息 只修改个人密码
  209. password = util.Se.EncodeString(password)
  210. update = map[string]interface{}{
  211. "$set": map[string]interface{}{
  212. "s_pass": password,
  213. },
  214. }
  215. } else if "y" != self && auth == 4 { //修改他人信息 只修改他人权限
  216. if userAuth == "开发员" || userAuth == "审核员" || userAuth == "管理员" {
  217. switch userAuth {
  218. case "开发员":
  219. update = map[string]interface{}{
  220. "$set": map[string]interface{}{
  221. "i_auth": 1,
  222. },
  223. }
  224. case "审核员":
  225. update = map[string]interface{}{
  226. "$set": map[string]interface{}{
  227. "i_auth": 2,
  228. },
  229. }
  230. case "管理员":
  231. update = map[string]interface{}{
  232. "$set": map[string]interface{}{
  233. "i_auth": 3,
  234. },
  235. }
  236. }
  237. }
  238. } else {
  239. f.ServeJson("没有权限!")
  240. return
  241. }
  242. ok := u.MgoEB.Update("user", query, update, false, false)
  243. if ok {
  244. f.ServeJson(map[string]interface{}{
  245. "status": "y",
  246. })
  247. } else {
  248. f.ServeJson(map[string]interface{}{
  249. "status": "n",
  250. })
  251. }
  252. }
  253. func (f *Front) CheckUsenamer() {
  254. username := f.GetString("username")
  255. if username != "" {
  256. query := map[string]interface{}{
  257. "s_name": username,
  258. }
  259. user, _ := u.MgoEB.FindOne("user", query)
  260. if user != nil && len(*user) > 0 {
  261. f.ServeJson(map[string]interface{}{
  262. "status": "hasUser",
  263. })
  264. } else {
  265. f.ServeJson(map[string]interface{}{
  266. "status": "notHasUser",
  267. })
  268. }
  269. }
  270. }
  271. func (f *Front) CheckEmail() {
  272. email := f.GetString("email")
  273. //校验邮箱
  274. if email != "" {
  275. query := map[string]interface{}{
  276. "s_email": email,
  277. }
  278. user, _ := u.MgoEB.FindOne("user", query)
  279. if user != nil && len(*user) > 0 {
  280. f.ServeJson(map[string]interface{}{
  281. "status": "hasEmail",
  282. })
  283. } else {
  284. f.ServeJson(map[string]interface{}{
  285. "status": "notHasEmail",
  286. })
  287. }
  288. }
  289. }
  290. //新增用户
  291. func (f *Front) SaveNewUser() {
  292. auth := qu.IntAll(f.GetSession("auth"))
  293. if auth != 4 {
  294. f.ServeJson("没有权限!")
  295. return
  296. } else {
  297. i_auth := 1
  298. username := f.GetString("username")
  299. password := f.GetString("password")
  300. relname := f.GetString("relname")
  301. password = util.Se.EncodeString(password)
  302. email := f.GetString("email")
  303. userAuth := f.GetString("userAuth")
  304. if userAuth == "开发员" {
  305. i_auth = 1
  306. } else if userAuth == "审核员" {
  307. i_auth = 2
  308. } else {
  309. i_auth = 3
  310. }
  311. time := time.Now().Unix()
  312. save := map[string]interface{}{
  313. "s_name": username,
  314. "s_fullname": relname,
  315. "s_email": email,
  316. "s_pass": password,
  317. "i_auth": i_auth,
  318. "i_delete": 0,
  319. "l_comeintime": time,
  320. }
  321. ok := u.MgoEB.Save("user", save)
  322. if ok != "" {
  323. f.ServeJson(map[string]interface{}{
  324. "status": "y",
  325. })
  326. } else {
  327. f.ServeJson(map[string]interface{}{
  328. "status": "n",
  329. })
  330. }
  331. }
  332. }
  333. func (f *Front) Logout() {
  334. email := f.GetSession("email").(string)
  335. f.DelSession("username")
  336. f.DelSession("userid")
  337. f.DelSession("email")
  338. f.DelSession("user")
  339. f.DelSession("loginuser")
  340. f.DelSession("auth")
  341. delete(SessMap, email)
  342. f.Redirect("/center")
  343. }
  344. //控制中心
  345. func (f *Front) LoadIndex() {
  346. auth := qu.IntAll(f.GetSession("auth"))
  347. if f.Method() == "POST" {
  348. start, _ := f.GetInteger("start")
  349. limit, _ := f.GetInteger("length")
  350. draw, _ := f.GetInteger("draw")
  351. searchStr := f.GetString("search[value]")
  352. event, _ := f.GetInteger("taskEvent") //节点
  353. //searchN := strings.Replace(searchStr, " ", "", -1)
  354. //search := strings.Replace(searchN, "\n", "", -1)
  355. search := strings.TrimSpace(searchStr)
  356. state, _ := f.GetInteger("state")
  357. urgency, _ := f.GetInteger("urgency") //节点
  358. platform := f.GetString("platform")
  359. query := map[string]interface{}{}
  360. if event > -1 {
  361. query["event"] = event
  362. }
  363. if urgency > -1 {
  364. query["urgency"] = urgency
  365. }
  366. if platform != "-1" {
  367. query["platform"] = platform
  368. }
  369. if search != "" {
  370. query["$or"] = []interface{}{
  371. map[string]interface{}{"code": map[string]interface{}{"$regex": search}},
  372. map[string]interface{}{"createuser": map[string]interface{}{"$regex": search}},
  373. map[string]interface{}{"param_common.1": map[string]interface{}{"$regex": search}},
  374. }
  375. }
  376. if auth == role_examine { //审核员
  377. if state > -1 {
  378. query["state"] = state
  379. } else {
  380. query["state"] = Sp_state_1
  381. }
  382. } else if auth == role_dev { //开发员
  383. if state > -1 {
  384. query["state"] = state
  385. }
  386. query["createuserid"] = f.GetSession("userid")
  387. } else { //管理员
  388. if state > -1 {
  389. query["state"] = state
  390. }
  391. }
  392. sort := `{"%s":%d}`
  393. orderIndex := f.GetString("order[0][column]")
  394. orderName := f.GetString(fmt.Sprintf("columns[%s][data]", orderIndex))
  395. orderType := 1
  396. if f.GetString("order[0][dir]") != "asc" {
  397. orderType = -1
  398. }
  399. if orderName == "param_common" {
  400. orderName = orderName + ".1"
  401. }
  402. sort = fmt.Sprintf(sort, orderName, orderType)
  403. page := start / 10
  404. //log.Println("sort", sort, orderName)
  405. qu.Debug("query:", query, "sort:", sort)
  406. //luas := *mgdb.Find("luaconfig", query, sort, list_fields, false, start, limit)
  407. //count := mgdb.Count("luaconfig", query)
  408. luas, _ := u.MgoEB.Find("luaconfig", query, sort, list_fields, false, start, limit)
  409. count := u.MgoEB.Count("luaconfig", query)
  410. for k, v := range *luas {
  411. v["num"] = k + 1 + page*10
  412. if v["modifytime"] != nil {
  413. v["modifytime"] = time.Unix(v["modifytime"].(int64), 0).Format("2006-01-02 15:04:05")
  414. } else {
  415. v["modifytime"] = "-"
  416. }
  417. if v["modifyuser"] == nil {
  418. v["modifytime"] = "-"
  419. }
  420. v["encode"] = util.Se.Encode2Hex(fmt.Sprint(v["code"]))
  421. if v["event"] == nil { //节点
  422. v["event"] = 0
  423. }
  424. user, _ := u.MgoEB.FindOne("user", map[string]interface{}{"s_name": qu.ObjToString(v["createuser"])})
  425. //v["state"] = LuaStateMap[qu.IntAll(v["state"])]
  426. v["i_scope"] = (*user)["i_scope"]
  427. }
  428. f.ServeJson(map[string]interface{}{"draw": draw, "data": luas, "recordsFiltered": count, "recordsTotal": count})
  429. } else {
  430. events := []string{}
  431. for k, _ := range util.Config.Uploadevents {
  432. events = append(events, k)
  433. }
  434. sort.Strings(events)
  435. f.T["events"] = events
  436. f.Render("index.html", &f.T)
  437. }
  438. }
  439. func (f *Front) Checkrepeat() {
  440. code := f.GetString("code")
  441. //one := *mgdb.FindOne("luaconfig", bson.M{"code": code})
  442. one, _ := u.MgoEB.FindOne("luaconfig", map[string]interface{}{"code": code})
  443. if len(*one) > 0 {
  444. f.ServeJson("y")
  445. } else {
  446. f.ServeJson("n")
  447. }
  448. }
  449. //新建
  450. func (f *Front) Spidernew() error {
  451. auth := qu.IntAll(f.GetSession("auth"))
  452. if auth != role_admin {
  453. return nil
  454. }
  455. copy := f.GetString("copy")
  456. if copy != "" {
  457. //one := *mgdb.FindOne("luaconfig", bson.M{"code": copy})
  458. one, _ := u.MgoEB.FindOne("luaconfig", map[string]interface{}{"code": copy})
  459. delete((*one), "_id")
  460. delete((*one), "code")
  461. base := (*one)["param_common"].([]interface{})
  462. base[0] = ""
  463. base[1] = ""
  464. (*one)["param_common"] = base
  465. f.T["lua"] = one
  466. }
  467. f.T["isflow"] = 1 //新建爬虫时,初始化isflow的值
  468. f.T["actiontext"] = "新建"
  469. f.T["restate"] = 4 //此处设置restate=4无意义,只为了页面不报错
  470. return f.Render("spideredit.html", &f.T)
  471. }
  472. //得到模型
  473. func (f *Front) SpiderModel() {
  474. f.ServeJson(util.Config.Model)
  475. }
  476. func (f *Front) RunPinYin() {
  477. word := f.GetString("word")
  478. str := gopinyin.Convert(word, true)
  479. f.Write(str)
  480. }
  481. type U struct {
  482. User string
  483. Name string
  484. Pwd string
  485. }
  486. func (f *Front) Reg() {
  487. }
  488. func (f *Front) Importfile() {
  489. auth := qu.IntAll(f.GetSession("auth"))
  490. if auth != role_admin {
  491. f.ServeJson("没有权限")
  492. return
  493. }
  494. if f.Method() == "POST" {
  495. mf, _, err := f.GetFile("xlsx")
  496. errorinfo := map[string]interface{}{}
  497. if err == nil {
  498. binary, _ := ioutil.ReadAll(mf)
  499. xls, _ := xlsx.OpenBinary(binary)
  500. sheet := xls.Sheets[0]
  501. rows := sheet.Rows
  502. for k, v := range rows {
  503. if k != 0 {
  504. cells := v.Cells
  505. if cells[1].Value != "" {
  506. o := make(map[string]interface{})
  507. o["name"] = cells[0].Value
  508. o["code"] = cells[1].Value
  509. o["channel"] = cells[2].Value
  510. o["channeladdr"] = cells[3].Value
  511. o["author"] = cells[4].Value
  512. o["timestamp"] = time.Now().Unix()
  513. o["status"] = 1
  514. o["next"] = cells[4].Value
  515. o["event"] = cells[5].Value
  516. o["historyevent"] = cells[6].Value
  517. if cells[7].Value == "是" {
  518. o["isflow"] = 1
  519. } else {
  520. o["isflow"] = 0
  521. }
  522. if cells[8].Value == "紧急" {
  523. o["urgency"] = 1
  524. } else {
  525. o["urgency"] = 0
  526. }
  527. o["platform"] = cells[9].Value
  528. o["area"] = cells[10].Value
  529. o["city"] = cells[11].Value
  530. o["district"] = cells[12].Value
  531. weigh, _ := cells[13].Int()
  532. o["weight"] = weigh
  533. //存储表
  534. o["coll"] = cells[14].Value
  535. //table := cells[6].Value
  536. //o["table"] = table
  537. //o["transfercode"] = qu.IntAll(Transfercode[table])
  538. query := map[string]interface{}{"code": cells[1].Value}
  539. rs, _ := u.MgoEB.FindOne("import", query)
  540. if len(*rs) > 0 {
  541. errorinfo[cells[1].Value] = "第" + strconv.Itoa(k) + "行重复,已经过滤"
  542. } else {
  543. ok, name := savelua(o) //保存爬虫
  544. if ok == false {
  545. errorinfo[cells[1].Value] = "第" + strconv.Itoa(k) + "行找不到作者,已经过滤"
  546. } else {
  547. o["author"] = name
  548. u.MgoEB.Save("import", o)
  549. }
  550. }
  551. }
  552. }
  553. }
  554. f.ServeJson(errorinfo)
  555. } else {
  556. f.ServeJson(false)
  557. }
  558. }
  559. }
  560. func savelua(o map[string]interface{}) (bool, string) {
  561. AutoTpl["Base.SpiderName"] = o["name"]
  562. AutoTpl["Base.SpiderCode"] = o["code"]
  563. AutoTpl["Base.SpiderChannel"] = o["channel"]
  564. AutoTpl["Base.SpiderTargetChannelUrl"] = o["channeladdr"]
  565. author := o["author"].(string)
  566. one, _ := u.MgoEB.FindOne("user", map[string]interface{}{"s_email": author})
  567. id := mongodb.BsonIdToSId((*one)["_id"])
  568. if len(*one) == 0 {
  569. return false, ""
  570. }
  571. common := []interface{}{
  572. AutoTpl["Base.SpiderCode"],
  573. AutoTpl["Base.SpiderName"],
  574. AutoTpl["Base.SpiderChannel"],
  575. AutoTpl["Base.SpiderDownDetailPage"],
  576. AutoTpl["Base.SpiderStartPage"],
  577. AutoTpl["Base.SpiderMaxPage"],
  578. AutoTpl["Base.SpiderRunRate"],
  579. //AutoTpl["Base.Spider2Collection"],
  580. //"bidding", //爬虫导入新建默认为bidding
  581. qu.ObjToString(o["coll"]),
  582. AutoTpl["Base.SpiderPageEncoding"],
  583. AutoTpl["Base.SpiderStoreMode"],
  584. AutoTpl["Base.SpiderStoreToMsgEvent"],
  585. AutoTpl["Base.SpiderTargetChannelUrl"],
  586. AutoTpl["Base.SpiderLastDownloadTime"],
  587. AutoTpl["Base.SpiderIsHistoricalMend"],
  588. AutoTpl["Base.SpiderIsMustDownload"],
  589. }
  590. ptime := []interface{}{
  591. AutoTpl["Step1.DateFormat"],
  592. AutoTpl["Step1.Address"],
  593. AutoTpl["Step1.ContentChooser"],
  594. }
  595. list := []interface{}{
  596. AutoTpl["Step2.Listadd"],
  597. AutoTpl["Step2.Listadds"],
  598. AutoTpl["Step2.BlockChooser"],
  599. AutoTpl["Step2.AddressChooser"],
  600. AutoTpl["Step2.TitleChooser"],
  601. AutoTpl["Step2.DateChooser"],
  602. AutoTpl["Step2.DateFormat"],
  603. }
  604. content := []interface{}{
  605. AutoTpl["Step3.ContentChooser"],
  606. AutoTpl["Step3.ElementChooser"],
  607. }
  608. param := map[string]interface{}{}
  609. param["param_common"] = common
  610. //向导模式
  611. param["param_time"] = ptime
  612. param["param_list"] = list
  613. param["param_content"] = content
  614. param["type_time"] = 0
  615. param["type_list"] = 0
  616. param["type_content"] = 0
  617. //专家模式
  618. param["str_time"] = ""
  619. param["str_list"] = ""
  620. param["str_content"] = ""
  621. param["comeintime"] = time.Now().Unix()
  622. param["code"] = o["code"]
  623. param["site"] = o["name"]
  624. param["channel"] = o["channel"]
  625. param["createuser"] = (*one)["s_name"]
  626. param["createuserid"] = id
  627. param["createuseremail"] = (*one)["s_email"]
  628. param["modifyuser"] = (*one)["s_name"]
  629. param["modifyuserid"] = id
  630. param["modifytime"] = time.Now().Unix()
  631. param["state"] = 0 //未完成
  632. if qu.IntAll(o["event"]) > 0 {
  633. param["event"] = qu.IntAll(o["event"])
  634. }
  635. s_model := "bid"
  636. configModel := util.Config.Model[s_model]
  637. model := map[string]interface{}{}
  638. for k, _ := range configModel {
  639. model[k] = qu.ObjToString(o[k])
  640. }
  641. param["model"] = model
  642. param["next"] = o["next"]
  643. param["urgency"] = o["urgency"]
  644. param["isflow"] = o["isflow"]
  645. param["spidertype"] = "history"
  646. historyevent := qu.ObjToString(o["historyevent"])
  647. if movevent, ok := util.Config.Uploadevents[historyevent].(string); ok && movevent != "" {
  648. param["spidermovevent"] = movevent
  649. } else {
  650. param["spidermovevent"] = "7700"
  651. }
  652. param["historyevent"] = qu.IntAll(o["historyevent"])
  653. param["platform"] = o["platform"]
  654. param["weight"] = o["weight"]
  655. //默认字段
  656. param["spidercompete"] = true //2021-11-20后爬虫加此字段(表示新爬虫,剑鱼网站不展示原文)
  657. param["spiderhistorymaxpage"] = 1 //历史最大页
  658. param["pendstate"] = 0 //
  659. param["grade"] = 0 //爬虫难易度(主要用于python爬虫使用)
  660. //qu.Debug("param---", param)
  661. ok := spider.SaveSpider(o["code"].(string), param)
  662. if ok { //保存成功,校验新导入的爬虫对应站点是否存在,否则加站点记录
  663. if u.MgoEB.Count("site", map[string]interface{}{"site": o["name"]}) == 0 {
  664. qu.Debug("补充站点信息:", o["name"])
  665. domain := u.DomainReg.FindString(qu.ObjToString(AutoTpl["Base.SpiderTargetChannelUrl"]))
  666. if domain != "" {
  667. domain = u.ReplaceReg.ReplaceAllString(domain, "")
  668. }
  669. siteInfo := map[string]interface{}{
  670. "site": o["name"],
  671. "domain": domain, //
  672. "another_name": "",
  673. "area": qu.ObjToString(model["area"]),
  674. "city": qu.ObjToString(model["city"]),
  675. "district": qu.ObjToString(model["district"]),
  676. "site_type": "",
  677. "industry": "",
  678. "p_site": "",
  679. "s_site": "",
  680. "remarktime": time.Now().Unix(),
  681. "event": fmt.Sprint(historyevent),
  682. "platform": o["platform"],
  683. "spider_status": "0/1",
  684. "updatetime": time.Now().Unix(),
  685. "delete": false,
  686. "comeintime": time.Now().Unix(),
  687. "important": 0,
  688. }
  689. u.MgoEB.Save("site", siteInfo)
  690. }
  691. }
  692. return ok, (*one)["s_name"].(string)
  693. }
  694. func (f *Front) Importdata() {
  695. auth := qu.IntAll(f.GetSession("auth"))
  696. if auth == role_admin {
  697. if f.Method() == "GET" {
  698. f.Render("import.html")
  699. } else {
  700. rss, _ := u.MgoEB.Find("import", nil, `{"timestamp": -1}`, nil, false, -1, -1)
  701. f.ServeJson(map[string]interface{}{
  702. "data": *rss,
  703. })
  704. }
  705. } else {
  706. f.Write("您没有导入脚本的权限")
  707. }
  708. }
  709. func Wlog(name, code, man, manid, types string, content map[string]interface{}) {
  710. obj := map[string]interface{}{
  711. "name": name,
  712. "code": code,
  713. "man": man,
  714. "manid": manid,
  715. "types": types,
  716. "time": time.Now().Unix(),
  717. "content": content,
  718. }
  719. u.MgoEB.Save("lua_logs", obj)
  720. }
  721. func (f *Front) Oldedit() {
  722. if f.Method() == "GET" {
  723. f.Render("oldedit.html")
  724. } else {
  725. }
  726. }
  727. func (f *Front) FindName() {
  728. words := f.GetString("words")
  729. if words == "" {
  730. f.ServeJson(map[string]interface{}{"error": "null"})
  731. }
  732. //query := bson.M{"$or": []interface{}{
  733. // bson.M{"param_common.0": bson.M{"$regex": words}},
  734. // bson.M{"param_common.1": bson.M{"$regex": words}},
  735. // bson.M{"createuser": bson.M{"$regex": words}},
  736. //}, "oldlua": bson.M{"$exists": false}}
  737. query := map[string]interface{}{
  738. "$or": []interface{}{
  739. map[string]interface{}{"param_common.0": map[string]interface{}{"$regex": words}},
  740. map[string]interface{}{"param_common.1": map[string]interface{}{"$regex": words}},
  741. map[string]interface{}{"createuser": map[string]interface{}{"$regex": words}},
  742. },
  743. "oldlua": map[string]interface{}{
  744. "$exists": false,
  745. },
  746. }
  747. //rs := *mgdb.Find("luaconfig", query, bson.M{"modifytime": -1}, bson.M{"param_common": 1}, false, -1, -1)
  748. rs, _ := u.MgoEB.Find("luaconfig", query, map[string]interface{}{"modifytime": -1}, map[string]interface{}{"param_common": 1}, false, -1, -1)
  749. if len(*rs) > 0 {
  750. f.ServeJson(map[string]interface{}{"data": (*rs)})
  751. } else {
  752. f.ServeJson(map[string]interface{}{"error": "data"})
  753. }
  754. }
  755. //分配爬虫
  756. func (f *Front) Assign() {
  757. auth := qu.IntAll(f.GetSession("auth"))
  758. if auth != role_admin {
  759. f.Write("n")
  760. return
  761. }
  762. codes := f.GetString("codes")
  763. userid := f.GetString("userid") //分配给谁
  764. codesarr := strings.Split(codes, ",") //被分配的爬虫
  765. user, _ := u.MgoEB.FindById("user", userid, nil)
  766. if user != nil && len(*user) > 0 {
  767. name := qu.ObjToString((*user)["s_name"])
  768. query := map[string]interface{}{
  769. "code": map[string]interface{}{
  770. "$in": codesarr,
  771. },
  772. }
  773. qu.Debug(query)
  774. set := map[string]interface{}{
  775. "$set": map[string]interface{}{
  776. "createuserid": userid,
  777. "createuser": name,
  778. "createuseremail": (*user)["s_email"],
  779. "modifyuser": name,
  780. "modifyuserid": userid,
  781. },
  782. }
  783. //b := u.MgoE.Update("luaconfig", query, set, false, true)
  784. b := u.MgoEB.Update("luaconfig", query, set, false, true)
  785. if b {
  786. go editModify(codesarr, userid, name) //修改爬虫对应任务的维护人
  787. f.Write("y")
  788. } else {
  789. f.Write("n")
  790. }
  791. } else {
  792. f.Write("null")
  793. }
  794. }
  795. //修改维护人
  796. func editModify(codesarr []string, userid, name string) {
  797. qu.Debug("修改爬虫对应任务的维护人:", name, codesarr)
  798. //修改modifyid和modify
  799. query := map[string]interface{}{
  800. "s_code": map[string]interface{}{
  801. "$in": codesarr,
  802. },
  803. "i_state": map[string]interface{}{
  804. "$nin": []int{4, 6},
  805. },
  806. }
  807. set := map[string]interface{}{
  808. "$set": map[string]interface{}{
  809. "s_modify": name,
  810. "s_modifyid": userid,
  811. },
  812. }
  813. b := u.MgoEB.Update("task", query, set, false, true)
  814. qu.Debug("任务重新分配成功", b)
  815. }
  816. //清理Redis
  817. func (f *Front) DelRedis() {
  818. hrefs := f.GetString("href")
  819. hrefsarr := strings.Split(hrefs, ",")
  820. auth := qu.IntAll(f.GetSession("auth"))
  821. err := []string{}
  822. if auth == role_admin { //权限控制
  823. if len(hrefsarr) > 0 {
  824. for k1, h := range hrefsarr {
  825. href := Reg.FindString(h)
  826. if href != "" {
  827. href = "url_repeat_" + href + "*"
  828. res := redis.GetKeysByPattern("title_repeat_judgement", href)
  829. if res != nil {
  830. for _, v := range res {
  831. hf := string(v.([]uint8))
  832. b := redis.Del("title_repeat_judgement", hf)
  833. if !b {
  834. err = append(err, "第"+strconv.Itoa(k1+1)+"个")
  835. }
  836. }
  837. }
  838. } else {
  839. err = append(err, "第"+strconv.Itoa(k1+1)+"个")
  840. }
  841. }
  842. }
  843. } else {
  844. err = append(err, "没有权限")
  845. }
  846. f.ServeJson(err)
  847. }
  848. func (f *Front) UpdatePendState() {
  849. success := false
  850. pendstate, _ := f.GetInteger("pendstate")
  851. code := f.GetString("code")
  852. stype := f.GetString("stype")
  853. qu.Debug(code, stype, pendstate)
  854. //success = u.MgoE.Update("luaconfig", map[string]interface{}{"code": code}, map[string]interface{}{"$set": map[string]interface{}{"pendstate": pendstate}}, false, false)
  855. success = u.MgoEB.Update("luaconfig", map[string]interface{}{"code": code}, map[string]interface{}{"$set": map[string]interface{}{"pendstate": pendstate, "pendtime": time.Now().Unix()}}, false, false)
  856. if success {
  857. if stype == "code" { //爬虫挂起时,关闭所有任务
  858. u.MgoEB.Update("task", map[string]interface{}{"s_code": code, "i_state": map[string]interface{}{"$ne": 6}}, map[string]interface{}{"$set": map[string]interface{}{"i_state": 6, "l_pendtime": time.Now().Unix()}}, false, true)
  859. } else if stype == "task" { //任务挂起任务时任务关闭
  860. id := f.GetString("id")
  861. u.MgoEB.UpdateById("task", id, map[string]interface{}{"$set": map[string]interface{}{"i_pendstate": pendstate, "i_state": 6, "l_pendtime": time.Now().Unix()}})
  862. }
  863. }
  864. f.ServeJson(map[string]interface{}{"success": success})
  865. }
  866. func (f *Front) UpdateESP() {
  867. val := f.GetString("val")
  868. w := f.GetString("w")
  869. id := f.GetString("id")
  870. code := f.GetString("c")
  871. query := map[string]interface{}{
  872. "_id": mongodb.StringTOBsonId(id),
  873. }
  874. set := map[string]interface{}{}
  875. update := map[string]interface{}{
  876. "$set": set,
  877. }
  878. //one, _ := u.MgoE.FindById("luaconfig", id, nil)
  879. one, _ := u.MgoEB.FindById("luaconfig", id, nil)
  880. if len(*one) == 0 {
  881. f.Write("n")
  882. return
  883. }
  884. if w == "urgency" { //修改紧急度
  885. urgency, _ := f.GetInteger("val")
  886. set["urgency"] = urgency
  887. } else if w == "state" { //无效爬虫改为待完成
  888. tmpEvent := qu.IntAll((*one)["event"])
  889. if one != nil && len(*one) > 0 {
  890. if (*one)["historyevent"] == nil && tmpEvent != 7000 { //除7000节点外没有historyevent的要重新设置
  891. set["historyevent"] = tmpEvent
  892. }
  893. }
  894. set["state"] = 0
  895. set["event"] = 7000
  896. set["spidertype"] = "history"
  897. //更新、新建任务
  898. task, _ := u.MgoEB.FindOne("task", map[string]interface{}{"s_code": code, "i_state": map[string]interface{}{"$in": []int{0, 1, 2, 3, 5}}})
  899. text := "指定追加描述:------------------------------\n无发布转待完成\n"
  900. if len(*task) > 0 { //已有任务,更新
  901. u.MgoEB.UpdateById("task", (*task)["_id"],
  902. map[string]interface{}{
  903. "$set": map[string]interface{}{
  904. "i_state": 2,
  905. "s_descript": qu.ObjToString((*task)["s_descript"]) + text,
  906. "l_updatetime": time.Now().Unix(),
  907. },
  908. })
  909. } else {
  910. save := map[string]interface{}{
  911. "s_channel": (*one)["channel"],
  912. "i_event": (*one)["event"],
  913. "i_frequencyerrtimes": 0,
  914. "i_state": 2,
  915. "s_descript": text,
  916. "l_complete": time.Now().Unix() + int64(24*3600),
  917. "s_urgency": "4",
  918. "i_pendstate": 0,
  919. "s_modifyid": (*one)["modifyuserid"],
  920. "s_source": "人工",
  921. "i_times": 0,
  922. "l_comeintime": time.Now().Unix(),
  923. "i_num": 0,
  924. "s_modify": (*one)["modifyuser"],
  925. "s_code": code,
  926. "s_site": (*one)["site"],
  927. "s_type": "0",
  928. }
  929. u.MgoEB.Save("task", save)
  930. }
  931. } else if w == "platform" {
  932. set["platform"] = val
  933. set["comeintime"] = time.Now().Unix()
  934. if val != "golua平台" { //由lua平台切换到其他平台,删除心跳;爬虫下架;修改爬虫状态
  935. b := u.MgoS.Update("spider_heart", map[string]interface{}{"code": code}, map[string]interface{}{"$set": map[string]interface{}{"del": true}}, false, true)
  936. qu.Debug("Del Heart:", b)
  937. b, err := spider.UpdateSpiderByCodeState(code, "6", qu.IntAll((*one)["event"])) //下架
  938. if b && err == nil {
  939. //历史节点下架为了避免线上运行爬虫待完成时改为7000采集历史,但是又转到其他平台,导致原线上运行节点爬虫并未下线,心跳异常
  940. if historyevent := (*one)["historyevent"]; historyevent != nil {
  941. b, err = spider.UpdateSpiderByCodeState(code, "6", qu.IntAll(historyevent))
  942. }
  943. //关闭任务
  944. u.MgoEB.Update("task", map[string]interface{}{"s_code": code, "i_state": map[string]interface{}{"$in": []int{0, 1, 2, 3, 5}}}, map[string]interface{}{"$set": map[string]interface{}{"i_state": 6}}, false, true)
  945. if b && err == nil {
  946. set["state"] = 0 //更新状态
  947. set["luauser"] = map[string]interface{}{
  948. "createuser": (*one)["createuser"],
  949. "createuserid": (*one)["createuserid"],
  950. "createuseremail": (*one)["createuseremail"],
  951. "modifyuser": (*one)["modifyuser"],
  952. "modifyuserid": (*one)["modifyuserid"],
  953. }
  954. } else {
  955. qu.Debug("历史节点下架失败")
  956. f.Write("n")
  957. return
  958. }
  959. } else {
  960. qu.Debug("增量节点下架失败")
  961. f.Write("n")
  962. return
  963. }
  964. //qu.Debug("下架:", upresult, code)
  965. //b, err := UpStateAndUpSpider(code, "", "", "", Sp_state_6) //线上爬虫下架
  966. //qu.Debug("爬虫下架成功:", b)
  967. //if !b || err != nil {
  968. // f.Write("n")
  969. // return
  970. //}
  971. }
  972. } else { //修改节点
  973. event, _ := strconv.Atoi(val)
  974. set["event"] = event
  975. set["historyevent"] = event
  976. //state := f.GetString("s")
  977. //if state == "5" { //已上架状态改为下架
  978. code := f.GetString("c")
  979. set["state"] = 6
  980. b, err := UpStateAndUpSpider(code, "", "", "", Sp_state_6) //线上爬虫下架
  981. qu.Debug("爬虫下架成功:", b)
  982. if !b || err != nil {
  983. f.Write("n")
  984. return
  985. }
  986. //}
  987. }
  988. //if mgdb.Update("luaconfig", query, update, false, false) {
  989. if u.MgoEB.Update("luaconfig", query, update, false, false) {
  990. log.Println("Id:", id, " Update", w, val, "Success")
  991. f.Write("y")
  992. return
  993. } else {
  994. log.Println("Id:", id, " Update", w, val, "Failed")
  995. f.Write("n")
  996. return
  997. }
  998. f.Write("n")
  999. }
  1000. func (f *Front) GetCity() {
  1001. area := f.GetString("area")
  1002. cityArr := []string{}
  1003. cityArr = u.Province[area]
  1004. f.ServeJson(cityArr)
  1005. }
  1006. func (f *Front) SpiderCopy() {
  1007. defer qu.Catch()
  1008. code := f.GetString("code")
  1009. code = strings.TrimSpace(code)
  1010. success := false
  1011. text := ""
  1012. encode := ""
  1013. if code != "" {
  1014. //lua := *mgdb.FindOne("luaconfig", map[string]interface{}{"code": code})
  1015. lua, _ := u.MgoEB.FindOne("luaconfig", map[string]interface{}{"code": code})
  1016. if len(*lua) > 0 {
  1017. codeOld := qu.ObjToString((*lua)["code"])
  1018. codeNew := codeOld + "_bu"
  1019. //luaTmp := *mgdb.FindOne("luaconfig", map[string]interface{}{"code": codeNew})
  1020. luaTmp, _ := u.MgoEB.FindOne("luaconfig", map[string]interface{}{"code": codeNew})
  1021. if len(*luaTmp) > 0 {
  1022. f.ServeJson(map[string]interface{}{"success": false, "text": "已存在补漏爬虫"})
  1023. return
  1024. }
  1025. //u.MgoE.Update("luaconfig", map[string]interface{}{"code": codeOld}, map[string]interface{}{"$set": map[string]interface{}{"relatecode": codeNew}}, false, false)
  1026. u.MgoEB.Update("luaconfig", map[string]interface{}{"code": codeOld}, map[string]interface{}{"$set": map[string]interface{}{"relatecode": codeNew}}, false, false)
  1027. (*lua)["code"] = codeNew
  1028. (*lua)["relatecode"] = codeOld
  1029. if param_common := (*lua)["param_common"].([]interface{}); len(param_common) < 13 {
  1030. f.ServeJson(map[string]interface{}{"success": false, "text": "脚本异常,请联系管理员"})
  1031. return
  1032. } else {
  1033. param_common = param_common[:13]
  1034. param_common[0] = codeNew //code
  1035. param_common = append(param_common, true) //历史补漏
  1036. param_common = append(param_common, false) //强制下载
  1037. (*lua)["param_common"] = param_common
  1038. }
  1039. str_list := qu.ObjToString((*lua)["str_list"])
  1040. (*lua)["str_list"] = strings.ReplaceAll(str_list, codeOld, codeNew)
  1041. (*lua)["comeintime"] = time.Now().Unix()
  1042. (*lua)["modifytime"] = time.Now().Unix()
  1043. (*lua)["spidertype"] = "increment"
  1044. (*lua)["event"] = 7000
  1045. (*lua)["state"] = 6
  1046. id := u.MgoEB.Save("luaconfig", (*lua))
  1047. if id != "" {
  1048. success = true
  1049. encode = util.Se.Encode2Hex(codeNew)
  1050. } else {
  1051. text = "新爬虫保存失败"
  1052. }
  1053. } else {
  1054. text = "未查询到复制原"
  1055. }
  1056. } else {
  1057. text = "脚本不能为空"
  1058. }
  1059. f.ServeJson(map[string]interface{}{"success": success, "text": text, "encode": encode})
  1060. }