forked from mcuadros/ofelia
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgotify.go
88 lines (70 loc) · 2.26 KB
/
gotify.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
package middlewares
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"github.com/mcuadros/ofelia/core"
)
type GotifyConfig struct {
GotifyWebhook string `gcfg:"gotify-webhook" mapstructure:"gotify-webhook"`
GotifyOnlyOnError bool `gcfg:"gotify-only-on-error" mapstructure:"gotify-only-on-error"`
GotifyPriority int64 `gcfg:"gotify-priority" mapstructure:"gotify-priority"`
}
// NewGotify returns a Gotify middleware if the given configuration is not empty
func NewGotify(c *GotifyConfig) core.Middleware {
var m core.Middleware
if !IsEmpty(c) {
m = &Gotify{*c}
}
return m
}
type Gotify struct {
GotifyConfig
}
// ContinueOnStop return allways true, we want always report the final status
func (m *Gotify) ContinueOnStop() bool {
return true
}
func (m *Gotify) Run(ctx *core.Context) error {
err := ctx.Next()
ctx.Stop(err)
if ctx.Execution.Failed || !m.GotifyOnlyOnError {
m.pushMessage(ctx)
}
return err
}
func (m *Gotify) pushMessage(ctx *core.Context) {
content, _ := json.Marshal(m.buildMessage(ctx))
r, err := http.Post(m.GotifyWebhook, "application/json", bytes.NewReader(content))
if err != nil {
ctx.Logger.Errorf("Gotify error calling %q error: %q", m.GotifyWebhook, err)
} else if r.StatusCode != 200 {
ctx.Logger.Errorf("Gotify error non-200 status code calling %q", m.GotifyWebhook)
}
}
func (m *Gotify) buildMessage(ctx *core.Context) *gotifyMessage {
msg := &gotifyMessage{Title: ctx.Job.GetName(), Priority: m.GotifyPriority, Extras: gotifyMessageExtras{ClientDisplay: gotifyMessageExtrasDisplay{ContentType: "text/markdown"}}}
msg.Message = fmt.Sprintf(
"Job *%q* finished in *%s*, command `%s`",
ctx.Job.GetName(), ctx.Execution.Duration, ctx.Job.GetCommand(),
)
if ctx.Execution.Failed {
msg.Message = "FAILED: " + msg.Message
} else if ctx.Execution.Skipped {
msg.Message = "Skipped: " + msg.Message
}
return msg
}
type gotifyMessage struct {
Title string `json:"title"`
Message string `json:"message"`
Priority int64 `json:"priority"`
Extras gotifyMessageExtras `json:"extras"`
}
type gotifyMessageExtras struct {
ClientDisplay gotifyMessageExtrasDisplay `json:"client::display"`
}
type gotifyMessageExtrasDisplay struct {
ContentType string `json:"contentType"`
}