Skip to content

Commit

Permalink
feat: add onedrive driver
Browse files Browse the repository at this point in the history
  • Loading branch information
xhofe committed Aug 30, 2022
1 parent c95a7c2 commit f551dc7
Show file tree
Hide file tree
Showing 21 changed files with 535 additions and 30 deletions.
1 change: 1 addition & 0 deletions drivers/all.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package drivers

import (
_ "github.com/alist-org/alist/v3/drivers/local"
_ "github.com/alist-org/alist/v3/drivers/onedrive"
_ "github.com/alist-org/alist/v3/drivers/virtual"
)

Expand Down
26 changes: 26 additions & 0 deletions drivers/base/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package base

import (
"net/http"
"time"

"github.com/go-resty/resty/v2"
)

var NoRedirectClient *resty.Client
var RestyClient = resty.New()
var HttpClient = &http.Client{}
var UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
var DefaultTimeout = time.Second * 10

func init() {
NoRedirectClient = resty.New().SetRedirectPolicy(
resty.RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}),
)
NoRedirectClient.SetHeader("user-agent", UserAgent)
RestyClient.SetHeader("user-agent", UserAgent)
RestyClient.SetRetryCount(3)
RestyClient.SetTimeout(DefaultTimeout)
}
8 changes: 8 additions & 0 deletions drivers/base/types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package base

type Json map[string]interface{}

type TokenResp struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
2 changes: 0 additions & 2 deletions drivers/local/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,13 @@ func (d *Local) Init(ctx context.Context, storage model.Storage) error {
}
if !utils.Exists(d.RootFolder) {
err = errors.Errorf("root folder %s not exists", d.RootFolder)
d.SetStatus(err.Error())
} else {
if !filepath.IsAbs(d.RootFolder) {
d.RootFolder, err = filepath.Abs(d.RootFolder)
if err != nil {
return errors.Wrap(err, "error while get abs path")
}
}
d.SetStatus("OK")
}
operations.MustSaveDriverStorage(d)
return err
Expand Down
2 changes: 1 addition & 1 deletion drivers/local/meta.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ type Addition struct {
}

