push

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 15 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 push receives Rust+ push notifications: server and device pairing, smart alarms, deaths and team logins.

Rust+ notifications travel Facepunch → Expo → Firebase Cloud Messaging. NewDevice creates a push device posing as the Rust+ Android app, obtains an Expo push token for it and links it with Facepunch to the account the auth token belongs to. Listen then receives and decodes the notifications. The package stores nothing: the application persists the Device and, optionally, the listener's persistent IDs.

dev, err := push.NewDevice(ctx, authToken)
// persist dev (e.g. as JSON) wherever the application keeps secrets
err = push.Listen(ctx, dev, func(n push.Notification) {
	switch ev := n.Event.(type) {
	case push.ServerPairing:
		cfg := ev.Config(authToken) // ready for rustplus.Dial
	case push.Alarm:
		// ...
	}
})

Index

Examples

Constants

View Source
const (

	// DeviceName prefixes the device ID registered with Facepunch; see
	// WithDeviceName.
	DeviceName = "rustplus-go"
)

Variables

View Source
var ErrLoginRejected = errors.New("push: device login rejected")

ErrLoginRejected is returned by Listener.Run when Google refuses the device credentials. Register a new device.

Functions

func Link(ctx context.Context, d Device, authToken string, opts ...Option) error

Link registers d with Facepunch for the account of authToken, so that the account's notifications are sent to d. Call it again after signing in to Rust+ anew: the registration is tied to the auth token. The device itself stays the same and needs no new registration.

func Listen

func Listen(ctx context.Context, d Device, handle func(Notification), opts ...Option) error

Listen is a shortcut for NewListener(d, opts...).Run(ctx, handle).

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"

	"github.com/roreng/rustplus/push"
)

func main() {
	ctx := context.Background()
	authToken := os.Getenv("RUSTPLUS_AUTH_TOKEN")
	var dev push.Device // loaded from the application's storage

	err := push.Listen(ctx, dev, func(n push.Notification) {
		switch ev := n.Event.(type) {
		case push.ServerPairing:
			cfg := ev.Config(authToken) // ready for rustplus.New
			fmt.Println("paired with", ev.Name, cfg.ServerID)
		case push.EntityPairing:
			fmt.Println("paired", ev.EntityName, ev.EntityID)
		case push.Alarm:
			fmt.Println("alarm:", ev.Title, ev.Message)
		case nil:
			fmt.Println("other notification on channel", n.Channel)
		}
	})
	if errors.Is(err, push.ErrLoginRejected) {
		log.Fatal("device credentials rejected; register a new device")
	}
}

Types

type Alarm

type Alarm struct {
	Server
	Title    string
	Message  string
	EntityID uint64 // zero for alarms sent by server plugins
}

Alarm is sent when a paired smart alarm triggers. Title and Message are the texts configured on the alarm.

type App

type App struct {
	APIKey      string // Firebase API key
	ProjectID   string // Firebase project ID
	SenderID    string // GCM sender ID (project number)
	AppID       string // GMS app ID, "1:<sender>:android:<hash>"
	PackageName string // Android package name
	PackageCert string // SHA-1 of the signing certificate, hex
}

App identifies the Android app the push device registers as. The default is the Rust+ app (see RustPlusApp); override it with WithApp only if Facepunch changes the app's Firebase configuration.

func RustPlusApp

func RustPlusApp() App

RustPlusApp returns the Firebase identity of the Rust+ Android app. Each call returns a new copy.

type Device

type Device struct {
	FCM           DeviceCredentials `json:"fcm_credentials"`
	ExpoPushToken string            `json:"expo_push_token"`
}

Device is a registered push device: everything needed to receive notifications again without registering. It holds secrets; the library does not store it. Persist it however the application keeps secrets, for example as JSON: the layout matches rustplus.config.json written by the rustplus.js CLI, so such files decode into a Device.

A Device is independent of the Rust+ auth token. Link attaches it to the account of a token; do that again after signing in to Rust+ anew.

func NewDevice

func NewDevice(ctx context.Context, authToken string, opts ...Option) (Device, error)

NewDevice registers a new push device and links it to the account of authToken: an Android device with Google, its Expo push token, and the registration with Facepunch.

On error, the returned Device holds the steps that did succeed. Persist it and call Complete to resume: calling NewDevice again would create yet another device.

