|
| 1 | +package http |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "github.com/alist-org/alist/v3/internal/model" |
| 6 | + "github.com/alist-org/alist/v3/internal/offline_download/tool" |
| 7 | + "github.com/alist-org/alist/v3/pkg/utils" |
| 8 | + "net/http" |
| 9 | + "net/url" |
| 10 | + "os" |
| 11 | + "path" |
| 12 | + "path/filepath" |
| 13 | +) |
| 14 | + |
| 15 | +type SimpleHttp struct { |
| 16 | + client http.Client |
| 17 | +} |
| 18 | + |
| 19 | +func (s SimpleHttp) Name() string { |
| 20 | + return "SimpleHttp" |
| 21 | +} |
| 22 | + |
| 23 | +func (s SimpleHttp) Items() []model.SettingItem { |
| 24 | + return nil |
| 25 | +} |
| 26 | + |
| 27 | +func (s SimpleHttp) Init() (string, error) { |
| 28 | + return "ok", nil |
| 29 | +} |
| 30 | + |
| 31 | +func (s SimpleHttp) IsReady() bool { |
| 32 | + return true |
| 33 | +} |
| 34 | + |
| 35 | +func (s SimpleHttp) AddURL(args *tool.AddUrlArgs) (string, error) { |
| 36 | + panic("should not be called") |
| 37 | +} |
| 38 | + |
| 39 | +func (s SimpleHttp) Remove(task *tool.DownloadTask) error { |
| 40 | + panic("should not be called") |
| 41 | +} |
| 42 | + |
| 43 | +func (s SimpleHttp) Status(task *tool.DownloadTask) (*tool.Status, error) { |
| 44 | + panic("should not be called") |
| 45 | +} |
| 46 | + |
| 47 | +func (s SimpleHttp) Run(task *tool.DownloadTask) error { |
| 48 | + u := task.Url |
| 49 | + // parse url |
| 50 | + _u, err := url.Parse(u) |
| 51 | + if err != nil { |
| 52 | + return err |
| 53 | + } |
| 54 | + req, err := http.NewRequestWithContext(task.Ctx(), http.MethodGet, u, nil) |
| 55 | + if err != nil { |
| 56 | + return err |
| 57 | + } |
| 58 | + resp, err := s.client.Do(req) |
| 59 | + if err != nil { |
| 60 | + return err |
| 61 | + } |
| 62 | + defer resp.Body.Close() |
| 63 | + if resp.StatusCode >= 400 { |
| 64 | + return fmt.Errorf("http status code %d", resp.StatusCode) |
| 65 | + } |
| 66 | + filename := path.Base(_u.Path) |
| 67 | + if n, err := parseFilenameFromContentDisposition(resp.Header.Get("Content-Disposition")); err == nil { |
| 68 | + filename = n |
| 69 | + } |
| 70 | + // save to temp dir |
| 71 | + _ = os.MkdirAll(task.TempDir, os.ModePerm) |
| 72 | + filePath := filepath.Join(task.TempDir, filename) |
| 73 | + file, err := os.Create(filePath) |
| 74 | + if err != nil { |
| 75 | + return err |
| 76 | + } |
| 77 | + defer file.Close() |
| 78 | + fileSize := resp.ContentLength |
| 79 | + err = utils.CopyWithCtx(task.Ctx(), file, resp.Body, fileSize, task.SetProgress) |
| 80 | + return err |
| 81 | +} |
| 82 | + |
| 83 | +func init() { |
| 84 | + tool.Tools.Add(&SimpleHttp{}) |
| 85 | +} |
0 commit comments