devices

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	//tygo:emit export type DeviceType = typeof DeviceTypeKobo | typeof DeviceTypeKindle | typeof DeviceTypeKOReader | typeof DeviceTypeOPDS | typeof DeviceTypeBrowser;
	DeviceTypeKobo     = "kobo"
	DeviceTypeKindle   = "kindle"
	DeviceTypeKOReader = "koreader"
	DeviceTypeOPDS     = "opds"
	DeviceTypeBrowser  = "browser"
)
View Source
const (
	//tygo:emit export type Connection = typeof ConnectionKoboSync | typeof ConnectionEReaderBrowser | typeof ConnectionOPDS | typeof ConnectionKOReaderSync | typeof ConnectionKOReaderPlugin;
	ConnectionKoboSync       = "kobo_sync"
	ConnectionEReaderBrowser = "ereader_browser"
	ConnectionOPDS           = "opds"
	ConnectionKOReaderSync   = "koreader_sync"
	// ConnectionKOReaderPlugin is the KOReader plugin's own API (ADR 0016).
	ConnectionKOReaderPlugin = "koreader_plugin"
)
View Source
const (
	//tygo:emit export type DeliveryRulesMode = typeof RulesModeDefault | typeof RulesModePreset | typeof RulesModeCustom;
	// RulesModeDefault follows the owner's default Delivery Rules.
	RulesModeDefault = "default"
	// RulesModePreset follows the Device type's preset.
	RulesModePreset = "preset"
	// RulesModeCustom is the Device's own list, in device_delivery_rules.
	RulesModeCustom = "custom"
)
View Source
const (
	//tygo:emit export type ScopeType = typeof ScopeAll | typeof ScopeLibrary | typeof ScopeList;
	ScopeAll     = "all"
	ScopeLibrary = "library"
	ScopeList    = "list"
)

Variables

View Source
var ErrNotFound = errors.New("device not found")

ErrNotFound is returned when a Device does not exist or is not the caller's.

Functions

func AllowsFileType

func AllowsFileType(deviceType, fileType string) bool

AllowsFileType reports whether a Device of deviceType can receive a File delivered as fileType.

func CheckRules

func CheckRules(deviceType, mode string, rules []delivery.Rule) error

CheckRules returns a *delivery.RulesError when a Device of deviceType can't follow rules in mode: an unknown mode, a preset for a type with none, or a custom list ValidateRules refuses.

func PresetRules

func PresetRules(deviceType string) []delivery.Rule

PresetRules returns deviceType's preset, or nil when it has none.

func RegisterRoutes

func RegisterRoutes(e *echo.Group, db *bun.DB, authMiddleware *auth.Middleware)

RegisterRoutes registers Device management routes: each user's own Devices under /user/devices, and every user's Devices under /devices for admins, which never return a credential.

func RuleOptions

func RuleOptions(deviceType string) []delivery.RuleOption

RuleOptions lists every source File Type a custom rule for a Device of deviceType can name, in the built-in rules' order, with only the File Types the type can receive. A source File Type with none is left out.

func SetDevice

func SetDevice(c echo.Context, device *Device)

SetDevice stores device for RequireDevice. Only DeviceAuth, OPDSAuth, BasicAuth, KOReader's sync auth, middleware that updates the Device, and tests standing in for them call it.

func TypeLabel

func TypeLabel(deviceType string) string

TypeLabel is how a Device type is written for a reader.

func TypeLabelWithArticle

func TypeLabelWithArticle(deviceType string) string

TypeLabelWithArticle is TypeLabel as a noun phrase, such as "a Kobo Device" or "an OPDS app Device".

func ValidateRules

func ValidateRules(deviceType string, rules []delivery.Rule) error

ValidateRules checks a custom list for a Device of deviceType: everything delivery.Validate checks, and no rule delivering a File Type the type can't receive.

Types

type AdminDeviceResponse

type AdminDeviceResponse struct {
	Device      `tstype:",extends"`
	Connections []string       `json:"connections" tstype:"Connection[]"`
	Owner       models.UserRef `json:"owner" tstype:"UserRef"`
}

AdminDeviceResponse is a Device in the admin listing of every user's Devices. It never carries the credential, so an admin cannot act as the Device's owner.

type CreateDevicePayload

type CreateDevicePayload struct {
	Name       string `json:"name" mod:"trim" validate:"required,max=100"`
	DeviceType string `json:"device_type" validate:"required,oneof=kobo kindle koreader opds browser" tstype:"DeviceType"`
}