var config = driver.Config{
Name: "Local",
Name: "local",
OnlyLocal: true,
LocalSort: true,
NoCache: true,
Expand Down
157 changes: 157 additions & 0 deletions drivers/onedrive/driver.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
package onedrive

import (
"context"
"net/http"
stdpath "path"

"github.com/alist-org/alist/v3/drivers/base"
"github.com/alist-org/alist/v3/internal/driver"
"github.com/alist-org/alist/v3/internal/errs"
"github.com/alist-org/alist/v3/internal/model"
"github.com/alist-org/alist/v3/pkg/utils"
"github.com/go-resty/resty/v2"
"github.com/pkg/errors"
)

type Onedrive struct {
model.Storage
Addition
AccessToken string
}

func (d *Onedrive) Config() driver.Config {
return config
}

func (d *Onedrive) GetAddition() driver.Additional {
return d.Addition
}

func (d *Onedrive) Init(ctx context.Context, storage model.Storage) error {
d.Storage = storage
err := utils.Json.UnmarshalFromString(d.Storage.Addition, &d.Addition)
if err != nil {
return errors.Wrap(err, "error while unmarshal addition")
}
return d.refreshToken()
}

func (d *Onedrive) Drop(ctx context.Context) error {
return nil
}

func (d *Onedrive) List(ctx context.Context, dir model.Obj, args model.ListArgs) ([]model.Obj, error) {
files, err := d.GetFiles(dir.GetID())
if err != nil {
return nil, err
}
objs := make([]model.Obj, len(files))
for i := 0; i < len(files); i++ {
objs[i] = fileToObj(files[i])
}
return objs, nil
}

func (d *Onedrive) Link(ctx context.Context, file model.Obj, args model.LinkArgs) (*model.Link, error) {
f, err := d.GetFile(file.GetID())
if err != nil {
return nil, err
}
if f.File == nil {
return nil, errs.NotFile
}
return &model.Link{
URL: f.Url,
}, nil
}

func (d *Onedrive) MakeDir(ctx context.Context, parentDir model.Obj, dirName string) error {
url := d.GetMetaUrl(false, parentDir.GetID()) + "/children"
data := base.Json{
"name": dirName,
"folder": base.Json{},
"@microsoft.graph.conflictBehavior": "rename",
}
_, err := d.Request(url, http.MethodPost, func(req *resty.Request) {
req.SetBody(data)
}, nil)
return err
}

func (d *Onedrive) Move(ctx context.Context, srcObj, dstDir model.Obj) error {
dst, err := d.GetFile(dstDir.GetID())
if err != nil {
return err
}
data := base.Json{
"parentReference": base.Json{
"id": dst.Id,
},
"name": srcObj.GetName(),
}
url := d.GetMetaUrl(false, srcObj.GetID())
_, err = d.Request(url, http.MethodPatch, func(req *resty.Request) {
req.SetBody(data)
}, nil)
return err
}

func (d *Onedrive) Rename(ctx context.Context, srcObj model.Obj, newName string) error {
dstDir, err := d.GetFile(stdpath.Dir(srcObj.GetID()))
if err != nil {
return err
}
data := base.Json{
"parentReference": base.Json{
"id": dstDir.Id,
},
"name": newName,
}
url := d.GetMetaUrl(false, srcObj.GetID())
_, err = d.Request(url, http.MethodPatch, func(req *resty.Request) {
req.SetBody(data)
}, nil)
return err
}

func (d *Onedrive) Copy(ctx context.Context, srcObj, dstDir model.Obj) error {
dst, err := d.GetFile(dstDir.GetID())
if err != nil {
return err
}
data := base.Json{
"parentReference": base.Json{
"driveId": dst.ParentReference.DriveId,
"id": dst.Id,
},
"name": srcObj.GetName(),
}
url := d.GetMetaUrl(false, srcObj.GetID()) + "/copy"
_, err = d.Request(url, http.MethodPost, func(req *resty.Request) {
req.SetBody(data)
}, nil)
return err
}

func (d *Onedrive) Remove(ctx context.Context, obj model.Obj) error {
url := d.GetMetaUrl(false, obj.GetID())
_, err := d.Request(url, http.MethodDelete, nil, nil)
return err
}

func (d *Onedrive) Put(ctx context.Context, dstDir model.Obj, stream model.FileStreamer, up driver.UpdateProgress) error {
var err error
if stream.GetSize() <= 4*1024*1024 {
err = d.upSmall(dstDir, stream)
} else {
err = d.upBig(ctx, dstDir, stream, up)
}
return err
}

func (d *Onedrive) Other(ctx context.Context, args model.OtherArgs) (interface{}, error) {
return nil, errs.NotSupport
}

var _ driver.Driver = (*Onedrive)(nil)
31 changes: 31 additions & 0 deletions drivers/onedrive/meta.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package onedrive

import (
"github.com/alist-org/alist/v3/internal/driver"
"github.com/alist-org/alist/v3/internal/operations"
)

type Addition struct {
driver.RootFolderPath
Region string `json:"region" type:"select" required:"true" options:"global,cn,us,de"`
IsSharepoint bool `json:"is_sharepoint"`
ClientId string `json:"client_id" required:"true"`
ClientSecret string `json:"client_secret" required:"true"`
RedirectUri string `json:"redirect_uri" required:"true" default:"https://tool.nn.ci/onedrive/callback"`
RefreshToken string `json:"refresh_token" required:"true"`
SiteId string `json:"site_id"`
}

var config = driver.Config{
Name: "onedrive",
LocalSort: true,
DefaultRoot: "/",
}

func New() driver.Driver {
return &Onedrive{}
}

func init() {
operations.RegisterDriver(config, New)
}
48 changes: 48 additions & 0 deletions drivers/onedrive/types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package onedrive

import (
"time"

"github.com/alist-org/alist/v3/internal/model"
)

type File struct {
Id string `json:"id"`
Name string `json:"name"`
Size int64 `json:"size"`
LastModifiedDateTime time.Time `json:"lastModifiedDateTime"`
Url string `json:"@microsoft.graph.downloadUrl"`
File *struct {
MimeType string `json:"mimeType"`
} `json:"file"`
Thumbnails []struct {
Medium struct {
Url string `json:"url"`
} `json:"medium"`
} `json:"thumbnails"`
ParentReference struct {
DriveId string `json:"driveId"`
} `json:"parentReference"`
}

func fileToObj(f File) *model.ObjectThumbnail {
thumb := ""
if len(f.Thumbnails) > 0 {
thumb = f.Thumbnails[0].Medium.Url
}
return &model.ObjectThumbnail{
Object: model.Object{
//ID: f.Id,
Name: f.Name,
Size: f.Size,
Modified: f.LastModifiedDateTime,
IsFolder: f.File == nil,
},
Thumbnail: model.Thumbnail{Thumbnail: thumb},
}
}

type Files struct {
Value []File `json:"value"`
NextLink string `json:"@odata.nextLink"`
}
Loading

0 comments on commit f551dc7

Please sign in to comment.