Documentation
¶
Overview ¶
Package hooks runs webhook HTTP posts and command hooks.
Index ¶
- Constants
- Variables
- func BuiltinWebhookTemplate(name string) (string, bool)
- func CountAll(hooks []*Config) (uint, uint)
- func DefaultContentType(name, rawURL string) string
- func Fire(ctx context.Context, hook *Config, payload *Payload) (string, error)
- func LogEvents(events []extract.Status) string
- func NormalizeNotifiarr(hook *Config)
- func PrepareSample(payload *Payload, event extract.Status) error
- func RedactHeaderSecrets(headers map[string]string)
- func SecretHeaderName(name string) bool
- func SendWithLog(log Logger, hook *Config, payload *Payload) error
- func ValidateCmdhooks(list []*Config, defaultTimeout time.Duration, expandHome func(string) string) error
- func ValidateHeaders(headers map[string]string) error
- func ValidateWebhooks(list []*Config, defaultTimeout time.Duration) error
- func WebhookTemplateFileName(name string) string
- type Config
- type HeaderMap
- type Item
- type Logger
- type Payload
- type Profile
- type Statuses
- type StringSlice
- type Worker
- type XtractPayload
Constants ¶
const ( ProfileNotifiarr = "notifiarr" ProfileDiscord = "discord" ProfileTelegram = "telegram" ProfileSlack = "slack" ProfilePushover = "pushover" ProfileGotify = "gotify" ProfileNtfy = "ntfy" ProfileApprise = "apprise" ProfileMattermost = "mattermost" ProfileCustom = "custom" )
Built-in webhook template names. Unknown URLs resolve to notifiarr.
const HeaderAPIKey = "X-Api-Key" //nolint:gosec // HTTP header name, not a secret
HeaderAPIKey is the Notifiarr client API key request header.
const WebhookTemplateApprise = `{
"title": {{encode (print (or (nickname) "Unpackerr") ": " .Title)}},
"body": "**App**: {{rawencode .App}} \n` +
`**Name**: {{rawencode (index .IDs "title")}} \n**Path**: {{rawencode .Path -}}
{{ if .Data }}{{ if .Data.Elapsed.Duration }} \n**Elapsed**: {{.Data.Elapsed}}{{end -}}
{{ if .Data.Archives }} \n**Archives**: {{len .Data.Archives}}{{end -}}
{{ if .Data.Files }} \n**Files**: {{len .Data.Files}}{{end -}}
{{ if .Data.Bytes }} \n**Size**: {{humanbytes .Data.Bytes}}{{end -}}
{{ if and (gt .Event 1) (lt .Event 5) }} \n**Queue**: {{.Data.Queue}}{{end -}}
{{ if .Data.Error}} \n**ERROR**: {{rawencode .Data.Error}}{{end}}{{end}}",
"type": {{ if or (eq 3 .Event) (eq 7 .Event) }}"failure"` +
`{{ else if or (eq 4 .Event) (eq 5 .Event) (eq 8 .Event) }}"success"{{ else }}"info"{{ end }}
}
`
WebhookTemplateApprise POSTs {title, body, type} at apprise-api /notify.
const WebhookTemplateDiscord = `` /* 1663-byte string literal not displayed */
WebhookTemplateDiscord is used when sending a webhook to discord.com.
const WebhookTemplateGotify = `{
"title": {{encode (print (or (nickname) "Unpackerr") ": " .Title)}},
"message": "**App**: {{rawencode .App}} \n` +
`**Name**: {{rawencode (index .IDs "title")}} \n**Path**: {{rawencode .Path -}}
{{ if .Data.Elapsed.Duration }} \n**Elapsed**: {{.Data.Elapsed}}{{end -}}
{{ if .Data.Archives }} \n**RARs**: {{len .Data.Archives}}{{end -}}
{{ if .Data.Files }} \n**Files**: {{len .Data.Files}}{{end -}}
{{ if .Data.Bytes }} \n**Bytes**: {{humanbytes .Data.Bytes}}{{end -}}
{{ if and (gt .Event 1) (lt .Event 5) }} \n**Queue**: {{.Data.Queue}}{{end -}}
{{ if .Data.Error}} \n**ERROR**:\n~~~\n{{rawencode .Data.Error}}\n~~~{{end}}",
"extras": {
"client::display": {
"contentType": "text/markdown"
},
"client::notification": {
"click": {
"url": ""
},
"bigImageUrl": ""
}
}
}
`
const WebhookTemplateMattermost = `{
"username": {{encode (nickname)}},
{{if channel}}"channel": {{encode (channel)}},{{end}}
"icon_url": "https://unpackerr.zip/img/icon.png",
"text": "#### Unpackerr: {{rawencode .Title}} \n` +
`**{{rawencode (index .IDs "title")}}** \n*App*: {{rawencode .App}} \n*Path*: {{rawencode .Path -}}
{{ if .Data }}{{ if .Data.Elapsed.Duration }} \n*Elapsed*: {{.Data.Elapsed}}{{end -}}
{{ if .Data.Archives }} \n*Archives*: {{len .Data.Archives}}{{end -}}
{{ if .Data.Files }} \n*Files*: {{len .Data.Files}}{{end -}}
{{ if .Data.Bytes }} \n*Size*: {{humanbytes .Data.Bytes}}{{end -}}
{{ if and (gt .Event 1) (lt .Event 5) }} \n*Queue*: {{.Data.Queue}}{{end -}}
{{ if .Data.Error}} \n**Error**: {{rawencode .Data.Error}}{{end}}{{end}}"
}
`
WebhookTemplateMattermost is an incoming-webhook payload for homelab Mattermost.
const WebhookTemplateNotifiarr = `` /* 1101-byte string literal not displayed */
WebhookTemplateNotifiarr is the default template when not using discord.com (below), or a custom template file.
const WebhookTemplateNtfy = `{
"title": {{encode (print (or (nickname) "Unpackerr") ": " .Title)}},
"message": "**App**: {{rawencode .App}} \n` +
`**Name**: {{rawencode (index .IDs "title")}} \n**Path**: {{rawencode .Path -}}
{{ if .Data }}{{ if .Data.Elapsed.Duration }} \n**Elapsed**: {{.Data.Elapsed}}{{end -}}
{{ if .Data.Archives }} \n**Archives**: {{len .Data.Archives}}{{end -}}
{{ if .Data.Files }} \n**Files**: {{len .Data.Files}}{{end -}}
{{ if .Data.Bytes }} \n**Size**: {{humanbytes .Data.Bytes}}{{end -}}
{{ if and (gt .Event 1) (lt .Event 5) }} \n**Queue**: {{.Data.Queue}}{{end -}}
{{ if .Data.Error}} \n**ERROR**: {{rawencode .Data.Error}}{{end}}{{end}}",
"priority": {{ if or (eq 3 .Event) (eq 7 .Event) }}5{{ else }}3{{ end }},
"tags": ["unpackerr"{{ if or (eq 3 .Event) (eq 7 .Event) }},"warning"{{ else }},"white_check_mark"{{ end }}]
}
`
WebhookTemplateNtfy POSTs JSON at a topic URL (ntfy.sh or a self-hosted ntfy).
const WebhookTemplatePushover = `token={{token}}&user={{channel}}&html=1&title={{formencode .Title}}&` +
`{{if nickname}}device={{nickname}}&{{end}}message=<pre><b>App</b>: {{formencode (htmlencode .App)}}
<b>Name</b>: {{formencode (index .IDs "title")}}
<b>Path</b>: {{formencode .Path}}
{{ if .Data -}}
{{ if .Data.Elapsed.Duration}}<b>Time</b>: {{.Data.Elapsed}}
{{end}}{{ if .Data.Archives}}<b>RARs</b>: {{len .Data.Archives}}
{{end}}{{ if .Data.Files}}<b>Files</b>: {{len .Data.Files}}
{{end}}{{ if .Data.Bytes}}<b>Bytes</b>: {{humanbytes .Data.Bytes}}
{{end}}{{ if and (gt .Event 1) (lt .Event 5)}}<b>Queue</b>: {{.Data.Queue}}
{{end}}{{ if .Data.Error}}
<font color="#FF0000"><b>ERROR</b>: {{formencode .Data.Error}}</font>
{{end}}{{end -}}</pre>`
const WebhookTemplateSlack = `` /* 1853-byte string literal not displayed */
WebhookTemplateSlack is a built-in template for sending a message to Slack.
const WebhookTemplateTelegram = `{
"chat_id": "{{nickname}}",
"parse_mode": "HTML",
"disable_web_page_preview": true,
"text": "<b><a href=\"https://github.com/Unpackerr/unpackerr/releases\">Unpackerr</a></b>: ` +
`{{rawencode (htmlencode .Title) -}}
\n<b>Title</b>: {{rawencode (index .IDs "title") -}}
\n<b>App</b>: {{htmlencode .App -}}
\n\n<b>Path</b>: <code>{{rawencode .Path}}</code>
{{- if .Data }}\n
{{- if .Data.Elapsed.Duration}}\n <b>Elapsed</b>: {{.Data.Elapsed}}{{end -}}
{{ if .Data.Archives}}\n <b>Archives</b>: {{len .Data.Archives}}{{end -}}
{{ if .Data.Files}}\n <b>Files</b>: {{len .Data.Files}}{{end -}}
{{ if .Data.Bytes}}\n <b>Size</b>: {{humanbytes .Data.Bytes}}{{end -}}
{{ if and (gt .Event 1) (lt .Event 5)}}\n <b>Queue</b>: {{.Data.Queue}}{{end -}}
{{ if .Data.Error}}\n\n <b>ERROR</b>: <pre>{{rawencode .Data.Error}}</pre>\n{{end -}}
{{end -}}"
}
`
Variables ¶
var ( ErrInvalidStatus = errors.New("invalid HTTP status reply") ErrUnknownEvent = errors.New("unknown extract event") ErrWebhookNoURL = errors.New("webhook without a URL configured; fix it") ErrCmdhookNoCmd = errors.New("cmdhook without a command configured; fix it") ErrNilConfig = errors.New("nil config entry") ErrMessageGone = errors.New("previous message is gone") ErrHeaderName = errors.New("webhook header name must be letters, digits, underscore, or hyphen") ErrHeaderValue = errors.New("webhook header value cannot contain a newline") ErrHeaderDup = errors.New("duplicate webhook header name") )
Errors produced by this package.
Functions ¶
func BuiltinWebhookTemplate ¶
BuiltinWebhookTemplate returns a built-in webhook template body.
func DefaultContentType ¶
DefaultContentType is JSON, except Pushover which posts a form body.
func Fire ¶
Fire delivers one webhook POST or command-hook run and returns the remote reply or command output. Used by the UI test; does not use the hook worker.
func NormalizeNotifiarr ¶
func NormalizeNotifiarr(hook *Config)
NormalizeNotifiarr strips a Notifiarr client API key off the webhook path and stores it as X-Api-Key. Existing header values win.
func PrepareSample ¶
PrepareSample mutates a sample payload for the requested event.
func RedactHeaderSecrets ¶
RedactHeaderSecrets blanks Authorization and other secret-looking header values.
func SecretHeaderName ¶
SecretHeaderName reports whether a webhook header looks like a secret (Authorization, tokens, API keys, cookies). Shared with env GET redaction.
func SendWithLog ¶
SendWithLog renders and POSTs a webhook payload. Sample -w stays a create.
func ValidateCmdhooks ¶
func ValidateCmdhooks(list []*Config, defaultTimeout time.Duration, expandHome func(string) string) error
ValidateCmdhooks applies command-hook defaults and requires a command. expandHome is optional; when set it is applied to the command path.
func ValidateHeaders ¶
ValidateHeaders checks extra webhook header names and values.
func ValidateWebhooks ¶
ValidateWebhooks applies webhook defaults and requires a URL.
func WebhookTemplateFileName ¶
WebhookTemplateFileName is the locked basename for a built-in template dump.
Types ¶
type Config ¶
type Config struct {
Name string `json:"name" toml:"name" xml:"name" yaml:"name"`
URL string `json:"url" toml:"url" xml:"url,omitempty" yaml:"url"`
Command string `json:"command" toml:"command" xml:"command,omitempty" yaml:"command"`
CType string `json:"contentType" toml:"content_type" xml:"content_type,omitempty" yaml:"contentType"`
TmplPath string `json:"templatePath" toml:"template_path" xml:"template_path,omitempty" yaml:"templatePath"`
TempName string `json:"template" toml:"template" xml:"template,omitempty" yaml:"template"`
Timeout cnfg.Duration `json:"timeout" toml:"timeout" xml:"timeout" yaml:"timeout"`
Shell bool `json:"shell" toml:"shell" xml:"shell" yaml:"shell"`
IgnoreSSL bool `json:"ignoreSsl" toml:"ignore_ssl" xml:"ignore_ssl,omitempty" yaml:"ignoreSsl"`
Silent bool `json:"silent" toml:"silent" xml:"silent" yaml:"silent"`
Events Statuses `json:"events" toml:"events" xml:"events" yaml:"events"`
Exclude StringSlice `json:"exclude" toml:"exclude" xml:"exclude" yaml:"exclude"`
Nickname string `json:"nickname" toml:"nickname" xml:"nickname,omitempty" yaml:"nickname"`
Token string `json:"token" toml:"token" xml:"token,omitempty" yaml:"token"`
Channel string `json:"channel" toml:"channel" xml:"channel,omitempty" yaml:"channel"`
Update *bool `json:"update" toml:"update" xml:"update,omitempty" yaml:"update"`
Headers HeaderMap `json:"headers" toml:"headers" xml:"headers,omitempty" yaml:"headers"`
sync.Mutex `json:"-" toml:"-" xml:"-" yaml:"-"`
// contains filtered or unexported fields
}
Config defines a webhook or command hook.
func (*Config) Excluded ¶
Excluded returns true if the dialect or instance name is in the Exclude slice. Dialect tokens (sonarr, radarr, …) skip every instance of that API. Any other value matches an instance name, case-insensitive.
func (*Config) HasEvent ¶
HasEvent returns true if a status event is in the Events slice. Also returns true if the Events slice has only one value of WAITING.
func (*Config) WantUpdate ¶
WantUpdate is true for Discord and Telegram unless the operator set update=false.
type Item ¶
type Item struct {
*Config
*Payload
// Done is called once per failed webhook POST or command-hook run.
Done func(error)
// LookupID/SaveID read and record Discord/Telegram message ids for later edits.
// Unpackerr wires these to a worker-local cache; the main loop persists Map.
LookupID func() string
SaveID func(string)
}
Item is one queued webhook or command hook delivery.
type Logger ¶
type Logger interface {
Printf(msg string, v ...any)
Errorf(msg string, v ...any)
Debugf(msg string, v ...any)
}
Logger is the logging surface hooks need from the daemon.
type Payload ¶
type Payload struct {
Path string `json:"path"` // Path for the extracted item.
App starr.App `json:"app"` // Application Triggering Event
IDs map[string]any `json:"ids,omitempty"` // Arbitrary IDs from each app.
CustomIDs map[string]string `json:"customIDs,omitempty" xml:"custom_id"` // User IDs from [hooks].custom_ids.
Event extract.Status `json:"unpackerr_eventtype"` // The type of the event.
Time time.Time `json:"time"` // Time of this event.
Data *XtractPayload `json:"data,omitempty"` // Payload from extraction process.
Config *Config `json:"-"` // Payload from extraction process.
// Application Metadata.
Retries uint `json:"retries"` // Extract retry count for this item.
EventTitle string `json:"eventTitle,omitempty"` // English (or customized) event title.
Go string `json:"go"` // Version of go compiled with
OS string `json:"os"` // Operating system: linux, windows, darwin
Arch string `json:"arch"` // Architecture: amd64, armhf
Version string `json:"version"` // Application Version
Revision string `json:"revision"` // Application Revision
Branch string `json:"branch"` // Branch built from.
Started time.Time `json:"started"` // App start time.
}
Payload defines the data sent to notifarr.com (and other) webhooks.
func SamplePayload ¶
func SamplePayload() *Payload
SamplePayload is a fake payload used by `unpackerr -w`.
type Profile ¶
Profile is the resolved webhook template and whether the destination can edit a prior message.
func Detect ¶
Detect picks a built-in template from a named template, custom file, or URL. Named builtins win. template_path wins when the name is empty or unknown. Everything else sniffs the URL; unknown URLs use the Notifiarr JSON payload.
func DetectTransport ¶
DetectTransport picks headers and content-type from the named template or URL. A custom template file still uses the destination (ntfy Bearer, Pushover form).
type Statuses ¶
Statuses allows us to create a custom environment variable unmarshaller.
func (*Statuses) MarshalENV ¶
func (*Statuses) UnmarshalENV ¶
UnmarshalENV turns environment variables into extraction statuses.
type StringSlice ¶
type StringSlice []string
StringSlice allows a special environment variable unmarshaller for a lot of strings.
func (*StringSlice) MarshalENV ¶
func (slice *StringSlice) MarshalENV(tag string) (map[string]string, error)
func (*StringSlice) UnmarshalENV ¶
func (slice *StringSlice) UnmarshalENV(_, envval string) error
UnmarshalENV turns environment variables into a string slice.
type Worker ¶
type Worker struct {
// contains filtered or unexported fields
}
Worker runs hook deliveries on a buffered channel.
type XtractPayload ¶
type XtractPayload struct {
Error string `json:"error,omitempty"` // error only during extractfailed
Archive []string `json:"archive,omitempty"` // list of all archive files extracted
Archives StringSlice `json:"archives,omitempty"` // list of all archive files extracted
Files StringSlice `json:"files,omitempty"` // list of all files extracted
File []string `json:"file,omitempty"` // list of all files extracted
Start time.Time `json:"start"` // start time of extraction
Output string `json:"output,omitempty"` // temporary items folder
Bytes uint64 `json:"bytes,omitempty"` // Bytes written
Elapsed cnfg.Duration `json:"elapsed"` // Duration as a string: 5m32s
Queue int `json:"queue,omitempty"` // Extraction Queue Size
}
XtractPayload is a rewrite of xtractr.Response.