CreateDevicePayload is the request body for POST /user/devices. A new Device gets every connection its type can use.

type Device

type Device struct {
	bun.BaseModel `bun:"table:devices,alias:d" json:"-"`

	ID         string `bun:"id,pk" json:"id"`
	UserID     int    `bun:"user_id,notnull" json:"user_id"`
	Name       string `bun:"name,notnull" json:"name"`
	DeviceType string `bun:"device_type,notnull" json:"device_type" tstype:"DeviceType"`
	// Credential is only sent to the Device's owner, through
	// DeviceResponse, so an admin listing can never act as another user.
	Credential     string `bun:"credential,notnull,unique" json:"-"`
	ScopeType      string `bun:"scope_type,notnull" json:"scope_type" tstype:"ScopeType"`
	ScopeLibraryID *int   `bun:"scope_library_id" json:"scope_library_id"`
	ScopeListID    *int   `bun:"scope_list_id" json:"scope_list_id"`
	// URLScopePending marks a Kobo migrated from an API key whose scope
	// still comes from the scope segment of its old sync URL. Its first
	// request sets the Device's scope and clears it, as do saving a scope
	// and regenerating the credential, which retires the old URL.
	URLScopePending bool `bun:"url_scope_pending,notnull" json:"url_scope_pending"`
	// DeliveryRulesMode says which Delivery Rules the Device follows: its
	// owner's default, its type's preset, or its own list (Service.Rules).
	DeliveryRulesMode string     `bun:"delivery_rules_mode,notnull" json:"delivery_rules_mode" tstype:"DeliveryRulesMode"`
	CreatedAt         time.Time  `bun:"created_at,notnull" json:"created_at"`
	UpdatedAt         time.Time  `bun:"updated_at,notnull" json:"updated_at"`
	LastAccessedAt    *time.Time `bun:"last_accessed_at" json:"last_accessed_at"`
	// PluginLastConnectedAt is when a KOReader Device last reached Shisho
	// through the KOReader plugin, and PluginVersion the plugin version it
	// reported then. Both are nil until it first does.
	PluginLastConnectedAt *time.Time `bun:"plugin_last_connected_at" json:"plugin_last_connected_at"`
	PluginVersion         *string    `bun:"plugin_version" json:"plugin_version"`
	// PluginLastSyncedAt is when the Device last uploaded its reading
	// through the KOReader plugin. Once it has, its progress sync pushes are
	// ignored, since the plugin reports the same reading.
	PluginLastSyncedAt *time.Time `bun:"plugin_last_synced_at" json:"plugin_last_synced_at"`

	Owner        *models.UserRef `bun:"rel:belongs-to,join:user_id=id" json:"-"`
	ScopeLibrary *models.Library `bun:"rel:belongs-to,join:scope_library_id=id" json:"-"`
	ScopeList    *models.List    `bun:"rel:belongs-to,join:scope_list_id=id" json:"-"`
}

Device is one reading app on one piece of hardware (ADR 0011). It belongs to one user and owns the credential every one of its connections uses.

func RequireDevice

func RequireDevice(c echo.Context) (*Device, error)

RequireDevice returns the Device DeviceAuth stored, or a 401 when there is none, so a route registered without DeviceAuth fails closed.

func SignedInDevice

func SignedInDevice(c echo.Context) *Device

SignedInDevice returns the Device a request signed in as, or nil for one signed in without a Device, as OPDS allows with the account password. Routes that always need a Device use RequireDevice.

func (*Device) ConnectionNames

func (d *Device) ConnectionNames() []string

ConnectionNames returns the connections the Device's type uses.

func (*Device) HasConnection

func (d *Device) HasConnection(connection string) bool

HasConnection reports whether the Device's type connects through connection.

func (*Device) Scope

func (d *Device) Scope() Scope

Scope returns the Device's scope.

type DeviceDeliveryRule

type DeviceDeliveryRule struct {
	bun.BaseModel `bun:"table:device_delivery_rules,alias:ddr"`

	DeviceID          string `bun:"device_id,pk"`
	SourceFileType    string `bun:"source_file_type,pk"`
	DeliveredFileType string `bun:"delivered_file_type,notnull"`
	Position          int    `bun:"position,notnull"`
}

DeviceDeliveryRule is one rule of a Device's own Delivery Rules. Only a Device whose DeliveryRulesMode is custom has rows.

