client.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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 feishu
  15. import (
  16. "context"
  17. "fmt"
  18. "net/http"
  19. "time"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/pkg/errors"
  22. "yunion.io/x/pkg/util/httputils"
  23. )
  24. const (
  25. // 获取 tenant_access_token(企业自建应用)
  26. ApiTenantAccessTokenInternal = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"
  27. // 获取群列表
  28. ApiChatList = "https://open.feishu.cn/open-apis/chat/v4/list"
  29. // 机器人发送消息
  30. ApiRobotSendMessage = "https://open.feishu.cn/open-apis/message/v4/send/"
  31. // 批量发送消息
  32. ApiRobotBatchSendMessage = "https://open.feishu.cn/open-apis/message/v4/batch_send/"
  33. // 使用手机号或邮箱获取用户ID
  34. ApiFetchUserID = "https://open.feishu.cn/open-apis/user/v1/batch_get_id"
  35. // 使用 webhook 机器人发送消息
  36. ApiWebhookRobotSendMessage = "https://open.feishu.cn/open-apis/bot/hook/"
  37. )
  38. var (
  39. cli = &http.Client{
  40. Transport: httputils.GetTransport(true),
  41. }
  42. ctx = context.Background()
  43. )
  44. func Request(method httputils.THttpMethod, url string, header http.Header, body jsonutils.JSONObject) (jsonutils.JSONObject, error) {
  45. _, resp, err := httputils.JSONRequest(cli, ctx, method, url, header, body, false)
  46. return resp, err
  47. }
  48. func checkErr(resp CommonResponser) error {
  49. if resp.GetCode() != 0 {
  50. return errors.Error(fmt.Sprintf("response error, code: %d, msg: %s", resp.GetCode(), resp.GetMsg()))
  51. }
  52. return nil
  53. }
  54. func unmarshal(resp jsonutils.JSONObject, obj CommonResponser) error {
  55. if err := resp.Unmarshal(obj); err != nil {
  56. return errors.Wrap(err, "unmarshal json")
  57. }
  58. return checkErr(obj)
  59. }
  60. // 获取 tenant_access_token(企业自建应用)https://open.feishu.cn/document/ukTMukTMukTM/uIjNz4iM2MjLyYzM
  61. func GetTenantAccessTokenInternal(appId string, appSecret string) (*TenantAccesstokenResp, error) {
  62. body := jsonutils.NewDict()
  63. body.Add(jsonutils.NewString(appId), "app_id")
  64. body.Add(jsonutils.NewString(appSecret), "app_secret")
  65. ret, err := Request(httputils.POST, ApiTenantAccessTokenInternal, http.Header{}, body)
  66. if err != nil {
  67. return nil, err
  68. }
  69. obj := new(TenantAccesstokenResp)
  70. err = unmarshal(ret, obj)
  71. return obj, err
  72. }
  73. type Tenant struct {
  74. AppId string
  75. AppSecret string
  76. AccessToken string
  77. Cache ICache
  78. }
  79. func BuildTokenHeader(token string) http.Header {
  80. h := http.Header{}
  81. h.Add("Authorization", fmt.Sprintf("Bearer %s", token))
  82. return h
  83. }
  84. func NewTenant(appId, appSecret string) (*Tenant, error) {
  85. t := &Tenant{
  86. AppId: appId,
  87. AppSecret: appSecret,
  88. AccessToken: "",
  89. Cache: nil,
  90. }
  91. t.Cache = NewFileCache(fmt.Sprintf(".%s_auth_file", appId))
  92. err := t.RefreshAccessToken()
  93. return t, err
  94. }
  95. // RefreshAccessToken is to get a valid access token
  96. func (t *Tenant) RefreshAccessToken() error {
  97. var data TenantAccesstoken
  98. err := t.Cache.Get(&data)
  99. if err == nil {
  100. t.AccessToken = data.TenantAccessToken
  101. return nil
  102. }
  103. tokenResp, err := GetTenantAccessTokenInternal(t.AppId, t.AppSecret)
  104. if err == nil {
  105. t.AccessToken = tokenResp.TenantAccessToken
  106. data = tokenResp.TenantAccesstoken
  107. data.Created = time.Now().Unix()
  108. err = t.Cache.Set(&data)
  109. }
  110. return err
  111. }
  112. func (t *Tenant) request(method httputils.THttpMethod, url string, data jsonutils.JSONObject, out CommonResponser) error {
  113. obj, err := Request(method, url, BuildTokenHeader(t.AccessToken), data)
  114. if err != nil {
  115. return err
  116. }
  117. err = unmarshal(obj, out)
  118. return err
  119. }
  120. func (t *Tenant) get(url string, query jsonutils.JSONObject, out CommonResponser) error {
  121. if query != nil {
  122. qs := query.QueryString()
  123. if len(qs) > 0 {
  124. url = fmt.Sprintf("%s?%s", url, qs)
  125. }
  126. }
  127. return t.request(httputils.GET, url, nil, out)
  128. }
  129. func (t *Tenant) post(url string, body jsonutils.JSONObject, out CommonResponser) error {
  130. return t.request(httputils.POST, url, body, out)
  131. }
  132. func (t *Tenant) ChatList(pageSize int, pageToken string) (*GroupListResp, error) {
  133. query := jsonutils.NewDict()
  134. if pageSize > 0 {
  135. query.Add(jsonutils.NewInt(int64(pageSize)), "page_size")
  136. }
  137. if pageToken != "" {
  138. query.Add(jsonutils.NewString(pageToken), "page_token")
  139. }
  140. resp := new(GroupListResp)
  141. err := t.get(ApiChatList, query, resp)
  142. return resp, err
  143. }
  144. func (t *Tenant) SendMessage(msg MsgReq) (*MsgResp, error) {
  145. body := jsonutils.Marshal(msg)
  146. resp := new(MsgResp)
  147. err := t.post(ApiRobotSendMessage, body, resp)
  148. return resp, err
  149. }
  150. // UserIdByMobile query the open id of user by mobile number. https://open.feishu.cn/document/ukTMukTMukTM/uUzMyUjL1MjM14SNzITN
  151. func (t *Tenant) UserIdByMobile(mobile string) (string, error) {
  152. query := jsonutils.NewDict()
  153. query.Set("mobiles", jsonutils.NewString(mobile))
  154. resp := new(UserIDResp)
  155. err := t.get(ApiFetchUserID, query, resp)
  156. if err != nil {
  157. return "", err
  158. }
  159. if len(resp.Data.MobilesNotExist) != 0 {
  160. return "", errors.Wrapf(errors.ErrNotFound, "no such user whose mobile is %s", mobile)
  161. }
  162. list, err := resp.Data.MobileUsers.GetArray(mobile)
  163. if err != nil {
  164. return "", errors.Wrap(err, "jsonutils.JSONObject.GetArray")
  165. }
  166. // len(list) must be positive
  167. return list[0].GetString("open_id")
  168. }
  169. // SendWebhookRobotMessage will send to message to Webhook address.
  170. // Webhook's format: https://open.feishu.cn/open-apis/bot/hook/xxxxxxxxxxxxxxxxxxxxxxxxxxx.
  171. // The hook represents the last part of webhook: 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'.
  172. func SendWebhookRobotMessage(hook string, msg WebhookRobotMsgReq) (*WebhookRobotMsgResp, error) {
  173. url := ApiWebhookRobotSendMessage + hook
  174. obj, err := Request(httputils.POST, url, http.Header{}, jsonutils.Marshal(msg))
  175. if err != nil {
  176. return nil, err
  177. }
  178. resp := new(WebhookRobotMsgResp)
  179. err = obj.Unmarshal(resp)
  180. if err != nil {
  181. return nil, errors.Wrap(err, "unmarshal json")
  182. }
  183. if !resp.Ok {
  184. return resp, fmt.Errorf("response error, msg: %s", resp.Error)
  185. }
  186. return resp, err
  187. }
  188. // BatchSendMessage batch send messages. Doc: https://open.feishu.cn/document/ukTMukTMukTM/ucDO1EjL3gTNx4yN4UTM
  189. func (t *Tenant) BatchSendMessage(msg BatchMsgReq) (*BatchMsgResp, error) {
  190. body := jsonutils.Marshal(msg)
  191. resp := new(BatchMsgResp)
  192. err := t.post(ApiRobotBatchSendMessage, body, resp)
  193. return resp, err
  194. }