robot.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 models
  15. import (
  16. "context"
  17. "fmt"
  18. "strings"
  19. "golang.org/x/text/language"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/log"
  22. "yunion.io/x/pkg/errors"
  23. "yunion.io/x/pkg/tristate"
  24. "yunion.io/x/pkg/utils"
  25. "yunion.io/x/sqlchemy"
  26. "yunion.io/x/onecloud/pkg/apis"
  27. api "yunion.io/x/onecloud/pkg/apis/notify"
  28. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  29. "yunion.io/x/onecloud/pkg/httperrors"
  30. "yunion.io/x/onecloud/pkg/mcclient"
  31. "yunion.io/x/onecloud/pkg/util/stringutils2"
  32. )
  33. type SRobotManager struct {
  34. db.SSharableVirtualResourceBaseManager
  35. db.SEnabledResourceBaseManager
  36. }
  37. var RobotManager *SRobotManager
  38. func init() {
  39. RobotManager = &SRobotManager{
  40. SSharableVirtualResourceBaseManager: db.NewSharableVirtualResourceBaseManager(
  41. SRobot{},
  42. "robots_tbl",
  43. "robot",
  44. "robots",
  45. ),
  46. }
  47. RobotManager.SetVirtualObject(RobotManager)
  48. }
  49. type SRobot struct {
  50. db.SSharableVirtualResourceBase
  51. db.SEnabledResourceBase
  52. Type string `width:"16" nullable:"false" create:"required" get:"user" list:"user" index:"true"`
  53. Address string `nullable:"false" create:"required" update:"user" get:"user" list:"user"`
  54. Lang string `width:"16" nullable:"false" create:"required" update:"user" get:"user" list:"user"`
  55. Header jsonutils.JSONObject `length:"long" charset:"utf8" nullable:"true" list:"user" create:"optional" update:"user"`
  56. Body jsonutils.JSONObject `length:"long" charset:"utf8" nullable:"true" list:"user" create:"optional" update:"user"`
  57. MsgKey string `width:"16" nullable:"true" update:"user" get:"user" list:"user"`
  58. // webhook 签名加密
  59. SecretKey string `width:"128" nullable:"true" update:"user"`
  60. UseTemplate tristate.TriState `default:"false" list:"domain" update:"user" create:"admin_optional"`
  61. }
  62. var RobotList = []string{api.FEISHU_ROBOT, api.DINGTALK_ROBOT, api.WORKWX_ROBOT, api.WEBHOOK, api.WEBHOOK_ROBOT}
  63. func (rm *SRobotManager) ValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, input api.RobotCreateInput) (api.RobotCreateInput, error) {
  64. var err error
  65. input.SharableVirtualResourceCreateInput, err = rm.SSharableVirtualResourceBaseManager.ValidateCreateData(ctx, userCred, ownerId, query, input.SharableVirtualResourceCreateInput)
  66. if err != nil {
  67. return input, errors.Wrap(err, "SSharableVirtualResourceBaseManager.ValidateCreateData")
  68. }
  69. // check type
  70. if !utils.IsInStringArray(fmt.Sprintf("%s-robot", input.Type), GetRobotTypes()) {
  71. return input, httperrors.NewInputParameterError("unkown type %s support: %s", input.Type, GetRobotTypes())
  72. }
  73. // check lang
  74. if input.Lang == "" {
  75. input.Lang = "zh_CN"
  76. }
  77. // check Address
  78. _, err = language.Parse(input.Lang)
  79. if err != nil {
  80. return input, errors.Wrap(err, "unable to validate address")
  81. }
  82. input.SetEnabled()
  83. input.Status = api.ROBOT_STATUS_READY
  84. driver := GetDriver(fmt.Sprintf("%s-robot", input.Type))
  85. err = driver.Send(ctx, api.SendParams{
  86. Receivers: api.SNotifyReceiver{
  87. Contact: input.Address,
  88. DomainId: input.ProjectDomainId,
  89. },
  90. Header: input.Header,
  91. Body: input.Body,
  92. MsgKey: input.MsgKey,
  93. SecretKey: input.SecretKey,
  94. Title: "Validate",
  95. Message: "This is a verification message, please ignore.",
  96. })
  97. if err != nil {
  98. if errors.ErrConnectRefused == errors.Cause(err) {
  99. return input, errors.Wrapf(errors.ErrNotImplemented, "url not allow :%s", err.Error())
  100. }
  101. return input, errors.Wrap(err, "robot validate")
  102. }
  103. return input, nil
  104. }
  105. func (rm *SRobotManager) FetchCustomizeColumns(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, objs []interface{}, fields stringutils2.SSortedStrings, isList bool) []api.RobotDetails {
  106. sRows := rm.SSharableVirtualResourceBaseManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList)
  107. rows := make([]api.RobotDetails, len(objs))
  108. for i := range rows {
  109. rows[i].SharableVirtualResourceDetails = sRows[i]
  110. }
  111. return rows
  112. }
  113. func (rm *SRobotManager) ListItemFilter(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, input api.RobotListInput) (*sqlchemy.SQuery, error) {
  114. q, err := rm.SSharableVirtualResourceBaseManager.ListItemFilter(ctx, q, userCred, input.SharableVirtualResourceListInput)
  115. if err != nil {
  116. return nil, err
  117. }
  118. q, err = rm.SEnabledResourceBaseManager.ListItemFilter(ctx, q, userCred, input.EnabledResourceBaseListInput)
  119. if err != nil {
  120. return nil, err
  121. }
  122. if len(input.Type) > 0 {
  123. q = q.Equals("type", input.Type)
  124. }
  125. if len(input.Lang) > 0 {
  126. q = q.Equals("lang", input.Lang)
  127. }
  128. return q, nil
  129. }
  130. func (r *SRobot) ValidateUpdateData(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input api.RobotUpdateInput) (api.RobotUpdateInput, error) {
  131. var err error
  132. input.SharableVirtualResourceBaseUpdateInput, err = r.SSharableVirtualResourceBase.ValidateUpdateData(ctx, userCred, query, input.SharableVirtualResourceBaseUpdateInput)
  133. if err != nil {
  134. return input, errors.Wrap(err, "SSharableVirtualResourceBase.ValidateUpdateData")
  135. }
  136. // check lang
  137. if len(input.Lang) > 0 {
  138. _, err = language.Parse(input.Lang)
  139. if err != nil {
  140. return input, httperrors.NewInputParameterError("invalid lang %q: %s", input.Lang, err.Error())
  141. }
  142. }
  143. if len(input.Address) > 0 {
  144. // check Address
  145. driver := GetDriver(fmt.Sprintf("%s-robot", r.Type))
  146. err := driver.Send(ctx, api.SendParams{
  147. Header: input.Header,
  148. Body: input.Body,
  149. MsgKey: input.MsgKey,
  150. SecretKey: input.SecretKey,
  151. Title: "Validate",
  152. Message: "This is a verification message, please ignore.",
  153. Receivers: api.SNotifyReceiver{
  154. Contact: input.Address,
  155. },
  156. })
  157. if err != nil {
  158. if errors.ErrConnectRefused == errors.Cause(err) {
  159. return input, errors.Wrapf(errors.ErrNotImplemented, "url not allow :%s", err.Error())
  160. }
  161. return input, errors.Wrap(err, "unable to validate address")
  162. }
  163. }
  164. return input, nil
  165. }
  166. func (r *SRobot) PostUpdate(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) {
  167. db.Update(r, func() error {
  168. header, ok := data.Get("header")
  169. if ok == nil && header.IsZero() {
  170. r.Header = nil
  171. }
  172. body, ok := data.Get("body")
  173. if ok == nil && body.IsZero() {
  174. r.Body = nil
  175. }
  176. return nil
  177. })
  178. }
  179. func (r *SRobot) CustomizeCreate(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data jsonutils.JSONObject) error {
  180. err := r.SSharableVirtualResourceBase.CustomizeCreate(ctx, userCred, ownerId, query, data)
  181. if err != nil {
  182. return err
  183. }
  184. r.Enabled = tristate.True
  185. r.Status = api.ROBOT_STATUS_READY
  186. return nil
  187. }
  188. func (rm *SRobotManager) FetchByIdOrNames(ctx context.Context, idOrNames ...string) ([]SRobot, error) {
  189. if len(idOrNames) == 0 {
  190. return nil, nil
  191. }
  192. var err error
  193. q := idOrNameFilter(rm.Query(), idOrNames...)
  194. robots := make([]SRobot, 0, len(idOrNames))
  195. err = db.FetchModelObjects(rm, q, &robots)
  196. if err != nil {
  197. return nil, err
  198. }
  199. return robots, nil
  200. }
  201. func (r *SRobot) IsEnabled() bool {
  202. return r.Enabled.Bool()
  203. }
  204. func (r *SRobot) IsEnabledContactType(ctype string) (bool, error) {
  205. return strings.Contains(ctype, api.ROBOT) || ctype == api.WEBHOOK, nil
  206. }
  207. func (r *SRobot) IsVerifiedContactType(ctype string) (bool, error) {
  208. return utils.IsInStringArray(ctype, RobotList), nil
  209. }
  210. func (r *SRobot) IsRobot() bool {
  211. return true
  212. }
  213. func (r *SRobot) IsReceiver() bool {
  214. return false
  215. }
  216. func (r *SRobot) GetContact(ctype string) (string, error) {
  217. return r.Address, nil
  218. }
  219. func (r *SRobot) GetTemplateLang(ctx context.Context) (string, error) {
  220. lang, err := language.Parse(r.Lang)
  221. if err != nil {
  222. return "", errors.Wrapf(err, "unable to prase language %q", r.Lang)
  223. }
  224. tLang := notifyclientI18nTable.LookupByLang(lang, tempalteLang)
  225. return tLang, nil
  226. }
  227. func (r *SRobot) GetDomainId() string {
  228. return r.DomainId
  229. }
  230. func (r *SRobot) PerformEnable(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input apis.PerformEnableInput) (jsonutils.JSONObject, error) {
  231. err := db.EnabledPerformEnable(r, ctx, userCred, true)
  232. if err != nil {
  233. return nil, errors.Wrap(err, "EnabledPerformEnable")
  234. }
  235. return nil, nil
  236. }
  237. func (r *SRobot) PerformDisable(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input apis.PerformDisableInput) (jsonutils.JSONObject, error) {
  238. err := db.EnabledPerformEnable(r, ctx, userCred, false)
  239. if err != nil {
  240. return nil, errors.Wrap(err, "EnabledPerformEnable")
  241. }
  242. return nil, nil
  243. }
  244. func (r *SRobot) PostDelete(ctx context.Context, userCred mcclient.TokenCredential) {
  245. q := SubscriberManager.Query().Equals("type", api.SUBSCRIBER_TYPE_ROBOT).Equals("identification", r.GetId())
  246. subscribers := make([]SSubscriber, 0, 2)
  247. err := db.FetchModelObjects(SubscriberManager, q, &subscribers)
  248. if err != nil {
  249. log.Errorf("unable to fetch subscribers with robot %q", r.GetId())
  250. return
  251. }
  252. for i := range subscribers {
  253. subscriber := &subscribers[i]
  254. _, err := db.Update(r, func() error {
  255. return subscriber.MarkDelete()
  256. })
  257. if err != nil {
  258. log.Errorf("unable to delete subscriber %q because of deleting of robot %q", subscribers[i].GetId(), r.GetId())
  259. }
  260. }
  261. }
  262. func GetRobotTypeById(id string) (string, error) {
  263. imode, err := RobotManager.FetchById(id)
  264. if err != nil {
  265. return "", errors.Wrap(err, "FetchById")
  266. }
  267. log.Infoln("this is robot:", jsonutils.Marshal(imode))
  268. robot := imode.(*SRobot)
  269. return robot.Type, nil
  270. }
  271. func (r *SRobot) GetName() string {
  272. return r.Name
  273. }