type DeviceDeliveryRulesPayload

type DeviceDeliveryRulesPayload struct {
	Mode  string          `json:"mode" validate:"required" tstype:"DeliveryRulesMode"`
	Rules []delivery.Rule `json:"rules,omitempty" validate:"dive" mod:"dive" tstype:"Rule[]"`
}

DeviceDeliveryRulesPayload makes a Device follow its owner's default, follow its type's preset, or use Rules as its own list. Rules is read only for a custom list, which can't be empty or deliver a File Type the Device's type can't receive.

type DeviceResponse

type DeviceResponse struct {
	Device      `tstype:",extends"`
	Credential  string   `json:"credential"`
	Connections []string `json:"connections" tstype:"Connection[]"`
	// ScopeName is the name of the scope's library or list. It is omitted
	// for All Books, and for a scope whose library or list was deleted.
	ScopeName string `json:"scope_name,omitempty"`
	// DeliveryRules are the rules the Device follows now, whichever way it
	// follows them. A custom list starts as a copy of them.
	DeliveryRules []delivery.Rule `json:"delivery_rules" tstype:"Rule[]"`
	// DeliveryRuleOptions lists every source File Type a custom rule can
	// name, with only the File Types the Device's type can receive.
	DeliveryRuleOptions []delivery.RuleOption `json:"delivery_rule_options" tstype:"RuleOption[]"`
	// HasPreset is true when the Device's type has a preset to follow.
	HasPreset bool `json:"has_preset"`
}

DeviceResponse is a Device as its owner sees it, with its credential, the connections its type uses, and the name of its scope's library or list. Only routes under /user/devices, which return the caller's own Devices, send it.

type DeviceScopePayload

type DeviceScopePayload struct {
	Type      string `json:"type" validate:"required,oneof=all library list" tstype:"ScopeType"`
	LibraryID *int   `json:"library_id,omitempty" tstype:"number"`
	ListID    *int   `json:"list_id,omitempty" tstype:"number"`
}

DeviceScopePayload sets a Device's scope. LibraryID is required for a library scope and ListID for a list scope.

type DeviceShortURL

type DeviceShortURL struct {
	bun.BaseModel `bun:"table:device_short_urls,alias:dsu" json:"-"`

	ID        string    `bun:"id,pk" json:"id"`
	DeviceID  string    `bun:"device_id,notnull" json:"device_id"`
	ShortCode string    `bun:"short_code,notnull,unique" json:"short_code"`
	ExpiresAt time.Time `bun:"expires_at,notnull" json:"expires_at"`
	CreatedAt time.Time `bun:"created_at,notnull" json:"created_at"`

	Device *Device `bun:"rel:belongs-to,join:device_id=id" json:"-"`
}

DeviceShortURL is a short-lived code that redirects to a Device's eReader browser URL, so it can be typed on an e-ink keyboard.

type Middleware

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

Middleware authenticates the device routes (Kobo and eReader) that carry a Device credential in the URL.

func NewMiddleware

func NewMiddleware(service *Service) *Middleware

NewMiddleware creates Device middleware backed by service.

func (*Middleware) BasicAuth added in v0.8.0

func (m *Middleware) BasicAuth(connection string) echo.MiddlewareFunc

BasicAuth signs a request in with Basic Auth: a username with the credential of one of that user's Devices whose type uses connection, as the KOReader plugin sends them. Any other username and password is a 401, a Device whose type doesn't use connection a 403, and the owner is checked with AuthenticateOwner. Like DeviceAuth, it touches the Device's last accessed time and stores the Device and its owner.

func (*Middleware) DeviceAuth

func (m *Middleware) DeviceAuth(connection string) echo.MiddlewareFunc

DeviceAuth validates the credential in c.Param("credential"), checks that its Device's type uses connection, and loads its owner with AuthenticateOwner, which rejects a missing or deactivated owner (401) and one without books:read (403). It touches the Device's last accessed time without waiting, stores the Device for RequireDevice, and stores the owner with auth.SetUser, so handlers read it with auth.RequireUser and auth.RequireLibraryAccessFor like every other route.

func (*Middleware) OPDSAuth

func (m *Middleware) OPDSAuth(passwordAuth echo.MiddlewareFunc) echo.MiddlewareFunc

