merak.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package dao
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/sha1"
  6. "encoding/hex"
  7. "encoding/json"
  8. "net/http"
  9. "sort"
  10. "strings"
  11. "go-common/library/log"
  12. "github.com/pkg/errors"
  13. )
  14. const (
  15. _privateKey = "37ba757817b4e9c45c7e97f6ed5eee4e1c7bac52"
  16. _publicKey = "71f079db59672ecec5b8d6f252c4b59ab2a8a227mainsite@bilibili.com"
  17. )
  18. // MerakNotify send notify
  19. func (d *Dao) MerakNotify(ctx context.Context, title, content string) error {
  20. params := map[string]string{
  21. "Action": "CreateWechatMessage",
  22. "PublicKey": _publicKey,
  23. "UserName": strings.Join(d.c.ReviewNotify.Users, ","),
  24. "Title": title,
  25. "Content": content,
  26. "TreeId": "",
  27. }
  28. sign, err := MerakSign(params)
  29. if err != nil {
  30. log.Error("Failed to sign params: %+v: %+v", params, err)
  31. return err
  32. }
  33. params["Signature"] = sign
  34. b, err := json.Marshal(params)
  35. if err != nil {
  36. return errors.WithStack(err)
  37. }
  38. req, err := http.NewRequest(http.MethodPost, d.merakURL, bytes.NewReader(b))
  39. if err != nil {
  40. return errors.WithStack(err)
  41. }
  42. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  43. res := struct {
  44. Action string `json:"Action"`
  45. RetCode int `json:"RetCode"`
  46. Data []string `json:"Data"`
  47. }{}
  48. if err = d.httpClient.Do(ctx, req, &res); err != nil {
  49. return err
  50. }
  51. if res.RetCode != 0 {
  52. err := errors.Errorf("Merak error: %d", res.RetCode)
  53. log.Error("Failed to send notify by merak with params: %+v: %+v", string(b), err)
  54. return err
  55. }
  56. return nil
  57. }
  58. // MerakSign is
  59. func MerakSign(params map[string]string) (string, error) {
  60. keys := make([]string, 0, len(params))
  61. for k := range params {
  62. keys = append(keys, k)
  63. }
  64. sort.Strings(keys)
  65. buf := bytes.Buffer{}
  66. for _, k := range keys {
  67. buf.WriteString(k + params[k])
  68. }
  69. h := sha1.New()
  70. if _, err := h.Write(buf.Bytes()); err != nil {
  71. return "", errors.WithStack(err)
  72. }
  73. if _, err := h.Write([]byte(_privateKey)); err != nil {
  74. return "", errors.WithStack(err)
  75. }
  76. sum := h.Sum(nil)
  77. return hex.EncodeToString(sum), nil
  78. }