hooks

package
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 26 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package hooks runs webhook HTTP posts and command hooks.

Index

Constants

View Source
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.

View Source
const HeaderAPIKey = "X-Api-Key" //nolint:gosec // HTTP header name, not a secret

HeaderAPIKey is the Notifiarr client API key request header.

View Source
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.

View Source
const WebhookTemplateDiscord = `` /* 1663-byte string literal not displayed */

WebhookTemplateDiscord is used when sending a webhook to discord.com.

View Source
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": ""
    }
  }
}
`
View Source
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.

View Source
const WebhookTemplateNotifiarr = `` /* 1101-byte string literal not displayed */

WebhookTemplateNotifiarr is the default template when not using discord.com (below), or a custom template file.

View Source
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).

View Source
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>`
View Source
const WebhookTemplateSlack = `` /* 1853-byte string literal not displayed */

WebhookTemplateSlack is a built-in template for sending a message to Slack.

View Source
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

View Source
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

func BuiltinWebhookTemplate(name string) (string, bool)

BuiltinWebhookTemplate returns a built-in webhook template body.

func CountAll

func CountAll(hooks []*Config) (uint, uint)

CountAll returns the total count of requests and errors for all hooks.

func DefaultContentType

func DefaultContentType(name, rawURL string) string

DefaultContentType is JSON, except Pushover which posts a form body.

func Fire

func Fire(ctx context.Context, hook *Config, payload *Payload) (string, error)

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 LogEvents

func LogEvents(events []extract.Status) string

LogEvents formats events for printing.

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

func PrepareSample(payload *Payload, event extract.Status) error

PrepareSample mutates a sample payload for the requested event.

func RedactHeaderSecrets

func RedactHeaderSecrets(headers map[string]string)

RedactHeaderSecrets blanks Authorization and other secret-looking header values.

func SecretHeaderName

func SecretHeaderName(name string) bool

SecretHeaderName reports whether a webhook header looks like a secret (Authorization, tokens, API keys, cookies). Shared with env GET redaction.

func SendWithLog

func SendWithLog(log Logger, hook *Config, payload *Payload) error

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

func ValidateHeaders(headers map[string]string) error

ValidateHeaders checks extra webhook header names and values.

func ValidateWebhooks

func ValidateWebhooks(list []*Config, defaultTimeout time.Duration) error

ValidateWebhooks applies webhook defaults and requires a URL.

func WebhookTemplateFileName

func WebhookTemplateFileName(name string) string

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 CloneList

func CloneList(src []*Config) []*Config

CloneList copies hooks without the mutex, counters, client, or template.

func (*Config) Counts

func (w *Config) Counts() (uint, uint)

Counts returns the total count of requests and failures for a webhook.

func (*Config) Excluded

func (w *Config) Excluded(app starr.App, name string) bool

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

func (w *Config) HasEvent(e extract.Status) bool

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) Send

func (w *Config) Send(body io.Reader) ([]byte, error)

Send marshals an any into json and POSTs it to a URL.

func (*Config) Template

func (w *Config) Template() (*template.Template, error)

Template returns a template specific to this webhook.

func (*Config) WantUpdate

func (w *Config) WantUpdate() bool

WantUpdate is true for Discord and Telegram unless the operator set update=false.

type HeaderMap

type HeaderMap = map[string]string

HeaderMap is extra HTTP headers sent with a webhook POST.

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`.

func (*Payload) Title

func (p *Payload) Title() string

Title is EventTitle, or Event.Desc() when that override is empty.

type Profile

type Profile struct {
	Name      string
	CanUpdate bool
}

Profile is the resolved webhook template and whether the destination can edit a prior message.

func Detect

func Detect(name, rawURL, tmplPath string) Profile

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

func DetectTransport(name, rawURL string) Profile

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

type Statuses []extract.Status

Statuses allows us to create a custom environment variable unmarshaller.

func (*Statuses) MarshalENV

func (statuses *Statuses) MarshalENV(tag string) (map[string]string, error)

func (*Statuses) UnmarshalENV

func (statuses *Statuses) UnmarshalENV(tag, envval string) error

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.

func NewWorker

func NewWorker(buf int) *Worker

NewWorker returns a buffered hook worker. Call Run in a goroutine.

func (*Worker) Cap

func (w *Worker) Cap() int

Cap is the queue capacity.

func (*Worker) Enqueue

func (w *Worker) Enqueue(item *Item)

Enqueue publishes a hook item. The caller is responsible for in-flight accounting.

func (*Worker) Len

func (w *Worker) Len() int

Len is the number of queued items.

func (*Worker) Run

func (w *Worker) Run(log Logger, after func())

Run delivers queued hooks until the queue is closed. after runs after each item.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL