welcomerimages

package
v0.0.0-...-fe3d589 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2023 License: AGPL-3.0 Imports: 48 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ConfigurationPath         = "welcomerimages.yaml"
	ErrOnConfigurationFailure = true
)
View Source
const VERSION = "0.4+120420212236"

VERSION respects semantic versioning.

Variables

This section is empty.

Functions

func DrawMultiline

func DrawMultiline(d font.Drawer, newFace func(float64) font.Face, args MultilineArguments) error

DrawMultiline draws text using multilines and adds stroke.

func ImagesCreate

func ImagesCreate(wi *WelcomerImageService) http.HandlerFunc

ImagesCreate handles creating images.

func ImagesGet

func ImagesGet(wi *WelcomerImageService) http.HandlerFunc

ImagesGet handles retrieving images.

Types

type Bench

type Bench struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Debugging tool showing timings between steps.

func NewBench

func NewBench() *Bench

func (*Bench) Add

func (b *Bench) Add(l string, t time.Time)

func (*Bench) Print

func (b *Bench) Print()

type FaceCache

type FaceCache struct {
	LastAccess

	Face *font.Face
}

FaceCache stores the Face and when it was last accessed.

type FileCache

type FileCache struct {
	LastAccess

	Filename string
	Ext      string
	Path     string
	Body     []byte
}

FileCache stores the file body and when it was last accessed.

type FontCache

type FontCache struct {
	LastAccessedMu sync.RWMutex
	LastAccessed   time.Time

	Font        *sfnt.Font
	FaceCacheMu sync.RWMutex
	FaceCache   map[float64]*FaceCache
}

FontCache stores the Font, last accessed and Faces for different sizes.

type GenerateImageArgs

type GenerateImageArgs struct {
	ImageOpts ImageOpts

	// Avatar with mask and background pre-applied
	Avatar image.Image
}

type GenerateThemeResp

type GenerateThemeResp struct {
	// Overlay
	Overlay image.Image

	// The target size of entire image
	TargetImageSize            image.Rectangle
	TargetImageW, TargetImageH int

	// The target size of backgrounds. This is
	// equal to TargetImage however changes if
	// there is a border.
	TargetBackgroundSize                 image.Rectangle
	TargetBackgroundW, TargetBackgroundH int

	// Point to move from (0,0) when
	// rendering the backgrounds
	BackgroundAnchor image.Point

	// Point to move from (0,0) when
	// rendering the overlay
	OverlayAnchor image.Point
}

type ImageCache

type ImageCache struct {
	LastAccess

	// The image format that is represented
	Format string

	Frames []image.Image

	// Config is the global color table (palette), width and height. A nil or
	// empty-color.Palette Config.ColorModel means that each frame has its own
	// color table and there is no global color table.
	Config image.Config

	// The successive delay times, one per frame, in 100ths of a second.
	Delay []int

	// LoopCount controls the number of times an animation will be
	// restarted during display.
	LoopCount int

	// Disposal is the successive disposal methods, one per frame.
	Disposal []byte

	// BackgroundIndex is the background index in the global color table, for
	// use with the DisposalBackground disposal method.
	BackgroundIndex byte
}

ImageCache stores the image and the extension for it.

func (*ImageCache) GetFrames

func (ic *ImageCache) GetFrames() []image.Image

GetFrames returns a copy of the ImageCache.Frames.

type ImageCreateArguments

type ImageCreateArguments struct {
	// cache = force_cache or filesize >= filesize_limit
	ForceCache    bool      `json:"force_cache"`
	FilesizeLimit int       `json:"filesize_limit"`
	Options       ImageOpts `json:"options"`
}

type ImageCreateResponse

type ImageCreateResponse struct {
	Success      bool       `json:"success"`
	Message      string     `json:"message,omitempty"`
	Bookmarkable string     `json:"bookmarkable,omitempty"`
	ImageData    *ImageData `json:"image_data,omitempty"`
}

