alist/internal/aria2/add.go

62 lines
1.6 KiB
Go
Raw Normal View History

2022-06-20 12:34:58 +00:00
package aria2
import (
"context"
2022-06-21 09:37:02 +00:00
"fmt"
2022-08-03 06:26:59 +00:00
"path/filepath"
2022-06-25 12:38:02 +00:00
"github.com/alist-org/alist/v3/internal/conf"
2022-06-23 07:57:10 +00:00
"github.com/alist-org/alist/v3/internal/errs"
"github.com/alist-org/alist/v3/internal/op"
2022-06-21 09:37:02 +00:00
"github.com/alist-org/alist/v3/pkg/task"
2022-06-20 14:29:52 +00:00
"github.com/google/uuid"
2022-06-20 12:34:58 +00:00
"github.com/pkg/errors"
)
2022-06-22 07:16:13 +00:00
func AddURI(ctx context.Context, uri string, dstDirPath string) error {
2022-07-10 06:45:39 +00:00
// check storage
storage, dstDirActualPath, err := op.GetStorageAndActualPath(dstDirPath)
2022-06-20 12:34:58 +00:00
if err != nil {
2022-07-10 06:45:39 +00:00
return errors.WithMessage(err, "failed get storage")
2022-06-20 12:34:58 +00:00
}
// check is it could upload
2022-07-10 06:45:39 +00:00
if storage.Config().NoUpload {
2022-06-23 08:03:27 +00:00
return errors.WithStack(errs.UploadNotSupported)
2022-06-20 12:34:58 +00:00
}
// check path is valid
obj, err := op.Get(ctx, storage, dstDirActualPath)
2022-06-20 12:34:58 +00:00
if err != nil {
if !errs.IsObjectNotFound(err) {
2022-06-20 12:34:58 +00:00
return errors.WithMessage(err, "failed get object")
}
} else {
if !obj.IsDir() {
// can't add to a file
return errors.WithStack(errs.NotFolder)
2022-06-20 12:34:58 +00:00
}
}
2022-06-20 14:29:52 +00:00
// call aria2 rpc
2022-06-21 09:37:02 +00:00
tempDir := filepath.Join(conf.Conf.TempDir, "aria2", uuid.NewString())
2022-06-20 14:29:52 +00:00
options := map[string]interface{}{
2022-06-21 09:37:02 +00:00
"dir": tempDir,
2022-06-20 14:29:52 +00:00
}
gid, err := client.AddURI([]string{uri}, options)
if err != nil {
return errors.Wrapf(err, "failed to add uri %s", uri)
}
2022-06-23 13:24:23 +00:00
DownTaskManager.Submit(task.WithCancelCtx(&task.Task[string]{
2022-06-21 09:37:02 +00:00
ID: gid,
Name: fmt.Sprintf("download %s to [%s](%s)", uri, storage.GetStorage().MountPath, dstDirActualPath),
2022-06-22 11:28:41 +00:00
Func: func(tsk *task.Task[string]) error {
2022-06-22 07:16:13 +00:00
m := &Monitor{
tsk: tsk,
tempDir: tempDir,
retried: 0,
dstDirPath: dstDirPath,
2022-06-21 09:37:02 +00:00
}
2022-06-22 07:16:13 +00:00
return m.Loop()
2022-06-21 09:37:02 +00:00
},
}))
2022-06-20 12:34:58 +00:00
return nil
}