media

package
v3.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 31 Imported by: 32

README

Scoping the media library

Searcher is the isolation boundary. It is applied to every media_libraries query in this package — the listing and chooser grid, folder trees, breadcrumbs, folder item counts, by-id reads, and the model's generic presets CRUD/search event funcs. Upload, new-folder and move targets are validated against it too.

media.New(db).Searcher(func(db *gorm.DB, ctx *web.EventContext) *gorm.DB {
    return db.Where("tenant_id = ?", currentTenantID(ctx.R))
})

CurrentUserID is not an isolation boundary. It only supplies a user_id = ? filter to the listing grid when no Searcher is configured, so rows stay reachable by id. That is deliberate: some roles are meant to see every user's uploads while the grid still defaults to their own. Configure a Searcher whenever rows must actually be isolated.

Two things a Searcher does not cover:

  • MediaBoxSetterFunc writes whatever MediaBox JSON the form submits, so a known URL can still be attached to a field without reading the row.
  • Anything an application queries from media_libraries on its own.

Cropping logic explanation

The principles of cropping are as follows

  1. Users get what they see in the media library selector after selecting an image. No matter it is in the PageBuilder or in SEO or other places
  2. Cropping an image won't affect any other places that use the same image
  • Crop will always create a new file with rule {file}_{size}_{crop_id}.ext
    • original file is file.png after crop will be file_{uuid}.png
    • original file is file_thumb.png after crop will be file_thumb_{uuid}.png
  • cropOption will not be saved in the media library table; cropOption will be saved where the image is used.
    • If the image is used in the SEO configuration. cropOption will be saved in the SEO record, the field name is OpenGraphImageFromMediaLibrary. it is a MediaBox
    • If the image is used in the PageBuilder. cropOption will be saved in the PageBuilder record, it is a MediaBox

To cleanup unused file copies

The cropping logic might leave some unused file copies. If we need to clean them up. We have to fetch all MediaBox records and compare it with the file names in the file system. Then remove the unused files.

Upload validation

Uploads through the media library are checked before they are stored:

  • File names ending in a dot or whitespace, or containing control characters, are rejected.
  • Files with script-capable extensions are rejected by default: the static list in base.DeniedExtensions() (.svg, .svgz, .html, .htm, .xhtml, .xht, .xml, .xsl, .xslt, .js, .mjs, .php, .phtml, .shtml, .swf, .ehtml, .rdf, .xbl, .xsd, .rss, .atom, .xul, .mml, .mht, .mhtml, .wsdl), plus any extension whose MIME type (mime.TypeByExtension) is HTML, XML, SVG or JavaScript.
  • The leading bytes are sniffed: files classified as images must be a raster image and files classified as videos must not be text. Content sniffed as HTML/SVG/XML is rejected for every type, and plain files (or extensions without a known MIME type) must not start with <.
  • AllowedExtensions(...) restricts uploads to the listed extensions (case-insensitive, with or without the dot). Listing a denied extension such as svg explicitly allows it and skips the markup check for it; do that only when the storage serves those files safely (separate domain, or Content-Disposition: attachment). Allowlisting any other extension never relaxes the markup check.
media.New(db).AllowedExtensions("jpg", "jpeg", "png", "gif", "mp4", "pdf")

Deleting stored files

Deleting media library items only deletes their rows by default, because MediaBox values elsewhere keep their own copy of the file URL. Opt in to also remove the stored files from oss.Storage:

media.New(db).DeleteFilesOnDelete(true)
  • When the URL template gives each row its own directory — a {{uuid}} segment, or {{primary_key}} right after {{class}} as in the default /system/{{class}}/{{primary_key}}/... — everything under that directory is removed, including crop copies.
  • Otherwise only the file, its original copy and its size variants are removed; crop copies ({file}_{crop_id}.ext) are not tracked on the row and stay.

Storage errors are logged and ignored. Media library rows are soft-deleted; with this option a restored row has no files.

Unguessable storage URLs

Besides {{class}}, {{primary_key}}, {{column}}, {{filename}}, {{basename}}, {{extension}}, {{hash}}, {{short_hash}}, {{filename_with_hash}} and {{filename_with_short_hash}}, URL templates support {{uuid}}: a random UUID v4, generated once per upload, so every size variant of an upload shares it. Use it instead of {{primary_key}} to make media URLs non-enumerable:

// overrides the template of every media field saved by the media library
// saver, including the MediaLibrary.File tag template
base.MediaLibraryURL = "/system/{{class}}/{{uuid}}/{{column}}.{{extension}}"
// or only the fallback for media fields without a `mediaLibrary:"url:..."` tag
oss.URLTemplate = "/system/{{class}}/{{uuid}}/{{column}}/{{filename_with_hash}}"

