p_hasher.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package backends
  2. import (
  3. "crypto/md5"
  4. "fmt"
  5. "io"
  6. "strings"
  7. "time"
  8. "github.com/flashmob/go-guerrilla/mail"
  9. )
  10. // ----------------------------------------------------------------------------------
  11. // Processor Name: hasher
  12. // ----------------------------------------------------------------------------------
  13. // Description : Generates a unique md5 checksum id for an email
  14. // ----------------------------------------------------------------------------------
  15. // Config Options: None
  16. // --------------:-------------------------------------------------------------------
  17. // Input : e.MailFrom, e.Subject, e.RcptTo
  18. // : assuming e.Subject was generated by "headersparser" processor
  19. // ----------------------------------------------------------------------------------
  20. // Output : Checksum stored in e.Hash
  21. // ----------------------------------------------------------------------------------
  22. func init() {
  23. processors["hasher"] = func() Decorator {
  24. return Hasher()
  25. }
  26. }
  27. // The hasher decorator computes a hash of the email for each recipient
  28. // It appends the hashes to envelope's Hashes slice.
  29. func Hasher() Decorator {
  30. return func(p Processor) Processor {
  31. return ProcessWith(func(e *mail.Envelope, task SelectTask) (Result, error) {
  32. if task == TaskSaveMail {
  33. // base hash, use subject from and timestamp-nano
  34. h := md5.New()
  35. ts := fmt.Sprintf("%d", time.Now().UnixNano())
  36. io.Copy(h, strings.NewReader(e.MailFrom.String()))
  37. io.Copy(h, strings.NewReader(e.Subject))
  38. io.Copy(h, strings.NewReader(ts))
  39. // using the base hash, calculate a unique hash for each recipient
  40. for i := range e.RcptTo {
  41. h2 := h
  42. io.Copy(h2, strings.NewReader(e.RcptTo[i].String()))
  43. sum := h2.Sum([]byte{})
  44. e.Hashes = append(e.Hashes, fmt.Sprintf("%x", sum))
  45. }
  46. return p.Process(e, task)
  47. } else {
  48. return p.Process(e, task)
  49. }
  50. })
  51. }
  52. }