push

package
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: AGPL-3.0 Imports: 62 Imported by: 0

Documentation

Overview

Package push is ReputeCast's web push channel (design expansion phase 8, M32): built in, with no outside account.

  • VAPID keys, generated here and rotated with a typed confirmation; the private key is sealed (internal/secrets) and never returned.
  • Sites: the publication website, whose service worker ReputeCast serves, and other sites with the snippet and rc-push-sw.js, which a check finds. Subscriptions from sites that aren't listed are refused.
  • Subscriptions: anonymous until linked to a contact, each with its consent record (page, exact prompt text and version, IP, time).
  • The prompt designer, a form type: a slide-in bar, a dialog or a bell button, when and where it shows, asking again after "Not now", and the Home Screen steps on iPhone and iPad.
  • Push campaigns with previews per platform, Review & send with its checks, the frequency cap and quiet hours, sending over the Web Push protocol (internal/push/webpush), expired subscriptions removed, shown and click tracking, and the report.
  • The Send push automation step.

Push builds on X21's channel model (internal/channels): campaigns carry channel 'push' and each notification is a row of the message log, kept 90 days and never in the audit log. Everything a person changes is audited.

Index

Constants

View Source
const (
	TitleMax   = 50
	MessageMax = 120
	// DefaultTTL is the default expiry: 4 hours.
	DefaultTTL = 240
)

Recommended lengths.

View Source
const (
	StyleBar    = "bar"    // slide-in bar at the bottom of the page
	StyleDialog = "dialog" // a centred card
	StyleBell   = "bell"   // a bell button that opens the prompt on click
)

Prompt styles.

View Source
const (
	PromptTitleMax   = 40
	PromptMessageMax = 120
)

Limits the composer counts against.

View Source
const (
	Pass  = "pass"
	Warn  = "warn"
	Block = "block"
)

Check statuses.

View Source
const (
	VerdictReady    = "ready"
	VerdictWarnings = "warnings"
	VerdictBlocked  = "blocked"
)

Verdicts.

View Source
const (
	KindPublication = "publication"
	KindSnippet     = "snippet"
)

Site kinds.

View Source
const (
	WorkerBuiltIn    = "built_in"
	WorkerFound      = "found"
	WorkerOld        = "old_version"
	WorkerMissing    = "missing"
	WorkerUnreach    = "unreachable"
	WorkerNotAWorker = "not_a_worker"
	WorkerUnchecked  = "unchecked"
)

Check statuses. A publication site's worker is always "built_in".

View Source
const (
	BrowserChrome        = "chrome"
	BrowserChromeAndroid = "chrome_android"
	BrowserEdge          = "edge"
	BrowserFirefox       = "firefox"
	BrowserSafari        = "safari"
	BrowserSafariIOS     = "safari_ios"
	BrowserOther         = "other"
)

Browsers, as the app groups them.

View Source
const DefaultFrequencyCap = 2

DefaultFrequencyCap is at most 2 notifications a day per subscriber.

View Source
const TokenReader linktoken.Kind = 220

TokenReader is a link that carries the reader to a site, so a subscription made there is linked to them (design expansion, X22: 220–229).

View Source
const WorkerFile = "rc-push-sw.js"

WorkerFile is the file a snippet site hosts at its root.

View Source
const WorkerVersion = 1

WorkerVersion is the version of the service worker this build serves. A site hosting an older rc-push-sw.js gets the "old version" warning.

Variables

View Source
var (
	ErrPushOff      = errors.New("push: push isn't on for this workspace")
	ErrSiteRefused  = errors.New("push: the site isn't a push site of this workspace")
	ErrBadEndpoint  = errors.New("push: the subscription isn't on a push service ReputeCast sends to")
	ErrSubscription = errors.New("push: the subscription's keys are malformed")
)

Subscribe errors the public endpoint answers with.

View Source
var ErrUnknownNotification = errors.New("push: unknown notification")

ErrUnknownNotification is a report or click for no notification of ours.

View Source
var Platforms = []Platform{
	{Key: "chrome_windows", TitleChars: 40, MessageLines: 3, LineChars: 47, Image: true, Buttons: true},
	{Key: "chrome_mac", TitleChars: 34, MessageLines: 2, LineChars: 31, Buttons: true},
	{Key: "safari_mac", TitleChars: 40, MessageLines: 2, LineChars: 43},
	{Key: "chrome_android", TitleChars: 38, MessageLines: 1, LineChars: 40, Image: true, Buttons: true},
	{Key: "safari_ios", TitleChars: 40, MessageLines: 4, LineChars: 44},
}

Platforms are the previews' platforms, in the composer's order.

Functions

func BrowserOf

func BrowserOf(ua string) (browser, platform string)

BrowserOf reads a browser and its platform from a User-Agent.

func Cut

func Cut(text string, lines, width int) (shown, hidden string)

Cut is what a platform shows of a text: lines of words up to its width, and the rest hidden.

func Erasure

func Erasure() erasure.Source

Erasure ends the contact's push subscriptions and drops their endpoints, keys and where they subscribed; the rows stay, removed, for counts (review 2026-11 DP-1).

func HostedWorker

func HostedWorker() []byte

HostedWorker is rc-push-sw.js: the worker as a site hosts it.

func ParseClick

func ParseClick(raw string) (uuid.UUID, string, bool)

ParseClick reads a click link's last part: "<id>.<token>".

func ParseOrigin

func ParseOrigin(raw string) (origin, host string, ok bool)

ParseOrigin reads a site address ("help.acme.io", "https://help.acme.io/ blog") as an origin: https, a host and maybe a port. http is accepted for localhost only, as browsers do for service workers.

func Register

func Register(h huma.API, s *Service)

Register adds the push operations.

func RegisterJobs

func RegisterJobs(reg *jobs.Registry, s *Service)

RegisterJobs adds the push workers and their schedules.

func Track

func Track(s *Service)

Track makes a service answer for the account section.

Types

type Approvals

