common

package
v0.2.2-0...-091e9c0 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2023 License: AGPL-3.0 Imports: 38 Imported by: 3

Documentation

Index

Constants

View Source
const (
	APP_VERSION       = "v0.5"
	LOG_PATH          = "data/state/log/"
	CONFIG_PATH       = "data/state/config/"
	DB_PATH           = "data/state/db/"
	FTS_PATH          = "data/state/search/"
	CERT_PATH         = "data/state/certs/"
	TMP_PATH          = "data/cache/tmp/"
	COOKIE_NAME_AUTH  = "auth"
	COOKIE_NAME_PROOF = "proof"
	COOKIE_NAME_ADMIN = "admin"
	COOKIE_PATH_ADMIN = "/admin/api/"
	COOKIE_PATH       = "/api/"
	URL_SETUP         = "/admin/setup"
)
View Source
const (
	ADMIN_CLAIM = "ADMIN"
)
View Source
const BACKEND_NIL = "_nothing_"
View Source
const IndentSize = "    "
View Source
const OverrideVideoSourceMapper = "/overrides/video-transcoder.js"
View Source
const PASSWORD_DUMMY = "{{PASSWORD}}"

Variables

View Source
var (
	BUILD_REF                     string
	BUILD_DATE                    string
	LICENSE                       string = "agpl"
	SECRET_KEY                    string
	SECRET_KEY_DERIVATE_FOR_PROOF string
	SECRET_KEY_DERIVATE_FOR_ADMIN string
	SECRET_KEY_DERIVATE_FOR_USER  string
	SECRET_KEY_DERIVATE_FOR_HASH  string
)
View Source
var (
	ErrNotFound             error = NewError("Not Found", 404)
	ErrNotAllowed           error = NewError("Not Allowed", 403)
	ErrPermissionDenied     error = NewError("Permission Denied", 403)
	ErrNotValid             error = NewError("Not Valid", 405)
	ErrConflict             error = NewError("Already exist", 409)
	ErrNotReachable         error = NewError("Cannot establish a connection", 502)
	ErrInvalidPassword      error = NewError("Invalid Password", 403)
	ErrNotImplemented       error = NewError("Not Implemented", 501)
	ErrNotSupported         error = NewError("Not supported", 501)
	ErrFilesystemError      error = NewError("Can't use filesystem", 503)
	ErrMissingDependency    error = NewError("Missing dependency", 424)
	ErrNotAuthorized        error = NewError("Not authorised", 401)
	ErrAuthenticationFailed error = NewError("Invalid account", 400)
	ErrCongestion           error = NewError("Traffic congestion, try again later", 500)
	ErrTimeout              error = NewError("Timeout", 500)
	ErrInternal             error = NewError("Internal Error", 500)
)
View Source
var Backend = NewDriver()
View Source
var HTTP = http.Client{
	Timeout: 10000 * time.Millisecond,
	Transport: NewTransformedTransport(&http.Transport{
		Dial: (&net.Dialer{
			Timeout:   5000 * time.Millisecond,
			KeepAlive: 5000 * time.Millisecond,
		}).Dial,
		TLSHandshakeTimeout:   5000 * time.Millisecond,
		IdleConnTimeout:       5000 * time.Millisecond,
		ResponseHeaderTimeout: 5000 * time.Millisecond,
	}),
}
View Source
var HTTPClient = http.Client{
	Timeout: 5 * time.Hour,
	Transport: NewTransformedTransport(&http.Transport{
		Dial: (&net.Dialer{
			Timeout:   10 * time.Second,
			KeepAlive: 10 * time.Second,
		}).Dial,
		TLSHandshakeTimeout:   5 * time.Second,
		IdleConnTimeout:       60 * time.Second,
		ResponseHeaderTimeout: 60 * time.Second,
	}),
}
View Source
var Hooks = struct {
	Get      Get
	Register Register
}{
	Get:      Get{},
	Register: Register{},
}
View Source
var Log = func() ILogger {
	l := log{}
	l.Enable(true)
	return &l
}()
View Source
var MOCK_CURRENT_DIR string
View Source
var MimeTypes map[string]string = make(map[string]string, 0)
View Source
var USER_AGENT = fmt.Sprintf("Filestash/%s.%s (http://filestash.app)", APP_VERSION, BUILD_DATE)

Functions

func AllMimeTypes

func AllMimeTypes() map[string]string

func CookieName

func CookieName(idx int) string

func DecryptString

