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 ¶
- Constants
- Variables
- func Link(ctx context.Context, d Device, authToken string, opts ...Option) error
- func Listen(ctx context.Context, d Device, handle func(Notification), opts ...Option) error
- type Alarm
- type App
- type Device
- type DeviceCredentials
- type EntityPairing
- type Event
- type HTTPError
- type Listener
- type Message
- type Notification
- type Option
- type PlayerDeath
- type Server
- type ServerPairing
- type TeamLogin
Examples ¶
Constants ¶
const ( // DeviceName prefixes the device ID registered with Facepunch; see // WithDeviceName. DeviceName = "rustplus-go" )
Variables ¶
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 ¶
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.
Example ¶
After signing in to Rust+ again, link the same device to the new token.
package main
import (
"context"
"log"
"os"
"github.com/roreng/rustplus/push"
)
func main() {
var dev push.Device // loaded from the application's storage
if err := push.Link(context.Background(), dev, os.Getenv("RUSTPLUS_AUTH_TOKEN")); err != nil {
log.Fatal(err)
}
}
Output:
func Listen ¶
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")
}
}
Output:
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 ¶
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)
}
}
}
Output:
func (*Device) Complete ¶
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) Registered ¶
Registered reports whether d holds a complete registration.
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.
type Listener ¶
type Listener struct {
// contains filtered or unexported fields
}
Listener receives Rust+ notifications for registered credentials.
func NewListener ¶
NewListener returns a listener for the push device d.
func (*Listener) PersistentIDs ¶
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 ¶
WithApp overrides the Firebase identity of the Rust+ app (RustPlusApp), for the case Facepunch changes it before this package is updated.
func WithDeviceName ¶
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 ¶
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 ¶
WithHTTPClient sets the HTTP client for all registration requests.
func WithHeartbeat ¶
WithHeartbeat sets how often the listener pings Google to detect a dead connection. The default is 4 minutes.
func WithLogger ¶
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 ¶
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
Logo 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 ¶
Config returns a rustplus.Config for connecting to the server as the paired player.
func (Server) GameServer ¶
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).