type ImageData

type ImageData struct {
	ID        string    `json:"id" msgpack:"i"`
	GuildID   int64     `json:"guild_id" msgpack:"g"`
	Size      int       `json:"size" msgpack:"s"`
	Path      string    `json:"path" msgpack:"p"`
	ExpiresAt time.Time `json:"expires_at" msgpack:"e"`
	CreatedAt time.Time `json:"created_at" msgpack:"c"`
	// contains filtered or unexported fields
}

type ImageOpts

type ImageOpts struct {
	// Newline split message
	Text string `json:"text"`

	GuildId int64 `json:"guild_id"`

	UserId int64  `json:"user_id"`
	Avatar string `json:"avatar"`

	AllowGIF bool `json:"allow_gif"`

	// Which theme to use when generating images
	Theme Theme `json:"layout"`

	// Identifier for background
	Background string `json:"background"`

	// Identifier for font to use (along with Noto)
	Font string `json:"font"`

	// Border applied to entire image. If transparent, there is no border.
	BorderColour    color.RGBA `json:"-"`
	BorderColourHex string     `json:"border_colour"`
	BorderWidth     int        `json:"border_width"`

	// Alignment of left or right (assuming not vertical layout)
	ProfileAlignment ProfileAlignment `json:"profile_alignment"`

	// Text alignment (left, center, right) (top, middle, bottom)
	TextAlignmentX Xalignment `json:"text_alignment_x"`
	TextAlignmentY Yalignment `json:"text_alignment_y"`

	// Include a border around profile pictures. This also fills
	// under the profile.
	ProfileBorderColour    color.RGBA `json:"-"`
	ProfileBorderColourHex string     `json:"profile_border_colour"`
	// Padding applied to profile pictures inside profile border
	ProfileBorderWidth int `json:"profile_border_width"`
	// Type of curving on the profile border (circle, rounded, square)
	ProfileBorderCurve ProfileBorderCurve `json:"profile_border_curve"`

	// Text stroke. If 0, there is no stroke
	TextStroke          int        `json:"text_stroke"`
	TextStrokeColour    color.RGBA `json:"-"`
	TextStrokeColourHex string     `json:"text_stroke_colour"`

	TextColour    color.RGBA `json:"-"`
	TextColourHex string     `json:"text_colour"`
}

type LastAccess

type LastAccess struct {
	sync.RWMutex   // Used to stop deletion whilst being used
	LastAccessed   time.Time
	LastAccessedMu sync.RWMutex
}

LastAccess stores the last access of the structure.

type MultilineArguments

type MultilineArguments struct {
	DefaultFontSize float64 // default font size to start with

	X int
	Y int

	Width  int
	Height int

	HorizontalAlignment Xalignment
	VerticalAlignment   Yalignment

	StrokeWeight int
	StrokeColour color.Color
	TextColour   color.Color

	Text string
}

MultilineArguments is a list of arguments for the DrawMultiline function.

type ProfileAlignment

type ProfileAlignment uint8
const (
	FloatLeft ProfileAlignment = iota
	FloatRight
)

type ProfileBorderCurve

type ProfileBorderCurve uint8
const (
	CurveCircle ProfileBorderCurve = iota
	CurveSoft
	CurveSquare
)

type RequestCache

type RequestCache struct {
	LastAccess

	URL  string
	Body []byte
}

RequestCache stores the request body and when it was last accessed.

type StaticImageCache

type StaticImageCache struct {
	LastAccess

	Format string
	Image  image.Image
}

StaticImageCache stores just an image.

type Theme

type Theme uint8
const (
	ThemeRegular Theme = iota
	ThemeBadge
	ThemeVertical
)

type WelcomerImageConfiguration

