notify

package
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: AGPL-3.0 Imports: 30 Imported by: 0 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 notify sends event notifications ("Discord/ Telegram/webhook/email on events... generic, not Discord-only") for things happening in the activity feed: grabbed, downloaded/imported, failed.

Index

Constants

View Source
const (
	EventAdded    = "added"    // a release was grabbed / sent to download
	EventImported = "imported" // a download finished and was imported
	EventFailed   = "failed"   // a download or import failed
	EventConflict = "conflict" // an import hit a file that already exists
	EventSubtitle = "subtitle" // a subtitle was downloaded
	EventHealth   = "health"   // something is wrong with the app (or recovered)
	EventUpdate   = "update"   // a new version of Mediarium is available
)

Event kinds a target can subscribe to. The activity feed's own event names map onto these with EventKind.

Variables

This section is empty.

Functions

func ApplyDefaults

func ApplyDefaults(typeName string, cfg map[string]string) map[string]string

ApplyDefaults fills in the defaults of empty optional fields (so "port" left blank means 587) and trims whitespace. It returns a fresh map.

func DefaultEvents

func DefaultEvents() []string

DefaultEvents is what a target subscribes to when it doesn't say.

func EventKind

func EventKind(eventType string) string

EventKind maps an event type from the activity feed to the kind a target subscribes to ("grabbed" is the "added" kind). Unknown types map to themselves, so they reach only targets that somehow subscribed to them.

func NormalizeEvents

func NormalizeEvents(in []string) ([]string, error)

NormalizeEvents keeps the valid, de-duplicated kinds in canonical order. An empty input yields DefaultEvents; input with only unknown kinds is an error.

func NotifyAll

func NotifyAll(ctx context.Context, senders []Sender, event Event) []error

NotifyAll sends event to every sender, collecting (not stopping on) the first error — one bad notification target shouldn't suppress the others, mirroring the indexer search engine's tolerate-one-failure design.

func RenderEmailHTML

func RenderEmailHTML(ev Event) string

RenderEmailHTML draws the message as an HTML page for email clients: a table layout with inline styles, which is all they agree on.

func RenderEmailText

func RenderEmailText(ev Event) string

RenderEmailText is the plain-text alternative of the same message.

func SplitAddresses

func SplitAddresses(s string) []string

SplitAddresses splits a comma- or semicolon-separated recipient list.

func SplitFields

func SplitFields(typ TypeInfo, cfg map[string]string) (public, secret map[string]string)

SplitFields separates cfg into public and secret values by the type's field kinds, dropping names the type doesn't have.

func Validate

func Validate(typeName string, cfg map[string]string) error

Validate checks cfg against the type's rules and returns a sentence a person can act on, or nil. Defaults are not applied here (see ApplyDefaults).

func WithSteps

func WithSteps(ctx context.Context, steps *Steps) context.Context

WithSteps makes the senders that get ctx write their progress into steps.

Types

type Detail

type Detail struct {
	Label string `json:"label"`
	Value string `json:"value"`
}

Detail is one row of the small table that goes with a message.

type DiscordSender

type DiscordSender struct {
	WebhookURL string
	Client     *http.Client
}

DiscordSender posts to a Discord incoming webhook URL.

func NewDiscordSender

func NewDiscordSender(webhookURL string) *DiscordSender

func (*DiscordSender) Send

func (s *DiscordSender) Send(ctx context.Context, event Event) error

type EmailSender

type EmailSender struct {
	Host     string
	Port     int
	Security string // "starttls" | "ssl" | "none"
	Username string
	Password string
	From     string   // "you@example.com" or "Name <you@example.com>"
	To       []string // one or more addresses

	// TLSConfig overrides the TLS settings (tests use it to trust a
	// self-signed certificate). Nil means verify against the system roots.
	TLSConfig *tls.Config
	// Timeout bounds the whole conversation; zero means 20 seconds.
	Timeout time.Duration
}

EmailSender delivers events over SMTP, using only the standard library.

func (*EmailSender) Send

func (s *EmailSender) Send(ctx context.Context, ev Event) error

Send delivers the event by SMTP. When ctx carries a Steps log (see WithSteps) each stage is written to it, with the reason for the first thing that fails.

type Event

type Event struct {
	Type      string // "grabbed" | "imported" | "failed" | "conflict" | "subtitle" | "health" | "update" | "test"
	Title     string // the subject: "Titanic (1997) is ready to watch"
	Message   string // the whole message as plain text
	Timestamp time.Time

	// The rest is set by Compose and ComposeText. An event without a Lead is
	// sent as Title and Message only.
	Lead        string   // the sentence under the subject
	Details     []Detail // the rows of the small table
	PosterURL   string   // a hosted poster image, or empty
	LinkURL     string   // where the title is in Mediarium, or empty
	SettingsURL string   // the notification settings in Mediarium, or empty
}

Event is one activity-feed-worthy occurrence.

func Compose

func Compose(eventType string, it Item, links Links, at time.Time) Event

Compose builds the event for a download-related occurrence.