func DecryptString(secret string, data string) (string, error)

func EncryptString

func EncryptString(secret string, data string) (string, error)

func EnforceDirectory

func EnforceDirectory(path string) string

func GenerateID

func GenerateID(ctx *App) string

Create a unique ID that can be use to identify different session

func GenerateMachineID

func GenerateMachineID() string

Create an ID that identify a machine

func GetAbsolutePath

func GetAbsolutePath(base string, opts ...string) string

func GetCurrentDir

func GetCurrentDir() string

func GetMimeType

func GetMimeType(p string) string

func HTTPFriendlyStatus

func HTTPFriendlyStatus(n int) string

func Hash

func Hash(str string, n int) string

func HashStream

func HashStream(r io.Reader, n int) string

func InitSecretDerivate

func InitSecretDerivate(secret string)

* Improve security by calculating derivative of the secret key to restrict the attack surface * in the worst case scenario with one compromise secret key

func IsATranslatedError

func IsATranslatedError(err error) bool

func IsDirectory

func IsDirectory(path string) bool

func JoinPath

func JoinPath(base, file string) string

* Join 2 path together, result has a file

func LoadConfig

func LoadConfig() ([]byte, error)

func NewBool

func NewBool(t bool) *bool

func NewBoolFromInterface

func NewBoolFromInterface(val interface{}) bool

func NewError

func NewError(message string, status int) error

func NewInt

func NewInt(t int) *int

func NewInt64pFromInterface

func NewInt64pFromInterface(val interface{}) *int64

func NewNilLogger

func NewNilLogger() *slog.Logger

func NewReadCloserFromBytes

func NewReadCloserFromBytes(t []byte) io.ReadCloser

func NewReadCloserFromReader

func NewReadCloserFromReader(r io.Reader) io.ReadCloser

func NewString

func NewString(t string) *string

func NewStringFromInterface

func NewStringFromInterface(val interface{}) string

func NewStringpFromInterface

func NewStringpFromInterface(val interface{}) *string

func NewTransformedTransport

func NewTransformedTransport(transport *http.Transport) http.RoundTripper

func Page

func Page(stuff string) string

func PrettyPrint

func PrettyPrint(json_dirty []byte) []byte

func PrintMemUsage

func PrintMemUsage()

func QuickHash

func QuickHash(str string, n int) string

func QuickString

func QuickString(n int) string

func RandomString

func RandomString(n int) string

func RedirectPage

func RedirectPage(url string) string

func ReversedBaseChange

func ReversedBaseChange(alphabet []rune, i int) string

func SafeOsMkdir

func SafeOsMkdir(path string, mode os.FileMode) error

func SafeOsOpenFile

func SafeOsOpenFile(path string, flag int, perm os.FileMode) (*os.File, error)

func SafeOsRemove

func SafeOsRemove(path string) error

func SafeOsRemoveAll

func SafeOsRemoveAll(path string) error

func SafeOsRename

func SafeOsRename(from string, to string) error

func SaveConfig

func SaveConfig(v []byte) error

func SendErrorResult

func SendErrorResult(res http.ResponseWriter, err error)

func SendRaw

func SendRaw(res http.ResponseWriter, data interface{})

func SendSuccessResult

func SendSuccessResult(res http.ResponseWriter, data interface{})

func SendSuccessResultWithEtagAndGzip

func SendSuccessResultWithEtagAndGzip(res http.ResponseWriter, req *http.Request, data interface{})

func SendSuccessResults

func SendSuccessResults(res http.ResponseWriter, data interface{})

func SendSuccessResultsWithMetadata

func SendSuccessResultsWithMetadata(res http.ResponseWriter, data interface{}, p interface{})

func SplitPath

func SplitPath(path string) (root string, filename string)

func VerifyApiKey

func VerifyApiKey(api_key string) (host string, err error)

Types

type APIErrorMessage

type APIErrorMessage struct {
	Status  string `json:"status"`
	Message string `json:"message,omitempty"`
}

type APISuccessResult

type APISuccessResult struct {
	Status string      `json:"status"`
	Result interface{} `json:"result,omitempty"`
}

type APISuccessResults

type APISuccessResults struct {
	Status  string      `json:"status"`
	Results interface{} `json:"results"`
}

type APISuccessResultsWithMetadata

type APISuccessResultsWithMetadata struct {
	Status   string      `json:"status"`
	Results  interface{} `json:"results"`
	Metadata interface{} `json:"permissions,omitempty"`
}

