Documentation
¶
Index ¶
- Constants
- Variables
- func AltTextFromPrompt(prompt string) string
- func BuildGenerationPrompt(prompt string, og bool) string
- func DetectImageMimeType(data []byte) string
- func ExtractHashFromURL(rawURL string) string
- func GenerateDuplicateFilename(filename string) string
- func HammingDistance(a, b uint64) int
- func ParseDateFilter(dateFilter string) (time.Time, bool)
- func PerceptualHash(r io.Reader) (uint64, error)
- func PerceptuallySimilar(a, b uint64) bool
- func SanitizeFilename(filename string) string
- func ValidateAltText(altText string) error
- func ValidateFileContent(buffer []byte) error
- func ValidateFileExtension(filename string) error
- func ValidateFileSignature(buffer []byte) error
- func ValidateFileSize(size int64) error
- func ValidateMimeType(mimeType string) error
- type DuplicateMediaError
- type ImageGenerationService
- type ImageMetadata
- type ImageReference
- type Media
- type MediaVariant
- type MimeType
- type ProcessResult
- type Processor
- func (p *Processor) ConvertToWebP(reader io.Reader) ([]byte, *ImageMetadata, error)
- func (p *Processor) CropToOpenGraph(data []byte) ([]byte, error)
- func (p *Processor) ExtractMetadata(reader io.Reader) (*ImageMetadata, error)
- func (p *Processor) GenerateHash(reader io.Reader) (string, error)
- func (p *Processor) Resize(reader io.Reader, maxWidth int) ([]byte, *ImageMetadata, error)
- type Redactor
- type ReencodeSummary
- type Repository
- type Service
- func (s *Service) Count(ctx context.Context, principal kernel.Principal, search string, ...) (int, error)
- func (s *Service) Delete(ctx context.Context, id int, principal kernel.Principal) error
- func (s *Service) ForceUpload(ctx context.Context, req UploadRequest) (*Media, error)
- func (s *Service) GenerateFromBytes(ctx context.Context, imageBytes []byte, principal kernel.Principal, ...) (*Media, error)
- func (s *Service) GetByID(ctx context.Context, id int) (*Media, error)
- func (s *Service) ListByCursor(ctx context.Context, userID int, limit int, beforeID int) ([]*Media, error)
- func (s *Service) ReencodeLibrary(ctx context.Context) (ReencodeSummary, error)
- func (s *Service) SearchMediaByCursor(ctx context.Context, principal kernel.Principal, search string, ...) ([]*Media, error)
- func (s *Service) Upload(ctx context.Context, req UploadRequest) (*Media, error)
- type ServiceOption
- type UploadRequest
Constants ¶
const ( // OGImageWidth and OGImageHeight are the exact dimensions of an Open Graph // social preview image (1200x630, ~1.91:1). OGImageWidth = 1200 OGImageHeight = 630 )
const ( // MaxFileSize is the maximum allowed file size (10MB) MaxFileSize = 10 * 1024 * 1024 // MaxAltTextLength is the maximum allowed alt text length MaxAltTextLength = 500 // MaxImageReferences is the maximum number of reference images accepted // for a single AI image generation request MaxImageReferences = 3 )
const ( // MaxPerceptualDistance is the largest Hamming distance (out of 64 bits) at // which two perceptual hashes still describe the same picture — roughly 10%, // conservative enough that distinct photographs stay apart while resizes, // recompressions, and format conversions of one picture compare equal. MaxPerceptualDistance = 6 )
const MinFileSize int64 = 1
MinFileSize is the minimum allowed file size (1 byte)
const OpenGraphPromptSuffix = "" /* 171-byte string literal not displayed */
OpenGraphPromptSuffix guides the model toward a wide social-preview composition when generating an Open Graph image.
Variables ¶
var ( // ErrMediaNotFound is returned when media cannot be found ErrMediaNotFound = errors.New("media not found") // ErrInvalidFile is returned when file validation fails ErrInvalidFile = errors.New("invalid file type") // ErrFileTooLarge is returned when file size exceeds limit ErrFileTooLarge = errors.New("file size exceeds limit") // ErrDuplicateMedia is returned when media with same hash already exists ErrDuplicateMedia = errors.New("media already exists") // ErrInvalidAltText is returned when alt text validation fails ErrInvalidAltText = errors.New("alt text is required and must be less than 500 characters") // ErrInvalidMimeType is returned when mime type is not supported ErrInvalidMimeType = errors.New("invalid mime type") ErrUnauthorized = errors.New("unauthorized to delete this media") // ErrInvalidFileContent is returned when file content does not match a supported image type ErrInvalidFileContent = errors.New("file content does not match a supported image type") // ErrImageReferencesNotSupported is returned when reference images are // provided but the configured AI model only supports text-to-image generation ErrImageReferencesNotSupported = errors.New("reference images are not supported by the configured AI model") // ErrPrivacyScanFailed is returned when the SAM privacy scan fails. The // upload is rejected fail-closed and nothing is stored. ErrPrivacyScanFailed = errors.New("privacy scan failed") )
var ( // SupportedMimeTypes contains all supported image mime types SupportedMimeTypes = map[string]bool{ "image/jpeg": true, "image/png": true, "image/gif": true, "image/webp": true, } // SupportedExtensions contains all supported file extensions SupportedExtensions = map[string]bool{ ".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".webp": true, } )
Functions ¶
func AltTextFromPrompt ¶ added in v1.2.1
AltTextFromPrompt derives alt text for a generated image from the generation prompt. Alt text caps at MaxAltTextLength runes, so over-long prompts are cut at the last whitespace boundary inside the cap — or hard-cut when a single token exceeds it.
func BuildGenerationPrompt ¶
BuildGenerationPrompt returns the provider prompt, with Open Graph composition guidance appended when og is true.
func DetectImageMimeType ¶
DetectImageMimeType detects the MIME type of image bytes. The bytes must have passed ValidateFileSignature first; anything DetectContentType cannot identify at that point is WebP, which it does not detect.
func ExtractHashFromURL ¶
ExtractHashFromURL pulls the media hash (or foreign filename stem) out of a stored media URL: the file base name minus any thumbnail-variant suffix this package generates (_large, _medium, _thumb). Foreign URLs (external images) degrade to their filename stem, so callers can still use the value as a best-effort lookup key against FindByHashPrefix.
func GenerateDuplicateFilename ¶
GenerateDuplicateFilename appends -2 suffix before extension
func HammingDistance ¶
HammingDistance counts the differing bits between two perceptual hashes.
func ParseDateFilter ¶
ParseDateFilter converts a predefined date filter string to a time threshold
func PerceptualHash ¶
PerceptualHash computes a 64-bit average hash (aHash) of the image: decode, downscale to 8×8, threshold each pixel's luma against the thumbnail mean. Visually identical pictures hash (nearly) identically regardless of their file bytes, resolution, or encoding, so callers can detect duplicate imagery that SHA-256 content dedup cannot see. Flat single-colour images all hash toward the same value — an accepted blind spot for cover detection.
func PerceptuallySimilar ¶
PerceptuallySimilar reports whether two perceptual hashes describe the same picture — their Hamming distance is at most MaxPerceptualDistance.
func SanitizeFilename ¶
SanitizeFilename sanitizes a filename by removing special characters
func ValidateAltText ¶
ValidateAltText validates the alt text field
func ValidateFileContent ¶
ValidateFileContent validates file content using http.DetectContentType on the first 512 bytes
func ValidateFileExtension ¶
ValidateFileExtension validates if a file extension is supported
func ValidateFileSignature ¶
ValidateFileSignature validates file content by checking magic number signatures
func ValidateFileSize ¶
ValidateFileSize validates if a file size is within limits
func ValidateMimeType ¶
ValidateMimeType validates if a mime type is supported
Types ¶
type DuplicateMediaError ¶
type DuplicateMediaError struct {
Existing *Media
}
DuplicateMediaError is returned when a media file with the same hash already exists
func (*DuplicateMediaError) Error ¶
func (e *DuplicateMediaError) Error() string
type ImageGenerationService ¶
type ImageGenerationService interface {
GenerateImage(
ctx context.Context,
prompt string,
references []ImageReference,
) ([]byte, error)
SupportsImageReferences() bool
}
ImageGenerationService defines the interface for AI image generation services.
type ImageMetadata ¶
ImageMetadata contains image dimension information
type ImageReference ¶
ImageReference is a single reference image guiding AI image generation. Data holds the raw image bytes and MimeType is the detected image MIME type.
func NewImageReference ¶
func NewImageReference(data []byte) (ImageReference, error)
NewImageReference validates raw bytes as an AI image-generation reference and returns the reference with its detected MIME type. Only JPEG, PNG, and WebP are accepted: GIF is rejected because the reference-capable providers (Gemini image models, GPT Image edits) do not support it.
type Media ¶
type Media struct {
ID int `json:"id"`
UserID int `json:"userId"`
Filename string `json:"filename"`
OriginalFilename string `json:"originalFilename"`
MimeType MimeType `json:"mimeType"`
FileSize int64 `json:"fileSize"`
Width int `json:"width"`
Height int `json:"height"`
AltText string `json:"altText"`
IsWebP bool `json:"isWebp"`
FilePath string `json:"filePath"`
URL string `json:"url"`
Hash string `json:"hash"`
Variants map[string]MediaVariant `json:"variants"`
UploadedBy string `json:"uploadedBy"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
Media represents a media file in the system
type MediaVariant ¶
type MediaVariant struct {
FilePath string `json:"filePath"`
URL string `json:"url"`
Width int `json:"width"`
Height int `json:"height"`
}
MediaVariant holds metadata for a single thumbnail variant.
type MimeType ¶
type MimeType string
MimeType represents the mime type of an image
const ( // MimeTypeJPEG represents JPEG image format MimeTypeJPEG MimeType = "image/jpeg" // MimeTypePNG represents PNG image format MimeTypePNG MimeType = "image/png" // MimeTypeGIF represents GIF image format MimeTypeGIF MimeType = "image/gif" // MimeTypeWebP represents WebP image format MimeTypeWebP MimeType = "image/webp" )
func (MimeType) IsSupported ¶
IsSupported checks if the mime type is supported for upload
type ProcessResult ¶
type ProcessResult struct {
WebpData []byte
Metadata *ImageMetadata
Hash string
}
ProcessResult contains the result of image processing
type Processor ¶
type Processor struct{}
Processor handles image processing operations
func (*Processor) ConvertToWebP ¶
ConvertToWebP ensures the input is a WebP image: already-WebP input is passed through (metadata chunks stripped, still frames validated — no re-encode, no generation loss); every other registered format is decoded and re-encoded as WebP at Quality 80 / Method 4.
func (*Processor) CropToOpenGraph ¶
CropToOpenGraph center-crops image data to the Open Graph aspect ratio and resizes it to exactly OGImageWidth x OGImageHeight, returning WebP bytes.
func (*Processor) ExtractMetadata ¶
func (p *Processor) ExtractMetadata(reader io.Reader) (*ImageMetadata, error)
ExtractMetadata extracts image metadata without full decoding
func (*Processor) GenerateHash ¶
GenerateHash generates a SHA-256 hash of the file content
type Redactor ¶ added in v1.2.1
Redactor blurs sensitive regions before anything is stored. The composition root adapts the privacy service onto it; a nil Redactor keeps the legacy pipeline byte-identical.
type ReencodeSummary ¶ added in v1.1.3
type ReencodeSummary struct {
Processed int `json:"processed"`
Skipped int `json:"skipped"`
BytesBefore int64 `json:"bytesBefore"`
BytesAfter int64 `json:"bytesAfter"`
}
ReencodeSummary reports a one-time library re-encode run: how many media records were rewritten in place (Processed) versus skipped after a per-file failure (Skipped), plus the total stored bytes before and after for the processed records. Filenames, URLs, hashes, and DB rows are untouched — only the stored bytes shrink.
type Repository ¶
type Repository interface {
Create(ctx context.Context, media *Media) error
FindByID(ctx context.Context, id int) (*Media, error)
FindByHash(ctx context.Context, hash string) (*Media, error)
FindByHashPrefix(ctx context.Context, prefix string) (*Media, error)
// ListByCursor returns the caller's media in newest-first (id DESC) order using keyset
// pagination. beforeID <= 0 means "first page"; otherwise only rows with a strictly
// smaller id are returned. Agent v1 list contract — cursor paging is stable under
// concurrent inserts/deletes (unlike offset paging).
ListByCursor(ctx context.Context, userID int, limit int, beforeID int) ([]*Media, error)
// FindAllByCursor returns media in newest-first (id DESC) order using keyset
// pagination. ownerID > 0 scopes the list to that user's library; 0 (the admin
// scope) returns every user's media. beforeID <= 0 means "first page"; otherwise
// only rows with a strictly smaller id are returned. Used by the browser admin
// media library (admins manage all site media).
FindAllByCursor(ctx context.Context, ownerID int, limit int, beforeID int) ([]*Media, error)
// FindAllByFilenameByCursor returns media matching a filename query in
// newest-first (id DESC) order using keyset pagination (beforeID <= 0 means
// first page). ownerID > 0 scopes the search to that user's library; 0 (the
// admin scope) searches every user's media.
FindAllByFilenameByCursor(
ctx context.Context,
ownerID int,
filename string,
limit int,
beforeID int,
) ([]*Media, error)
// FindAllByDateRangeByCursor returns media created since the given time in
// newest-first (id DESC) order using keyset pagination (beforeID <= 0 means
// first page). ownerID > 0 scopes the list to that user's library; 0 (the
// admin scope) returns every user's media.
FindAllByDateRangeByCursor(
ctx context.Context,
ownerID int,
since time.Time,
limit int,
beforeID int,
) ([]*Media, error)
// FindAllByFilenameAndDateRangeByCursor returns media matching a filename
// query and created since the given time in newest-first (id DESC) order
// using keyset pagination (beforeID <= 0 means first page). ownerID > 0
// scopes the search to that user's library; 0 (the admin scope) searches
// every user's media.
FindAllByFilenameAndDateRangeByCursor(
ctx context.Context,
ownerID int,
filename string,
since time.Time,
limit int,
beforeID int,
) ([]*Media, error)
// Count returns the total number of media matching the given owner scope,
// filename query, and creation-time threshold. ownerID > 0 counts only that
// user's media; 0 (the admin scope) counts all. since is the zero time when
// no date filter applies. It mirrors the WHERE clauses of the FindAll*ByCursor
// methods so a list's total always matches its rows.
Count(ctx context.Context, ownerID int, search string, since time.Time) (int, error)
DeleteByID(ctx context.Context, id int) error
DeleteByOwner(ctx context.Context, id int, userID int) error
// UpdateFileSize refreshes the stored file size after an in-place
// rewrite (e.g. the one-time alpha-compression re-encode). Filenames,
// URLs, and hashes are untouched — only the size column follows the
// bytes actually on disk.
UpdateFileSize(ctx context.Context, id int, size int64) error
}
Repository defines the interface for media repository operations
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service handles media business logic
func NewService ¶
func NewService( repo Repository, storage kernelstorage.Storage, thumbnailService *thumbnail.Service, opts ...ServiceOption, ) *Service
NewService creates a new media service
func (*Service) Count ¶
func (s *Service) Count(ctx context.Context, principal kernel.Principal, search string, dateFilter string) (int, error)
Count returns the total number of media matching the given search and date filters under the principal's scope — admins count the whole library, any other role counts their own. Used to render the total badge next to the browser admin media library's title.
func (*Service) Delete ¶
Delete deletes media by ID. Admin users can delete any media; others can only delete their own.
func (*Service) ForceUpload ¶
ForceUpload handles media upload bypassing hash uniqueness check
func (*Service) GenerateFromBytes ¶
func (s *Service) GenerateFromBytes( ctx context.Context, imageBytes []byte, principal kernel.Principal, altText string, originalFilename string, ) (*Media, error)
GenerateFromBytes creates a media record from raw image bytes by converting to WebP, generating a hash, saving to storage, creating thumbnail variants, and storing in the database. This is used for AI-generated or programmatically-created images that don't come from file uploads.
func (*Service) ListByCursor ¶
func (s *Service) ListByCursor(ctx context.Context, userID int, limit int, beforeID int) ([]*Media, error)
ListByCursor retrieves the caller's media in newest-first (id DESC) order using keyset pagination (beforeID <= 0 means first page). Thin pass-through; all pagination/encoding intelligence lives in the agent handler.
func (*Service) ReencodeLibrary ¶ added in v1.1.3
func (s *Service) ReencodeLibrary(ctx context.Context) (ReencodeSummary, error)
ReencodeLibrary walks every stored original and each variant file and normalizes it through ConvertToWebP (already-WebP files pass through sanitize-only — metadata stripped, pixels untouched; other formats are transcoded at Quality 80), overwriting each object in place via Save with the same filename. Filenames, URLs, and hashes are untouched; only the stored bytes may change, and each record's stored file size is refreshed to match. It pages FindAllByCursor in admin scope (owner 0) so a large library streams. A record whose any file fails to open, decode, re-encode, or save counts as skipped and the run continues with the next record; already-overwritten files of a skipped record stay overwritten (the run is documented one-time use because lossy re-runs lose quality).
func (*Service) SearchMediaByCursor ¶
func (s *Service) SearchMediaByCursor( ctx context.Context, principal kernel.Principal, search string, dateFilter string, limit int, beforeID int, ) ([]*Media, error)
SearchMediaByCursor retrieves media with optional search and date filters in newest-first (id DESC) order using keyset pagination (beforeID <= 0 means first page). Admins search every user's media; any other role is scoped to their own library. All pagination/encoding intelligence lives in the browser handler.
type ServiceOption ¶ added in v1.2.1
type ServiceOption func(*Service)
ServiceOption configures a Service. The composition root supplies every option; direct construction without options yields the legacy pipeline.
func WithRedactor ¶ added in v1.2.1
func WithRedactor(redactor Redactor) ServiceOption
WithRedactor adopts the privacy redactor (composition root, nil when AI_SAM_API_KEY is unset). Without one uploads skip the scan entirely.
type UploadRequest ¶
type UploadRequest struct {
File multipart.File
FileHeader *multipart.FileHeader
UserID int
AltText string
}
UploadRequest represents a request to upload media