func ComposeTestEmail added in v1.4.0

func ComposeTestEmail(it Item, links Links, at time.Time) Event

ComposeTestEmail is the test message for an email notification: it looks like a real "ready to watch" email, using a title from the library, so the person sees the design they will get. Nothing was downloaded, and it says so.

func ComposeText

func ComposeText(eventType, title, message string, links Links, at time.Time) Event

ComposeText builds the event for the ones that carry no title of their own (a broken connection, a new version, a test): a subject, a sentence and no table.

type EventInfo

type EventInfo struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	Help  string `json:"help"`
}

EventInfo describes one subscribable event for the UI.

func EventKinds

func EventKinds() []EventInfo

EventKinds lists every subscribable event in display order.

type Field

type Field struct {
	Name        string   `json:"name"`
	Label       string   `json:"label"`
	Kind        string   `json:"kind"` // text | password | number | select
	Required    bool     `json:"required"`
	Placeholder string   `json:"placeholder,omitempty"`
	Default     string   `json:"default,omitempty"`
	Options     []Option `json:"options,omitempty"`
	Help        string   `json:"help"`
}

Field describes one input of a target's form.

func (Field) Secret

func (f Field) Secret() bool

Secret fields are stored encrypted and never returned by the API.

type GotifySender

type GotifySender struct {
	URL    string
	Token  string
	Client *http.Client
}

GotifySender pushes to a Gotify server with an application token.

func NewGotifySender

func NewGotifySender(url, token string) *GotifySender

func (*GotifySender) Send

func (s *GotifySender) Send(ctx context.Context, ev Event) error

type Item

type Item struct {
	Media     string // "movie" | "show" | "episode" | "album"; anything else reads as a movie
	Title     string // "Titanic", "Severance", "Radiohead - OK Computer"
	Year      int    // 0 when unknown
	Episode   string // "S02E03" or "Season 2"; empty for a movie or a whole show
	Quality   string // "Bluray-1080p"
	SizeBytes int64  // 0 when unknown
	Path      string // where the file was saved
	Release   string // the release name that was grabbed
	Reason    string // why a download failed, in plain words
	Language  string // a subtitle's language
	PosterURL string // a hosted poster image, or empty
	LinkPath  string // where the title lives in Mediarium, like /title/597
}

Item is what a download-related event is about. Compose turns it into the subject, the sentence and the detail rows every channel shows.

func (Item) Name

func (it Item) Name() string

Name is how the item reads in a subject: "Titanic (1997)" or "Severance S02E03".

type Links struct {
	Base string // like https://mediarium.example.com, no trailing slash
}

Links holds the addresses the person set for Mediarium. Empty means no links are added to messages.

type NtfySender

type NtfySender struct {
	Server string // base URL, default https://ntfy.sh
	Topic  string
	Token  string // optional bearer token
	Client *http.Client
}

NtfySender publishes to an ntfy topic (ntfy.sh or a self-hosted server) using its JSON publish API, so non-ASCII titles need no header encoding.

func NewNtfySender

func NewNtfySender(server, topic, token string) *NtfySender

func (*NtfySender) Send

func (s *NtfySender) Send(ctx context.Context, ev Event) error

type Option

type Option struct {
	Value string `json:"value"`
	Label string `json:"label"`
}

Option is one choice of a "select" field.

type PushoverSender

type PushoverSender struct {
	UserKey string
	Token   string
	Client  *http.Client
	// contains filtered or unexported fields
}

PushoverSender sends through the Pushover message API.

func NewPushoverSender

func NewPushoverSender(userKey, token string) *PushoverSender

func NewPushoverSenderWithBaseURL

func NewPushoverSenderWithBaseURL(userKey, token, baseURL string) *PushoverSender

NewPushoverSenderWithBaseURL points the sender at a fixture server in tests.

func (*PushoverSender) Send

func (s *PushoverSender) Send(ctx context.Context, ev Event) error

type Repo

type Repo struct {
	// contains filtered or unexported fields
}

func NewRepo

func NewRepo(db *sql.DB, box *crypto.Box) *Repo

func (*Repo) Create

func (r *Repo) Create(t Target) (Target, error)

func (*Repo) Delete

func (r *Repo) Delete(id int64) error

func (*Repo) Get

func (r *Repo) Get(id int64) (Target, error)

Get returns one target, or sql.ErrNoRows.

func (*Repo) List

func (r *Repo) List() ([]Target, error)

func (*Repo) MigrateSecrets

func (r *Repo) MigrateSecrets() (int, error)

MigrateSecrets re-saves the targets that still keep a secret value in plain text, so that it ends up encrypted. It matters after a field becomes a secret (Discord and webhook addresses and ntfy topics contain the whole credential) and for targets saved before the generic config existed, whose address sits in a plain column. It returns how many targets it changed and is safe to run at every start: with nothing left in plain text it does nothing.

func (*Repo) Senders

func (r *Repo) Senders() ([]Sender, error)

Senders builds a live Sender for every enabled target, ready to pass to NotifyAll.

