texture

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 37 Imported by: 0

Documentation

Overview

Package texture owns uploaded skins and capes: the upload pipeline, the files (blobs, reference counted), the skin library and closets.

Index

Constants

View Source
const (
	MaxWidth    = 2048
	MaxUploadKB = 8192
)

Hard limits, whatever the settings say. Every accepted shape has height ≤ width, so one upload decodes at most MaxWidth² pixels (16 MiB as 8-bit RGBA).

View Source
const (
	SortTime  = "time"
	SortLikes = "likes"
)

Sort orders of the skin library (a whitelist; Blessing Skin sorted by any column the client named, including users' emails and password hashes, S07).

View Source
const MaxNameLen = 50

MaxNameLen is counted in characters (Blessing Skin's column was 50 wide).

View Source
const SweepGrace = time.Hour

SweepGrace is how long an unreferenced file is kept: an upload writes its file before its transaction, and a file just written again by an upload of the same image must not be deleted under it.

View Source
const SweepJobKind = "texture.sweep"

SweepJobKind deletes a file that no texture uses any more, once it is safe (see SweepFile).

Variables

View Source
var (
	// ErrInCloset: the texture is in the closet already.
	ErrInCloset = errors.New("already in the closet")
	// ErrNotInCloset: the closet has no such texture.
	ErrNotInCloset = errors.New("not in the closet")
)
View Source
var (
	ErrNotFound = errors.New("texture not found")
	// ErrPrivate means the texture exists but the viewer may not see it.
	ErrPrivate = errors.New("texture is private")
)
View Source
var ErrForbidden = errors.New("only the uploader or an administrator can do this")

ErrForbidden: only the uploader and administrators change a texture.

View Source
var ErrNotSkin = errors.New("only a skin can be an avatar")

ErrNotSkin refuses a cape where a skin is needed (an avatar is a skin's head).

Functions

func Lock

func Lock(ctx context.Context, tx *ent.Client, id int64) error

Lock takes the row lock of texture id for the rest of tx, as the first lock of a transaction that changes it or the scores tied to it (see score.Lock). It reports ErrNotFound when the texture is gone (deleted by the transaction it waited for).

func SettingDefs

func SettingDefs() []settings.Def

SettingDefs are the texture settings (Blessing Skin equivalents in docs/design/02 §4).

func ValidateName

func ValidateName(name string, rule *regexp.Regexp) error

ValidateName checks a texture name: 1–50 printable characters after trimming, and the site's name rule if it has one.

Types

type ClosetFilter

type ClosetFilter struct {
	Category string // "", skin or cape
	Query    string // item name fragment
	Before   int64  // cursor: items added before this one
	Limit    int
}

ClosetFilter selects items of a closet.

type Edit

type Edit struct {
	Name   *string
	Type   *string
	Public *bool
}

Edit changes the fields that are set.

type Filter

type Filter struct {
	Category   string // "", skin (steve and alex), steve, alex or cape
	Query      string // name fragment
	UploaderID int64
	Sort       string // SortTime (default) or SortLikes
	Cursor     string // from the previous page
	Limit      int
}

Filter selects textures for the skin library.

type Policy

type Policy struct {
	MaxBytes      int64
	MaxWidth      int
	NameRule      *regexp.Regexp // nil = any name
	AllowDownload bool
	PrivateStatus int // 403 or 404
}

Policy is what uploads and downloads need from the settings.

func PolicyFrom

func PolicyFrom(s *settings.Snapshot) Policy

PolicyFrom reads the policy from a settings snapshot.

type PublicDuplicateError

type PublicDuplicateError struct{ ID int64 }

PublicDuplicateError refuses to make a texture public when the same image is public already (as Blessing Skin did): the library shows each image once.

func (*PublicDuplicateError) Error

func (e *PublicDuplicateError) Error() string

type RescanResult added in v1.1.0

type RescanResult struct {
	Checked int `json:"checked"`
	Updated int `json:"updated"`
	Missing int `json:"missing"`
	Invalid int `json:"invalid"`
}

RescanResult summarizes RescanMissingBlobs.

type SearchDoc added in v1.1.0

type SearchDoc struct {
	ID         int64     `json:"id"`
	Name       string    `json:"name"`
	Type       string    `json:"type"`
	Hash       string    `json:"hash"`
	UploaderID int64     `json:"uploaderId,omitempty"`
	Public     bool      `json:"public"`
	Likes      int       `json:"likes"`
	CreatedAt  time.Time `json:"createdAt"`
	UpdatedAt  time.Time `json:"updatedAt"`
}

SearchDoc describes a texture document pushed to an external SearchProvider.

type SearchProvider added in v1.1.0

type SearchProvider interface {
	Index(ctx context.Context, doc SearchDoc) error
	Delete(ctx context.Context, textureID int64) error
	Search(ctx context.Context, q SearchQuery) (SearchResult, error)
}

SearchProvider is a hot-swappable full-text search backend registered by an authorized native plugin with the "provider.search" permission.

type SearchQuery added in v1.1.0

type SearchQuery struct {
	Query          string
	Category       string
	UploaderID     int64
	IncludePrivate bool
	Sort           string
	Cursor         string
	Limit          int
}

SearchQuery carries full-text search parameters delegated to a SearchProvider.

type SearchResult added in v1.1.0

type SearchResult struct {
	IDs        []int64
	NextCursor string
	Total      int64
}

SearchResult holds ranked texture IDs and pagination cursor from a SearchProvider.

type Service

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

Service implements textures.

func NewService

func NewService(db *ent.Client, store storage.Store, log *slog.Logger) *Service

NewService creates the service.

func (*Service) Avatar

func (s *Service) Avatar(ctx context.Context, userID int64) (*ent.Texture, error)

Avatar returns the skin whose head is a user's avatar, or nil: none set, gone, private to someone else (it went private after being chosen), so an avatar never shows what its owner could not see, or the user is banned or deleted (as a banned owner's players show the placeholder).

func (*Service) BeforeUserDelete

func (s *Service) BeforeUserDelete(ctx context.Context, tx *ent.Client, userID int64) error

BeforeUserDelete runs in the transaction that deletes an account for good, before the user's row goes:

  • it locks, in the one order (see score.Lock), every texture the deletion changes (the user's uploads, which lose their uploader, and the textures in their closet), then the user and everyone whose avatar is one of the private uploads. Deleting the row first locked the user and then, through the foreign key, their textures: the reverse of a closet add, and the two deadlocked;
  • it deletes the private uploads: nobody else could ever see them. Public ones stay, without an uploader (Blessing Skin left both behind, C09);
  • it counts the closet items, which the foreign key deletes, out of the textures' likes (they drifted upwards, Blessing Skin C04).

The caller kicks the job worker once the transaction has committed (file sweeps).

func (*Service) ByHash

func (s *Service) ByHash(ctx context.Context, hash string) (*ent.Texture, error)

ByHash returns a texture with this file (the oldest), for the hash-addressed avatar and preview routes; ErrNotFound if none.

func (*Service) CalibrateLikes

func (s *Service) CalibrateLikes(ctx context.Context) (int, error)

CalibrateLikes sets every texture's likes back to the number of closets holding it and reports how many it corrected. Likes change with every closet add and removal, in the same transaction; this catches what slips past: an account deleted at the very moment its owner added a texture, data imported from Blessing Skin (design 04 §5.2). It reads in pages and corrects one texture per transaction, under that texture's lock, so it never holds two locks and cannot deadlock with anything.

func (*Service) ClearSearchProvider added in v1.1.0

func (s *Service) ClearSearchProvider(owner string)

ClearSearchProvider removes the active SearchProvider only if it is owned by owner.

func (*Service) Closet

func (s *Service) Closet(ctx context.Context, userID int64, f ClosetFilter) ([]*ent.ClosetItem, int64, error)

Closet returns a page of a user's closet, newest first, with each item's texture.

func (*Service) ClosetPage

func (s *Service) ClosetPage(ctx context.Context, userID int64, f ClosetFilter, page, perPage int) ([]*ent.ClosetItem, int, error)

ClosetPage is a numbered page of a user's closet with the total, as Blessing Skin's resource API pages it (newest texture first; page from 1, perPage 1–100).

func (*Service) ClosetSize

func (s *Service) ClosetSize(ctx context.Context, userID int64) (int, error)

ClosetSize is how many textures a user's closet holds.

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, v Viewer, id int64, refund bool, rec *audit.Entry) error

Delete removes a texture (its uploader or an administrator). With refund, everyone who added it to a closet gets the fee back, and the uploader gets back what the upload cost in all (upload and visibility changes, net of the upload award; a net gain is taken back if the uploader can cover it). Players wearing it wear nothing. The file goes once no texture uses it (SweepFile). rec is written to the audit log in the same transaction when the viewer is not the uploader (an administrator moderating), with the texture's name and hash.

func (*Service) DeleteIn

func (s *Service) DeleteIn(ctx context.Context, tx *ent.Client, id int64, refund bool) error

DeleteIn deletes a texture as Delete does, inside the caller's transaction (a report review deletes the texture and settles the report at once). The caller checks who may delete it, and calls Kick once the transaction has committed.

func (*Service) Favorite

func (s *Service) Favorite(ctx context.Context, v Viewer, id int64, name string, r score.Rates) (*ent.ClosetItem, int64, error)

Favorite adds a texture the viewer may see to their closet (Blessing Skin calls it a "like"): it costs r.PerClosetItem, and the uploader, if it is someone else, earns r.AwardPerLike.

func (*Service) FileURL

func (s *Service) FileURL(hash string) string

FileURL is where a stored file can be fetched without passing through this server (an S3 store with a public URL, usually a CDN), or "".

func (*Service) Get

func (s *Service) Get(ctx context.Context, id int64, v Viewer) (*ent.Texture, error)

Get returns a texture the viewer may see, with its uploader.

func (*Service) GiveToCloset

func (s *Service) GiveToCloset(ctx context.Context, userID, id int64, rec *audit.Entry) (*ent.ClosetItem, error)

GiveToCloset adds a texture to a user's closet as an administrator does (Blessing Skin's closet management API): free, and nothing for the uploader. Taking it out again is Unfavorite, which refunds only what this item cost: nothing. A private texture goes only into its uploader's closet, as everywhere else (dropOthers). rec, if not nil, is written to the audit log in the same transaction.

func (*Service) HandleSweepJob

func (s *Service) HandleSweepJob(ctx context.Context, payload json.RawMessage) error

HandleSweepJob is the job handler for SweepJobKind.

func (*Service) InCloset

func (s *Service) InCloset(ctx context.Context, userID, textureID int64) (bool, error)

InCloset reports whether the texture is in the user's closet.

func (*Service) Kick

func (s *Service) Kick()

Kick wakes the job worker after a transaction that called DeleteIn has committed.

func (*Service) List

func (s *Service) List(ctx context.Context, f Filter, v Viewer) ([]*ent.Texture, string, error)

List returns a page of the skin library and the cursor of the next page ("" at the end). The library is public textures; private ones are listed only among the uploads of one user, to that user and to administrators. (Mixing "or my own private ones" into every page would keep the query from walking one index in order.)

func (*Service) Open

func (s *Service) Open(ctx context.Context, id int64, v Viewer) (*ent.Texture, storage.File, error)

Open returns the stored file of a texture the viewer may see (/raw/{tid}).

func (*Service) OpenHash

func (s *Service) OpenHash(ctx context.Context, hash string) (storage.File, error)

OpenHash returns a stored file by hash (/textures/{hash}). Hashes are the SHA-256 of the image, so knowing one means having seen the texture.

func (*Service) ReadFile

func (s *Service) ReadFile(ctx context.Context, hash string) ([]byte, error)

ReadFile reads a whole stored file (for rendering; textures are small).

func (*Service) RenameClosetItem

func (s *Service) RenameClosetItem(ctx context.Context, userID, id int64, name string) (*ent.ClosetItem, error)

RenameClosetItem renames a texture in the user's closet.

func (*Service) RescanMissingBlobs added in v1.1.0

func (s *Service) RescanMissingBlobs(ctx context.Context) (RescanResult, error)

RescanMissingBlobs inspects blobs whose width == 0 (for example textures imported before their files were synced via rsync/rclone/S3), verifies each stored file's SHA-256 and PNG dimensions, and fills in width, height, and exact byte size.

func (*Service) SearchProviderOwner added in v1.1.0

func (s *Service) SearchProviderOwner() string

SearchProviderOwner returns the owner of the currently registered SearchProvider, or "".

func (*Service) SetAvatar

func (s *Service) SetAvatar(ctx context.Context, v Viewer, id int64) error

SetAvatar makes a skin the viewer can see their avatar (Blessing Skin's "set as avatar"); 0 clears it.

func (*Service) SetHooks

func (s *Service) SetHooks(b *hook.Bus)

SetHooks sets the bus texture, closet and player events are published to (none before it is set).

func (*Service) SetJobNotifier

func (s *Service) SetJobNotifier(f func())

SetJobNotifier sets a function called after a transaction that queued a job commits, so the worker picks it up without waiting for its next poll.

func (*Service) SetSearchProvider added in v1.1.0

func (s *Service) SetSearchProvider(owner string, p SearchProvider)

SetSearchProvider atomically installs p under owner (e.g. "plugin:<id>"). Passing nil removes any custom search provider.

func (*Service) SweepFile

func (s *Service) SweepFile(ctx context.Context, hash string, now time.Time) (bool, error)

SweepFile deletes a stored file that no blob row names and that nothing has written for SweepGrace. Both conditions matter: the row is created only after an upload's file is written, and writing the same image again refreshes the file's time.

func (*Service) SweepOrphans

func (s *Service) SweepOrphans(ctx context.Context, now time.Time) (int, error)

SweepOrphans deletes every stored file without a blob row, older than SweepGrace: files of uploads whose transaction failed, or whose sweep job was lost.

func (*Service) Unfavorite

func (s *Service) Unfavorite(ctx context.Context, userID, id int64, refund bool, rec *audit.Entry) (int64, error)

Unfavorite removes a texture from the user's closet and from the user's players (players only wear closet textures). With refund the closet fee comes back, and the uploader's award for it is taken back if the uploader can still cover it. rec, if not nil, is written to the audit log in the same transaction (an administrator taking it out).

func (*Service) Update

func (s *Service) Update(ctx context.Context, v Viewer, id int64, e Edit, p Policy, r score.Rates, rec *audit.Entry) (*ent.Texture, error)

Update applies an uploader's or administrator's edit.

  • A new type must fit the image (a skin cannot become a cape of the wrong shape), and players wearing it in the slot it no longer fits take it off (Blessing Skin left capes on as skins, C08).
  • Going private costs the uploader the difference between the private and the public price of the upload, including the award public uploads earn; going public gives the same difference back (Blessing Skin took the award back on the way to private and never returned it, C12). Administrators changing someone else's texture charge nobody. Other users' closets lose a texture that goes private, with their fees returned and their players reset.

rec is written to the audit log in the same transaction when the viewer is not the uploader (an administrator moderating).

func (*Service) Upload

func (s *Service) Upload(ctx context.Context, uploader int64, in UploadInput, p Policy, r score.Rates) (*UploadResult, error)

Upload checks, stores and charges for a new texture, and puts it in the uploader's closet. The same image already in the library (public, or the uploader's own) is returned instead of stored twice.

func (*Service) Usage

func (s *Service) Usage(ctx context.Context, userID int64) (count int, bytes int64, err error)

Usage is how much a user has uploaded.

func (*Service) UsersOf

func (s *Service) UsersOf(ctx context.Context, tx *ent.Client, id int64) ([]int64, error)

UsersOf lists the users a deletion of texture id changes, for a caller that locks them first (score.Lock): everyone whose closet holds it, its uploader, and everyone showing it as their avatar.

type UploadInput

type UploadInput struct {
	Name   string
	Type   string
	Public bool
	Data   []byte
	Form   map[string]any
}

UploadInput is one upload.

type UploadResult

type UploadResult struct {
	Texture   *ent.Texture
	Duplicate bool
	Cost      int64 // score spent (negative: earned)
	Balance   int64
}

UploadResult is the uploaded texture, or the existing one when the same image is already in the library (Duplicate; nothing is charged).

type Viewer

type Viewer struct {
	UserID int64
	Admin  bool
}

Viewer is who is looking: 0 for a guest.

func (Viewer) MayView

func (v Viewer) MayView(t *ent.Texture) bool

MayView reports whether the viewer may see t.

Jump to

Keyboard shortcuts

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