Re-rendering the URL without a new upload (cropping) keeps the existing UUID, so crop copies stay in the same directory; a new upload gets a new UUID.

Keep a per-row component ({{uuid}} or {{primary_key}}) in the path: a template without one, e.g. /system/{{class}}/{{column}}.{{extension}}, makes different rows write to — and overwrite — the same files.

The default templates are unchanged.

Documentation

Index

Constants

View Source
const (
	OpenFileChooserEvent = "mediaLibrary_OpenFileChooserEvent"

	ImageSearchEvent   = "mediaLibrary_ImageSearchEvent"
	ImageJumpPageEvent = "mediaLibrary_ImageJumpPageEvent"
	UploadFileEvent    = "mediaLibrary_UploadFileEvent"

	UpdateDescriptionEvent       = "mediaLibrary_UpdateDescriptionEvent"
	DeleteConfirmationEvent      = "mediaLibrary_DeleteConfirmationEvent"
	DoDeleteEvent                = "mediaLibrary_DoDelete"
	CreateFolderEvent            = "mediaLibrary_CreateFolderEvent"
	RenameDialogEvent            = "mediaLibrary_RenameDialogEvent"
	RenameEvent                  = "mediaLibrary_RenameEvent"
	UpdateDescriptionDialogEvent = "mediaLibrary_UpdateDescriptionDialogEvent"
	NewFolderDialogEvent         = "mediaLibrary_NewFolderDialogEvent"
	MoveToFolderDialogEvent      = "mediaLibrary_MoveToFolderDialogEvent"
	MoveToFolderEvent            = "mediaLibrary_MoveToFolderEvent"
	NextFolderEvent              = "mediaLibrary_NextFolderEvent"
)
View Source
const (
	MediaBoxConfig      MediaBoxConfigKey = iota
	I18nMediaLibraryKey i18n.ModuleKey    = "I18nMediaLibraryKey"

	ParamName               = "name"
	ParamParentID           = "parent_id"
	ParamSelectFolderID     = "select_folder_id"
	ParamSelectIDS          = "select_ids"
	ParamField              = "field"
	ParamCurrentDescription = "current_description"
	ParamCfg                = "cfg"
)
View Source
const (
	PermUpload      = "perm_media_library_upload"
	PermDelete      = "perm_media_library_delete"
	PermUpdateDesc  = "perm_media_library_update_desc"
	PermUpdateName  = "perm_media_library_update_name"
	PermMovieTo     = "perm_media_library_move_to"
	PermCopyURL     = "perm_media_library_copy_url"
	PermNewFolder   = "perm_media_library_new_folder"
	PermListFolders = "perm_media_library_list_folders"
)

DO NOT associate media_library permissions with parent resources WRONG: permPolicy.On("*:post:*") right: permPolicy.On("*") right: permPolicy.On("*:media_libraries:*") right: permPolicy.On("*:media_libraries:1")

View Source
const ParamMediaIDS = "media_ids"

Variables

