This commit is contained in:
liwei committed 2024-12-21 15:57:10 +08:00
1 parent 63296f6950
commit a06549a11a
13 files changed
+135 -100

No files matched your search

+22 -10
View File
@@ -54,29 +54,34 @@ func Create(startCfg *model.StartConfig) (*Instance, error) {
return i, nil
}
func (i *Instance) StartHttp() *model.Result[any] {
func (i *Instance) Listener(listener download.Listener) *model.Result[any] {
i.downloader.Listener(listener)
return model.NewNilResult()
}
func (i *Instance) StartHttp() *model.Result[int] {
i.httpLock.Lock()
defer i.httpLock.Unlock()
return i.startHttp()
}
func (i *Instance) startHttp() *model.Result[any] {
func (i *Instance) startHttp() *model.Result[int] {
httpCfg := i.getHttpConfig()
if httpCfg == nil || !httpCfg.Enable {
return model.NewErrorResult[any]("HTTP API server not enabled")
return model.NewErrorResult[int]("HTTP API server not enabled")
}
if i.srv != nil {
return model.NewErrorResult[any]("HTTP API server already started")
return model.NewErrorResult[int]("HTTP API server already started")
}
port, start, err := ListenHttp(httpCfg, i)
if err != nil {
return model.NewErrorResult[any](err.Error())
return model.NewErrorResult[int](err.Error())
}
httpCfg.RunningPort = port
go start()
return model.NewNilResult()
return model.NewOkResult(port)
}
func (i *Instance) getHttpConfig() *base.DownloaderHttpConfig {
@@ -112,7 +117,7 @@ func (i *Instance) stopHttp() *model.Result[any] {
return model.NewNilResult()
}
func (i *Instance) RestartHttp() *model.Result[any] {
func (i *Instance) RestartHttp() *model.Result[int] {
i.httpLock.Lock()
defer i.httpLock.Unlock()
@@ -169,7 +174,7 @@ func (i *Instance) CreateTaskBatch(req *model.CreateTaskBatch) *model.Result[[]s
func (i *Instance) PauseTask(taskId string) *model.Result[any] {
err := i.downloader.Pause(&download.TaskFilter{
IDs: []string{taskId},
ID: []string{taskId},
})
if err != nil {
return model.NewErrorResult[any](err.Error())
@@ -187,7 +192,7 @@ func (i *Instance) PauseTasks(filter *download.TaskFilter) *model.Result[any] {
func (i *Instance) ContinueTask(taskId string) *model.Result[any] {
err := i.downloader.Continue(&download.TaskFilter{
IDs: []string{taskId},
ID: []string{taskId},
})
if err != nil {
return model.NewErrorResult[any](err.Error())
@@ -205,7 +210,7 @@ func (i *Instance) ContinueTasks(filter *download.TaskFilter) *model.Result[any]
func (i *Instance) DeleteTask(taskId string, force bool) *model.Result[any] {
err := i.downloader.Delete(&download.TaskFilter{
IDs: []string{taskId},
ID: []string{taskId},
}, force)
if err != nil {
return model.NewErrorResult[any](err.Error())
@@ -344,6 +349,13 @@ func (i *Instance) Close() *model.Result[any] {
return model.NewNilResult()
}
func (i *Instance) Clear() *model.Result[any] {
if err := i.downloader.Clear(); err != nil {
return model.NewErrorResult[any](err.Error())
}
return model.NewNilResult()
}
type Request struct {
Method string `json:"method"`
Params []any `json:"params"`
+3 -2
View File
@@ -7,8 +7,6 @@ import (
"testing"
)
var instance, _ = Create(nil)
func TestInvoke(t *testing.T) {
doTestInvoke(t, "Info", []any{}, model.CodeOk)
doTestInvoke(t, "Info1", []any{}, model.CodeError)
@@ -21,6 +19,9 @@ func TestInvoke(t *testing.T) {
}
func doTestInvoke(t *testing.T, method string, params []any, expectCode model.RespCode) {
instance, _ := Create(nil)
defer instance.Close()
result := Invoke(instance, &Request{
Method: method,
Params: params,
+4 -4
View File
@@ -47,8 +47,8 @@ func ListenHttp(httpCfg *base.DownloaderHttpConfig, ai *Instance) (int, func(),
r.Methods(http.MethodDelete).Path("/api/v1/extensions/{identity}").HandlerFunc(DeleteExtension)
r.Methods(http.MethodGet).Path("/api/v1/extensions/{identity}/upgrade").HandlerFunc(UpgradeCheckExtension)
r.Methods(http.MethodPost).Path("/api/v1/extensions/{identity}/upgrade").HandlerFunc(UpgradeExtension)
r.Path("/api/v1/proxy").HandlerFunc(DoProxy)
if ai.startCfg.WebEnable {
r.Path("/api/v1/proxy").HandlerFunc(DoProxy)
r.PathPrefix("/fs/tasks").Handler(http.FileServer(&taskFileSystem{
downloader: ai.downloader,
}))
@@ -359,9 +359,9 @@ func parseFilter(r *http.Request, w http.ResponseWriter, filter *download.TaskFi
return false
}
filter.IDs = r.Form["id"]
filter.Statuses = convertStatues(r.Form["status"])
filter.NotStatuses = convertStatues(r.Form["notStatus"])
filter.ID = r.Form["id"]
filter.Status = convertStatues(r.Form["status"])
filter.NotStatus = convertStatues(r.Form["notStatus"])
return true
}
@@ -21,8 +21,8 @@ import (
)
var (
instance, _ = Create(nil)
restPort int
httpInstance *Instance
restPort int
taskReq = &base.Request{
Extra: map[string]any{
@@ -91,7 +91,7 @@ func TestCreateTask(t *testing.T) {
var wg sync.WaitGroup
wg.Add(1)
Downloader.Listener(func(event *download.Event) {
httpInstance.Listener(func(event *download.Event) {
if event.Key == download.EventKeyFinally {
wg.Done()
}
@@ -118,7 +118,7 @@ func TestCreateDirectTask(t *testing.T) {
doTest(func() {
var wg sync.WaitGroup
wg.Add(1)
Downloader.Listener(func(event *download.Event) {
httpInstance.Listener(func(event *download.Event) {
if event.Key == download.EventKeyFinally {
wg.Done()
}
@@ -157,7 +157,7 @@ func TestCreateDirectTaskWithResoled(t *testing.T) {
doTest(func() {
var wg sync.WaitGroup
wg.Add(1)
Downloader.Listener(func(event *download.Event) {
httpInstance.Listener(func(event *download.Event) {
if event.Key == download.EventKeyFinally {
wg.Done()
}
@@ -181,7 +181,7 @@ func TestPauseAndContinueTask(t *testing.T) {
doTest(func() {
var wg sync.WaitGroup
wg.Add(1)
Downloader.Listener(func(event *download.Event) {
httpInstance.Listener(func(event *download.Event) {
switch event.Key {
case download.EventKeyFinally:
wg.Done()
@@ -215,10 +215,7 @@ func TestPauseAndContinueTask(t *testing.T) {
func TestPauseAllAndContinueALLTasks(t *testing.T) {
doTest(func() {
cfg, err := Downloader.GetConfig()
if err != nil {
t.Fatal(err)
}
cfg := UnwrapResult(httpInstance.GetConfig())
createAndPause := func() {
taskId := httpRequestCheckOk[string](http.MethodPost, "/api/v1/tasks", createReq)
@@ -276,7 +273,7 @@ func TestDeleteAllTasks(t *testing.T) {
var wg sync.WaitGroup
wg.Add(taskCount)
Downloader.Listener(func(event *download.Event) {
httpInstance.Listener(func(event *download.Event) {
if event.Key == download.EventKeyFinally {
wg.Done()
}
@@ -302,7 +299,7 @@ func TestDeleteTasksByStatues(t *testing.T) {
var wg sync.WaitGroup
wg.Add(taskCount)
Downloader.Listener(func(event *download.Event) {
httpInstance.Listener(func(event *download.Event) {
if event.Key == download.EventKeyFinally {
wg.Done()
}
@@ -326,7 +323,7 @@ func TestGetTasks(t *testing.T) {
doTest(func() {
var wg sync.WaitGroup
wg.Add(1)
Downloader.Listener(func(event *download.Event) {
httpInstance.Listener(func(event *download.Event) {
if event.Key == download.EventKeyFinally {
wg.Done()
}
@@ -450,16 +447,16 @@ func TestDeleteExtension(t *testing.T) {
})
}
func TestUpdateCheckExtension(t *testing.T) {
func TestUpgradeCheckExtension(t *testing.T) {
doTest(func() {
identity := httpRequestCheckOk[string](http.MethodPost, "/api/v1/extensions", installExtensionReq)
resp := httpRequestCheckOk[*model.UpgradeCheckExtensionResp](http.MethodGet, "/api/v1/extensions/"+identity+"/update", nil)
resp := httpRequestCheckOk[*model.UpgradeCheckExtensionResp](http.MethodGet, "/api/v1/extensions/"+identity+"/upgrade", nil)
// no new version
if resp.NewVersion != "" {
t.Errorf("UpgradeCheckExtension() got = %v, want %v", resp.NewVersion, "")
}
// force update
httpRequestCheckOk[any](http.MethodPost, "/api/v1/extensions/"+identity+"/update", nil)
httpRequestCheckOk[any](http.MethodPost, "/api/v1/extensions/"+identity+"/upgrade", nil)
})
}
@@ -510,13 +507,19 @@ func TestDoProxy(t *testing.T) {
func TestApiToken(t *testing.T) {
var cfg = &model.StartConfig{}
cfg.Init()
cfg.ApiToken = "123456"
fileListener := doStart(cfg)
cfg.DownloadConfig = &base.DownloaderStoreConfig{
Http: &base.DownloaderHttpConfig{
Enable: true,
ApiToken: "123456",
},
}
httpInstance, _ = Create(cfg)
fileListener := doStart()
defer func() {
if err := fileListener.Close(); err != nil {
panic(err)
}
Stop()
httpInstance.Close()
}()
status, _ := doHttpRequest0(http.MethodGet, "/api/v1/config", nil, nil)
@@ -525,7 +528,7 @@ func TestApiToken(t *testing.T) {
}
status, _ = doHttpRequest0(http.MethodGet, "/api/v1/config", map[string]string{
"X-Api-Token": cfg.ApiToken,
"X-Api-Token": cfg.DownloadConfig.Http.ApiToken,
}, nil)
if status != http.StatusOK {
t.Errorf("TestApiToken() got = %v, want %v", status, http.StatusOK)
@@ -536,18 +539,24 @@ func TestApiToken(t *testing.T) {
func TestAuthorization(t *testing.T) {
var cfg = &model.StartConfig{}
cfg.Init()
cfg.ApiToken = "123456"
cfg.DownloadConfig = &base.DownloaderStoreConfig{
Http: &base.DownloaderHttpConfig{
Enable: true,
ApiToken: "123456",
},
}
cfg.WebEnable = true
cfg.WebBasicAuth = &model.WebBasicAuth{
Username: "admin",
Password: "123456",
}
fileListener := doStart(cfg)
httpInstance, _ = Create(cfg)
fileListener := doStart()
defer func() {
if err := fileListener.Close(); err != nil {
panic(err)
}
Stop()
httpInstance.Close()
}()
status, _ := doHttpRequest0(http.MethodGet, "/api/v1/config", nil, nil)
@@ -563,7 +572,7 @@ func TestAuthorization(t *testing.T) {
}
status, _ = doHttpRequest0(http.MethodGet, "/api/v1/config", map[string]string{
"X-Api-Token": cfg.ApiToken,
"X-Api-Token": cfg.DownloadConfig.Http.ApiToken,
}, nil)
if status != http.StatusOK {
t.Errorf("TestAuthorization() got = %v, want %v", status, http.StatusOK)
@@ -577,17 +586,23 @@ func doTest(handler func()) {
cfg.Storage = storage
cfg.StorageDir = ".test_storage"
cfg.WebEnable = true
fileListener := doStart(cfg)
cfg.DownloadConfig = &base.DownloaderStoreConfig{
Http: &base.DownloaderHttpConfig{
Enable: true,
},
}
httpInstance, _ = Create(cfg)
fileListener := doStart()
defer func() {
if err := fileListener.Close(); err != nil {
panic(err)
}
Stop()
Downloader.Clear()
httpInstance.StopHttp()
httpInstance.Clear()
}()
defer func() {
Downloader.Pause(nil)
Downloader.Delete(nil, true)
httpInstance.PauseTasks(nil)
httpInstance.DeleteTasks(nil, true)
os.RemoveAll(cfg.StorageDir)
}()
taskReq.URL = "http://" + fileListener.Addr().String() + "/" + test.BuildName
@@ -597,15 +612,19 @@ func doTest(handler func()) {
testFunc(model.StorageBolt)
}
func doStart(cfg *model.StartConfig) net.Listener {
port, err := Start(cfg)
if err != nil {
panic(err)
}
func doStart() net.Listener {
port := UnwrapResult(httpInstance.StartHttp())
restPort = port
return test.StartTestFileServer()
}
func UnwrapResult[T any](result *model.Result[T]) T {
if result.HasError() {
panic(result.Msg)
}
return result.Data
}
func doHttpRequest0(method string, path string, headers map[string]string, body any) (int, []byte) {
var reader io.Reader
if body != nil {