-
Notifications
You must be signed in to change notification settings - Fork 469
/
SlackNotificationService.go
294 lines (273 loc) · 10.3 KB
/
SlackNotificationService.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
/*
* Copyright (c) 2020 Devtron Labs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package notifier
import (
"encoding/json"
"fmt"
"github.com/devtron-labs/devtron/internal/sql/repository"
"github.com/devtron-labs/devtron/internal/util"
"github.com/devtron-labs/devtron/pkg/sql"
"github.com/devtron-labs/devtron/pkg/team"
repository2 "github.com/devtron-labs/devtron/pkg/user/repository"
util2 "github.com/devtron-labs/devtron/util/event"
"github.com/go-pg/pg"
"go.uber.org/zap"
"strings"
"time"
)
const SLACK_CONFIG_TYPE = "slack"
type SlackNotificationService interface {
SaveOrEditNotificationConfig(channelReq []SlackConfigDto, userId int32) ([]int, error)
FetchSlackNotificationConfigById(id int) (*SlackConfigDto, error)
FetchAllSlackNotificationConfig() ([]*SlackConfigDto, error)
FetchAllSlackNotificationConfigAutocomplete() ([]*NotificationChannelAutoResponse, error)
RecipientListingSuggestion(value string) ([]*NotificationRecipientListingResponse, error)
DeleteNotificationConfig(deleteReq *SlackConfigDto, userId int32) error
}
type SlackNotificationServiceImpl struct {
logger *zap.SugaredLogger
teamService team.TeamService
slackRepository repository.SlackNotificationRepository
userRepository repository2.UserRepository
notificationSettingsRepository repository.NotificationSettingsRepository
}
type SlackChannelConfig struct {
Channel util2.Channel `json:"channel" validate:"required"`
SlackConfigDtos []SlackConfigDto `json:"configs"`
}
type SlackConfigDto struct {
OwnerId int32 `json:"userId" validate:"number"`
TeamId int `json:"teamId" validate:"required"`
WebhookUrl string `json:"webhookUrl" validate:"required"`
ConfigName string `json:"configName" validate:"required"`
Description string `json:"description"`
Id int `json:"id" validate:"number"`
}
func NewSlackNotificationServiceImpl(logger *zap.SugaredLogger, slackRepository repository.SlackNotificationRepository, teamService team.TeamService,
userRepository repository2.UserRepository, notificationSettingsRepository repository.NotificationSettingsRepository) *SlackNotificationServiceImpl {
return &SlackNotificationServiceImpl{
logger: logger,
teamService: teamService,
slackRepository: slackRepository,
userRepository: userRepository,
notificationSettingsRepository: notificationSettingsRepository,
}
}
func (impl *SlackNotificationServiceImpl) SaveOrEditNotificationConfig(channelReq []SlackConfigDto, userId int32) ([]int, error) {
var responseIds []int
slackConfigs := buildSlackNewConfigs(channelReq, userId)
for _, config := range slackConfigs {
if config.Id != 0 {
model, err := impl.slackRepository.FindOne(config.Id)
if err != nil && !util.IsErrNoRows(err) {
impl.logger.Errorw("err while fetching slack config", "err", err)
return []int{}, err
}
impl.buildConfigUpdateModel(config, model, userId)
model, uErr := impl.slackRepository.UpdateSlackConfig(model)
if uErr != nil {
impl.logger.Errorw("err while updating slack config", "err", err)
return []int{}, uErr
}
} else {
_, iErr := impl.slackRepository.SaveSlackConfig(config)
if iErr != nil {
impl.logger.Errorw("err while inserting slack config", "err", iErr)
return []int{}, iErr
}
}
responseIds = append(responseIds, config.Id)
}
return responseIds, nil
}
func (impl *SlackNotificationServiceImpl) FetchSlackNotificationConfigById(id int) (*SlackConfigDto, error) {
slackConfig, err := impl.slackRepository.FindOne(id)
if err != nil && !util.IsErrNoRows(err) {
impl.logger.Errorw("cannot find all slack config", "err", err)
return nil, err
}
slackConfigDto := impl.adaptSlackConfig(*slackConfig)
return &slackConfigDto, nil
}
func (impl *SlackNotificationServiceImpl) FetchAllSlackNotificationConfig() ([]*SlackConfigDto, error) {
var responseDto []*SlackConfigDto
slackConfigs, err := impl.slackRepository.FindAll()
if err != nil && !util.IsErrNoRows(err) {
impl.logger.Errorw("cannot find all slack config", "err", err)
return []*SlackConfigDto{}, err
}
for _, slackConfig := range slackConfigs {
slackConfigDto := impl.adaptSlackConfig(slackConfig)
responseDto = append(responseDto, &slackConfigDto)
}
if responseDto == nil {
responseDto = make([]*SlackConfigDto, 0)
}
return responseDto, nil
}
func (impl *SlackNotificationServiceImpl) FetchAllSlackNotificationConfigAutocomplete() ([]*NotificationChannelAutoResponse, error) {
var responseDto []*NotificationChannelAutoResponse
slackConfigs, err := impl.slackRepository.FindAll()
if err != nil && !util.IsErrNoRows(err) {
impl.logger.Errorw("cannot find all slack config", "err", err)
return []*NotificationChannelAutoResponse{}, err
}
for _, slackConfig := range slackConfigs {
slackConfigDto := &NotificationChannelAutoResponse{
Id: slackConfig.Id,
ConfigName: slackConfig.ConfigName,
TeamId: slackConfig.TeamId,
}
responseDto = append(responseDto, slackConfigDto)
}
return responseDto, nil
}
func (impl *SlackNotificationServiceImpl) adaptSlackConfig(slackConfig repository.SlackConfig) SlackConfigDto {
slackConfigDto := SlackConfigDto{
OwnerId: slackConfig.OwnerId,
TeamId: slackConfig.TeamId,
WebhookUrl: slackConfig.WebHookUrl,
ConfigName: slackConfig.ConfigName,
Description: slackConfig.Description,
Id: slackConfig.Id,
}
return slackConfigDto
}
func buildSlackNewConfigs(slackReq []SlackConfigDto, userId int32) []*repository.SlackConfig {
var slackConfigs []*repository.SlackConfig
for _, c := range slackReq {
slackConfig := &repository.SlackConfig{
Id: c.Id,
ConfigName: c.ConfigName,
WebHookUrl: c.WebhookUrl,
Description: c.Description,
AuditLog: sql.AuditLog{
CreatedBy: userId,
CreatedOn: time.Now(),
UpdatedOn: time.Now(),
UpdatedBy: userId,
},
}
if c.TeamId != 0 {
slackConfig.TeamId = c.TeamId
} else {
slackConfig.OwnerId = userId
}
slackConfigs = append(slackConfigs, slackConfig)
}
return slackConfigs
}
func (impl *SlackNotificationServiceImpl) buildConfigUpdateModel(slackConfig *repository.SlackConfig, model *repository.SlackConfig, userId int32) {
model.WebHookUrl = slackConfig.WebHookUrl
model.ConfigName = slackConfig.ConfigName
model.Description = slackConfig.Description
if slackConfig.TeamId != 0 {
model.TeamId = slackConfig.TeamId
} else {
model.OwnerId = slackConfig.OwnerId
}
model.UpdatedOn = time.Now()
model.UpdatedBy = userId
}
func (impl *SlackNotificationServiceImpl) RecipientListingSuggestion(value string) ([]*NotificationRecipientListingResponse, error) {
var results []*NotificationRecipientListingResponse
sesConfigs, err := impl.slackRepository.FindByName(value)
if err != nil && !util.IsErrNoRows(err) {
impl.logger.Errorw("cannot find all slack config", "err", err)
return []*NotificationRecipientListingResponse{}, err
}
for _, sesConfig := range sesConfigs {
result := &NotificationRecipientListingResponse{
ConfigId: sesConfig.Id,
Recipient: sesConfig.ConfigName,
Dest: util2.Slack}
results = append(results, result)
}
userList, err := impl.userRepository.FetchUserMatchesByEmailIdExcludingApiTokenUser(value)
if err != nil && !util.IsErrNoRows(err) {
impl.logger.Errorw("cannot find all slack config", "err", err)
return []*NotificationRecipientListingResponse{}, err
}
for _, item := range userList {
result := &NotificationRecipientListingResponse{
ConfigId: int(item.Id),
Recipient: item.EmailId,
Dest: util2.SES}
results = append(results, result)
}
nsv, err := impl.notificationSettingsRepository.FindAll(0, 20)
if err != nil && !util.IsErrNoRows(err) {
impl.logger.Errorw("cannot find all slack config", "error", err)
return []*NotificationRecipientListingResponse{}, err
}
for _, item := range nsv {
var dat map[string]interface{}
if err := json.Unmarshal([]byte(item.Config), &dat); err != nil {
impl.logger.Errorw("Unmarshal error", "error", err)
return []*NotificationRecipientListingResponse{}, err
}
providers := dat["providers"]
if providers != nil {
data := providers.([]interface{})
for _, item := range data {
if item != nil {
for k, v := range item.(map[string]interface{}) {
if v != nil && len(value) > 0 {
if k == "recipient" && strings.Contains(v.(string), value) {
result := &NotificationRecipientListingResponse{
Recipient: v.(string),
}
if strings.Contains(v.(string), "https://") {
result.Dest = util2.Slack
} else {
result.Dest = util2.SES
}
results = append(results, result)
}
}
}
}
}
}
}
return results, nil
}
func (impl *SlackNotificationServiceImpl) DeleteNotificationConfig(deleteReq *SlackConfigDto, userId int32) error {
existingConfig, err := impl.slackRepository.FindOne(deleteReq.Id)
if err != nil {
impl.logger.Errorw("No matching entry found for delete", "err", err, "id", deleteReq.Id)
return err
}
notifications, err := impl.notificationSettingsRepository.FindNotificationSettingsByConfigIdAndConfigType(deleteReq.Id, SLACK_CONFIG_TYPE)
if err != nil && err != pg.ErrNoRows {
impl.logger.Errorw("error in deleting slack config", "config", deleteReq)
return err
}
if len(notifications) > 0 {
impl.logger.Errorw("found notifications using this config, cannot delete", "config", deleteReq)
return fmt.Errorf(" Please delete all notifications using this config before deleting")
}
existingConfig.UpdatedOn = time.Now()
existingConfig.UpdatedBy = userId
//deleting slack config
err = impl.slackRepository.MarkSlackConfigDeleted(existingConfig)
if err != nil {
impl.logger.Errorw("error in deleting slack config", "err", err, "id", existingConfig.Id)
return err
}
return nil
}