View Source
var Messages_en_US = &Messages{
	Crop:                        "Crop",
	CropImage:                   "Crop Image",
	ChooseFile:                  "Choose File",
	Delete:                      "Delete",
	ChooseAFile:                 "Choose a File",
	Search:                      "Search",
	UploadFiles:                 "Upload files",
	Cropping:                    "Cropping",
	DescriptionUpdated:          "Description Updated",
	DescriptionForAccessibility: "description for accessibility",
	OrderBy:                     "Order By",
	UploadedAt:                  "Date Uploaded",
	UploadedAtDESC:              "Date Uploaded (DESC)",
	All:                         "All",
	Images:                      "Images",
	Videos:                      "Videos",
	Files:                       "Files",

	Copy:                                  "Copy",
	CopyUpdated:                           "Copy Updated",
	Rename:                                "Rename",
	RenameUpdated:                         "Rename Updated",
	Name:                                  "Name",
	NewFolder:                             "New Folder",
	UpdateDescription:                     "Update Description",
	UpdateDescriptionTextFieldPlaceholder: "Description",
	ChooseFolder:                          "Choose Folder",
	MoveTo:                                "Move to",
	MovedFailed:                           "Moved Failed",
	MovedSuccess:                          "Moved Success",
	Folders:                               "Folders",
	UploadFile:                            "Upload File",
	DeleteObjects: func(v int) string {
		return fmt.Sprintf(`Are you sure you want to delete %v objects`, v)
	},

	MediaLibrary:      "Media Library",
	UnSupportFileType: "UnSupport FileType",
	CopyImageURL:      "copy image URL",
}
View Source
var Messages_ja_JP = &Messages{
	Crop:                        "トリミング",
	CropImage:                   "画像をトリミング",
	ChooseFile:                  "ファイルを選択",
	Delete:                      "削除",
	ChooseAFile:                 "ファイルを選択",
	Search:                      "検索",
	UploadFiles:                 "ファイルをアップロード",
	Cropping:                    "トリミング中",
	DescriptionUpdated:          "説明を更新しました",
	DescriptionForAccessibility: "画像の説明",
	OrderBy:                     "並び替え",
	UploadedAt:                  "アップロード日時",
	UploadedAtDESC:              "アップロード日時 (降順)",
	All:                         "すべて",
	Images:                      "画像",
	Videos:                      "動画",
	Files:                       "ファイル",

	Copy:                                  "コピー",
	CopyUpdated:                           "コピーが更新されました",
	Rename:                                "名前を変更する",
	RenameUpdated:                         "名前の変更が成功しました",
	Name:                                  "名称",
	NewFolder:                             "新規フォルダ",
	UpdateDescription:                     "画像の説明を編集する",
	UpdateDescriptionTextFieldPlaceholder: "画像の説明",
	ChooseFolder:                          "フォルダを選択",
	MoveTo:                                "移動する",
	MovedFailed:                           "移動に失敗しました",
	MovedSuccess:                          "移動に成功しました",
	Folders:                               "フォルダ",
	UploadFile:                            "ファイルをアップロード",
	DeleteObjects: func(v int) string {
		return fmt.Sprintf(`Are you sure you want to delete %v objects`, v)
	},
	MediaLibrary:      "メディアライブラリ",
	UnSupportFileType: "サポートされていないファイル形式",
	CopyImageURL:      "画像のURLをコピー",
}
View Source
var Messages_zh_CN = &Messages{
	Crop:                        "剪裁",
	CropImage:                   "剪裁图片",
	ChooseFile:                  "选择文件",
	Delete:                      "删除",
	ChooseAFile:                 "选择一个文件",
	Search:                      "搜索",
	UploadFiles:                 "上传多个文件",
	Cropping:                    "正在剪裁...",
	DescriptionUpdated:          "描述更新成功",
	DescriptionForAccessibility: "图片描述",
	OrderBy:                     "排序",
	UploadedAt:                  "上传时间",
	UploadedAtDESC:              "上传时间 (降序)",
	All:                         "全部",
	Images:                      "图片",
	Videos:                      "视频",
	Files:                       "文件",

	Copy:                                  "拷贝",
	CopyUpdated:                           "拷贝成功",
	Rename:                                "重命名",
	RenameUpdated:                         "重命名成功",
	Name:                                  "名称",
	NewFolder:                             "新文件夹",
	UpdateDescription:                     "更新描述",
	UpdateDescriptionTextFieldPlaceholder: "描述",
	ChooseFolder:                          "选择文件夹",
	MoveTo:                                "移动到",
	MovedFailed:                           "移动失败",
	MovedSuccess:                          "移动成功",
	Folders:                               "文件夹",
	UploadFile:                            "上传文件",
	DeleteObjects: func(v int) string {
		return fmt.Sprintf(`是否删除 %v 个条目`, v)
	},
	MediaLibrary:      "媒体库",
	UnSupportFileType: "不支持的文件类型",
	CopyImageURL:      "拷贝图片链接",
}

Functions

func AutoMigrate added in v3.0.2

func AutoMigrate(db *gorm.DB) (err error)

func ChooseFileButtonID added in v3.0.5

func ChooseFileButtonID(field string) string

func MediaBoxComponentFunc added in v3.0.1

func MediaBoxComponentFunc(db *gorm.DB, readonly bool) presets.FieldComponentFunc

func MediaBoxListFunc added in v3.0.1

func MediaBoxListFunc() presets.FieldComponentFunc

func MediaBoxSetterFunc added in v3.0.1

func MediaBoxSetterFunc(db *gorm.DB) presets.FieldSetterFunc

Types

type Builder added in v3.0.1

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

func New added in v3.0.1

func New(db *gorm.DB) *Builder

func (*Builder) Activity added in v3.2.0

func (b *Builder) Activity(v *activity.Builder) *Builder

func (*Builder) AllowTypes added in v3.0.5

func (b *Builder) AllowTypes(v ...string) *Builder

func (*Builder) AllowedExtensions added in v3.4.1

func (b *Builder) AllowedExtensions(exts ...string) *Builder

AllowedExtensions restricts uploads to files with the given extensions. Extensions match case-insensitively, with or without the leading dot ("png", ".PNG"). Calls accumulate.

Without an allowlist every extension is accepted except the built-in denylist of script-capable formats (base.DeniedExtensions: .svg, .html, .xml, .js, ...). Listing one of those here explicitly allows it, and also skips the markup content check for that extension — only do so when the storage serves such files safely (e.g. from a separate domain or with Content-Disposition: attachment).

func (*Builder) AutoMigrate added in v3.0.2

func (b *Builder) AutoMigrate() *Builder

func (*Builder) CurrentUserID added in v3.0.2

