sendmail.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. package tomail
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "net/http"
  7. "net/smtp"
  8. "qfw/util"
  9. mgdb "qfw/util/mongodb"
  10. sp "spiderutil"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/cron"
  15. "gopkg.in/mgo.v2/bson"
  16. . "gopkg.in/mgo.v2/bson"
  17. )
  18. var Mail map[string]interface{}
  19. func TimeTask() {
  20. defer util.Catch()
  21. c := cron.New()
  22. c.Start()
  23. c.AddFunc("0 20 9 ? * MON-FRI", CheckCreateTask)
  24. c.AddFunc("0 0 */1 ? * *", CheckLuaMove)
  25. c.Start()
  26. }
  27. //监测爬虫由历史转增量时未成功的
  28. func CheckLuaMove() {
  29. defer util.Catch()
  30. util.Debug("开始检测爬虫节点移动...")
  31. query := map[string]interface{}{
  32. "comeintime": map[string]interface{}{
  33. "$gte": time.Now().Add(-(time.Hour * 1)).Unix(),
  34. "$lte": time.Now().Unix(),
  35. },
  36. "ok": false,
  37. }
  38. util.Debug("query:", query)
  39. list := *mgdb.Find("luamovelog", query, nil, nil, false, -1, -1)
  40. text := ""
  41. if len(list) > 0 {
  42. for _, l := range list {
  43. stype := util.ObjToString(l["type"])
  44. code := util.ObjToString(l["code"])
  45. text += code + ":" + stype + ";"
  46. }
  47. }
  48. if text != "" {
  49. for i := 1; i <= 3; i++ {
  50. res, err := http.Get(fmt.Sprintf("%s?to=%s&title=%s&body=%s", sp.Config.JkMail["api"], sp.Config.JkMail["to"], "lua-move-fail", text))
  51. if err == nil {
  52. res.Body.Close()
  53. read, err := ioutil.ReadAll(res.Body)
  54. util.Debug("邮件发送:", string(read), err)
  55. break
  56. }
  57. }
  58. }
  59. }
  60. //检测创建任务失败的爬虫
  61. func CheckCreateTask() {
  62. defer util.Catch()
  63. util.Debug("开始检测任务创建...")
  64. query := map[string]interface{}{
  65. "comeintime": map[string]interface{}{
  66. "$gte": GetTime(0),
  67. },
  68. }
  69. codes := []string{}
  70. list := *mgdb.Find("luacreatetaskerr", query, nil, nil, false, -1, -1)
  71. if len(list) > 0 {
  72. for _, l := range list {
  73. code := util.ObjToString(l["code"])
  74. codes = append(codes, code)
  75. }
  76. }
  77. if len(codes) > 0 {
  78. for i := 1; i <= 3; i++ {
  79. res, err := http.Get(fmt.Sprintf("%s?to=%s&title=%s&body=%s", sp.Config.JkMail["api"], sp.Config.JkMail["to"], "lua-createtask-err", "爬虫:"+strings.Join(codes, ";")))
  80. if err == nil {
  81. res.Body.Close()
  82. read, err := ioutil.ReadAll(res.Body)
  83. util.Debug("邮件发送:", string(read), err)
  84. break
  85. }
  86. }
  87. }
  88. }
  89. func SendToMail() {
  90. mailInfo := *(util.ObjToMap(Mail["smtp"]))
  91. host := mailInfo["host"].(string)
  92. from := mailInfo["from"].(string)
  93. pwd := mailInfo["password"].(string)
  94. subject := mailInfo["subject"].(string)
  95. hour := time.Now().Hour()
  96. if hour == 8 {
  97. //定时查询数据库 查询需要发邮件的人和相关信息
  98. timeStr := time.Now().Format("2006-01-02")
  99. the_time, _ := time.ParseInLocation("2006-01-02", timeStr, time.Local)
  100. time_zero := the_time.Unix() //当日凌晨的时间戳
  101. time_twentyFour := time_zero + 86399 //当日24时的时间戳
  102. //聚合查询数据
  103. //mgdb.InitMongodbPool(5, "192.168.3.207:27080", "editor")
  104. sess := mgdb.GetMgoConn()
  105. defer mgdb.DestoryMongoConn(sess)
  106. var res []M
  107. sess.DB("editor").C("task").Pipe([]M{M{"$match": M{"l_complete": M{"$gte": time_zero, "$lte": time_twentyFour}, "i_state": M{"$gte": 1, "$lte": 2}}},
  108. M{"$group": M{"_id": "$s_modifyid", "count": M{"$sum": 1}}}}).All(&res)
  109. //遍历数据进行发邮件
  110. for _, v := range res {
  111. _id, ok := v["_id"].(string)
  112. if ok {
  113. query := bson.M{
  114. "_id": bson.ObjectIdHex(_id),
  115. }
  116. user := *mgdb.FindOne("user", query)
  117. if user["s_email"] == nil {
  118. continue
  119. }
  120. num := strconv.Itoa(v["count"].(int))
  121. body := `<html><body><h3>你有` + num + `条任务需要今天完成</h3></body></html>`
  122. hp := strings.Split(host, ":")
  123. auth := smtp.PlainAuth("", from, pwd, hp[0])
  124. content_type := "Content-Type: text/html; charset=UTF-8"
  125. msg := []byte("To: " + user["s_email"].(string) + "\r\nFrom: " + from + "\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
  126. send_to := strings.Split(user["s_email"].(string), ";")
  127. err := smtp.SendMail(host, auth, from, send_to, msg)
  128. if err == nil {
  129. log.Println(user["s_email"].(string), " sendMail success")
  130. } else {
  131. log.Println(user["s_email"].(string), " sendMail fail")
  132. }
  133. }
  134. }
  135. time.Sleep(1 * time.Hour)
  136. }
  137. //time.AfterFunc(30*time.Minute, func() { SendToMail(to, num) })
  138. time.AfterFunc(30*time.Minute, SendToMail)
  139. }
  140. //获取第day天凌晨的时间戳
  141. func GetTime(day int) int64 {
  142. defer util.Catch()
  143. nowTime := time.Now().AddDate(0, 0, day)
  144. timeStr := util.FormatDate(&nowTime, util.Date_Short_Layout)
  145. t, _ := time.ParseInLocation(util.Date_Short_Layout, timeStr, time.Local)
  146. return t.Unix()
  147. }