2020-05-15 12:20:07 +00:00
|
|
|
package ui
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"opslag.de/schobers/zntg"
|
|
|
|
)
|
|
|
|
|
2020-05-25 20:24:06 +00:00
|
|
|
var _ PhysicalResources = &CopyResources{}
|
2020-05-15 12:20:07 +00:00
|
|
|
|
2020-05-25 20:24:06 +00:00
|
|
|
// CopyResources copies the resource to a temporary directory when fetched. Optionally the resource is fetched as well before opening.
|
2020-05-15 12:20:07 +00:00
|
|
|
type CopyResources struct {
|
|
|
|
Source Resources
|
|
|
|
|
|
|
|
copy *zntg.Dir
|
2020-05-25 20:24:06 +00:00
|
|
|
|
|
|
|
mustCopyBeforeOpen bool
|
2020-05-15 12:20:07 +00:00
|
|
|
}
|
|
|
|
|
2020-05-25 20:24:06 +00:00
|
|
|
func newCopyResources(prefix string, source Resources, mustCopyBeforeOpen bool) (*CopyResources, error) {
|
2020-05-15 12:20:07 +00:00
|
|
|
copy, err := zntg.NewTempDir(prefix)
|
|
|
|
if nil != err {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-05-25 20:24:06 +00:00
|
|
|
return &CopyResources{source, copy, mustCopyBeforeOpen}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewCopyResources creates a proxy that copies resources first to disk. Copy on OpenResource only happens when mustCopyBeforeOpen is set to true.
|
|
|
|
func NewCopyResources(prefix string, source Resources, mustCopyBeforeOpen bool) (*CopyResources, error) {
|
|
|
|
return newCopyResources(prefix, source, false)
|
2020-05-15 12:20:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// FetchResource copies the file from the source to disk and returns the path to it.
|
|
|
|
func (r *CopyResources) FetchResource(name string) (string, error) {
|
|
|
|
path := r.copy.FilePath(name)
|
|
|
|
if !zntg.FileExists(path) {
|
|
|
|
src, err := r.Source.OpenResource(name)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
defer src.Close()
|
|
|
|
|
|
|
|
err = r.copy.Write(name, src)
|
|
|
|
if nil != err {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return path, nil
|
|
|
|
}
|
|
|
|
|
2020-05-25 20:24:06 +00:00
|
|
|
// OpenResource opens the (optionally copied) resource.
|
2020-05-15 12:20:07 +00:00
|
|
|
func (r *CopyResources) OpenResource(name string) (io.ReadCloser, error) {
|
2020-05-25 20:24:06 +00:00
|
|
|
if r.mustCopyBeforeOpen {
|
|
|
|
path, err := r.FetchResource(name)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return os.Open(path)
|
|
|
|
}
|
|
|
|
return r.Source.OpenResource(name)
|
2020-05-15 12:20:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Destroy destroy the copy of the resources.
|
|
|
|
func (r *CopyResources) Destroy() error {
|
|
|
|
return r.copy.Destroy()
|
|
|
|
}
|