type AdminToken

type AdminToken struct {
	Claim  string    `json:"token"`
	Expire time.Time `json:"time"`
}

func NewAdminToken

func NewAdminToken() AdminToken

func (AdminToken) IsAdmin

func (this AdminToken) IsAdmin() bool

func (AdminToken) IsValid

func (this AdminToken) IsValid() bool

type All

type All struct{}

type App

type App struct {
	Backend IBackend
	Body    map[string]interface{}
	Session map[string]string
	Share   Share
	Context context.Context
}

type AppCache

type AppCache struct {
	Cache *cache.Cache
}

func NewAppCache

func NewAppCache(arg ...time.Duration) AppCache

func NewQuickCache

func NewQuickCache(arg ...time.Duration) AppCache

func (*AppCache) Del

func (a *AppCache) Del(key map[string]string)

func (*AppCache) Get

func (a *AppCache) Get(key interface{}) interface{}

func (*AppCache) OnEvict

func (a *AppCache) OnEvict(fn func(string, interface{}))

func (*AppCache) Set

func (a *AppCache) Set(key map[string]string, value interface{})

func (*AppCache) SetKey

func (a *AppCache) SetKey(key string, value interface{})

type AppError

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

func (AppError) Error

func (e AppError) Error() string

func (AppError) Status

func (e AppError) Status() int

type AuditQueryResult

type AuditQueryResult struct {
	Form       *Form  `json:"form"`
	RenderHTML string `json:"render"`
}

type ChangeListener

type ChangeListener struct {
	Id       string
	Listener chan interface{}
}

type Configuration

type Configuration struct {
	Form []Form
	Conn []map[string]interface{}
	// contains filtered or unexported fields
}
var (
	Config Configuration
)

func NewConfiguration

func NewConfiguration() Configuration

func (*Configuration) Bool

func (this *Configuration) Bool() bool

func (*Configuration) Debug

func (this *Configuration) Debug() *FormElement

func (*Configuration) Default

func (this *Configuration) Default(value interface{}) *Configuration

func (*Configuration) Export

func (this *Configuration) Export() interface{}

func (*Configuration) Get

func (this *Configuration) Get(key string) *Configuration

func (*Configuration) Initialise

func (this *Configuration) Initialise()

func (*Configuration) Int

func (this *Configuration) Int() int

func (*Configuration) Interface

func (this *Configuration) Interface() interface{}

func (*Configuration) ListenForChange

func (this *Configuration) ListenForChange() ChangeListener

func (*Configuration) Load

func (this *Configuration) Load()

func (*Configuration) MarshalJSON

func (this *Configuration) MarshalJSON() ([]byte, error)

func (*Configuration) Save

func (this *Configuration) Save()

func (*Configuration) Schema

func (this *Configuration) Schema(fn func(*FormElement) *FormElement) *Configuration

func (*Configuration) Set

func (this *Configuration) Set(value interface{}) *Configuration

func (*Configuration) String

func (this *Configuration) String() string

func (*Configuration) UnlistenForChange

func (this *Configuration) UnlistenForChange(c ChangeListener)

type Driver

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

func NewDriver

func NewDriver() Driver

func (*Driver) Drivers

func (d *Driver) Drivers() map[string]IBackend

func (*Driver) Get

func (d *Driver) Get(name string) IBackend

func (*Driver) Register

func (d *Driver) Register(name string, driver IBackend)

type File

type File struct {
	FName     string `json:"name"`
	FType     string `json:"type"`
	FTime     int64  `json:"time"`
	FSize     int64  `json:"size"`
	FPath     string `json:"path,omitempty"`
	CanRename *bool  `json:"can_rename,omitempty"`
	CanMove   *bool  `json:"can_move_directory,omitempty"`
	CanDelete *bool  `json:"can_delete,omitempty"`
}

func (File) IsDir

func (f File) IsDir() bool

func (File) ModTime

func (f File) ModTime() time.Time

func (File) Mode

func (f File) Mode() os.FileMode

func (File) Name

func (f File) Name() string

func (File) Path

func (f File) Path() string

func (File) Size

func (f File) Size() int64

func (File) Sys

func (f File) Sys() interface{}

type Form

type Form struct {
	Title  string
	Form   []Form
	Elmnts []FormElement
}

func (*Form) Iterator

func (this *Form) Iterator() []FormIterator

func (Form) MarshalJSON

func (this Form) MarshalJSON() ([]byte, error)