Example

The package stores nothing: the application persists the Device, here as a JSON file. Complete resumes a registration that failed half-way without creating another device.

package main

import (
	"context"
	"encoding/json"
	"log"
	"os"

	"github.com/roreng/rustplus/push"
)

func main() {
	ctx := context.Background()
	authToken := os.Getenv("RUSTPLUS_AUTH_TOKEN")

	var dev push.Device
	if b, err := os.ReadFile("device.json"); err == nil {
		if err := json.Unmarshal(b, &dev); err != nil {
			log.Fatal(err)
		}
	}
	if !dev.Registered() {
		err := dev.Complete(ctx, authToken)
		if b, merr := json.Marshal(dev); merr == nil {
			_ = os.WriteFile("device.json", b, 0o600) // save progress even on error
		}
		if err != nil {
			log.Fatal(err)
		}
	}
}

func (*Device) Complete

func (d *Device) Complete(ctx context.Context, authToken string, opts ...Option) error

Complete performs the registration steps d is still missing (Android device, Expo push token) and then links d to the account of authToken. It updates d as each step succeeds, so it can be called again after a failure.

func (Device) GoString

func (d Device) GoString() string

GoString implements fmt.GoStringer (%#v) with the secrets redacted.

func (Device) LogValue

func (d Device) LogValue() slog.Value

LogValue implements slog.LogValuer with the secrets redacted.

func (Device) Registered

func (d Device) Registered() bool

Registered reports whether d holds a complete registration.

func (Device) String

func (d Device) String() string

String implements fmt.Stringer with the secrets redacted.

type DeviceCredentials

type DeviceCredentials struct {
	// AndroidID and SecurityToken are the Android device credentials.
	AndroidID     uint64
	SecurityToken uint64
	// Token is the FCM registration token of the device.
	Token string
}

DeviceCredentials identify the push device registered with Google. Their JSON layout matches the "fcm_credentials" object of rustplus.js.

func (DeviceCredentials) GoString

func (d DeviceCredentials) GoString() string

GoString implements fmt.GoStringer (%#v) with the secrets redacted.

func (DeviceCredentials) LogValue

func (d DeviceCredentials) LogValue() slog.Value

LogValue implements slog.LogValuer with the secrets redacted.

func (DeviceCredentials) MarshalJSON

func (d DeviceCredentials) MarshalJSON() ([]byte, error)

MarshalJSON writes {"gcm":{"androidId","securityToken"},"fcm":{"token"}}.

func (DeviceCredentials) String

func (d DeviceCredentials) String() string

String implements fmt.Stringer with the secrets redacted.

func (*DeviceCredentials) UnmarshalJSON

func (d *DeviceCredentials) UnmarshalJSON(b []byte) error

UnmarshalJSON reads the layout written by MarshalJSON.

type EntityPairing

type EntityPairing struct {
	Server
	EntityID   uint64
	EntityType rustplus.EntityType
	// EntityName is the device kind as the game names it, e.g.
	// "Smart Switch", "Smart Alarm", "Storage Monitor".
	EntityName string
}

EntityPairing is sent when the player pairs a smart device.

type Event

type Event interface {
	// GameServer returns the server the notification is about.
	GameServer() Server
	// contains filtered or unexported methods
}

Event is the typed payload of a Notification. It is implemented only by the types of this package: ServerPairing, EntityPairing, Alarm, PlayerDeath and TeamLogin.

switch ev := n.Event.(type) {
case push.ServerPairing:
case push.Alarm:
}

type HTTPError

type HTTPError struct {
	URL        string
	StatusCode int
	Body       string
	// contains filtered or unexported fields
}

HTTPError is returned when an endpoint answers with a non-2xx status.

func (*HTTPError) Error

func (e *HTTPError) Error() string

type Listener

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

Listener receives Rust+ notifications for registered credentials.

func NewListener

func NewListener(d Device, opts ...Option) *Listener

NewListener returns a listener for the push device d.

func (*Listener) PersistentIDs

func (l *Listener) PersistentIDs() []string

PersistentIDs returns the IDs of notifications received since the last acknowledgement to Google. To avoid receiving them again after a restart, persist them and pass them to WithPersistentIDs.

func (*Listener) Run

func (l *Listener) Run(ctx context.Context, handle func(Notification)) error

Run receives notifications and calls handle for each until ctx is done, reconnecting as needed. Run must not be called concurrently, and handle runs on Run's goroutine: move long work elsewhere so heartbeats are not delayed.

Messages that cannot be decoded go to the WithErrorHandler function, or are logged. Notifications of unknown kinds are delivered with a nil Event.

Run returns ctx.Err() when ctx is done. When the device credentials are no longer valid it returns ErrLoginRejected or an *HTTPError (status 400, 401 or 403); register a new device then.

type Message

type Message struct {
	ID           string
	From         string
	Category     string
	PersistentID string
	// Sent is when the message was sent, if FCM reports it.
	Sent time.Time
	// Data is the key/value payload; Rust+ puts its fields here.
	Data map[string]string
	// RawData is the binary payload, if any.
	RawData []byte
}

Message is a raw push message as received from FCM.

type Notification

type Notification struct {
	// Channel is the notification channel: "pairing", "alarm", "player",
	// "team", "news", ...
	Channel string
	// Title and Message are the texts shown in the phone notification.
	Title   string
	Message string
	// Event is the typed payload, or nil for notifications this package
	// does not know. Use a type switch over the Event implementations.
	Event Event
	// Body is the raw JSON payload.
	Body json.RawMessage
	// Received is when the notification was sent (per FCM), or when it
	// arrived if FCM did not say.
	Received time.Time
	// Raw is the underlying push message.
	Raw Message
}

Notification is a decoded Rust+ push notification.

func ParseMessage

func ParseMessage(m Message) (Notification, error)

ParseMessage decodes a push message into a Rust+ notification. It returns an error for messages that are not Rust+ notifications.

type Option

type Option func(*options)

Option configures NewDevice, Complete, Link and the listener.

func WithApp

func WithApp(app App) Option

WithApp overrides the Firebase identity of the Rust+ app (RustPlusApp), for the case Facepunch changes it before this package is updated.

func WithDeviceName

func WithDeviceName(name string) Option

WithDeviceName sets the device ID registered with Facepunch. By default it is "rustplus-go-<hash of the push token>", unique per device. Use the same name only for the same device: registering another device under it takes its notifications away.

func WithErrorHandler

func WithErrorHandler(fn func(Message, error)) Option

WithErrorHandler sets a function called for push messages the listener cannot decode as Rust+ notifications, for example after a format change by Facepunch. By default they are logged at warning level.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sets the HTTP client for all registration requests.

func WithHeartbeat

func WithHeartbeat(d time.Duration) Option

WithHeartbeat sets how often the listener pings Google to detect a dead connection. The default is 4 minutes.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the logger for push and its FCM connection. Without it, connection logs are discarded and undecodable messages are logged to slog.Default.

func WithPersistentIDs

func WithPersistentIDs(ids []string) Option

WithPersistentIDs resumes a listener after the notifications with these IDs, as returned by Listener.PersistentIDs in an earlier run, so they are not delivered again. Storing them is up to the application.

type PlayerDeath

type PlayerDeath struct {
	Server
	Title string
	// KillerID and KillerName identify the killer; KillerID is zero for
	// non-player deaths.
	KillerID   uint64
	KillerName string
}

PlayerDeath is sent when the player is killed.

type Server

type Server struct {
	// ID is the server's relay ID, used as rustplus.Config.ServerID.
	ID          string
	Name        string
	Description string
	Image       string
	URL         string
	// IP and Port are only sent by servers that predate the relay.
	IP   string
	Port string
	// PlayerID and PlayerToken identify the paired player on the server.
	PlayerID    uint64
	PlayerToken int32
}

Server describes the game server a notification is about. It is part of every notification body.

func (Server) Config

func (s Server) Config(authToken string) rustplus.Config

Config returns a rustplus.Config for connecting to the server as the paired player.

func (Server) GameServer

func (s Server) GameServer() Server

GameServer returns s; it makes every Event expose its server.

type ServerPairing

type ServerPairing struct {
	Server
}

ServerPairing is sent when the player pairs a server ("Pair with server" in the game menu).

type TeamLogin

type TeamLogin struct {
	Server
	Title        string
	Message      string
	TeammateID   uint64
	TeammateName string
}

TeamLogin is sent when a teammate comes online.

Jump to

Keyboard shortcuts

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