Documentation
¶
Overview ¶
Package hath is Hentai@Home client implementation in golang
Index ¶
- Constants
- Variables
- func FileFromBytesTo(result []byte, f *File) error
- func FromRequest(req *http.Request) (net.IP, error)
- func GetRoughCacheSize(count int64) uint64
- func IsUnexpected(err error) bool
- func UnmarshalFileTo(data []byte, f *File) error
- type APIResponse
- type Args
- type BoltDB
- func (d BoltDB) Add(f File) error
- func (d BoltDB) AddBatch(files []File) error
- func (d BoltDB) Close() error
- func (d BoltDB) Count() (count int)
- func (d BoltDB) Exists(f File) (exists bool)
- func (d BoltDB) Get(id []byte) (f File, err error)
- func (d BoltDB) GetBatch(files chan File, max int64) (err error)
- func (d BoltDB) GetOldFiles(maxCount int, deadline time.Time) (files []File, err error)
- func (d BoltDB) GetOldFilesCount(deadline time.Time) (count int64, err error)
- func (d BoltDB) Remove(f File) error
- func (d BoltDB) RemoveBatch(files []File) error
- func (d BoltDB) Size() (sum int64, err error)
- func (d BoltDB) Use(f File) error
- func (d BoltDB) UseBatch(files []File) error
- type Client
- func (c Client) ActionURL(args ...string) *url.URL
- func (c Client) AddFiles(files []File) error
- func (c Client) CheckStats() error
- func (c Client) Close() error
- func (c Client) GetFile(u *url.URL) (rc io.ReadCloser, err error)
- func (c Client) Login() error
- func (c Client) More() error
- func (c Client) RemoveFiles(files []File) error
- func (c Client) RequestFile(f File, u *url.URL) (rc io.ReadCloser, err error)
- func (c Client) Resume() error
- func (c Client) Settings() (cfg Settings, err error)
- func (c Client) Start() error
- func (c Client) StillAlive() error
- func (c Client) Suspend() error
- func (c Client) Tokens(files []File) (result map[string]string, err error)
- type ClientConfig
- type Credentials
- type DataBase
- type DefaultServer
- type DirectCache
- type DirectFrontend
- func (d *DirectFrontend) Add(file File, r io.Reader) error
- func (d *DirectFrontend) Check(file File) error
- func (d *DirectFrontend) Get(file File) (io.ReadCloser, error)
- func (d *DirectFrontend) Handle(file File, w http.ResponseWriter) error
- func (d *DirectFrontend) Remove(file File) error
- func (d *DirectFrontend) RemoveBatch(files []File) error
- func (d *DirectFrontend) Scan(files chan File, progress chan Progress) error
- type ErrUnexpected
- type Event
- type EventType
- type File
- func (f File) Basex() string
- func (f *File) Buffer() *bytes.Buffer
- func (f File) ByteID() []byte
- func (f File) Bytes() []byte
- func (f File) ContentType() string
- func (f File) Dir() string
- func (f File) HexID() string
- func (f File) InRange(r StaticRange) bool
- func (f File) KeyStamp(key string, timestamp int64) string
- func (f File) LastUsageBefore(t time.Time) bool
- func (f File) Marshal() ([]byte, error)
- func (f File) Path() string
- func (f File) Range() (r StaticRange)
- func (f *File) SetHash(s string) error
- func (f File) String() string
- func (f *File) Use()
- type FileCache
- func (c *FileCache) Add(file File, r io.Reader) error
- func (c *FileCache) Check(file File) error
- func (c *FileCache) Get(file File) (io.ReadCloser, error)
- func (c *FileCache) Remove(file File) error
- func (c *FileCache) RemoveBatch(files []File) error
- func (c *FileCache) Scan(results chan File, progress chan Progress) error
- type FileGenerator
- type FileType
- type Frontend
- type HTTPClient
- type Progress
- type ProxyMode
- type Server
- type ServerConfig
- type Settings
- type StaticRange
- type StaticRanges
- type Stats
- type Vars
- func (v Vars) Get(k string) string
- func (v Vars) GetInt(k string) (int, error)
- func (v Vars) GetInt64(k string) (int64, error)
- func (v Vars) GetProxyMode(k string) (p ProxyMode, err error)
- func (v Vars) GetStaticRange(k string) (s StaticRanges, err error)
- func (v Vars) GetUint64(k string) (uint64, error)
Constants ¶
const ( // HashSize is length of sha1 hash in bytes HashSize = 20 // FileMaximumSize is maximum image size in hath FileMaximumSize = size10MB )
Variables ¶
var ( // ErrFileNotFound should be returned when file does not exist in frontend ErrFileNotFound = errors.New("File not found in cache") // ErrFileBadLength means that file size does not equals read size ErrFileBadLength = errors.New("Bad lenght in file") // ErrFileInconsistent should be returned if file failed to check sha1 hash ErrFileInconsistent = errors.New("File has bad hash") )
var ( // FileTypes list for allowerd images FileTypes = []string{"jpg", "png", "gif"} // FileTypesN count of FileTypes FileTypesN = len(FileTypes) )
var ( // ErrClientKeyExpired timestampt drift occured ErrClientKeyExpired = errors.New("Client key is expired") // ErrClientFailedConnectionTest client failed to response on test correctly ErrClientFailedConnectionTest = errors.New("Client failed connection test") // ErrClientStartupFlood api rpc server flood protection is enabled // client should wait ErrClientStartupFlood = errors.New("API flood protection enabled") // ErrClientOtherConnected other client with same clientID connected ErrClientOtherConnected = errors.New("Other client is connected") // ErrClientUnexpectedResponse unexpected/unhandler error ErrClientUnexpectedResponse = errors.New("Unexpected error") // ErrTimeDesync timestamp delta too bit ErrTimeDesync = errors.New("Time on server and on client differ too much") // ErrClientVersionOld api outdated ErrClientVersionOld = errors.New("Client version is too old") )
var ( // ErrFileTypeUnknown when FileType is UnknownImage ErrFileTypeUnknown = errors.New("hath => file type unknown") // ErrHashBadLength when hash size is not HashSize ErrHashBadLength = errors.New("hath => hash of image has bad length") )
var ( // ContentTypes is map of file types to conent types ContentTypes = map[FileType]string{ JPG: "image/jpeg", PNG: "image/png", GIF: "image/gif", UnknownImage: "application/octet-stream", } )
var ( // ErrNoFilesToRemove is flag that there is 0 files to remove ErrNoFilesToRemove = errors.New("No more unused files") )
var ( // LocalNetworks is slice of net.IPNet for all local networks subnets LocalNetworks []net.IPNet )
Functions ¶
func FileFromBytesTo ¶
FileFromBytesTo deserializes byte slice into file by pointer
func FromRequest ¶
FromRequest extracts the user IP address from req, if present.
func GetRoughCacheSize ¶
GetRoughCacheSize is cache size estimation based on average file size
func IsUnexpected ¶
IsUnexpected return true if err is ErrUnexpected or ErrClientUnexpectedResponse
func UnmarshalFileTo ¶
UnmarshalFileTo deserializes file info fron byte array by pointer
Types ¶
type APIResponse ¶
APIResponse represents response from rpc api
func (APIResponse) ParseVars ¶
func (r APIResponse) ParseVars() Vars
ParseVars parses k=v map from r.Data
type Args ¶
Args represents additional arguments in request string
type BoltDB ¶
type BoltDB struct {
// contains filtered or unexported fields
}
BoltDB stores info about files in cache stores data in b-tree structure stores index on LastUsage+Hash implements DataBase interface
func (BoltDB) GetOldFiles ¶
GetOldFiles returns maxCount or less expired files
func (BoltDB) GetOldFilesCount ¶
GetOldFilesCount count of files that LastUsage is older than deadline
func (BoltDB) RemoveBatch ¶
RemoveBatch remove file and corresponding index records
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is api for hath rpc
func (Client) CheckStats ¶
CheckStats checks time desync and minumum client build returns nil, of time is synced and client version is up to date
func (Client) RemoveFiles ¶
RemoveFiles notifies api server of removed files
func (Client) RequestFile ¶
RequestFile from hath server
type ClientConfig ¶
type ClientConfig struct {
Credentials
Host string
Debug bool
}
ClientConfig is configuration for client
type DataBase ¶
type DataBase interface {
Add(f File) error
AddBatch(f []File) error
Use(f File) error
UseBatch(files []File) error
Remove(f File) error
RemoveBatch(f []File) error
Close() error
Count() int
GetOldFiles(maxCount int, deadline time.Time) (files []File, err error)
GetOldFilesCount(deadline time.Time) (count int64, err error)
Size() (int64, error)
Exists(f File) bool
Get(id []byte) (File, error)
GetBatch(files chan File, max int64) (err error)
}
DataBase is interface for storing info about files in some DB
type DefaultServer ¶
type DefaultServer struct {
// contains filtered or unexported fields
}
DefaultServer uses hard drive to respond
func NewServer ¶
func NewServer(cfg ServerConfig) *DefaultServer
NewServer cleares default server with provided client and frontend
func (DefaultServer) PopulateFromFrontend ¶
func (s DefaultServer) PopulateFromFrontend() error
PopulateFromFrontend scans frontend and adds all files in it to database
func (*DefaultServer) ServeHTTP ¶
func (s *DefaultServer) ServeHTTP(w http.ResponseWriter, r *http.Request)
func (*DefaultServer) Start ¶
func (s *DefaultServer) Start() error
Start server internal goroutines
type DirectCache ¶
type DirectCache interface {
Get(file File) (io.ReadCloser, error)
Remove(f File) error
RemoveBatch(f []File) error
Add(file File, r io.Reader) error
Check(file File) error
Scan(chan File, chan Progress) error
}
DirectCache is engine for serving files in hath directly from block devices i.e. not using any redirects
type DirectFrontend ¶
type DirectFrontend struct {
// contains filtered or unexported fields
}
DirectFrontend is frontend that uses DirectCache
func (*DirectFrontend) Add ¶
func (d *DirectFrontend) Add(file File, r io.Reader) error
Add file to frontend
func (*DirectFrontend) Get ¶
func (d *DirectFrontend) Get(file File) (io.ReadCloser, error)
Get returns file from fontend
func (*DirectFrontend) Handle ¶
func (d *DirectFrontend) Handle(file File, w http.ResponseWriter) error
Handle request for file returns ErrFileNotFound, ErrFileBadLength can return unexpected errors
func (*DirectFrontend) RemoveBatch ¶
func (d *DirectFrontend) RemoveBatch(files []File) error
RemoveBatch removes files
type ErrUnexpected ¶
type ErrUnexpected struct {
Err error
Response APIResponse
}
ErrUnexpected error while processing request/response
func (ErrUnexpected) Error ¶
func (e ErrUnexpected) Error() string
type EventType ¶
type EventType byte
EventType is type of event from server
const ( // EventSent issued when file is sent to hath network EventSent EventType = iota // EventDownloaded issued when file is downloaded by server from hath EventDownloaded // EventAdded issued when file is added to cache EventAdded // EventRemoved issued when file is removed from cache EventRemoved )
type File ¶
type File struct {
Hash [HashSize]byte `json:"hash"` // 20 byte
Type FileType `json:"type"` // 1 byte
// Static files should never be removed
Static bool `json:"static"` // 1 byte
Size int64 `json:"size"` // 4 byte (maximum size 4095mb)
Width int `json:"width"` // 2 byte
Height int `json:"height"` // 2 byte
// LastUsage is Unix timestamp
LastUsage int64 `json:"last_usage"` // 8 byte (can be optimized)
}
File is hath file representation total 20 + 4 + 2 + 2 + 1 + 8 + 1 = 38 bytes in memory = 56 bytes
func FileFromBytes ¶
FileFromBytes deserializes byte slice into file
func FileFromID ¶
FileFromID generates new File from provided ID
func UnmarshalFile ¶
UnmarshalFile deserializes file info fron byte array
func (File) InRange ¶
func (f File) InRange(r StaticRange) bool
InRange returns true if file is in static range r
func (File) LastUsageBefore ¶
LastUsageBefore returns true, if last usage occured before deadline t
type FileCache ¶
type FileCache struct {
// contains filtered or unexported fields
}
FileCache serves files from disk no internal buffering, caching or rate limiting is done and should be implement separetaly
func (*FileCache) Get ¶
func (c *FileCache) Get(file File) (io.ReadCloser, error)
Get returns readcloser for file if file does not exist, it will return ErrFileNotFound
func (*FileCache) RemoveBatch ¶
RemoveBatch removes files from storage
type FileGenerator ¶
type FileGenerator struct {
SizeMax int64
SizeMin int64
ResolutionMax int
ResolutionMin int
Dir string
TimeDelta int64
}
FileGenerator is factory for random files
func (FileGenerator) New ¶
func (g FileGenerator) New() (f File, err error)
New generates random file and returns it, writing on disk
func (FileGenerator) NewFake ¶
func (g FileGenerator) NewFake() (f File)
NewFake generates random file without writing it on disk
type FileType ¶
type FileType byte
FileType represents file format of image
func ParseFileType ¶
ParseFileType returns FileType from string
type Frontend ¶
type Frontend interface {
Handle(file File, w http.ResponseWriter) error
DirectCache
}
Frontend is cache backend that should processes requests to specidif files, returning them with correct headers and processing IO errors
func NewDirectFrontend ¶
func NewDirectFrontend(cache DirectCache) Frontend
NewDirectFrontend create direct frontend
func NewFrontend ¶
type HTTPClient ¶
type HTTPClient interface {
Get(url string) (*http.Response, error)
Do(req *http.Request) (*http.Response, error)
}
HTTPClient is underlying http client
type ProxyMode ¶
type ProxyMode byte
ProxyMode sets proxy security politics
const ( // ProxyDisabled no requests allowed ProxyDisabled ProxyMode = iota + 1 // starts with 1 // ProxyLocalNetworksProtected allows requests from local network with passkey ProxyLocalNetworksProtected // 2 // ProxyLocalNetworksOpen allows any requests from local network ProxyLocalNetworksOpen // 3 // ProxyAllNetworksProtected allows requests from any network with passkey (not recommended) ProxyAllNetworksProtected // 4 // ProxyAllNetworksOpen allows any requests from any network (very not recommended) ProxyAllNetworksOpen // 5 )
type Server ¶
Server should handle requests from users (and rpc?) speedtests server commands:
/servercmd/<command>/<additional:kwds>/<timestamp:int>/<key>'
image file request:
/h/<fileid>/<additional:kwds>/<filename>
type ServerConfig ¶
type ServerConfig struct {
Credentials
Frontend Frontend
DataBase DataBase
Client *Client
DontCheckTimestamps bool
DontCheckSHA1 bool
RemoveTimeout time.Duration
RemoveRate time.Duration
UpdateRate time.Duration
MaxDownloadAttemps int
Settings Settings
Debug bool
}
ServerConfig cfg for server
func (*ServerConfig) PopulateDefaults ¶
func (cfg *ServerConfig) PopulateDefaults()
PopulateDefaults of the config
type Settings ¶
type Settings struct {
RPCServers []net.IP
ImageServer string
RequestServer string
LowMemory bool
ProxyMode ProxyMode
StaticRanges StaticRanges
Name string
Host net.IP
Port int
MaximumBytesPerSecond int64
MaximumCacheSize int64
DiskReamainingBytes int64
}
Settings of hath client
type StaticRange ¶
type StaticRange [staticRangeBytes]byte
StaticRange is prefix for static ranges assigned to user
func ParseStaticRange ¶
func ParseStaticRange(s string) (r StaticRange, err error)
ParseStaticRange parses hex string static range start
func (StaticRange) String ¶
func (s StaticRange) String() string
type StaticRanges ¶
type StaticRanges map[StaticRange]bool
StaticRanges contain ranges
func (StaticRanges) Contains ¶
func (s StaticRanges) Contains(f File) bool
Contains returns true if file f is in static ranges
func (StaticRanges) String ¶
func (s StaticRanges) String() string
type Stats ¶
type Stats struct {
FilesTotal int
FilesSent int
FilesSentBytes int64
FilesDownloaded int
FilesDownloadedBytes int64
Started time.Time
Uptime time.Duration
}
Stats for server
type Vars ¶
Vars represents k-v map from APIResponse.Data
func (Vars) GetProxyMode ¶
GetProxyMode parses ProxyMode
func (Vars) GetStaticRange ¶
func (v Vars) GetStaticRange(k string) (s StaticRanges, err error)
GetStaticRange parses static range list