OPDSAuth signs an OPDS request in with Basic Auth. A username with the credential of one of that user's Devices that uses OPDS signs in as the Device, so feeds and downloads follow its Delivery Rules and scope. Anything else goes to passwordAuth, so the account password still signs in without a Device. A Device is looked up before the password is checked, so signing in with a credential costs no bcrypt comparison, and only for a password shaped like a credential, so a password sign-in answered from passwordAuth's cache costs no query. A Device whose owner is deactivated gets the Basic challenge, as a wrong password does; an owner without books:read gets the 403 password sign-in gets from RequirePermission. Like DeviceAuth, a Device sign-in does not wait on a forced password reset, which only the account password is subject to.

type RulesChange

type RulesChange struct {
	Mode  string
	Rules []delivery.Rule
}

RulesChange makes a Device follow its owner's default, follow its type's preset, or use Rules as its own list (Mode is a RulesMode constant).

type Scope

type Scope struct {
	Type      string
	LibraryID *int
	ListID    *int
}

Scope is the set of books a Device reaches through every connection: all the owner's books, one library, or one list.

type Service

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

func NewService

func NewService(db *bun.DB) *Service

func (*Service) ApplyURLScope

func (s *Service) ApplyURLScope(ctx context.Context, device *Device, scope Scope) (*Device, error)

ApplyURLScope sets a migrated Kobo's scope from the scope segment of its old sync URL, the first time it connects after upgrading, and returns the Device as stored afterwards. Later requests, and Devices that never had a scope in their URL, keep the Device's own scope.

func (*Service) AuthenticateOwner

func (s *Service) AuthenticateOwner(ctx context.Context, device *Device) (*models.User, error)

AuthenticateOwner loads the user who owns device, with Role, Role.Permissions and LibraryAccess, and checks that the owner may still use it. A missing or deactivated owner returns 401, and an owner whose role lacks books:read returns 403. Middleware.DeviceAuth calls this so a Device never outlives its owner's access, and stores the returned user with auth.SetUser for handlers to reuse. The eReader short URL calls it too.

func (*Service) ClearKoboSyncHistory

func (s *Service) ClearKoboSyncHistory(ctx context.Context, userID int, id string) error

ClearKoboSyncHistory deletes all Kobo sync points for userID's Device id, forcing a fresh sync.

func (*Service) Create

func (s *Service) Create(ctx context.Context, userID int, name, deviceType string) (*Device, error)

Create adds a Device for userID with every connection its type can use.

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, userID int, id string) error

Delete removes userID's Device id, with its short URLs and Kobo sync state.

func (*Service) GenerateShortURL

func (s *Service) GenerateShortURL(ctx context.Context, userID int, id string) (*DeviceShortURL, error)

GenerateShortURL creates a short URL for userID's Device id that expires after shortURLTTL.

func (*Service) GetByCredential

func (s *Service) GetByCredential(ctx context.Context, credential string) (*Device, error)

GetByCredential returns the Device whose credential is exactly credential, or nil. The column compares bytes, so a credential typed in another case, with a hyphen, or with a lookalike letter matches nothing.

func (*Service) GetByOwnerCredential

func (s *Service) GetByOwnerCredential(ctx context.Context, username, credential string) (*Device, error)

GetByOwnerCredential returns the Device of the user named username (in any case, as password sign-in matches it) whose credential is exactly credential, or nil. It compares against each of that user's Devices in constant time, so a guess reveals nothing about how close it came, and costs one query, not a bcrypt comparison.

func (*Service) GetByOwnerCredentialMD5 added in v0.7.0

func (s *Service) GetByOwnerCredentialMD5(ctx context.Context, username, key, connection string) (*Device, error)

GetByOwnerCredentialMD5 returns the Device of the user named username (in any case) that uses connection and whose credential has the MD5 key, or nil. KOReader's progress sync sends only the MD5 of its password. It compares against every matching Device in constant time, so a guess reveals nothing about how close it came.

func (*Service) List

func (s *Service) List(ctx context.Context, userID int) ([]*Device, error)

List returns userID's Devices, oldest first.

func (*Service) ListAll

func (s *Service) ListAll(ctx context.Context) ([]*Device, error)

ListAll returns every user's Devices with their owners, ordered by owner and then oldest first.

func (*Service) RecordPluginConnection added in v0.8.0

func (s *Service) RecordPluginConnection(ctx context.Context, id, pluginVersion string) error

RecordPluginConnection notes that Device id reached Shisho through the KOReader plugin now, reporting pluginVersion.