type WelcomerImageConfiguration struct {
	Logging struct {
		Level                 string `json:"level" yaml:"level"`
		ConsoleLoggingEnabled bool   `json:"console_logging" yaml:"console_logging"`
		FileLoggingEnabled    bool   `json:"file_logging" yaml:"file_logging"`

		EncodeAsJSON bool `json:"encode_as_json" yaml:"encode_as_json"` // Make the framework log as json

		Directory  string `json:"directory" yaml:"directory"`     // Directory to log into.
		Filename   string `json:"filename" yaml:"filename"`       // Name of logfile.
		MaxSize    int    `json:"max_size" yaml:"max_size"`       // Size in MB before a new file.
		MaxBackups int    `json:"max_backups" yaml:"max_backups"` // Number of files to keep.
		MaxAge     int    `json:"max_age" yaml:"max_age"`         // Number of days to keep a logfile.
	} `json:"logging" yaml:"logging"`

	HTTP struct {
		Host            string `json:"host" yaml:"host"`
		BookmarkableURL string `json:"bookmarkable_url" yaml:"bookmarkable_url"`
	} `json:"http" yaml:"http"`

	Store struct {
		// List of paths for fonts to be stored in
		FontPath []string `json:"font_path" yaml:"font_path"`

		// Path for custom backgrounds to be stored in
		BackgroundsPath string `json:"backgrounds_path" yaml:"backgrounds_path"`

		// Path that serves static files
		StaticPath string `json:"static_path" yaml:"static_path"`

		// Path for images to be stored in
		StorePath string `json:"store_path" yaml:"store_path"`

		// Path of backgrounds that persist throughout the lifespan of the service
		StaticBackgroundsPath string `json:"static_backgrounds_path" yaml:"static_backgrounds_path"`

		// Name of StaticBackground to serve if failed to load custom one
		BackgroundFallback string `json:"background_fallback" yaml:"background_fallback"`

		// Font to serve if the one specified was not found
		DefaultFont string `json:"default_font" yaml:"default_font"`

		// Image to serve if no image was found
		DefaultImageLocation string `json:"default_image_location" yaml:"default_image_location"`

		// Image to serve when backgrounds fail. If empty will return a 500 rather than continue on
		FallbackProfileLocation string `json:"fallback_profile_location" yaml:"fallback_profile_location"`

		// Location of index folder to show on home page
		IndexLocation string `json:"index_location" yaml:"index_location"`

		// Does not require API key to use the image generation endpoints. Useful when localhost only.
		AllowAnonymousAccess bool `json:"allow_anonymous_access" yaml:"allow_anonymous_access"`

		// Location of embedded KV store.
		BoltDBLocation string `json:"bolt_db_location" yaml:"bolt_db_location"`
	} `json:"store" yaml:"store"`

	Prometheus struct {
		Enabled bool   `json:"enabled" yaml:"enabled"`
		Host    string `json:"host" yaml:"host"`
	} `json:"prometheus" yaml:"prometheus"`

	Internal struct {
		ConcurrentQuantizers int `json:"concurrent_quantizers" yaml:"concurrent_quantizers"`

		QuantizerSpeed      int `json:"quantizer_speed" yaml:"quantizer_speed"`
		QuantizerQualityMin int `json:"quantizer_quality_min" yaml:"quantizer_quality_min"`
		QuantizerQualityMax int `json:"quantizer_quality_max" yaml:"quantizer_quality_max"`
	}

	APIKeys []string `json:"api_keys" yaml:"api_keys"`

	FallbackFonts []string `json:"fallback_fonts" yaml:"fallback_fonts"`
}

WelcomerImageConfiguration represents the configuration of the service.

type WelcomerImageService