func (b *Builder) CurrentUserID(v UserIDFunc) *Builder

func (*Builder) DeleteFilesOnDelete added in v3.4.1

func (b *Builder) DeleteFilesOnDelete(v bool) *Builder

DeleteFilesOnDelete makes deleting media library items also remove their files from oss.Storage once the database delete has committed. Storage errors are logged and do not fail the request.

When the URL template gives each row its own directory — a {{uuid}} segment, or {{primary_key}} right after {{class}} as in the default "/system/{{class}}/{{primary_key}}/..." — everything under that directory is removed (via Storage.List), including crop copies. Otherwise only the file, its original copy and its size variants are removed; crop copies, whose crop id is not stored on the row, are left in place.

It is off by default: MediaBox fields store their own copy of the file URL, so pages that still reference a deleted item would break. It is also incompatible with restoring soft-deleted media library rows: the row can be restored, its files cannot.

func (*Builder) FileAccept added in v3.0.5

func (b *Builder) FileAccept(v string) *Builder

func (*Builder) GetPresetsModelBuilder added in v3.2.0

func (b *Builder) GetPresetsModelBuilder() *presets.ModelBuilder

func (*Builder) Install added in v3.0.1

func (b *Builder) Install(pb *presets.Builder) error

func (*Builder) MediaLibraryPerPage added in v3.0.1

func (b *Builder) MediaLibraryPerPage(v int) *Builder

func (*Builder) Searcher added in v3.0.2

func (b *Builder) Searcher(v SearchFunc) *Builder

func (*Builder) WrapSaverFunc added in v3.0.4

func (b *Builder) WrapSaverFunc(w func(in SaverFunc) SaverFunc) (r *Builder)

type MediaBoxConfigKey added in v3.0.1

type MediaBoxConfigKey int

type Messages added in v3.0.1

type Messages struct {
	Crop                        string
	CropImage                   string
	ChooseFile                  string
	Delete                      string
	ChooseAFile                 string
	Search                      string
	UploadFiles                 string
	Cropping                    string
	DescriptionUpdated          string
	DescriptionForAccessibility string
	OrderBy                     string
	UploadedAt                  string
	UploadedAtDESC              string
	All                         string
	Images                      string
	Videos                      string
	Files                       string
	SampleArgsText              func(id string) string

	Copy                                  string
	CopyUpdated                           string
	Rename                                string
	RenameUpdated                         string
	Name                                  string
	NewFolder                             string
	UpdateDescription                     string
	UpdateDescriptionTextFieldPlaceholder string
	ChooseFolder                          string
	MoveTo                                string
	MovedFailed                           string
	MovedSuccess                          string
	Folders                               string
	UploadFile                            string
	DeleteObjects                         func(v int) string
	MediaLibrary                          string
	UnSupportFileType                     string
	CopyImageURL                          string
}

type QMediaBoxBuilder added in v3.0.1

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

func QMediaBox added in v3.0.1

func QMediaBox(db *gorm.DB) (r *QMediaBoxBuilder)

func SimpleMediaBox added in v3.0.2

func SimpleMediaBox(url, fieldName string, readOnly bool, cfg *media_library.MediaBoxConfig, db *gorm.DB) *QMediaBoxBuilder

func (*QMediaBoxBuilder) Config added in v3.0.1

func (*QMediaBoxBuilder) Disabled added in v3.0.1

func (b *QMediaBoxBuilder) Disabled(v bool) (r *QMediaBoxBuilder)

func (*QMediaBoxBuilder) ErrorMessages added in v3.0.5

func (b *QMediaBoxBuilder) ErrorMessages(v ...string) (r *QMediaBoxBuilder)

func (*QMediaBoxBuilder) FieldName added in v3.0.1

func (b *QMediaBoxBuilder) FieldName(v string) (r *QMediaBoxBuilder)

func (*QMediaBoxBuilder) Label added in v3.0.1

func (b *QMediaBoxBuilder) Label(v string) (r *QMediaBoxBuilder)

func (*QMediaBoxBuilder) MarshalHTML added in v3.0.1

func (b *QMediaBoxBuilder) MarshalHTML(c context.Context) (r []byte, err error)

func (*QMediaBoxBuilder) Readonly added in v3.0.1

func (b *QMediaBoxBuilder) Readonly(v bool) (r *QMediaBoxBuilder)

func (*QMediaBoxBuilder) Value added in v3.0.1

type SaverFunc added in v3.0.4

type SaverFunc func(db *gorm.DB, obj interface{}, id string, ctx *web.EventContext) error

type SearchFunc added in v3.0.2

type SearchFunc func(db *gorm.DB, ctx *web.EventContext) *gorm.DB

type UserIDFunc added in v3.0.2

type UserIDFunc func(ctx *web.EventContext) uint

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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