func (*Service) RecordPluginSync added in v0.8.0

func (s *Service) RecordPluginSync(ctx context.Context, id string, at time.Time) error

RecordPluginSync notes that Device id uploaded its reading through the KOReader plugin at at.

func (*Service) RegenerateCredential

func (s *Service) RegenerateCredential(ctx context.Context, userID int, id string) (*Device, error)

RegenerateCredential gives userID's Device id a new credential, so URLs holding the old one stop working. Its short URLs are deleted, since they would otherwise redirect to the new credential.

func (*Service) ResolveShortCode

func (s *Service) ResolveShortCode(ctx context.Context, shortCode string) (*Device, error)

ResolveShortCode returns the Device an unexpired short code belongs to, or nil.

func (*Service) Retrieve

func (s *Service) Retrieve(ctx context.Context, userID int, id string) (*Device, error)

Retrieve returns userID's Device id, or ErrNotFound.

func (*Service) Revoke

func (s *Service) Revoke(ctx context.Context, id string) error

Revoke removes any user's Device id. Admins use it to cut off a lost Device.

func (*Service) Rules

func (s *Service) Rules(ctx context.Context, device *Device) ([]delivery.Rule, error)

Rules returns the Delivery Rules device follows: its owner's default without the rules its type can't receive, its type's preset, or its own list. Every channel a Device connects through delivers by these.

func (*Service) RulesFor

func (s *Service) RulesFor(ctx context.Context, devices []*Device) (map[string][]delivery.Rule, error)

RulesFor returns the Delivery Rules each of devices follows, by Device id, as Rules does. It loads every custom list in one query and each owner's default once, so listing Devices costs the same few queries however many there are.

func (*Service) RulesInMode

func (s *Service) RulesInMode(ctx context.Context, device *Device, mode string, rules []delivery.Rule) ([]delivery.Rule, error)

RulesInMode returns the Delivery Rules device would follow in mode, with rules as its own list when mode is custom, without saving anything, so a change can be previewed before it is saved. It returns a *delivery.RulesError for a mode or list the Device can't have.

func (*Service) SetRules

func (s *Service) SetRules(ctx context.Context, userID int, id string, mode string, rules []delivery.Rule) (*Device, error)

SetRules makes userID's Device id follow the owner's default, follow its type's preset, or use rules as its own list, and returns the Device. A following mode ignores rules and drops any list saved before. It returns a *delivery.RulesError for a mode or list the Device can't have.

func (*Service) TouchLastAccessed

func (s *Service) TouchLastAccessed(ctx context.Context, id string) error

TouchLastAccessed updates the last_accessed_at timestamp for a Device.

func (*Service) Update

func (s *Service) Update(ctx context.Context, userID int, id string, opts UpdateDeviceOptions) (*Device, error)

Update applies opts to userID's Device id, in one transaction, and returns it. It returns a *delivery.RulesError, before saving anything, for rules the Device's resulting type can't follow.

type UpdateDeviceOptions

type UpdateDeviceOptions struct {
	Name       *string
	DeviceType *string
	Scope      *Scope
	Rules      *RulesChange
}

UpdateDeviceOptions holds the changes Update applies. A nil field is left unchanged. Callers check that a scope's library or list is one the owner can see. A new DeviceType puts the Device back on the rules that type starts with, since its own list may name File Types the new type can't receive, unless Rules says what to follow instead.

type UpdateDevicePayload

type UpdateDevicePayload struct {
	Name *string `json:"name,omitempty" mod:"trim" validate:"omitempty,min=1,max=100" tstype:"string"`
	// DeviceType changes the Device's type, which puts it back on the rules
	// the new type starts with.
	DeviceType *string `json:"device_type,omitempty" validate:"omitempty,oneof=kobo kindle koreader opds browser" tstype:"DeviceType"`
	// DeliveryRules sets which Delivery Rules the Device follows. It applies
	// after DeviceType.
	DeliveryRules *DeviceDeliveryRulesPayload `json:"delivery_rules,omitempty" tstype:"DeviceDeliveryRulesPayload"`
	// Scope replaces the Device's scope, and stops a migrated Kobo from
	// taking its scope from its old sync URL.
	Scope *DeviceScopePayload `json:"scope,omitempty" tstype:"DeviceScopePayload"`
}

UpdateDevicePayload is the request body for PATCH /user/devices/:id. An omitted field keeps its saved value.

Jump to

Keyboard shortcuts

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