func (Form) ToJSON

func (this Form) ToJSON(fn func(el FormElement) string) string

type FormElement

type FormElement struct {
	Id          string      `json:"id,omitempty"`
	Name        string      `json:"label"`
	Type        string      `json:"type"`
	Description string      `json:"description,omitempty"`
	Placeholder string      `json:"placeholder,omitempty"`
	Opts        []string    `json:"options,omitempty"`
	Target      []string    `json:"target,omitempty"`
	ReadOnly    bool        `json:"readonly"`
	Default     interface{} `json:"default"`
	Value       interface{} `json:"value"`
	MultiValue  bool        `json:"multi,omitempty"`
	Datalist    []string    `json:"datalist,omitempty"`
	Order       int         `json:"-"`
	Required    bool        `json:"required"`
}

type FormIterator

type FormIterator struct {
	Path string
	*FormElement
}

type Get

type Get struct{}

func (Get) AuditEngine

func (this Get) AuditEngine() IAuditPlugin

func (Get) AuthenticationMiddleware

func (this Get) AuthenticationMiddleware() map[string]IAuthentication

func (Get) AuthorisationMiddleware

func (this Get) AuthorisationMiddleware() []IAuthorisation

func (Get) CSS

func (this Get) CSS() string

func (Get) FrontendOverrides

func (this Get) FrontendOverrides() []string

func (Get) HttpEndpoint

func (this Get) HttpEndpoint() []func(*mux.Router, *App) error

func (Get) Onload

func (this Get) Onload() []func()

func (Get) ProcessFileContentBeforeSend

func (this Get) ProcessFileContentBeforeSend() []func(io.ReadCloser, *App, *http.ResponseWriter, *http.Request) (io.ReadCloser, error)

func (Get) SearchEngine

func (this Get) SearchEngine() ISearch

func (Get) Starter

func (this Get) Starter() []func(*mux.Router)

func (Get) Thumbnailer

func (this Get) Thumbnailer() map[string]IThumbnailer

func (Get) XDGOpen

func (this Get) XDGOpen() []string

type IAuditPlugin

type IAuditPlugin interface {
	Query(ctx *App, searchParams map[string]string) (AuditQueryResult, error)
}

type IAuthentication

type IAuthentication interface {
	Setup() Form
	EntryPoint(idpParams map[string]string, req *http.Request, res http.ResponseWriter) error
	Callback(formData map[string]string, idpParams map[string]string, res http.ResponseWriter) (map[string]string, error)
}

type IAuthorisation

type IAuthorisation interface {
	Ls(ctx *App, path string) error
	Cat(ctx *App, path string) error
	Mkdir(ctx *App, path string) error
	Rm(ctx *App, path string) error
	Mv(ctx *App, from string, to string) error
	Save(ctx *App, path string) error
	Touch(ctx *App, path string) error
}

type IBackend

type IBackend interface {
	Init(params map[string]string, app *App) (IBackend, error)
	Ls(path string) ([]os.FileInfo, error)
	Cat(path string) (io.ReadCloser, error)
	Mkdir(path string) error
	Rm(path string) error
	Mv(from string, to string) error
	Save(path string, file io.Reader) error
	Touch(path string) error
	LoginForm() Form
}

type IFile

type IFile interface {
	os.FileInfo
	Path() string
}

type ILogger

type ILogger interface {
	Debug(format string, v ...interface{})
	Info(format string, v ...interface{})
	Warning(format string, v ...interface{})
	Error(format string, v ...interface{})
	Stdout(format string, v ...interface{})
	SetVisibility(str string)
}

type ISearch

type ISearch interface {
	Query(ctx App, basePath string, term string) ([]IFile, error)
}

type IThumbnailer

type IThumbnailer interface {
	Generate(io.ReadCloser, *App, *http.ResponseWriter, *http.Request) (io.ReadCloser, error)
}

type JSONIterator

type JSONIterator struct {
	Path  string
	Value interface{}
}

func JsonIterator

func JsonIterator(json string) []JSONIterator

type KeyValueStore

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

func NewKeyValueStore

func NewKeyValueStore() KeyValueStore

func (*KeyValueStore) Clear

func (this *KeyValueStore) Clear()

func (*KeyValueStore) Get

func (this *KeyValueStore) Get(key string) interface{}

func (*KeyValueStore) Set

func (this *KeyValueStore) Set(key string, value interface{})

type Metadata

