alist/internal/fs/util.go

66 lines
1.5 KiB
Go
Raw Normal View History

2022-06-10 09:26:43 +00:00
package fs
2022-06-10 09:18:27 +00:00
import (
2022-06-15 10:08:13 +00:00
"io"
"mime"
"net/http"
"os"
stdpath "path"
"strings"
"github.com/alist-org/alist/v3/internal/model"
"github.com/pkg/errors"
2022-06-10 09:18:27 +00:00
)
2022-06-15 12:41:17 +00:00
func containsByName(files []model.Obj, file model.Obj) bool {
2022-06-10 09:18:27 +00:00
for _, f := range files {
if f.GetName() == file.GetName() {
return true
}
}
return false
}
2022-06-15 10:08:13 +00:00
var httpClient = &http.Client{}
2022-06-15 12:41:17 +00:00
func getFileStreamFromLink(file model.Obj, link *model.Link) (model.FileStreamer, error) {
2022-06-15 10:08:13 +00:00
var rc io.ReadCloser
mimetype := mime.TypeByExtension(stdpath.Ext(file.GetName()))
if link.Data != nil {
rc = link.Data
} else if link.FilePath != nil {
f, err := os.Open(*link.FilePath)
if err != nil {
return nil, errors.Wrapf(err, "failed to open file %s", *link.FilePath)
}
rc = f
} else {
req, err := http.NewRequest(http.MethodGet, link.URL, nil)
if err != nil {
return nil, errors.Wrapf(err, "failed to create request for %s", link.URL)
}
for h, val := range link.Header {
req.Header[h] = val
}
res, err := httpClient.Do(req)
if err != nil {
return nil, errors.Wrapf(err, "failed to get response for %s", link.URL)
}
mt := res.Header.Get("Content-Type")
if mt != "" && strings.ToLower(mt) != "application/octet-stream" {
mimetype = mt
}
rc = res.Body
}
// if can't get mimetype, use default application/octet-stream
if mimetype == "" {
mimetype = "application/octet-stream"
}
stream := model.FileStream{
2022-06-15 12:41:17 +00:00
Obj: file,
2022-06-15 10:08:13 +00:00
ReadCloser: rc,
Mimetype: mimetype,
}
return stream, nil
}