front.go 27 KB

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