dingtalk.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package sender
  15. import (
  16. "context"
  17. "fmt"
  18. "net/url"
  19. "strings"
  20. "time"
  21. "yunion.io/x/jsonutils"
  22. "yunion.io/x/pkg/errors"
  23. "yunion.io/x/pkg/util/httputils"
  24. api "yunion.io/x/onecloud/pkg/apis/notify"
  25. "yunion.io/x/onecloud/pkg/notify/models"
  26. )
  27. type SDingTalkSender struct {
  28. config map[string]api.SNotifyConfigContent
  29. }
  30. func (dingSender *SDingTalkSender) GetSenderType() string {
  31. return api.DINGTALK
  32. }
  33. func (dingSender *SDingTalkSender) Send(ctx context.Context, args api.SendParams) error {
  34. body := map[string]interface{}{
  35. "agent_id": models.ConfigMap[fmt.Sprintf("%s-%s", api.DINGTALK, args.DomainId)].Content.AgentId,
  36. "msg": map[string]interface{}{
  37. "msgtype": "markdown",
  38. "markdown": map[string]interface{}{
  39. "title": args.Title,
  40. "text": fmt.Sprintf("%s (%s)", args.Message, time.Now().Format("2006-01-02 15:04")),
  41. },
  42. },
  43. "userid_list": args.Receivers.Contact,
  44. }
  45. params := url.Values{}
  46. params.Set("access_token", models.ConfigMap[fmt.Sprintf("%s-%s", api.DINGTALK, args.DomainId)].Content.AccessToken)
  47. req, err := sendRequest(ctx, ApiDingtalkSendMessage, httputils.POST, nil, params, jsonutils.Marshal(body))
  48. if err != nil {
  49. subCode, _ := req.GetString("sub_code")
  50. switch subCode {
  51. // token失效或不合法
  52. case "40014":
  53. // 尝试重新获取token
  54. err = dingSender.GetAccessToken(ctx, fmt.Sprintf("%s-%s", api.DINGTALK, args.DomainId))
  55. if err != nil {
  56. return errors.Wrap(err, "reset token")
  57. }
  58. // 重新发送通知
  59. params = url.Values{}
  60. params.Set("access_token", models.ConfigMap[fmt.Sprintf("%s-%s", api.DINGTALK, args.DomainId)].Content.AccessToken)
  61. req, err = sendRequest(ctx, ApiDingtalkSendMessage, httputils.POST, nil, params, jsonutils.Marshal(body))
  62. if err != nil {
  63. return errors.Wrap(err, "dingtalk resend message")
  64. }
  65. }
  66. if err != nil {
  67. return errors.Wrap(err, "dingtalk send message")
  68. }
  69. }
  70. // 获取消息通知发送结果
  71. task_id, _ := req.GetString("task_id")
  72. body = map[string]interface{}{
  73. "agent_id": models.ConfigMap[fmt.Sprintf("%s-%s", api.DINGTALK, args.DomainId)].Content.AgentId,
  74. "task_id": task_id,
  75. }
  76. _, err = sendRequest(ctx, ApiDingtalkSendMessage, httputils.POST, nil, params, jsonutils.Marshal(body))
  77. return err
  78. }
  79. func (dingSender *SDingTalkSender) ValidateConfig(ctx context.Context, config api.NotifyConfig) (string, error) {
  80. // 校验accesstoken
  81. _, err := dingSender.getAccessToken(ctx, config.AppKey, config.AppSecret)
  82. if err != nil {
  83. if strings.Contains(err.Error(), "40089") {
  84. return "invalid AppKey or AppSecret", err
  85. }
  86. return "", err
  87. }
  88. return "", nil
  89. }
  90. func (dingSender *SDingTalkSender) ContactByMobile(ctx context.Context, mobile, domainId string) (string, error) {
  91. err := dingSender.GetAccessToken(ctx, domainId)
  92. if err != nil {
  93. return "", err
  94. }
  95. body := jsonutils.Marshal(map[string]interface{}{
  96. "mobile": mobile,
  97. })
  98. params := url.Values{}
  99. params.Set("access_token", models.ConfigMap[fmt.Sprintf("%s-%s", api.DINGTALK, domainId)].Content.AccessToken)
  100. res, err := sendRequest(ctx, ApiDingtalkGetUserByMobile, httputils.POST, nil, params, body)
  101. if err != nil {
  102. return "", errors.Wrap(err, "get user by mobile")
  103. }
  104. userId, err := res.GetString("result", "userid")
  105. if err != nil {
  106. return "", errors.Wrapf(err, "user result:%v", res)
  107. }
  108. return userId, err
  109. }
  110. func (dingSender *SDingTalkSender) IsPersonal() bool {
  111. return true
  112. }
  113. func (dingSender *SDingTalkSender) IsRobot() bool {
  114. return false
  115. }
  116. func (dingSender *SDingTalkSender) IsValid() bool {
  117. return len(dingSender.config) > 0
  118. }
  119. func (dingSender *SDingTalkSender) IsPullType() bool {
  120. return true
  121. }
  122. func (dingSender *SDingTalkSender) IsSystemConfigContactType() bool {
  123. return true
  124. }
  125. func (dingSender *SDingTalkSender) RegisterConfig(config models.SConfig) {
  126. models.ConfigMap[fmt.Sprintf("%s-%s", config.Type, config.DomainId)] = config
  127. }
  128. func (dingSender *SDingTalkSender) GetAccessToken(ctx context.Context, domainId string) error {
  129. key := fmt.Sprintf("%s-%s", api.DINGTALK, domainId)
  130. if _, ok := models.ConfigMap[key]; !ok {
  131. return errors.Wrapf(errors.ErrNotSupported, "contact-type:%s,domain_id:%s is missing config", api.DINGTALK, domainId)
  132. }
  133. appKey, appSecret := models.ConfigMap[key].Content.AppKey, models.ConfigMap[key].Content.AppSecret
  134. token, err := dingSender.getAccessToken(ctx, appKey, appSecret)
  135. if err != nil {
  136. return errors.Wrap(err, "dingtalk getAccessToken")
  137. }
  138. models.ConfigMap[key].Content.AccessToken = token
  139. return nil
  140. }
  141. func (dingSender *SDingTalkSender) getAccessToken(ctx context.Context, appKey, appSecret string) (string, error) {
  142. params := url.Values{}
  143. params.Set("appkey", appKey)
  144. params.Set("appsecret", appSecret)
  145. res, err := sendRequest(ctx, ApiDingtalkGetToken, httputils.GET, nil, params, nil)
  146. if err != nil {
  147. return "", errors.Wrap(err, "get dingtalk token")
  148. }
  149. return res.GetString("access_token")
  150. }
  151. func init() {
  152. models.Register(&SDingTalkSender{
  153. config: map[string]api.SNotifyConfigContent{},
  154. })
  155. }