Path: blob/main/internal/offline_download/http/client.go
1562 views
package http12import (3"fmt"4"net/http"5"net/url"6"os"7"path"8"path/filepath"9"strings"1011"github.com/alist-org/alist/v3/internal/model"12"github.com/alist-org/alist/v3/internal/offline_download/tool"13"github.com/alist-org/alist/v3/pkg/utils"14)1516type SimpleHttp struct {17client http.Client18}1920func (s SimpleHttp) Name() string {21return "SimpleHttp"22}2324func (s SimpleHttp) Items() []model.SettingItem {25return nil26}2728func (s SimpleHttp) Init() (string, error) {29return "ok", nil30}3132func (s SimpleHttp) IsReady() bool {33return true34}3536func (s SimpleHttp) AddURL(args *tool.AddUrlArgs) (string, error) {37panic("should not be called")38}3940func (s SimpleHttp) Remove(task *tool.DownloadTask) error {41panic("should not be called")42}4344func (s SimpleHttp) Status(task *tool.DownloadTask) (*tool.Status, error) {45panic("should not be called")46}4748func (s SimpleHttp) Run(task *tool.DownloadTask) error {49u := task.Url50// parse url51_u, err := url.Parse(u)52if err != nil {53return err54}55req, err := http.NewRequestWithContext(task.Ctx(), http.MethodGet, u, nil)56if err != nil {57return err58}59resp, err := s.client.Do(req)60if err != nil {61return err62}63defer resp.Body.Close()64if resp.StatusCode >= 400 {65return fmt.Errorf("http status code %d", resp.StatusCode)66}67// If Path is empty, use Hostname; otherwise, filePath euqals TempDir which causes os.Create to fail68urlPath := _u.Path69if urlPath == "" {70urlPath = strings.ReplaceAll(_u.Host, ".", "_")71}72filename := path.Base(urlPath)73if n, err := parseFilenameFromContentDisposition(resp.Header.Get("Content-Disposition")); err == nil {74filename = n75}76// save to temp dir77_ = os.MkdirAll(task.TempDir, os.ModePerm)78filePath := filepath.Join(task.TempDir, filename)79file, err := os.Create(filePath)80if err != nil {81return err82}83defer file.Close()84fileSize := resp.ContentLength85task.SetTotalBytes(fileSize)86err = utils.CopyWithCtx(task.Ctx(), file, resp.Body, fileSize, task.SetProgress)87return err88}8990func init() {91tool.Tools.Add(&SimpleHttp{})92}939495