type Metadata struct {
	CanSee             *bool      `json:"can_read,omitempty"`
	CanCreateFile      *bool      `json:"can_create_file,omitempty"`
	CanCreateDirectory *bool      `json:"can_create_directory,omitempty"`
	CanRename          *bool      `json:"can_rename,omitempty"`
	CanMove            *bool      `json:"can_move,omitempty"`
	CanUpload          *bool      `json:"can_upload,omitempty"`
	CanDelete          *bool      `json:"can_delete,omitempty"`
	CanShare           *bool      `json:"can_share,omitempty"`
	HideExtension      *bool      `json:"hide_extension,omitempty"`
	RefreshOnCreate    *bool      `json:"refresh_on_create,omitempty"`
	Expire             *time.Time `json:"-"`
}

type NonceGenerator

type NonceGenerator struct {
	*sync.Mutex
	// contains filtered or unexported fields
}
var (
	Letters                 = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
	GCMNonce NonceGenerator = NewNonceGenerator(12)
)

func NewNonceGenerator

func NewNonceGenerator(size int) NonceGenerator

func (*NonceGenerator) Next

func (this *NonceGenerator) Next() []byte

type Nothing

type Nothing struct{}

func (Nothing) Cat

func (b Nothing) Cat(path string) (io.ReadCloser, error)

func (Nothing) Init

func (b Nothing) Init(params map[string]string, app *App) (IBackend, error)

func (Nothing) LoginForm

func (b Nothing) LoginForm() Form

func (Nothing) Ls

func (b Nothing) Ls(path string) ([]os.FileInfo, error)

func (Nothing) Mkdir

func (b Nothing) Mkdir(path string) error

func (Nothing) Mv

func (b Nothing) Mv(from string, to string) error

func (Nothing) Rm

func (b Nothing) Rm(path string) error

func (Nothing) Save

func (b Nothing) Save(path string, file io.Reader) error

func (Nothing) Touch

func (b Nothing) Touch(path string) error

type Plugin

type Plugin struct {
	Type   string
	Enable bool
}

type Register

type Register struct{}

func (Register) AuditEngine

func (this Register) AuditEngine(a IAuditPlugin)

func (Register) AuthenticationMiddleware

func (this Register) AuthenticationMiddleware(id string, am IAuthentication)

func (Register) AuthorisationMiddleware

func (this Register) AuthorisationMiddleware(a IAuthorisation)

func (Register) CSS

func (this Register) CSS(stylesheet string)

func (Register) CSSFunc

func (this Register) CSSFunc(stylesheet func() string)

func (Register) FrontendOverrides

func (this Register) FrontendOverrides(url string)

func (Register) HttpEndpoint

func (this Register) HttpEndpoint(fn func(*mux.Router, *App) error)

func (Register) Onload

func (this Register) Onload(fn func())

func (Register) ProcessFileContentBeforeSend

func (this Register) ProcessFileContentBeforeSend(fn func(io.ReadCloser, *App, *http.ResponseWriter, *http.Request) (io.ReadCloser, error))

func (Register) SearchEngine

func (this Register) SearchEngine(s ISearch)

func (Register) Starter

func (this Register) Starter(fn func(*mux.Router))

func (Register) Thumbnailer

func (this Register) Thumbnailer(mimeType string, fn IThumbnailer)

func (Register) XDGOpen

func (this Register) XDGOpen(jsString string)

type Share

type Share struct {
	Id           string  `json:"id"`
	Backend      string  `json:"-"`
	Auth         string  `json:"auth,omitempty"`
	Path         string  `json:"path"`
	Password     *string `json:"password,omitempty"`
	Users        *string `json:"users,omitempty"`
	Expire       *int64  `json:"expire,omitempty"`
	Url          *string `json:"url,omitempty"`
	CanShare     bool    `json:"can_share"`
	CanManageOwn bool    `json:"can_manage_own"`
	CanRead      bool    `json:"can_read"`
	CanWrite     bool    `json:"can_write"`
	CanUpload    bool    `json:"can_upload"`
}

func (Share) IsValid

func (s Share) IsValid() error

func (*Share) MarshalJSON

func (s *Share) MarshalJSON() ([]byte, error)

func (*Share) UnmarshallJSON

func (s *Share) UnmarshallJSON(b []byte) error

type TransformedTransport

type TransformedTransport struct {
	Orig http.RoundTripper
}

func (*TransformedTransport) RoundTrip

func (this *TransformedTransport) RoundTrip(req *http.Request) (*http.Response, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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