type Approvals interface {
	ChannelGate(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (*store.ApprovalRequest, error)
	ChannelReview(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (approvals.ReviewApproval, error)
}

Approvals is the approvals seam for push campaigns.

type CheckArgs

type CheckArgs struct{}

CheckArgs checks the snippet sites' service workers, once a day each.

func (CheckArgs) InsertOpts

func (CheckArgs) InsertOpts() river.InsertOpts

InsertOpts implements river.JobArgsWithInsertOpts.

func (CheckArgs) Kind

func (CheckArgs) Kind() string

Kind implements river.JobArgs.

type CheckResult

type CheckResult struct {
	Status     string
	Version    *int
	Scope      string
	HTTPStatus *int
	Detail     string
}

CheckResult is what fetching a site's worker found.

func FetchWorker

func FetchWorker(ctx context.Context, client *http.Client, u, mode string) CheckResult

FetchWorker fetches a site's worker and says what it is. Browsers don't follow redirects for service workers, so neither does the check.

type CheckWorker

type CheckWorker struct {
	river.WorkerDefaults[CheckArgs]
	S *Service
}

CheckWorker runs CheckArgs.

func (*CheckWorker) Timeout

func (w *CheckWorker) Timeout(*river.Job[CheckArgs]) time.Duration

Timeout bounds one pass.

func (*CheckWorker) Work

func (w *CheckWorker) Work(ctx context.Context, _ *river.Job[CheckArgs]) error

Work implements river.Worker.

type Content

type Content struct {
	Title      string       `json:"title"`
	Message    string       `json:"message"`
	Link       string       `json:"link"`
	Image      string       `json:"image,omitempty"`
	Icon       string       `json:"icon,omitempty"`
	Buttons    []PushButton `json:"buttons,omitempty"`
	Tag        string       `json:"tag,omitempty"`
	Replace    bool         `json:"replace,omitempty"`
	TTLMinutes int          `json:"ttl"`
	// UTM is the utm_campaign its links carry.
	UTM string `json:"utm,omitempty"`
}

Content is a notification's content, kept with the message until it goes.

type DispatchArgs

type DispatchArgs struct{}

DispatchArgs sends the notifications that are due.

func (DispatchArgs) InsertOpts

func (DispatchArgs) InsertOpts() river.InsertOpts

InsertOpts implements river.JobArgsWithInsertOpts.

func (DispatchArgs) Kind

func (DispatchArgs) Kind() string

Kind implements river.JobArgs.

type DispatchWorker

type DispatchWorker struct {
	river.WorkerDefaults[DispatchArgs]
	S *Service
}

DispatchWorker runs DispatchArgs.

func (*DispatchWorker) NextRetry

func (w *DispatchWorker) NextRetry(job *river.Job[DispatchArgs]) time.Time

NextRetry implements river.Worker: a failed run goes again within seconds.

func (*DispatchWorker) Timeout

Timeout bounds one run.

func (*DispatchWorker) Work

Work implements river.Worker.

type Guards

type Guards struct {
	Cap int
	// Quiet is whether push keeps to the window.
	Quiet  bool
	Window channels.Window
}

Guards are the frequency cap and quiet hours as code reads them.

type Payload

type Payload struct {
	V        int             `json:"v"`
	ID       string          `json:"id"`
	Token    string          `json:"t"`
	Title    string          `json:"title"`
	Body     string          `json:"body"`
	Icon     string          `json:"icon,omitempty"`
	Image    string          `json:"image,omitempty"`
	URL      string          `json:"url"`
	Tag      string          `json:"tag,omitempty"`
	Renotify bool            `json:"renotify,omitempty"`
	Actions  []PayloadAction `json:"actions,omitempty"`
	// Events is where the worker reports shown and closed.
	Events string `json:"events"`
	// Expires is when the notification is stale (the TTL from its send).
	Expires int64 `json:"expires"`
}

Payload is what the service worker receives (static/sw.js reads it).

type PayloadAction

type PayloadAction struct {
	Action string `json:"action"`
	Title  string `json:"title"`
	URL    string `json:"url"`
}

PayloadAction is a button.

type Platform

type Platform struct {
	Key          string
	TitleChars   int
	MessageLines int
	LineChars    int
	Image        bool
	Buttons      bool
}

Platform is how a platform shows a notification: about how many characters of the title fit, and how many lines of the message of about how many characters. The composer's previews cut the text the same way.

type PushAccess

type PushAccess struct {
	CanEdit bool `json:"canEdit"`
	CanSend bool `json:"canSend"`
	// Missing are the permissions sending needs that the viewer lacks.
	Missing []string `json:"missing"`
	Helpers []string `json:"helpers"`
}

PushAccess is what the viewer may do with a push campaign.

type PushAccountSubscription

type PushAccountSubscription struct {
	ID string `json:"id"`
	// Browser names it in English; Kind is the browser's key, which the
	// account page names in its own language (data-browser-<kind>).
	Browser string    `json:"browser"`
	Kind    string    `json:"kind"`
	Since   time.Time `json:"since"`
	// Endpoint is how the page tells this browser apart: its own
	// subscription's push resource.
	Endpoint string `json:"endpoint"`
}

PushAccountSubscription is one of the member's browsers.

type PushAudience

type PushAudience struct {
	// Total is every live subscription of the chosen sites (narrowed by
	// lists and segments when there are any).
	Total     int64 `json:"total"`
	Linked    int64 `json:"linked"`
	Anonymous int64 `json:"anonymous"`
	// OverCap already got the frequency cap's notifications today.
	OverCap int64 `json:"overCap"`
	// Final is who it goes to.
	Final int64 `json:"final"`
	// Narrowed is true when lists or segments narrow the sites'
	// subscribers to linked ones.
	Narrowed bool `json:"narrowed"`
}

PushAudience is how many subscriptions the campaign reaches.

type PushAudienceRef

type PushAudienceRef struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Kind string `json:"kind" enum:"list,segment"`
}

PushAudienceRef is a list or segment narrowing the audience.

type PushAudienceSite

type PushAudienceSite struct {
	ID          string `json:"id"`
	Host        string `json:"host"`
	Subscribers int64  `json:"subscribers"`
	Selected    bool   `json:"selected"`
}

PushAudienceSite is a site in the audience picker.

type PushButton

type PushButton struct {
	Label string `json:"label" maxLength:"40"`
	URL   string `json:"url" maxLength:"2000"`
}

PushButton is a notification's button.

type PushCSV

type PushCSV struct {
	ContentType        string `header:"Content-Type"`
	ContentDisposition string `header:"Content-Disposition"`
	Body               []byte
}

PushCSV is a CSV download.

type PushCampaign

type PushCampaign struct {
	ID          string     `json:"id"`
	Name        string     `json:"name"`
	Status      string     `json:"status" enum:"draft,approval,approved,scheduled,sending,paused,sent,cancelled,failed"`
	Version     int        `json:"version"`
	AutosavedAt *time.Time `json:"autosavedAt,omitempty"`
	UpdatedAt   time.Time  `json:"updatedAt"`
	UpdatedBy   string     `json:"updatedBy"`
	CreatedBy   string     `json:"createdBy"`

	Title      string             `json:"title"`
	Message    string             `json:"message"`
	Link       string             `json:"link"`
	UTM        string             `json:"utm"`
	Image      *PushImage         `json:"image,omitempty"`
	Buttons    []PushButton       `json:"buttons"`
	TTLMinutes int                `json:"ttlMinutes"`
	Tag        string             `json:"tag"`
	ReplaceTag bool               `json:"replaceTag"`
	Sites      []PushAudienceSite `json:"sites"`
	Lists      []PushAudienceRef  `json:"lists"`
	Segments   []PushAudienceRef  `json:"segments"`
	Audience   PushAudience       `json:"audience"`
	// IconURL is the first chosen site's icon; Host its address (the
	// previews show both).
	IconURL string `json:"iconUrl"`
	Host    string `json:"host"`
	// Guards are the frequency cap and quiet hours as they apply now.
	Guards PushGuards `json:"guards"`
	// Schedule is the send settings Review & send keeps; the composer's
	// quiet-hours choice changes them.
	Schedule PushSchedule     `json:"schedule"`
	Test     *PushTestResult  `json:"test,omitempty"`
	Access   PushAccess       `json:"access"`
	PushOn   bool             `json:"pushOn"`
	Limits   PushLengthLimits `json:"limits"`
}

PushCampaign is the composer's view of a push campaign.

type PushCampaignCreate

type PushCampaignCreate struct {
	Name string `json:"name" minLength:"1" maxLength:"200"`
	// SiteIDs are the sites it goes to; empty picks every site.
	SiteIDs []string `json:"siteIds,omitempty" maxItems:"20"`
	Title   string   `json:"title,omitempty" maxLength:"200"`
	Message string   `json:"message,omitempty" maxLength:"500"`
	Link    string   `json:"link,omitempty" maxLength:"2000"`
}

PushCampaignCreate makes a push campaign.

type PushCampaignPath

type PushCampaignPath struct {
	api.WorkspaceInput
	CampaignID string `path:"campaignId" format:"uuid" doc:"Campaign id"`
}

PushCampaignPath names a push campaign.

type PushCampaignUpdate

type PushCampaignUpdate struct {
	Name         string       `json:"name" minLength:"1" maxLength:"200"`
	Title        string       `json:"title" maxLength:"200"`
	Message      string       `json:"message" maxLength:"500"`
	Link         string       `json:"link" maxLength:"2000"`
	ImageMediaID string       `json:"imageMediaId,omitempty" maxLength:"40"`
	Buttons      []PushButton `json:"buttons" maxItems:"2"`
	TTLMinutes   int          `json:"ttlMinutes" minimum:"5" maximum:"40320"`
	Tag          string       `json:"tag" maxLength:"64"`
	ReplaceTag   bool         `json:"replaceTag"`
	SiteIDs      []string     `json:"siteIds" maxItems:"20"`
	Lists        []string     `json:"lists" maxItems:"50"`
	Segments     []string     `json:"segments" maxItems:"50"`
	// Version is the version the composer edited; a save from an older one
	// is refused.
	Version int `json:"version" minimum:"0"`
}

PushCampaignUpdate is an autosave from the composer.

type PushCheck

type PushCheck struct {
	Key    string `json:"key" enum:"keys,worker,audience,frequency_cap,quiet_hours,link,lengths,image,approval"`
	Status string `json:"status" enum:"pass,warn,block"`
	// Keys.
	KeysCreatedAt  *time.Time `json:"keysCreatedAt,omitempty"`
	KeysAcceptedAt *time.Time `json:"keysAcceptedAt,omitempty"`
	// Service worker: each site of the audience; OtherSites is how many
	// push sites aren't in it.
	Sites      []PushCheckSite `json:"sites"`
	OtherSites int             `json:"otherSites"`
	// Audience: Count is who it goes to, Linked and Anonymous split them.
	Count     int64 `json:"count"`
	Linked    int64 `json:"linked"`
	Anonymous int64 `json:"anonymous"`
	// Frequency cap: the cap, how many are over it, how many had any today.
	Cap      int   `json:"cap"`
	OverCap  int64 `json:"overCap"`
	HadToday int64 `json:"hadToday"`
	// Quiet hours.
	QuietOff  bool       `json:"quietOff"`
	Window    string     `json:"window"`
	At        time.Time  `json:"at"`
	AtZone    string     `json:"atZone"`
	Inside    int64      `json:"inside"`
	Held      int64      `json:"held"`
	HeldZones []PushZone `json:"heldZones"`
	Skipped   int64      `json:"skipped"`
	// Link: what it answered.
	Link       string `json:"link,omitempty"`
	LinkStatus int    `json:"linkStatus,omitempty"`
	LinkMillis int    `json:"linkMillis,omitempty"`
	LinkError  string `json:"linkError,omitempty"`
	// LinkDemo: a demo site's address, which is never fetched.
	LinkDemo bool `json:"linkDemo,omitempty"`
	// Lengths.
	TitleLength   int       `json:"titleLength"`
	MessageLength int       `json:"messageLength"`
	Cuts          []PushCut `json:"cuts"`
	// Image.
	Image *PushImage `json:"image,omitempty"`
	Ratio string     `json:"ratio,omitempty"`
	// Approval.
	Author     string   `json:"author,omitempty"`
	AuthorRole string   `json:"authorRole,omitempty"`
	Missing    []string `json:"missing"`
	Helpers    []string `json:"helpers"`
	Rules      []string `json:"rules"`
}

PushCheck is one pre-send check, with what it found. The app words it.

type PushCheckSite

type PushCheckSite struct {
	Host        string `json:"host"`
	Status      string `json:"status" enum:"built_in,found,old_version,missing,unreachable,not_a_worker,unchecked"`
	Subscribers int64  `json:"subscribers"`
	URL         string `json:"url"`
	Version     *int   `json:"version,omitempty"`
	HTTPStatus  *int   `json:"httpStatus,omitempty"`
}

PushCheckSite is a site in the service worker check.

type PushConsentRecord

type PushConsentRecord struct {
	Browser   string    `json:"browser"`
	Site      string    `json:"site"`
	Contact   string    `json:"contact,omitempty"`
	ContactID string    `json:"contactId,omitempty"`
	LinkedBy  string    `json:"linkedBy,omitempty"`
	At        time.Time `json:"at"`
	TimeZone  string    `json:"timeZone"`
	IP        string    `json:"ip,omitempty"`
	Page      string    `json:"page"`
	Version   int       `json:"version"`
	Text      string    `json:"text"`
	// PublishedAt and PublishedBy are when that version went live.
	PublishedAt *time.Time `json:"publishedAt,omitempty"`
	PublishedBy string     `json:"publishedBy,omitempty"`
}

PushConsentRecord is one subscription's consent, as the designer shows the latest one made through the prompt.

type PushContactCard

type PushContactCard struct {
	PushOn        bool                      `json:"pushOn"`
	Subscriptions []PushContactSubscription `json:"subscriptions"`
	CanEdit       bool                      `json:"canEdit"`
}

PushContactCard is the contact profile's push subscriptions card.

type PushContactInput

type PushContactInput struct {
	Contact string `json:"contact" minLength:"1" maxLength:"200"`
}

PushContactInput changes the contact the push services get.

type PushContactPath

type PushContactPath struct {
	api.WorkspaceInput
	ContactID string `path:"contactId" format:"uuid" doc:"Contact id"`
}

PushContactPath names a contact.

type PushContactSubscription

type PushContactSubscription struct {
	ID       string     `json:"id"`
	Browser  string     `json:"browser" enum:"chrome,chrome_android,edge,firefox,safari,safari_ios,other"`
	Platform string     `json:"platform"`
	Site     string     `json:"site"`
	Since    time.Time  `json:"since"`
	LinkedBy string     `json:"linkedBy" enum:"member,link,account,preferences,"`
	LastSeen *time.Time `json:"lastSeen,omitempty"`
	TimeZone string     `json:"timeZone"`
}

PushContactSubscription is one of a contact's subscriptions.

type PushCount

type PushCount struct {
	Key   string `json:"key"`
	Count int64  `json:"count"`
}

PushCount is a count by browser or site.

type PushCut

type PushCut struct {
	Platform string `json:"platform" enum:"chrome_windows,chrome_mac,safari_mac,chrome_android,safari_ios"`
	// Lines is how many lines of the message it shows.
	Lines int  `json:"lines"`
	Title bool `json:"title"`
}

PushCut is a platform that cuts the message or the title.

type PushEnableInput

type PushEnableInput struct {
	// Contact is the address the push services can reach the workspace at:
	// a mailto: or https: URI. Empty uses the member's email.
	Contact string `json:"contact,omitempty" maxLength:"200"`
}

PushEnableInput turns push on.

type PushEvent

type PushEvent struct {
	At time.Time `json:"at"`
	// Kind is the normalized event: sent (accepted by the push service),
	// gone, failed, shown, clicked, closed.
	Kind     string `json:"kind" enum:"sent,gone,failed,shown,clicked,closed,queued,delivered,undelivered,replied,opted_out,opted_in,help,read"`
	Raw      string `json:"raw"`
	Browser  string `json:"browser"`
	Site     string `json:"site"`
	Source   string `json:"source"`
	SourceID string `json:"sourceId,omitempty"`
	// SourceKind is campaign, automation or test.
	SourceKind string `json:"sourceKind" enum:"campaign,automation,test,confirmation,reply"`
	Message    string `json:"message"`
}

PushEvent is one line of the Events tab: what happened to a notification, raw beside what ReputeCast made of it.

type PushEventList

type PushEventList struct {
	Items []PushEvent `json:"items"`
	// Removed is how many subscriptions the push services reported gone in
	// the last 30 days.
	Removed int64 `json:"removed"`
	More    bool  `json:"more"`
}

PushEventList is a page of events.

type PushGuards

type PushGuards struct {
	Cap int `json:"cap"`
	// OverCap already got Cap notifications today; SentToday is what they
	// got.
	OverCap   int64           `json:"overCap"`
	SentToday []PushSentToday `json:"sentToday"`
	Quiet     bool            `json:"quiet"`
	Window    string          `json:"window"`
	// Zones is the audience by time zone, with what quiet hours do to a
	// notification sent now.
	Zones []PushZone `json:"zones"`
	// Held is how many a notification sent now holds until the window
	// opens; Inside how many get it now.
	Held   int64 `json:"held"`
	Inside int64 `json:"inside"`
	// Unknown subscribers' time zones came from nowhere: they're treated
	// as the workspace's.
	Unknown int64 `json:"unknown"`
}

PushGuards is the frequency cap and quiet hours for an audience.

type PushImage

type PushImage struct {
	MediaID string `json:"mediaId"`
	URL     string `json:"url"`
	Name    string `json:"name"`
	Width   int    `json:"width"`
	Height  int    `json:"height"`
	Bytes   int    `json:"bytes"`
}

PushImage is the notification's image.

type PushKeysView

type PushKeysView struct {
	PublicKey      string     `json:"publicKey"`
	CreatedAt      time.Time  `json:"createdAt"`
	CreatedBy      string     `json:"createdBy"`
	Contact        string     `json:"contact"`
	LastAcceptedAt *time.Time `json:"lastAcceptedAt,omitempty"`
}

PushKeysView is the keys card. The private key is never returned.

type PushLengthLimits

type PushLengthLimits struct {
	Title   int `json:"title"`
	Message int `json:"message"`
	// TitleWindows is about how much of the title Chrome on Windows shows.
	TitleWindows int `json:"titleWindows"`
}

PushLengthLimits are the composer's counters.

type PushListHighlight

type PushListHighlight struct {
	ListID string `json:"listId"`
	Name   string `json:"name"`
	Count  int64  `json:"count"`
}

PushListHighlight is the list whose members most often have a linked subscription: "612 belong to Acme Summit 2026 registrants".

type PushMonth

type PushMonth struct {
	Sent      int64     `json:"sent"`
	Campaigns int64     `json:"campaigns"`
	ShownPct  float64   `json:"shownPct"`
	Month     time.Time `json:"month"`
}

PushMonth is this month's sending.

type PushPrompt

type PushPrompt struct {
	FormID string `json:"formId"`
	Name   string `json:"name"`
	Status string `json:"status" enum:"draft,live,paused"`
	// Draft is what's being edited; Live what readers see (nil before the
	// first publication).
	Draft       PushPromptConfig  `json:"draft"`
	Live        *PushPromptConfig `json:"live,omitempty"`
	LiveVersion int               `json:"liveVersion"`
	LiveSince   *time.Time        `json:"liveSince,omitempty"`
	// Changed is true while the draft differs from what's live.
	Changed   bool                   `json:"changed"`
	Site      *PushPromptSiteOption  `json:"site,omitempty"`
	Sites     []PushPromptSiteOption `json:"sites"`
	PushOn    bool                   `json:"pushOn"`
	Stats     PushPromptStats        `json:"stats"`
	Consent   *PushConsentRecord     `json:"consent,omitempty"`
	IconURL   string                 `json:"iconUrl,omitempty"`
	UpdatedAt time.Time              `json:"updatedAt"`
	UpdatedBy string                 `json:"updatedBy"`
	CanEdit   bool                   `json:"canEdit"`
}

PushPrompt is the designer's view of a prompt.

type PushPromptCard

type PushPromptCard struct {
	FormID  string           `json:"formId"`
	Name    string           `json:"name"`
	Site    string           `json:"site"`
	Status  string           `json:"status" enum:"draft,live,paused"`
	Config  PushPromptConfig `json:"config"`
	Version int              `json:"version"`
	Stats   PushPromptStats  `json:"stats"`
}

PushPromptCard is a prompt in Setup's Prompts card.

type PushPromptConfig

type PushPromptConfig struct {
	Style string `json:"style" enum:"bar,dialog,bell"`
	// Corner is where a bell button sits.
	Corner  string         `json:"corner,omitempty" enum:"bottom_right,bottom_left,"`
	Title   string         `json:"title" maxLength:"60"`
	Message string         `json:"message" maxLength:"160"`
	Allow   string         `json:"allow" maxLength:"30"`
	NotNow  string         `json:"notNow" maxLength:"30"`
	When    PushPromptWhen `json:"when"`
	// Pages: every page except Paths ("all_except"), or only Paths.
	Pages string   `json:"pages" enum:"all_except,only"`
	Paths []string `json:"paths" maxItems:"20"`
	// AskAgainDays is how long "Not now" keeps the prompt away.
	AskAgainDays int `json:"askAgainDays" minimum:"1" maximum:"365"`
	// IOS: "steps" shows how to add the site to the Home Screen; "hidden"
	// keeps the prompt away on iPhone and iPad.
	IOS string `json:"ios" enum:"steps,hidden"`
}

PushPromptConfig is a prompt: style, text, when, where, how often and what iPhone and iPad readers see.

type PushPromptCreate

type PushPromptCreate struct {
	Name string `json:"name" minLength:"1" maxLength:"120"`
	// SiteID is the push site it's for; empty picks the first.
	SiteID string `json:"siteId,omitempty" maxLength:"40"`
}

PushPromptCreate makes a prompt.

type PushPromptPath

type PushPromptPath struct {
	api.WorkspaceInput
	FormID string `path:"formId" format:"uuid" doc:"Push prompt (form) id"`
}

PushPromptPath names a push prompt (its form).

type PushPromptRule

type PushPromptRule struct {
	On bool `json:"on"`
	N  int  `json:"n" minimum:"0" maximum:"10000"`
}

PushPromptRule is a "When" rule: on or off and its number.

type PushPromptSave

type PushPromptSave struct {
	Config PushPromptConfig `json:"config"`
	// SiteID is the push site the prompt is for.
	SiteID string `json:"siteId,omitempty" maxLength:"40"`
}

PushPromptSave is the draft from the designer.

type PushPromptSiteOption

type PushPromptSiteOption struct {
	// ID is the push site's id, empty for the publication website when it
	// isn't a push site yet.
	ID       string `json:"id,omitempty"`
	Host     string `json:"host"`
	Origin   string `json:"origin"`
	Kind     string `json:"kind" enum:"publication,snippet"`
	PushSite bool   `json:"pushSite"`
	// Website is the publication website's own home page (the preview
	// shows it).
	Website bool `json:"website"`
}

PushPromptSiteOption is a site the prompt can be on.

type PushPromptStats

type PushPromptStats struct {
	// Since is where the period starts: 30 days ago, or the day the site's
	// snippet was installed when that's later.
	Since        time.Time `json:"since"`
	SinceSnippet bool      `json:"sinceSnippet"`
	Shown        int64     `json:"shown"`
	Allowed      int64     `json:"allowed"`
	Granted      int64     `json:"granted"`
	NotNow       int64     `json:"notNow"`
	Closed       int64     `json:"closed"`
	BellClicked  int64     `json:"bellClicked"`
	Blocked      int64     `json:"blocked"`
	// AllowedPct, NotNowPct and ClosedPct are shares of the times it was
	// shown (bell clicks for a bell); GrantedPct is a share of Allow.
	AllowedPct float64 `json:"allowedPct"`
	GrantedPct float64 `json:"grantedPct"`
	NotNowPct  float64 `json:"notNowPct"`
	ClosedPct  float64 `json:"closedPct"`
	// iPhone and iPad.
	IOSSubscribers int64   `json:"iosSubscribers"`
	IOSSteps       int64   `json:"iosSteps"`
	IOSAdded       int64   `json:"iosAdded"`
	IOSAddedPct    float64 `json:"iosAddedPct"`
}

PushPromptStats are a prompt's numbers over a period.

type PushPromptStatus

type PushPromptStatus struct {
	Status string `json:"status" enum:"live,paused"`
}

PushPromptStatus pauses or resumes a live prompt.

type PushPromptWhen

type PushPromptWhen struct {
	// Seconds on a page.
	Seconds PushPromptRule `json:"seconds"`
	// Scroll is the percent of a post scrolled.
	Scroll PushPromptRule `json:"scroll"`
	// Posts read on the site.
	Posts PushPromptRule `json:"posts"`
	// Button: when the reader clicks the publisher's own button
	// (an element with data-rc-push).
	Button bool `json:"button"`
}

PushPromptWhen is when the prompt shows: as soon as one checked rule is met. A bell button opens when the reader clicks it.

type PushPublicConfig

type PushPublicConfig struct {
	Key     string             `json:"key"`
	Site    string             `json:"site"`
	Name    string             `json:"name"`
	Icon    string             `json:"icon,omitempty"`
	Accent  string             `json:"accent,omitempty"`
	Worker  string             `json:"worker"`
	Scope   string             `json:"scope"`
	Prompts []PushPublicPrompt `json:"prompts"`
	// Base is where the script calls (the site itself for the publication
	// website, else the instance).
	Base      string `json:"base"`
	Workspace string `json:"workspace"`
	// Text is ReputeCast's own words in the prompt (the Home Screen steps),
	// in the reader's language.
	Text map[string]string `json:"text"`
}

PushPublicConfig is what a site's prompt script reads.

type PushPublicPrompt

type PushPublicPrompt struct {
	ID      string           `json:"id"`
	Version int              `json:"version"`
	Config  PushPromptConfig `json:"config"`
}

PushPublicPrompt is a live prompt as the prompt script reads it.

type PushReport

type PushReport struct {
	ID         string     `json:"id"`
	Name       string     `json:"name"`
	Status     string     `json:"status" enum:"draft,approval,approved,scheduled,sending,paused,sent,cancelled,failed"`
	SentAt     *time.Time `json:"sentAt,omitempty"`
	SentBy     string     `json:"sentBy"`
	Sites      []string   `json:"sites"`
	Tag        string     `json:"tag"`
	TTLMinutes int        `json:"ttlMinutes"`
	// Planned is everyone the send was for; Skipped those the frequency cap
	// or quiet hours left out, by reason; Held those waiting for their
	// window; Queued those not handed over yet.
	Planned int64            `json:"planned"`
	Skipped map[string]int64 `json:"skipped"`
	Held    int64            `json:"held"`
	Queued  int64            `json:"queued"`
	// Sent were accepted by the push services; Failed weren't, Expired of
	// them because the subscription was gone (404, 410), and removed.
	Sent            int64               `json:"sent"`
	Failed          int64               `json:"failed"`
	Expired         int64               `json:"expired"`
	Shown           int64               `json:"shown"`
	ShownPct        float64             `json:"shownPct"`
	Clicks          int64               `json:"clicks"`
	ClicksPct       float64             `json:"clicksPct"`
	Unsubscribed    int64               `json:"unsubscribed"`
	UnsubscribedPct float64             `json:"unsubscribedPct"`
	ByBrowser       []PushReportBrowser `json:"byBrowser"`
	BySite          []PushReportSite    `json:"bySite"`
	// SitesNotIn are push sites that weren't in this audience.
	SitesNotIn []string          `json:"sitesNotIn"`
	Clicks24   []PushReportPoint `json:"clicks24"`
	CanSend    bool              `json:"canSend"`
}

PushReport is a push campaign's report.

type PushReportBrowser

type PushReportBrowser struct {
	Browser  string  `json:"browser" enum:"chrome,chrome_android,edge,firefox,safari,safari_ios,other"`
	Sent     int64   `json:"sent"`
	Shown    int64   `json:"shown"`
	ShownPct float64 `json:"shownPct"`
	Clicks   int64   `json:"clicks"`
}

PushReportBrowser is one browser's row.

type PushReportPoint

type PushReportPoint struct {
	Minutes int   `json:"minutes"`
	Clicks  int64 `json:"clicks"`
}

PushReportPoint is the clicks so far, Minutes after the send started.

type PushReportSite

type PushReportSite struct {
	Host string `json:"host"`
	Sent int64  `json:"sent"`
}

PushReportSite is one site's part.

type PushReview

type PushReview struct {
	ID        string                   `json:"id"`
	Name      string                   `json:"name"`
	Status    string                   `json:"status"`
	Version   int                      `json:"version"`
	Verdict   string                   `json:"verdict" enum:"ready,warnings,blocked"`
	CheckedAt time.Time                `json:"checkedAt"`
	Checks    []PushCheck              `json:"checks"`
	Sites     []PushReviewSite         `json:"sites"`
	Audience  PushAudience             `json:"audience"`
	Guards    PushGuards               `json:"guards"`
	Schedule  PushSchedule             `json:"schedule"`
	Test      *PushTestResult          `json:"test,omitempty"`
	Approval  approvals.ReviewApproval `json:"approval"`
	Access    PushAccess               `json:"access"`
	// Send is set once the campaign was scheduled or sent.
	Send *PushSendState `json:"send,omitempty"`
}

PushReview is Review & send for a push campaign.

type PushReviewSite

type PushReviewSite struct {
	Host        string `json:"host"`
	Subscribers int64  `json:"subscribers"`
}

PushReviewSite is a site's part of the audience.

type PushRotateInput

type PushRotateInput struct {
	Confirm string `json:"confirm" maxLength:"20" doc:"The number of subscriptions that end, as Rotation's confirm says."`
}

PushRotateInput confirms a rotation by typing the number of subscriptions that end.

type PushRotation

type PushRotation struct {
	Subscriptions int64             `json:"subscriptions"`
	Sites         []PushRotationRow `json:"sites"`
	// Scheduled are the notifications waiting to go that would reach
	// nobody: scheduled campaigns and live automations' push steps.
	Scheduled []string `json:"scheduled"`
	// Confirm is what to type: the number of subscriptions, without
	// separators ("4264").
	Confirm string `json:"confirm"`
}

PushRotation is what rotating the keys would end.

type PushRotationRow

type PushRotationRow struct {
	Host          string `json:"host"`
	Subscriptions int64  `json:"subscriptions"`
}

PushRotationRow is a site's subscriptions that end.

type PushSchedule

type PushSchedule struct {
	Mode   string     `json:"mode" enum:"now,at"`
	SendAt *time.Time `json:"sendAt,omitempty"`
	Zone   string     `json:"zone"`
	// Outside quiet hours: hold until the window opens, or skip.
	Outside    string `json:"outside" enum:"hold,skip"`
	TTLMinutes int    `json:"ttlMinutes"`
}

PushSchedule is when the campaign goes.

type PushSendInput

type PushSendInput struct {
	// Version is the version Review & send showed; a newer one is refused.
	Version int `json:"version" minimum:"1"`
}

PushSendInput sends or schedules a push campaign as reviewed.

type PushSendResult

type PushSendResult struct {
	Status      string    `json:"status" enum:"scheduled,sending"`
	ScheduledAt time.Time `json:"scheduledAt"`
	Recipients  int64     `json:"recipients"`
}

PushSendResult is what Send did.

type PushSendSettings

type PushSendSettings struct {
	Mode    string     `json:"mode" enum:"now,at"`
	SendAt  *time.Time `json:"sendAt,omitempty"`
	Outside string     `json:"outside" enum:"hold,skip"`
}

PushSendSettings is the schedule Review & send picks.

type PushSendState

type PushSendState struct {
	Phase       string     `json:"phase" enum:"scheduled,sending,completed,cancelled"`
	ScheduledAt time.Time  `json:"scheduledAt"`
	Recipients  int64      `json:"recipients"`
	StartedBy   string     `json:"startedBy,omitempty"`
	CompletedAt *time.Time `json:"completedAt,omitempty"`
}

PushSendState is a scheduled or running send.

type PushSentToday

type PushSentToday struct {
	Name string `json:"name"`
	// Kind is "campaign" or "automation"; By the campaign's sender or the
	// automation's name.
	Kind string    `json:"kind" enum:"campaign,automation"`
	By   string    `json:"by"`
	To   int64     `json:"to"`
	At   time.Time `json:"at"`
}

PushSentToday is a notification sent today.

type PushSettingsInput

type PushSettingsInput struct {
	// FrequencyCap is the most notifications a subscriber gets a day.
	FrequencyCap int `json:"frequencyCap" minimum:"1" maximum:"24"`
	// QuietHours keeps notifications to the window texts use.
	QuietHours bool `json:"quietHours"`
}

PushSettingsInput is the frequency cap and quiet hours.

type PushSetup

type PushSetup struct {
	On          bool             `json:"on"`
	Keys        *PushKeysView    `json:"keys,omitempty"`
	Cap         int              `json:"cap"`
	Quiet       bool             `json:"quiet"`
	Window      string           `json:"window"`
	Sites       []PushSite       `json:"sites"`
	CheckedAt   *time.Time       `json:"checkedAt,omitempty"`
	Subscribers PushSubscribers  `json:"subscribers"`
	Month       PushMonth        `json:"month"`
	Prompts     []PushPromptCard `json:"prompts"`
	Snippet     PushSnippet      `json:"snippet"`
	// Website is the publication website's address when it isn't a push
	// site yet: one click adds it.
	Website   string   `json:"website,omitempty"`
	CanManage bool     `json:"canManage"`
	Helpers   []string `json:"helpers"`
	// CanEditPrompts is forms:edit, which the prompts need.
	CanEditPrompts bool `json:"canEditPrompts"`
}

PushSetup is Sending providers › Push › Setup.

type PushSite

type PushSite struct {
	ID     string `json:"id"`
	Origin string `json:"origin"`
	Host   string `json:"host"`
	Kind   string `json:"kind" enum:"publication,snippet"`
	// Label is "Publication site", "Company site".
	Label         string           `json:"label"`
	Subscribers   int64            `json:"subscribers"`
	Linked        int64            `json:"linked"`
	Worker        PushWorker       `json:"worker"`
	Prompts       []PushSitePrompt `json:"prompts"`
	SnippetSeenAt *time.Time       `json:"snippetSeenAt,omitempty"`
	AddedAt       time.Time        `json:"addedAt"`
	AddedBy       string           `json:"addedBy"`
	IconURL       string           `json:"iconUrl,omitempty"`
	Demo          bool             `json:"demo"`
}

PushSite is a site readers turn notifications on from.

type PushSiteInput

type PushSiteInput struct {
	// Address is the site's address: "help.acme.io" or "https://help.acme.io".
	Address string `json:"address" minLength:"1" maxLength:"300"`
	Label   string `json:"label,omitempty" maxLength:"80"`
}

PushSiteInput adds a site.

type PushSitePath

type PushSitePath struct {
	api.WorkspaceInput
	SiteID string `path:"siteId" format:"uuid" doc:"Push site id"`
}

PushSitePath names a push site.

type PushSitePrompt

type PushSitePrompt struct {
	FormID    string     `json:"formId"`
	Name      string     `json:"name"`
	Style     string     `json:"style" enum:"bar,dialog,bell"`
	Status    string     `json:"status" enum:"draft,live,paused"`
	LiveSince *time.Time `json:"liveSince,omitempty"`
}

PushSitePrompt is a site's prompt in the sites table.

type PushSiteUpdate

type PushSiteUpdate struct {
	Label      string `json:"label" maxLength:"80"`
	WorkerMode string `json:"workerMode" enum:"file,import"`
	// WorkerPath is where the site's worker answers: /rc-push-sw.js, or the
	// site's own worker (/sw.js) that imports ours.
	WorkerPath string `json:"workerPath" maxLength:"200"`
	// IconMediaID is a 192 × 192 image from the media library; empty uses
	// the workspace logo.
	IconMediaID string `json:"iconMediaId,omitempty" maxLength:"40"`
}

PushSiteUpdate changes a site's label, its worker and its icon.

type PushSnippet

type PushSnippet struct {
	// Script is the snippet's src; ImportLine the line for a site that
	// already has a worker.
	Script        string `json:"script"`
	WorkerFile    string `json:"workerFile"`
	WorkerBytes   int    `json:"workerBytes"`
	WorkerVersion int    `json:"workerVersion"`
	WorkerURL     string `json:"workerUrl"`
	ImportURL     string `json:"importUrl"`
}

PushSnippet is what another site installs.

type PushStepEstimate

type PushStepEstimate struct {
	// Contacts are the flow's contacts waiting or in it; Linked those with
	// a linked subscription.
	Contacts      int64 `json:"contacts"`
	Linked        int64 `json:"linked"`
	Subscriptions int64 `json:"subscriptions"`
	PushOn        bool  `json:"pushOn"`
	// Window and Quiet: the quiet hours the step keeps to.
	Window string `json:"window"`
	Quiet  bool   `json:"quiet"`
}

PushStepEstimate is what the step's panel says about who it reaches.

type PushStepStats

type PushStepStats struct {
	NodeID  string           `json:"nodeId"`
	Sent    int64            `json:"sent"`
	Shown   int64            `json:"shown"`
	Clicks  int64            `json:"clicks"`
	Waiting int64            `json:"waiting"`
	Skipped map[string]int64 `json:"skipped"`
	FirstAt *time.Time       `json:"firstAt,omitempty"`
	LastAt  *time.Time       `json:"lastAt,omitempty"`
}

PushStepStats are a push step's numbers over 30 days.

type PushStepStatsList

type PushStepStatsList struct {
	Steps []PushStepStats `json:"steps"`
}

PushStepStatsList is a flow's push steps' numbers.

type PushSubscribers

type PushSubscribers struct {
	Total     int64              `json:"total"`
	Linked    int64              `json:"linked"`
	Anonymous int64              `json:"anonymous"`
	ByBrowser []PushCount        `json:"byBrowser"`
	BySite    []PushCount        `json:"bySite"`
	Highlight *PushListHighlight `json:"highlight,omitempty"`
}

PushSubscribers is the subscribers card.

type PushTestInput

type PushTestInput struct {
	Endpoint string `json:"endpoint" minLength:"1" maxLength:"1024"`
	P256dh   string `json:"p256dh" minLength:"1" maxLength:"200"`
	Auth     string `json:"auth" minLength:"1" maxLength:"100"`
}

PushTestInput is the member's browser subscription, made with the workspace's key by "Send to my browser".

type PushTestResult

type PushTestResult struct {
	At       time.Time `json:"at"`
	Browser  string    `json:"browser"`
	Platform string    `json:"platform"`
	Status   string    `json:"status" enum:"queued,sent,shown,clicked,failed"`
	Detail   string    `json:"detail,omitempty"`
}

PushTestResult is the last "Send to my browser".

type PushWorker

type PushWorker struct {
	Status string `json:"status" enum:"built_in,found,old_version,missing,unreachable,not_a_worker,unchecked"`
	// URL is where the worker must answer (https://acme.io/rc-push-sw.js).
	URL string `json:"url"`
	// Mode is "file" (rc-push-sw.js) or "import" (one line in the site's
	// own worker).
	Mode    string `json:"mode" enum:"file,import"`
	Path    string `json:"path"`
	Version *int   `json:"version,omitempty"`
	// Current is the version this build serves.
	Current    int        `json:"current"`
	Scope      string     `json:"scope"`
	HTTPStatus *int       `json:"httpStatus,omitempty"`
	Detail     string     `json:"detail,omitempty"`
	CheckedAt  *time.Time `json:"checkedAt,omitempty"`
}

PushWorker is a site's service worker as the last check found it.

type PushZone

type PushZone struct {
	Zone        string    `json:"zone"`
	LocalTime   string    `json:"localTime"`
	Subscribers int64     `json:"subscribers"`
	Inside      bool      `json:"inside"`
	Until       time.Time `json:"until"`
}

PushZone is the audience in one time zone.

type SegmentResolver

type SegmentResolver interface {
	ContactIDs(ctx context.Context, workspaceID, segmentID uuid.UUID) ([]uuid.UUID, error)
}

SegmentResolver lists a segment's contacts.

type Service

type Service struct {
	Pool  *pgxpool.Pool
	Q     *store.Queries
	Audit *audit.Logger
	Box   *secrets.Box
	Log   *slog.Logger
	URLs  publicurl.Builder
	Links *linktoken.Signer
	// Jobs enqueues River jobs (read at call time: the client is built
	// after the services).
	Jobs func() *jobs.Client
	Now  func() time.Time
	// HTTP is the SSRF-guarded client push services and sites are called
	// through.
	HTTP *http.Client
	// Demo is the in-process push service the demo's subscriptions are
	// sent to: they never reach FCM, Mozilla, Apple or Windows.
	Demo func() *webpushtest.Service
	// Segments resolves a segment's contacts for an audience.
	Segments SegmentResolver
	// Approvals evaluates the workspace's approval rules for push
	// campaigns and holds their requests (internal/approvals).
	Approvals Approvals
	// Changed re-checks a campaign's open approval after an edit.
	Changed func(ctx context.Context, ws *store.Workspace, campaignID uuid.UUID)
	// Emit sends outgoing webhook events (internal/webhooks).
	Emit func(ctx context.Context, q store.DBTX, ws *store.Workspace, event string, data any) error
	// Website says whether the workspace's publication website is on and
	// its address (https://news.acme.io), "" when it has none.
	Website func(ctx context.Context, ws *store.Workspace) string
	// Member is the contact signed in on the website with a request's
	// session cookie (uuid.Nil when nobody is).
	Member func(ctx context.Context, ws *store.Workspace, r *http.Request) uuid.UUID
	// icon of their own ("" when it has none).
	Logo func(ctx context.Context, ws *store.Workspace) string
	// Brand is the publisher's colour and name (Forms & pages › Branding):
	// the prompt's Allow button and the Home Screen steps use them.
	Brand func(ctx context.Context, ws *store.Workspace) (accent, name string)
}

Service is the push domain.

func (*Service) AddSite

func (s *Service) AddSite(ctx context.Context, ws *store.Workspace, p *authz.Principal, in PushSiteInput) (PushSite, error)

AddSite adds a site. The publication website's address becomes a built-in site; any other gets the snippet and the file to host.

func (*Service) Campaign

func (s *Service) Campaign(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (PushCampaign, error)

Campaign is the composer's view.

func (*Service) CampaignReport

func (s *Service) CampaignReport(ctx context.Context, ws *store.Workspace, id uuid.UUID, canSend bool) (PushReport, error)

CampaignReport is the report of a push campaign.

func (*Service) Cancel

func (s *Service) Cancel(ctx context.Context, ws *store.Workspace, id uuid.UUID) error

Cancel stops a sending campaign: notifications not yet handed to the push services don't go.

func (*Service) CheckAll

func (s *Service) CheckAll(ctx context.Context) error

CheckAll is the daily check of every snippet site.

func (*Service) CheckSite

func (s *Service) CheckSite(ctx context.Context, ws *store.Workspace, id uuid.UUID) (PushSite, error)

CheckSite fetches a snippet site's worker now and keeps what it found. The demo's sites answer from the demo data: they're never fetched.

func (*Service) CheckStale

func (s *Service) CheckStale(ctx context.Context, age time.Duration) error

CheckStale checks the snippet sites not checked for a while.

func (*Service) Click

func (s *Service) Click(ctx context.Context, id uuid.UUID, tok string, action int, userAgent string) (string, error)

Click records a click on a notification (action 0) or one of its buttons (1, 2) and returns where it goes, with UTM parameters. Only the notification's own links are ever a target.

func (*Service) ClickTarget

func (s *Service) ClickTarget(ctx context.Context, id uuid.UUID, tok string, action int) (string, error)

ClickTarget is where a click goes, without counting it: link previews and HEAD requests aren't readers.

func (*Service) ContactActivity

func (s *Service) ContactActivity(ctx context.Context, ws *store.Workspace, contactID uuid.UUID, before *time.Time, beforeID string, limit int) ([]audience.ContactActivityItem, int64, error)

ContactActivity puts a contact's notifications on their timeline (implements audience.ActivitySource): each notification to a linked subscription with how far it got (push_sent, push_shown, push_clicked, push_failed, push_skipped), and each subscription linked to them or ended (push_subscribed, push_unsubscribed), with its site and browser.

func (*Service) ContactCard

func (s *Service) ContactCard(ctx context.Context, ws *store.Workspace, p *authz.Principal, contactID uuid.UUID) (PushContactCard, error)

ContactCard lists a contact's linked subscriptions.

func (*Service) CreateCampaign

func (s *Service) CreateCampaign(ctx context.Context, ws *store.Workspace, p *authz.Principal, in PushCampaignCreate) (PushCampaign, error)

CreateCampaign makes a push campaign, audited like any campaign.

func (*Service) CreatePrompt

func (s *Service) CreatePrompt(ctx context.Context, ws *store.Workspace, p *authz.Principal, in PushPromptCreate) (PushPrompt, error)

CreatePrompt makes a push prompt: a form of type "push", a draft until it's published.

func (*Service) DeletePrompt

func (s *Service) DeletePrompt(ctx context.Context, ws *store.Workspace, id uuid.UUID) error

DeletePrompt deletes a prompt (logged): readers stop seeing it. The subscriptions it made stay, with their consent records (the exact text and version are kept with each).

func (*Service) DescribeForApproval

func (s *Service) DescribeForApproval(ctx context.Context, ws *store.Workspace, campaignID uuid.UUID) (approvals.ChannelCampaign, error)

DescribeForApproval describes a push campaign to the approvals domain (approvals.ChannelCampaigns).

func (*Service) Discard

func (s *Service) Discard(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (PushPrompt, error)

Discard throws the draft away: it becomes what's live again.

func (*Service) Dispatch

func (s *Service) Dispatch(ctx context.Context, budget time.Duration) (again time.Duration, done bool, err error)

Dispatch sends due notifications for up to budget. again is when to look next; done is true when nothing is queued at all.

func (*Service) DuplicateCampaign

func (s *Service) DuplicateCampaign(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (PushCampaign, error)

DuplicateCampaign copies a push campaign as a new draft.

func (*Service) Enable

Enable generates the keys and turns push on, with the publication website as the first site when the workspace has one: it works at once because ReputeCast serves its service worker.

func (*Service) Enabled

func (s *Service) Enabled(ctx context.Context, workspaceID uuid.UUID) (bool, error)

Enabled reports whether the workspace can send push: it has keys and a site. The channel switch shows push once it does.

func (*Service) Events

func (s *Service) Events(ctx context.Context, ws *store.Workspace, before *time.Time, limit int) (PushEventList, error)

Events lists the latest events, newest first.

func (*Service) FillChannelRows

func (s *Service) FillChannelRows(ctx context.Context, ws *store.Workspace, items []campaigns.CampaignListItem)

FillChannelRows fills in the campaigns list's push rows (implements campaigns.ChannelRows): the sites and how many each reached, shown and click rates once notifications went, and the review's verdict before.

func (*Service) MoveScheduled

func (s *Service) MoveScheduled(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, to approvals.ChannelMove) error

MoveScheduled moves a scheduled push campaign that hasn't started to another time: the calendar's reschedule (review 2026-11 CA-9). Push goes out at one time for everyone, so a time in each recipient's zone is refused.

func (*Service) PageRoutes

func (s *Service) PageRoutes(r chi.Router, workspace func(*http.Request) (*store.Workspace, bool))

PageRoutes mounts a workspace's push endpoints (under /p/{ws}/push).

func (*Service) Prompt

func (s *Service) Prompt(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (PushPrompt, error)

Prompt is the designer's view.

func (*Service) PublicRoutes

func (s *Service) PublicRoutes(r chi.Router, spa http.Handler)

PublicRoutes mounts the scripts, the workers and the click link. The workspace endpoints are under /p/{ws}/push (PageRoutes).

func (*Service) Publish

func (s *Service) Publish(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (PushPrompt, error)

Publish makes the draft what readers see: a new version, live.

func (*Service) RecordPromptEvent

func (s *Service) RecordPromptEvent(ctx context.Context, ws *store.Workspace, formID uuid.UUID, event string) error

RecordPromptEvent adds one event to the prompt's day.

func (*Service) RemoveContactSubscription

func (s *Service) RemoveContactSubscription(ctx context.Context, ws *store.Workspace, contactID, id uuid.UUID) error

RemoveContactSubscription ends one of a contact's subscriptions, by a person (audited).

func (*Service) RemoveSite

func (s *Service) RemoveSite(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) error

RemoveSite removes a site. Its subscriptions end: browsers there can no longer be reached.

func (*Service) Report

func (s *Service) Report(ctx context.Context, ws *store.Workspace, id uuid.UUID, tok, event string) error

Report records what the service worker reports: "shown" or "closed".

func (*Service) ReportCSV

func (s *Service) ReportCSV(ctx context.Context, ws *store.Workspace, id uuid.UUID) ([]byte, string, error)

ReportCSV exports the report by browser and site (audited).

func (*Service) Review

func (s *Service) Review(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (PushReview, error)

Review is Review & send.

func (*Service) Rotate

Rotate replaces the keys. Every subscription made with the old keys ends: readers have to allow notifications again.

func (*Service) Rotation

func (s *Service) Rotation(ctx context.Context, ws *store.Workspace) (PushRotation, error)

Rotation previews a rotation.

func (*Service) SaveDraft

func (s *Service) SaveDraft(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, in PushPromptSave) (PushPrompt, error)

SaveDraft keeps the designer's draft. Readers see it once it's published.

func (*Service) SaveSendSettings

func (s *Service) SaveSendSettings(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, in PushSendSettings) (PushReview, error)

SaveSendSettings keeps the schedule and what quiet hours do.

func (*Service) SaveSettings

func (s *Service) SaveSettings(ctx context.Context, ws *store.Workspace, p *authz.Principal, in PushSettingsInput) error

SaveSettings changes the frequency cap and quiet hours.

func (*Service) Send

Send sends the campaign now or schedules it, after the checks and the approval rules. Sending needs campaigns:send and push:send.

func (*Service) SendTest

func (s *Service) SendTest(ctx context.Context, ws *store.Workspace, p *authz.Principal, campaignID uuid.UUID, in PushTestInput, userAgent string) (PushTestResult, error)

SendTest sends the campaign to the member's own browser (logged).

func (*Service) SetContact

func (s *Service) SetContact(ctx context.Context, ws *store.Workspace, in PushContactInput) error

SetContact changes the contact address.

func (*Service) SetStatus

SetStatus pauses a prompt (readers stop seeing it; subscriptions stay) or resumes it.

func (*Service) Setup

func (s *Service) Setup(ctx context.Context, ws *store.Workspace, p *authz.Principal) (PushSetup, error)

Setup is the Setup tab.

func (*Service) SiteScripts

func (s *Service) SiteScripts(ctx context.Context, ws *store.Workspace, host string) []string

SiteScripts are the scripts a site page of the publication website loads for push: the prompt, when the site is a push site.

func (*Service) StartDue

func (s *Service) StartDue(ctx context.Context) error

StartDue starts the sends whose time has come.

func (*Service) StepEstimate

func (s *Service) StepEstimate(ctx context.Context, ws *store.Workspace, automationID uuid.UUID) (PushStepEstimate, error)

StepEstimate counts the flow's contacts with a linked subscription.

func (*Service) StepStats

func (s *Service) StepStats(ctx context.Context, ws *store.Workspace, automationID uuid.UUID) (PushStepStatsList, error)

StepStats are the flow's push steps' numbers over 30 days.

func (*Service) Subscribe

func (s *Service) Subscribe(ctx context.Context, ws *store.Workspace, in SubscribeRequest) (Subscribed, error)

Subscribe saves a browser's subscription from a listed site, with its consent record, linked to a contact when ReputeCast knows who it is.

func (*Service) TurnOff

func (s *Service) TurnOff(ctx context.Context, ws *store.Workspace, host string, l i18n.Lang) (label, done, none string, ok bool)

TurnOff is the preference center's "Turn off notifications in this browser" when host is a push site.

func (*Service) Unschedule

func (s *Service) Unschedule(ctx context.Context, ws *store.Workspace, id uuid.UUID) error

Unschedule takes a scheduled campaign back to a draft.

func (*Service) Unsubscribe

func (s *Service) Unsubscribe(ctx context.Context, ws *store.Workspace, endpoint, reason string) (bool, error)

Unsubscribe ends a browser's subscription: the reader turned notifications off on the account page or the preference center ("turned_off"), or the browser said it ended ("unsubscribed").

func (*Service) UpdateCampaign

func (s *Service) UpdateCampaign(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, in PushCampaignUpdate) (PushCampaign, error)

UpdateCampaign autosaves the composer: the notification, its buttons, expiry and tag, and the audience.

func (*Service) UpdateSite

func (s *Service) UpdateSite(ctx context.Context, ws *store.Workspace, id uuid.UUID, in PushSiteUpdate) (PushSite, error)

UpdateSite saves a site's settings.

type StartArgs

type StartArgs struct{}

StartArgs starts the scheduled sends whose time has come.

func (StartArgs) InsertOpts

func (StartArgs) InsertOpts() river.InsertOpts

InsertOpts implements river.JobArgsWithInsertOpts.

func (StartArgs) Kind

func (StartArgs) Kind() string

Kind implements river.JobArgs.

type StartWorker

type StartWorker struct {
	river.WorkerDefaults[StartArgs]
	S *Service
}

StartWorker runs StartArgs.

func (*StartWorker) Work

func (w *StartWorker) Work(ctx context.Context, _ *river.Job[StartArgs]) error

Work implements river.Worker.

type Step

type Step struct{ S *Service }

Step sends the "Send push" steps (automations.ChannelStep).

func (Step) Condition

Condition answers nothing: push has no branch conditions of its own.

func (Step) Permission

func (Step) Permission() authz.Permission

Permission is what publishing a flow with a push step needs.

func (Step) Send

Send queues the step's notification for the run's contact.

func (Step) Validate

Validate checks the step beyond the engine's own checks.

type SubscribeRequest

type SubscribeRequest struct {
	Origin   string
	Endpoint string
	P256dh   string
	Auth     string
	TimeZone string
	Page     string
	// FormID and Version are the prompt that asked, when one did.
	FormID  uuid.UUID
	Version int
	// Token is a reader token from the page's address (a personal link
	// from an email or a text, the preference center's link).
	Token     string
	Member    uuid.UUID
	IP        *netip.Addr
	UserAgent string
	// LinkedBy says why a contact is known: member, link, account, preferences.
	LinkedBy string
}

SubscribeRequest is what the prompt sends once the browser allowed notifications.

type Subscribed

type Subscribed struct {
	ID     uuid.UUID
	Linked bool
	New    bool
}

Subscribed is the answer to a subscribe.

type SweepArgs

type SweepArgs struct{}

SweepArgs purges clicks after 90 days and prompt counts after 400.

func (SweepArgs) InsertOpts

func (SweepArgs) InsertOpts() river.InsertOpts

InsertOpts implements river.JobArgsWithInsertOpts.

func (SweepArgs) Kind

func (SweepArgs) Kind() string

Kind implements river.JobArgs.

type SweepWorker

type SweepWorker struct {
	river.WorkerDefaults[SweepArgs]
	S *Service
}

SweepWorker runs SweepArgs.

func (*SweepWorker) Work

func (w *SweepWorker) Work(ctx context.Context, _ *river.Job[SweepArgs]) error

Work implements river.Worker.

Directories

Path Synopsis
Package webpush speaks the Web Push protocol with the standard library only (design expansion phase 8, X22):
Package webpush speaks the Web Push protocol with the standard library only (design expansion phase 8, X22):
webpushtest
Package webpushtest is an in-process push service for tests and the demo: it answers the requests FCM, Mozilla's autopush, Apple and Windows would get, checks the VAPID token as they do, decrypts the payload when it made the subscription, and records every message.
Package webpushtest is an in-process push service for tests and the demo: it answers the requests FCM, Mozilla's autopush, Apple and Windows would get, checks the VAPID token as they do, decrypts the payload when it made the subscription, and records every message.

Jump to

Keyboard shortcuts

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