|
| 1 | +package zulip |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | + |
| 10 | + gzb "github.com/ifo/gozulipbot" |
| 11 | + "github.com/pkg/errors" |
| 12 | +) |
| 13 | + |
| 14 | +//go:generate mockery --name=zulipClient --output=. --case=underscore --inpackage |
| 15 | +type zulipClient interface { |
| 16 | + Message(gzb.Message) (*http.Response, error) |
| 17 | +} |
| 18 | + |
| 19 | +// Compile-time check to ensure that zulip message client implements the zulipClient interface. |
| 20 | +var _ zulipClient = new(gzb.Bot) |
| 21 | + |
| 22 | +// Zulip struct holds necessary data to communicate with the Zulip API. |
| 23 | +type Zulip struct { |
| 24 | + client zulipClient |
| 25 | + receivers []*Receiver |
| 26 | +} |
| 27 | + |
| 28 | +func New(domain, apiKey, botEmail string) *Zulip { |
| 29 | + client := &gzb.Bot{ |
| 30 | + APIURL: fmt.Sprintf("https://%s.zulipchat.com/api/v1/", domain), |
| 31 | + APIKey: apiKey, |
| 32 | + Email: botEmail, |
| 33 | + } |
| 34 | + |
| 35 | + client.Init() |
| 36 | + |
| 37 | + zulip := &Zulip{ |
| 38 | + client: client, |
| 39 | + receivers: make([]*Receiver, 0), |
| 40 | + } |
| 41 | + |
| 42 | + return zulip |
| 43 | +} |
| 44 | + |
| 45 | +func (z *Zulip) AddReceivers(receivers ...*Receiver) { |
| 46 | + z.receivers = append(z.receivers, receivers...) |
| 47 | +} |
| 48 | + |
| 49 | +func (z *Zulip) Send(ctx context.Context, subject, message string) error { |
| 50 | + fullMessage := subject + "\n" + message // Treating subject as message title |
| 51 | + |
| 52 | + for _, receiver := range z.receivers { |
| 53 | + select { |
| 54 | + case <-ctx.Done(): |
| 55 | + return ctx.Err() |
| 56 | + default: |
| 57 | + emails := make([]string, 0) |
| 58 | + if receiver.email != "" { |
| 59 | + emails = append(emails, receiver.email) |
| 60 | + } |
| 61 | + |
| 62 | + msg := gzb.Message{ |
| 63 | + Content: fullMessage, |
| 64 | + Emails: emails, |
| 65 | + Stream: receiver.stream, |
| 66 | + Topic: receiver.topic, |
| 67 | + } |
| 68 | + |
| 69 | + resp, err := z.client.Message(msg) |
| 70 | + if err != nil { |
| 71 | + return errors.Wrapf(err, "failed to send message to Zulip receiver") |
| 72 | + } |
| 73 | + defer resp.Body.Close() |
| 74 | + body, _ := io.ReadAll(resp.Body) |
| 75 | + |
| 76 | + switch resp.StatusCode { |
| 77 | + case http.StatusBadRequest: |
| 78 | + var errorResp ErrorResponse |
| 79 | + _ = json.Unmarshal(body, &errorResp) |
| 80 | + |
| 81 | + return errors.Errorf("failed to send message to Zulip receiver: %s", errorResp.Message) |
| 82 | + |
| 83 | + case http.StatusOK: |
| 84 | + break |
| 85 | + |
| 86 | + default: |
| 87 | + return errors.Errorf("failed to send message to Zulip receiver: %s", body) |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + return nil |
| 93 | +} |
0 commit comments