type WelcomerImageService struct {
	Logger zerolog.Logger `json:"-"`

	Start time.Time `json:"uptime"`

	Configuration *WelcomerImageConfiguration `json:"configuration"`

	PoolConcurrency limiter.ConcurrencyLimiter `json:"-"`
	PoolWaiter      sync.WaitGroup             `json:"-"`

	ServiceClosing abool.AtomicBool `json:"-"`

	Router *methodrouter.MethodRouter `json:"-"`

	Database *bolt.DB `json:"-"`

	DefaultImage        ImageData
	DefaultImageContent []byte

	UseFallbackProfile bool
	FallbackProfile    *StaticImageCache

	FallbackFonts []string

	FontCacheMu sync.RWMutex
	FontCache   map[string]*FontCache

	BackgroundCacheMu sync.RWMutex
	BackgroundCache   map[string]*ImageCache

	StaticBackgroundCache map[string]*ImageCache

	ProfileCacheMu sync.RWMutex
	ProfileCache   map[int64]*StaticImageCache
	// contains filtered or unexported fields
}

WelcomerImageService stores caches and any analytical data.

func NewService

func NewService(logger io.Writer) (wi *WelcomerImageService, err error)

NewService creates the Welcomer Image service and intializes it.

func (*WelcomerImageService) Close

func (wi *WelcomerImageService) Close() (err error)

Close will gracefully close the application and wait for any images being generated.

func (*WelcomerImageService) CreateFontPack

func (wi *WelcomerImageService) CreateFontPack(font string, size float64) *multiface.Face

CreateFontPack creates a pack of fonts with fallback and the one passed.

func (*WelcomerImageService) CreateFontPackHook

func (wi *WelcomerImageService) CreateFontPackHook(f string) func(float64) font.Face

CreateFontPackHook returns a newFace function with an argument.

func (*WelcomerImageService) EncodeImages

func (wi *WelcomerImageService) EncodeImages(b *bytes.Buffer, frames []image.Image, im *ImageCache) (string, error)

EncodeImages encodes a list of []image.Image and takes an input of AllowGifs. Outputs the file extension.

func (*WelcomerImageService) FetchAvatar

func (wi *WelcomerImageService) FetchAvatar(u int64, a string) (*StaticImageCache, error)

FetchAvatar fetches an avatar from a user id and avatar hash.

func (*WelcomerImageService) FetchBackground

func (wi *WelcomerImageService) FetchBackground(b string, allowGifs bool) (*ImageCache, error)

FetchBackground fetches a background from its id. Returns the image and boolean indicating GIF.

func (*WelcomerImageService) FetchFont

func (wi *WelcomerImageService) FetchFont(f string, size float64) (*FaceCache, *FontCache, error)

FetchFont fetches a font face with the specified size.

func (*WelcomerImageService) GenerateAvatar

func (wi *WelcomerImageService) GenerateAvatar(avatar *StaticImageCache, imageOpts ImageOpts) (image.Image, error)

GenerateAvatar applies masking and resizing to the avatar. Outputs an image.Image with same dimension as src image.

func (*WelcomerImageService) GenerateImage

func (wi *WelcomerImageService) GenerateImage(b *bytes.Buffer, imageOpts ImageOpts) (string, error)

GenerateImage generates an Image.

func (*WelcomerImageService) HandleRequest

func (wi *WelcomerImageService) HandleRequest(ctx *fasthttp.RequestCtx)

HandleRequest handles the HTTP requests.

func (*WelcomerImageService) LoadConfiguration

func (wi *WelcomerImageService) LoadConfiguration(path string) (configuration *WelcomerImageConfiguration, err error)

LoadConfiguration loads the service configuration.

func (*WelcomerImageService) Open

func (wi *WelcomerImageService) Open() (err error)

Opens starts up the services and loads the configuration and starts up the HTTP server.

func (*WelcomerImageService) PrometheusFetcher

func (wi *WelcomerImageService) PrometheusFetcher()

PrometheusFetcher fetches extra information such as store usage.

type Xalignment

type Xalignment uint8
const (
	AlignLeft Xalignment = iota
	AlignMiddle
	AlignRight
)

type Yalignment

type Yalignment uint8
const (
	AlignTop Yalignment = iota
	AlignCenter
	AlignBottom
)

Jump to

Keyboard shortcuts

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