func (*Repo) SendersFor

func (r *Repo) SendersFor(kind string) ([]Sender, error)

SendersFor builds a Sender for every enabled target subscribed to kind (see EventKind); an empty kind means every enabled target. A target that can't be built (a type this version doesn't know) is skipped.

func (*Repo) Update

func (r *Repo) Update(t Target) (Target, error)

Update replaces a target's name, enabled flag, events and config. A secret field left empty in t.Config keeps the value already stored, so an edit form doesn't need the secrets it was never shown.

type Sender

type Sender interface {
	Send(ctx context.Context, event Event) error
}

Sender delivers one Event to one configured destination.

func NewSender

func NewSender(t Target) (Sender, error)

NewSender builds the live Sender for a target from its config.

type SlackSender

type SlackSender struct {
	WebhookURL string
	Client     *http.Client
}

SlackSender posts to a Slack incoming webhook.

func NewSlackSender

func NewSlackSender(webhookURL string) *SlackSender

func (*SlackSender) Send

func (s *SlackSender) Send(ctx context.Context, ev Event) error

type Step

type Step struct {
	Time time.Time `json:"time"`
	Text string    `json:"text"`
	OK   bool      `json:"ok"`
}

Step is one line of the log a test message leaves: what Mediarium did, when, and whether it worked.

type Steps

type Steps struct {
	// contains filtered or unexported fields
}

Steps collects the lines of one test. The senders write into it through the context (see WithSteps), so sending a real notification, where no one is listening, costs nothing. A nil *Steps ignores everything.

func NewSteps

func NewSteps(secrets ...string) *Steps

NewSteps starts an empty log. Every secret given is blanked out of each line that is added, on top of the general clean-up the app's log gets.

func (*Steps) Add

func (s *Steps) Add(ok bool, format string, args ...any)

Add writes one line. ok false marks it as the point where things went wrong.

func (*Steps) List

func (s *Steps) List() []Step

List returns the lines so far, in order.

type Target

type Target struct {
	ID       int64
	Name     string
	Type     TargetType
	URL      string // alias of Config["url"]
	BotToken string // alias of Config["botToken"]
	ChatID   string // alias of Config["chatId"]
	Enabled  bool
	Events   []string          // kinds this target hears about (see EventKinds); empty means all
	Config   map[string]string // field name -> value
}

Target is a configured notification destination.

Config holds every field of the target's type (see Types), secrets included; the repo stores the secret ones encrypted. URL, BotToken and ChatID are the original webhook/Discord/Telegram fields, kept as aliases of Config["url"], ["botToken"] and ["chatId"].

func (Target) Subscribed

func (t Target) Subscribed(kind string) bool

Subscribed reports whether the target wants events of the given kind.

type TargetType

type TargetType string
const (
	TargetWebhook  TargetType = "webhook"
	TargetDiscord  TargetType = "discord"
	TargetTelegram TargetType = "telegram"
	TargetEmail    TargetType = "email"
	TargetNtfy     TargetType = "ntfy"
	TargetGotify   TargetType = "gotify"
	TargetPushover TargetType = "pushover"
	TargetSlack    TargetType = "slack"
)

type TelegramSender

type TelegramSender struct {
	BotToken string
	ChatID   string
	Client   *http.Client
	// contains filtered or unexported fields
}

TelegramSender posts via the Telegram Bot API's sendMessage method.

func NewTelegramSender

func NewTelegramSender(botToken, chatID string) *TelegramSender

func NewTelegramSenderWithBaseURL

func NewTelegramSenderWithBaseURL(botToken, chatID, baseURL string) *TelegramSender

NewTelegramSenderWithBaseURL is used by tests to point at a local fixture server instead of the real Telegram Bot API (tests use local fixtures, not live network calls) — same pattern as internal/metadata.NewWithBaseURL.

func (*TelegramSender) Send

func (s *TelegramSender) Send(ctx context.Context, event Event) error

type TypeInfo

type TypeInfo struct {
	Type   string  `json:"type"`
	Label  string  `json:"label"`
	Fields []Field `json:"fields"`
}

TypeInfo describes one kind of notification target.

func TypeByName

func TypeByName(name string) (TypeInfo, bool)

TypeByName finds a type in the catalog.

func Types

func Types() []TypeInfo

Types is the catalog of target types, in display order. The UI builds its forms from this, so every field carries its own short how-to-find-it help.

type WebhookSender

type WebhookSender struct {
	URL    string
	Client *http.Client
	// Template, when set, is a JSON body with {{event}}, {{title}}, {{message}}
	// and {{at}} placeholders; empty sends the fixed {event,title,message,at}.
	Template string
}

WebhookSender POSTs a generic JSON payload — the "not Discord-only" fallback that works with anything expecting a plain JSON webhook.

func NewWebhookSender

func NewWebhookSender(url string) *WebhookSender

func (*WebhookSender) Send

func (s *WebhookSender) Send(ctx context.Context, event Event) error

Jump to

Keyboard shortcuts

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