izapple2/resources.go

123 lines
2.5 KiB
Go
Raw Normal View History

2022-01-28 18:25:52 +00:00
package izapple2
import (
"archive/zip"
"bytes"
"compress/gzip"
2022-01-28 18:25:52 +00:00
"embed"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
2022-01-28 18:25:52 +00:00
"github.com/ivanizag/izapple2/storage"
)
const (
internalPrefix = "<internal>/"
2022-01-28 18:25:52 +00:00
embedPrefix = "resources/"
httpPrefix = "http://"
httpsPrefix = "https://"
)
2022-01-28 18:25:52 +00:00
//go:embed resources
var internalFiles embed.FS
func isInternalResource(filename string) bool {
return strings.HasPrefix(filename, internalPrefix)
}
func isHTTPResource(filename string) bool {
return strings.HasPrefix(filename, httpPrefix) ||
strings.HasPrefix(filename, httpsPrefix)
}
// LoadResource loads in memory a file from the filesystem, http or embedded
func LoadResource(filename string) ([]uint8, bool, error) {
var writeable bool
var file io.Reader
if isInternalResource(filename) {
// load from embedded resource
2022-01-28 18:25:52 +00:00
resource := embedPrefix + strings.TrimPrefix(filename, internalPrefix)
resourceFile, err := internalFiles.Open(resource)
if err != nil {
return nil, false, err
}
defer resourceFile.Close()
file = resourceFile
writeable = false
} else if isHTTPResource(filename) {
response, err := http.Get(filename)
if err != nil {
return nil, false, err
}
defer response.Body.Close()
file = response.Body
writeable = false
} else {
diskFile, err := os.Open(filename)
if err != nil {
return nil, false, err
}
defer diskFile.Close()
file = diskFile
writeable = true
}
data, err := ioutil.ReadAll(file)
if err != nil {
return nil, false, err
}
contentType := http.DetectContentType(data)
if contentType == "application/x-gzip" {
writeable = false
gz, err := gzip.NewReader(bytes.NewReader(data))
if err != nil {
return nil, false, err
}
defer gz.Close()
data, err = ioutil.ReadAll(gz)
if err != nil {
return nil, false, err
}
} else if contentType == "application/zip" {
writeable = false
z, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
return nil, false, err
}
for _, zf := range z.File {
f, err := zf.Open()
if err != nil {
return nil, false, err
}
defer f.Close()
bytes, err := ioutil.ReadAll(f)
if err != nil {
return nil, false, err
}
2022-01-28 18:25:52 +00:00
if storage.IsDiskette(bytes) {
data = bytes
break
}
}
}
return data, writeable, nil
}
2022-01-28 18:25:52 +00:00
// LoadDiskette returns a Diskette by detecting the format
func LoadDiskette(filename string) (storage.Diskette, error) {
data, writeable, err := LoadResource(filename)
if err != nil {
return nil, err
}
return storage.MakeDiskette(data, filename, writeable)
}