From 3cf8fdec7555f069201de714a9b40cc289a55b09 Mon Sep 17 00:00:00 2001 From: Adphi Date: Mon, 22 Jul 2019 16:17:11 +0200 Subject: [PATCH] code restructuration: private implementation --- types/app.go => app.go | 2 +- apps.go => apps_impl.go | 34 +-- apps_test.go => apps_impl_test.go | 0 appsconfig.go => appsconfig_impl.go | 30 +-- appsconfig_test.go => appsconfig_impl_test.go | 0 auth.go => auth_impl.go | 12 +- types/capabilities.go => capabilities.go | 2 +- client.go | 101 --------- client_impl.go | 99 ++++++++ doc.go | 6 +- types/errors.go => errors.go | 2 +- types/errors_test.go => errors_test.go | 5 +- go.mod | 1 - go.sum | 2 - types/interfaces.go => gonextcloud.go | 24 +- gonextcloud_test.go | 36 +-- types/group.go => group.go | 2 +- groupfolders.go | 169 ++++---------- groupfolders_impl.go | 140 ++++++++++++ ...lders_test.go => groupfolders_impl_test.go | 6 +- groups.go => groups_impl.go | 38 ++-- {types/mocks => mocks}/Apps.go | 15 +- {types/mocks => mocks}/AppsConfig.go | 0 {types/mocks => mocks}/Auth.go | 0 {types/mocks => mocks}/Client.go | 63 +++--- {types/mocks => mocks}/GroupFolders.go | 27 ++- {types/mocks => mocks}/Groups.go | 15 +- {types/mocks => mocks}/Notifications.go | 23 +- {types/mocks => mocks}/Shares.go | 49 ++-- {types/mocks => mocks}/Users.go | 35 +-- monitoring.go | 76 +++++-- monitoring_impl.go | 16 ++ types/notification.go => notification.go | 2 +- notifications.go => notifications_impl.go | 32 +-- ...ions_test.go => notifications_impl_test.go | 0 types/responses.go => responses.go | 2 +- shares.go | 213 ++++-------------- shares_impl.go | 174 ++++++++++++++ types/groupfolders.go | 57 ----- types/monitoring.go | 65 ------ types/shares.go | 53 ----- types/webdav.go | 39 ---- update_test.go | 10 +- types/user.go => user.go | 2 +- users.go => users_impl.go | 114 +++++----- utils.go | 10 +- webdav.go | 105 +++------ webdav_impl.go | 82 +++++++ webdav_test.go => webdav_impl_test.go | 6 +- 49 files changed, 1007 insertions(+), 989 deletions(-) rename types/app.go => app.go (99%) rename apps.go => apps_impl.go (65%) rename apps_test.go => apps_impl_test.go (100%) rename appsconfig.go => appsconfig_impl.go (73%) rename appsconfig_test.go => appsconfig_impl_test.go (100%) rename auth.go => auth_impl.go (82%) rename types/capabilities.go => capabilities.go (99%) delete mode 100644 client.go create mode 100644 client_impl.go rename types/errors.go => errors.go (98%) rename types/errors_test.go => errors_test.go (97%) rename types/interfaces.go => gonextcloud.go (89%) rename types/group.go => group.go (92%) create mode 100644 groupfolders_impl.go rename groupfolders_test.go => groupfolders_impl_test.go (94%) rename groups.go => groups_impl.go (66%) rename {types/mocks => mocks}/Apps.go (87%) rename {types/mocks => mocks}/AppsConfig.go (100%) rename {types/mocks => mocks}/Auth.go (100%) rename {types/mocks => mocks}/Client.go (55%) rename {types/mocks => mocks}/GroupFolders.go (79%) rename {types/mocks => mocks}/Groups.go (89%) rename {types/mocks => mocks}/Notifications.go (78%) rename {types/mocks => mocks}/Shares.go (68%) rename {types/mocks => mocks}/Users.go (89%) create mode 100644 monitoring_impl.go rename types/notification.go => notification.go (97%) rename notifications.go => notifications_impl.go (72%) rename notifications_test.go => notifications_impl_test.go (100%) rename types/responses.go => responses.go (99%) create mode 100644 shares_impl.go delete mode 100644 types/groupfolders.go delete mode 100644 types/monitoring.go delete mode 100644 types/shares.go delete mode 100644 types/webdav.go rename types/user.go => user.go (98%) rename users.go => users_impl.go (76%) create mode 100644 webdav_impl.go rename webdav_test.go => webdav_impl_test.go (94%) diff --git a/types/app.go b/app.go similarity index 99% rename from types/app.go rename to app.go index 514288f..880d8bd 100644 --- a/types/app.go +++ b/app.go @@ -1,4 +1,4 @@ -package types +package gonextcloud //App type App struct { diff --git a/apps.go b/apps_impl.go similarity index 65% rename from apps.go rename to apps_impl.go index 0fd7fca..dcacde7 100644 --- a/apps.go +++ b/apps_impl.go @@ -1,29 +1,29 @@ package gonextcloud import ( - req "github.com/levigross/grequests" - "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" "net/http" + + req "github.com/levigross/grequests" ) -//Apps contains all Apps available actions -type Apps struct { - c *Client +//apps contains all apps available actions +type apps struct { + c *client } -//List return the list of the Nextcloud Apps -func (a *Apps) List() ([]string, error) { +//List return the list of the Nextcloud apps +func (a *apps) List() ([]string, error) { res, err := a.c.baseRequest(http.MethodGet, routes.apps, nil) if err != nil { return nil, err } - var r types.AppListResponse + var r AppListResponse res.JSON(&r) return r.Ocs.Data.Apps, nil } //ListEnabled lists the enabled apps -func (a *Apps) ListEnabled() ([]string, error) { +func (a *apps) ListEnabled() ([]string, error) { ro := &req.RequestOptions{ Params: map[string]string{"filter": "enabled"}, } @@ -31,13 +31,13 @@ func (a *Apps) ListEnabled() ([]string, error) { if err != nil { return nil, err } - var r types.AppListResponse + var r AppListResponse res.JSON(&r) return r.Ocs.Data.Apps, nil } //ListDisabled lists the disabled apps -func (a *Apps) ListDisabled() ([]string, error) { +func (a *apps) ListDisabled() ([]string, error) { ro := &req.RequestOptions{ Params: map[string]string{"filter": "disabled"}, } @@ -45,30 +45,30 @@ func (a *Apps) ListDisabled() ([]string, error) { if err != nil { return nil, err } - var r types.AppListResponse + var r AppListResponse res.JSON(&r) return r.Ocs.Data.Apps, nil } //Infos return the app's details -func (a *Apps) Infos(name string) (types.App, error) { +func (a *apps) Infos(name string) (App, error) { res, err := a.c.baseRequest(http.MethodGet, routes.apps, nil, name) if err != nil { - return types.App{}, err + return App{}, err } - var r types.AppResponse + var r AppResponse res.JSON(&r) return r.Ocs.Data, nil } //Enable enables an app -func (a *Apps) Enable(name string) error { +func (a *apps) Enable(name string) error { _, err := a.c.baseRequest(http.MethodPost, routes.apps, nil, name) return err } //Disable disables an app -func (a *Apps) Disable(name string) error { +func (a *apps) Disable(name string) error { _, err := a.c.baseRequest(http.MethodDelete, routes.apps, nil, name) return err } diff --git a/apps_test.go b/apps_impl_test.go similarity index 100% rename from apps_test.go rename to apps_impl_test.go diff --git a/appsconfig.go b/appsconfig_impl.go similarity index 73% rename from appsconfig.go rename to appsconfig_impl.go index e4d8f7e..c4a6b3a 100644 --- a/appsconfig.go +++ b/appsconfig_impl.go @@ -1,52 +1,52 @@ package gonextcloud import ( - req "github.com/levigross/grequests" - "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" "net/http" "sync" + + req "github.com/levigross/grequests" ) -//AppsConfig contains all Apps Configuration available actions -type AppsConfig struct { - c *Client +//appsConfig contains all apps Configuration available actions +type appsConfig struct { + c *client } //List lists all the available apps -func (a *AppsConfig) List() (apps []string, err error) { +func (a *appsConfig) List() (apps []string, err error) { res, err := a.c.baseRequest(http.MethodGet, routes.appsConfig, nil) if err != nil { return nil, err } - var r types.AppConfigResponse + var r AppConfigResponse res.JSON(&r) return r.Ocs.Data.Data, nil } //Keys returns the app's config keys -func (a *AppsConfig) Keys(id string) (keys []string, err error) { +func (a *appsConfig) Keys(id string) (keys []string, err error) { res, err := a.c.baseRequest(http.MethodGet, routes.appsConfig, nil, id) if err != nil { return nil, err } - var r types.AppConfigResponse + var r AppConfigResponse res.JSON(&r) return r.Ocs.Data.Data, nil } //Value get the config value for the given app's key -func (a *AppsConfig) Value(id, key string) (string, error) { +func (a *appsConfig) Value(id, key string) (string, error) { res, err := a.c.baseRequest(http.MethodGet, routes.appsConfig, nil, id, key) if err != nil { return "", err } - var r types.AppcConfigValueResponse + var r AppcConfigValueResponse res.JSON(&r) return r.Ocs.Data.Data, nil } //SetValue set the config value for the given app's key -func (a *AppsConfig) SetValue(id, key, value string) error { +func (a *appsConfig) SetValue(id, key, value string) error { ro := &req.RequestOptions{ Data: map[string]string{ "value": value, @@ -57,13 +57,13 @@ func (a *AppsConfig) SetValue(id, key, value string) error { } //DeleteValue delete the config value and (!! be careful !!) the key -func (a *AppsConfig) DeleteValue(id, key, value string) error { +func (a *appsConfig) DeleteValue(id, key, value string) error { _, err := a.c.baseRequest(http.MethodDelete, routes.appsConfig, nil, id, key) return err } //Get returns all apps AppConfigDetails -func (a *AppsConfig) Get() (map[string]map[string]string, error) { +func (a *appsConfig) Get() (map[string]map[string]string, error) { config := map[string]map[string]string{} m := sync.Mutex{} appsIDs, err := a.List() @@ -88,7 +88,7 @@ func (a *AppsConfig) Get() (map[string]map[string]string, error) { } //Details returns all the config's key, values pair of the app -func (a *AppsConfig) Details(appID string) (map[string]string, error) { +func (a *appsConfig) Details(appID string) (map[string]string, error) { config := map[string]string{} m := sync.Mutex{} var err error diff --git a/appsconfig_test.go b/appsconfig_impl_test.go similarity index 100% rename from appsconfig_test.go rename to appsconfig_impl_test.go diff --git a/auth.go b/auth_impl.go similarity index 82% rename from auth.go rename to auth_impl.go index cb074dc..74cbfae 100644 --- a/auth.go +++ b/auth_impl.go @@ -4,14 +4,12 @@ import ( "fmt" req "github.com/levigross/grequests" - - "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" ) var errUnauthorized = fmt.Errorf("login first") // Login perform login and create a session with the Nextcloud API. -func (c *Client) Login(username string, password string) error { +func (c *client) Login(username string, password string) error { c.username = username c.password = password options := req.RequestOptions{ @@ -25,14 +23,14 @@ func (c *Client) Login(username string, password string) error { if err != nil { return err } - var r types.CapabilitiesResponse + var r CapabilitiesResponse res.JSON(&r) // No need to check for Ocs.Meta.StatusCode as capabilities are always returned c.capabilities = &r.Ocs.Data.Capabilities c.version = &r.Ocs.Data.Version // Check if authentication failed if !c.loggedIn() { - e := types.APIError{Message: "authentication failed"} + e := APIError{Message: "authentication failed"} return &e } // Create webdav client @@ -41,7 +39,7 @@ func (c *Client) Login(username string, password string) error { } // Logout logs out from the Nextcloud API, close the session and delete session's cookie -func (c *Client) Logout() error { +func (c *client) Logout() error { c.session.CloseIdleConnections() c.session.HTTPClient.Jar = nil // Clear capabilities as it is used to check for valid authentication @@ -49,7 +47,7 @@ func (c *Client) Logout() error { return nil } -func (c *Client) loggedIn() bool { +func (c *client) loggedIn() bool { // When authentication failed, capabilities doesn't contains core information if c.capabilities == nil { return false diff --git a/types/capabilities.go b/capabilities.go similarity index 99% rename from types/capabilities.go rename to capabilities.go index 32dd44e..c416ba4 100644 --- a/types/capabilities.go +++ b/capabilities.go @@ -1,4 +1,4 @@ -package types +package gonextcloud //Capabilities type Capabilities struct { diff --git a/client.go b/client.go deleted file mode 100644 index ec9a70e..0000000 --- a/client.go +++ /dev/null @@ -1,101 +0,0 @@ -package gonextcloud - -import ( - "net/url" - - req "github.com/levigross/grequests" - "gitlab.bertha.cloud/adphi/gowebdav" - - "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" -) - -// Client is the API client that performs all operations against a Nextcloud server. -type Client struct { - baseURL *url.URL - username string - password string - session *req.Session - headers map[string]string - capabilities *types.Capabilities - version *types.Version - - apps *Apps - appsConfig *AppsConfig - groupFolders *GroupFolders - notifications *Notifications - shares *Shares - users *Users - groups *Groups - webdav *webDav -} - -// NewClient create a new Client from the Nextcloud Instance URL -func NewClient(hostname string) (*Client, error) { - baseURL, err := url.ParseRequestURI(hostname) - if err != nil { - baseURL, err = url.ParseRequestURI("https://" + hostname) - if err != nil { - return nil, err - } - } - - c := &Client{ - baseURL: baseURL, - headers: map[string]string{ - "OCS-APIREQUEST": "true", - "Accept": "application/json", - }, - } - - c.apps = &Apps{c} - c.appsConfig = &AppsConfig{c} - c.groupFolders = &GroupFolders{c} - c.notifications = &Notifications{c} - c.shares = &Shares{c} - c.users = &Users{c} - c.groups = &Groups{c} - // Create empty webdav client - // It will be replaced after login - c.webdav = &webDav{Client: &gowebdav.Client{}} - return c, nil -} - -// Apps return the Apps client Interface -func (c *Client) Apps() types.Apps { - return c.apps -} - -// AppsConfig return the AppsConfig client Interface -func (c *Client) AppsConfig() types.AppsConfig { - return c.appsConfig -} - -// GroupFolders return the GroupFolders client Interface -func (c *Client) GroupFolders() types.GroupFolders { - return c.groupFolders -} - -// Notifications return the Notifications client Interface -func (c *Client) Notifications() types.Notifications { - return c.notifications -} - -// Shares return the Shares client Interface -func (c *Client) Shares() types.Shares { - return c.shares -} - -// Users return the Users client Interface -func (c *Client) Users() types.Users { - return c.users -} - -// Groups return the Groups client Interface -func (c *Client) Groups() types.Groups { - return c.groups -} - -// WebDav return the WebDav client Interface -func (c *Client) WebDav() types.WebDav { - return c.webdav -} diff --git a/client_impl.go b/client_impl.go new file mode 100644 index 0000000..abf3ffa --- /dev/null +++ b/client_impl.go @@ -0,0 +1,99 @@ +package gonextcloud + +import ( + "net/url" + + req "github.com/levigross/grequests" + "gitlab.bertha.cloud/adphi/gowebdav" +) + +// client is the API client that performs all operations against a Nextcloud server. +type client struct { + baseURL *url.URL + username string + password string + session *req.Session + headers map[string]string + capabilities *Capabilities + version *Version + + apps *apps + appsConfig *appsConfig + groupFolders *groupFolders + notifications *notifications + shares *shares + users *users + groups *groups + webdav *webDav +} + +// newClient create a new client from the Nextcloud Instance URL +func newClient(hostname string) (*client, error) { + baseURL, err := url.ParseRequestURI(hostname) + if err != nil { + baseURL, err = url.ParseRequestURI("https://" + hostname) + if err != nil { + return nil, err + } + } + + c := &client{ + baseURL: baseURL, + headers: map[string]string{ + "OCS-APIREQUEST": "true", + "Accept": "application/json", + }, + } + + c.apps = &apps{c} + c.appsConfig = &appsConfig{c} + c.groupFolders = &groupFolders{c} + c.notifications = ¬ifications{c} + c.shares = &shares{c} + c.users = &users{c} + c.groups = &groups{c} + // Create empty webdav client + // It will be replaced after login + c.webdav = &webDav{Client: &gowebdav.Client{}} + return c, nil +} + +// apps return the apps client Interface +func (c *client) Apps() Apps { + return c.apps +} + +// appsConfig return the appsConfig client Interface +func (c *client) AppsConfig() AppsConfig { + return c.appsConfig +} + +// groupFolders return the groupFolders client Interface +func (c *client) GroupFolders() GroupFolders { + return c.groupFolders +} + +// notifications return the notifications client Interface +func (c *client) Notifications() Notifications { + return c.notifications +} + +// shares return the shares client Interface +func (c *client) Shares() Shares { + return c.shares +} + +// users return the users client Interface +func (c *client) Users() Users { + return c.users +} + +// groups return the groups client Interface +func (c *client) Groups() Groups { + return c.groups +} + +// WebDav return the WebDav client Interface +func (c *client) WebDav() WebDav { + return c.webdav +} diff --git a/doc.go b/doc.go index df2a23c..4698188 100644 --- a/doc.go +++ b/doc.go @@ -21,7 +21,7 @@ For example, to list all the Nextcloud's instance users: url := "https://www.mynextcloud.com" username := "admin" password := "password" - c, err := gonextcloud.NewClient(url) + c, err := gonextcloud.newClient(url) if err != nil { panic(err) } @@ -30,11 +30,11 @@ For example, to list all the Nextcloud's instance users: } defer c.Logout() - users, err := c.Users().List() + users, err := c.users().List() if err != nil { panic(err) } - fmt.Println("Users :", users) + fmt.Println("users :", users) } */ package gonextcloud diff --git a/types/errors.go b/errors.go similarity index 98% rename from types/errors.go rename to errors.go index 5f73d57..8c178bc 100644 --- a/types/errors.go +++ b/errors.go @@ -1,4 +1,4 @@ -package types +package gonextcloud import ( "fmt" diff --git a/types/errors_test.go b/errors_test.go similarity index 97% rename from types/errors_test.go rename to errors_test.go index 08bfa0c..af23338 100644 --- a/types/errors_test.go +++ b/errors_test.go @@ -1,11 +1,12 @@ -package types +package gonextcloud import ( "errors" - "github.com/stretchr/testify/assert" "strconv" "sync" "testing" + + "github.com/stretchr/testify/assert" ) func TestUserUpdateErrors(t *testing.T) { diff --git a/go.mod b/go.mod index 720b9b2..e4cc512 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,6 @@ require ( github.com/pkg/errors v0.0.0-20181023235946-059132a15dd0 github.com/sirupsen/logrus v1.4.2 github.com/stretchr/testify v1.2.2 - github.com/studio-b12/gowebdav v0.0.0-20190103184047-38f79aeaf1ac gitlab.bertha.cloud/adphi/gowebdav v0.0.0-20190720232020-771eec6e76d0 golang.org/x/net v0.0.0-20190628185345-da137c7871d7 // indirect golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7 // indirect diff --git a/go.sum b/go.sum index e62c82d..bae990b 100644 --- a/go.sum +++ b/go.sum @@ -23,8 +23,6 @@ github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/studio-b12/gowebdav v0.0.0-20190103184047-38f79aeaf1ac h1:xQ9gCVzqb939vjhxuES4IXYe4AlHB4Q71/K06aazQmQ= -github.com/studio-b12/gowebdav v0.0.0-20190103184047-38f79aeaf1ac/go.mod h1:gCcfDlA1Y7GqOaeEKw5l9dOGx1VLdc/HuQSlQAaZ30s= gitlab.bertha.cloud/adphi/gowebdav v0.0.0-20190720232020-771eec6e76d0 h1:kjJ5Xn+FgD+QvWP670A2hmdMqxWkOuffMukEA1JSGo4= gitlab.bertha.cloud/adphi/gowebdav v0.0.0-20190720232020-771eec6e76d0/go.mod h1:Nr6YgM/ZBLPOlAAjcER6HSAXF64AAlal6AJ2CEKg2Fc= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= diff --git a/types/interfaces.go b/gonextcloud.go similarity index 89% rename from types/interfaces.go rename to gonextcloud.go index 2f70f1c..993a171 100644 --- a/types/interfaces.go +++ b/gonextcloud.go @@ -1,6 +1,11 @@ -package types +package gonextcloud -//Client is the main client interface +// NewClient create a new client +func NewClient(hostname string) (Client, error) { + return newClient(hostname) +} + +// Client is the main client interface type Client interface { Apps() Apps AppsConfig() AppsConfig @@ -10,6 +15,7 @@ type Client interface { Users() Users Groups() Groups WebDav() WebDav + Monitoring() (*Monitoring, error) Login(username string, password string) error Logout() error } @@ -19,7 +25,7 @@ type Auth interface { Logout() error } -//Apps available methods +// Apps available methods type Apps interface { List() ([]string, error) ListEnabled() ([]string, error) @@ -29,7 +35,7 @@ type Apps interface { Disable(name string) error } -//AppsConfig available methods +// AppsConfig available methods type AppsConfig interface { List() (apps []string, err error) Keys(id string) (keys []string, err error) @@ -40,7 +46,7 @@ type AppsConfig interface { Details(appID string) (map[string]string, error) } -//Groups available methods +// Groups available methods type Groups interface { List() ([]string, error) ListDetails(search string) ([]Group, error) @@ -51,7 +57,7 @@ type Groups interface { SubAdminList(name string) ([]string, error) } -//GroupFolders available methods +// GroupFolders available methods type GroupFolders interface { List() (map[int]GroupFolder, error) Get(id int) (GroupFolder, error) @@ -63,7 +69,7 @@ type GroupFolders interface { SetQuota(folderID int, quota int) error } -//Notifications available methods +// Notifications available methods type Notifications interface { List() ([]Notification, error) Get(id int) (Notification, error) @@ -74,7 +80,7 @@ type Notifications interface { Available() error } -//Shares available methods +// Shares available methods type Shares interface { List() ([]Share, error) GetFromPath(path string, reshares bool, subfiles bool) ([]Share, error) @@ -95,7 +101,7 @@ type Shares interface { UpdatePermissions(shareID int, permissions SharePermission) error } -//Users available methods +// Users available methods type Users interface { List() ([]string, error) ListDetails() (map[string]UserDetails, error) diff --git a/gonextcloud_test.go b/gonextcloud_test.go index 7b1b1d7..690261f 100644 --- a/gonextcloud_test.go +++ b/gonextcloud_test.go @@ -2,9 +2,6 @@ package gonextcloud import ( "fmt" - "github.com/stretchr/testify/assert" - "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" - "gopkg.in/yaml.v2" "io/ioutil" "math/rand" "net/http" @@ -15,6 +12,9 @@ import ( "sync" "testing" "time" + + "github.com/stretchr/testify/assert" + "gopkg.in/yaml.v2" ) type Config struct { @@ -35,7 +35,7 @@ type test = func(t *testing.T) var ( config = Config{} - c *Client + c *client groupID = 37 provisionningTests = []struct { string @@ -52,7 +52,7 @@ var ( "create client", func(t *testing.T) { var err error - c, err = NewClient(config.URL) + c, err = newClient(config.URL) assert.NoError(t, err, "aie") }, }, @@ -131,7 +131,7 @@ var ( // return // } // username := fmt.Sprintf("%s-2", config.NotExistingUser) - // user := &types.Users{ + // user := &types.users{ // ID: username, // Displayname: strings.ToUpper(username), // Email: "some@address.com", @@ -140,9 +140,9 @@ var ( // Phone: "42 42 242 424", // Website: "my.site.com", // } - // err := c.Users().Create(username, password, user) + // err := c.users().Create(username, password, user) // assert.NoError(t, err) - // u, err := c.Users().Get(username) + // u, err := c.users().Get(username) // assert.NoError(t, err) // o := structs.Map(user) // r := structs.Map(u) @@ -153,7 +153,7 @@ var ( // assert.Equal(t, o[k], r[k]) // } // // Clean up - // err = c.Users().Delete(u.ID) + // err = c.users().Delete(u.ID) // assert.NoError(t, err) // }, //}, @@ -283,8 +283,8 @@ var ( quota := int64(1024 * 1024 * 1024) err := c.Users().UpdateQuota(config.NotExistingUser, quota) assert.NoError(t, err) - // TODO : Find better verification : A never connected Users does not have quota available - //u, err := c.Users(config.NotExistingUser) + // TODO : Find better verification : A never connected users does not have quota available + //u, err := c.users(config.NotExistingUser) //assert.NoError(t, err) //assert.Equal(t, quota, u.Quota.Quota) }, @@ -407,15 +407,15 @@ var ( { "TestLoggedIn", func(t *testing.T) { - c := &Client{} - c.capabilities = &types.Capabilities{} + c := &client{} + c.capabilities = &Capabilities{} assert.False(t, c.loggedIn()) }, }, { "TestLoginInvalidURL", func(t *testing.T) { - c, _ = NewClient("") + c, _ = newClient("") err := c.Login("", "") assert.Error(t, err) }, @@ -423,7 +423,7 @@ var ( { "TestBaseRequest", func(t *testing.T) { - c, _ = NewClient("") + c, _ = newClient("") _, err := c.baseRequest(http.MethodGet, routes.capabilities, nil, "admin", "invalid") assert.Error(t, err) }, @@ -463,10 +463,10 @@ func TestUserCreateBatchWithoutPassword(t *testing.T) { if c.version.Major < 14 { t.SkipNow() } - var us []types.User + var us []User for i := 0; i < 5; i++ { u := fmt.Sprintf(config.NotExistingUser+"_%d", i) - us = append(us, types.User{ + us = append(us, User{ Username: u, DisplayName: strings.Title(u), Groups: []string{"admin"}, @@ -547,7 +547,7 @@ func initClient() error { return err } var err error - c, err = NewClient(config.URL) + c, err = newClient(config.URL) if err != nil { return err } diff --git a/types/group.go b/group.go similarity index 92% rename from types/group.go rename to group.go index 7fb81b9..4c5c655 100644 --- a/types/group.go +++ b/group.go @@ -1,4 +1,4 @@ -package types +package gonextcloud //Group type Group struct { diff --git a/groupfolders.go b/groupfolders.go index 8ae966e..f055a4a 100644 --- a/groupfolders.go +++ b/groupfolders.go @@ -1,140 +1,57 @@ package gonextcloud -import ( - "fmt" - req "github.com/levigross/grequests" - "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" - "net/http" - "strconv" -) +import "strconv" -//GroupFolders contains all Groups Folders available actions -type GroupFolders struct { - c *Client +type GroupFolderBadFormatIDAndGroups struct { + ID string `json:"id"` + MountPoint string `json:"mount_point"` + Groups map[string]string `json:"groups"` + Quota string `json:"quota"` + Size int `json:"size"` } -//List returns the groups folders -func (g *GroupFolders) List() (map[int]types.GroupFolder, error) { - res, err := g.c.baseRequest(http.MethodGet, routes.groupfolders, nil) - if err != nil { - return nil, err - } - var r types.GroupFoldersListResponse - res.JSON(&r) - gfs := formatBadIDAndGroups(r.Ocs.Data) - return gfs, nil +type GroupFolderBadFormatGroups struct { + ID int `json:"id"` + MountPoint string `json:"mount_point"` + Groups map[string]string `json:"groups"` + Quota string `json:"quota"` + Size int `json:"size"` } -//Get returns the group folder details -func (g *GroupFolders) Get(id int) (types.GroupFolder, error) { - res, err := g.c.baseRequest(http.MethodGet, routes.groupfolders, nil, strconv.Itoa(id)) - if err != nil { - return types.GroupFolder{}, err - } - var r types.GroupFoldersResponse - res.JSON(&r) - if r.Ocs.Data.ID == 0 { - return types.GroupFolder{}, fmt.Errorf("%d is not a valid groupfolder's id", id) - } - return r.Ocs.Data.FormatGroupFolder(), nil +type GroupFolder struct { + ID int `json:"id"` + MountPoint string `json:"mount_point"` + Groups map[string]SharePermission `json:"groups"` + Quota int `json:"quota"` + Size int `json:"size"` } -//Create creates a group folder -func (g *GroupFolders) Create(name string) (id int, err error) { - // TODO: Validate Folder name - ro := &req.RequestOptions{ - Data: map[string]string{ - "mountpoint": name, - }, +func (gf *GroupFolderBadFormatGroups) FormatGroupFolder() GroupFolder { + g := GroupFolder{} + g.ID = gf.ID + g.MountPoint = gf.MountPoint + g.Groups = map[string]SharePermission{} + for k, v := range gf.Groups { + p, _ := strconv.Atoi(v) + g.Groups[k] = SharePermission(p) } - res, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro) - if err != nil { - return 0, err - } - var r types.GroupFoldersCreateResponse - res.JSON(&r) - id, _ = strconv.Atoi(r.Ocs.Data.ID) - return id, nil + q, _ := strconv.Atoi(gf.Quota) + g.Quota = q + g.Size = gf.Size + return g } -//Rename renames the group folder -func (g *GroupFolders) Rename(groupID int, name string) error { - ro := &req.RequestOptions{ - Data: map[string]string{ - "mountpoint": name, - }, +func (gf *GroupFolderBadFormatIDAndGroups) FormatGroupFolder() GroupFolder { + g := GroupFolder{} + g.ID, _ = strconv.Atoi(gf.ID) + g.MountPoint = gf.MountPoint + g.Groups = map[string]SharePermission{} + for k, v := range gf.Groups { + p, _ := strconv.Atoi(v) + g.Groups[k] = SharePermission(p) } - // GroupFolders's response does not give any clues about success or failure - _, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(groupID), "mountpoint") - if err != nil { - return err - } - return nil -} - -//TODO func (c *Client) GroupFoldersDelete(id int) error { - -//AddGroup adds group to folder -func (g *GroupFolders) AddGroup(folderID int, groupName string) error { - ro := &req.RequestOptions{ - Data: map[string]string{ - "group": groupName, - }, - } - // GroupFolders's response does not give any clues about success or failure - _, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "groups") - if err != nil { - return err - } - return nil -} - -//RemoveGroup remove a group from the group folder -func (g *GroupFolders) RemoveGroup(folderID int, groupName string) error { - // GroupFolders's response does not give any clues about success or failure - _, err := g.c.baseRequest(http.MethodDelete, routes.groupfolders, nil, strconv.Itoa(folderID), "groups", groupName) - if err != nil { - return err - } - return nil -} - -//SetGroupPermissions set groups permissions -func (g *GroupFolders) SetGroupPermissions(folderID int, groupName string, permission types.SharePermission) error { - ro := &req.RequestOptions{ - Data: map[string]string{ - "permissions": strconv.Itoa(int(permission)), - }, - } - // GroupFolders's response does not give any clues about success or failure - _, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "groups", groupName) - if err != nil { - return err - } - return nil -} - -//SetQuota set quota on the group folder. quota in bytes, use -3 for unlimited -func (g *GroupFolders) SetQuota(folderID int, quota int) error { - ro := &req.RequestOptions{ - Data: map[string]string{ - "quota": strconv.Itoa(int(quota)), - }, - } - // GroupFolders's response does not give any clues about success or failure - _, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "quota") - if err != nil { - return err - } - return nil -} - -func formatBadIDAndGroups(g map[string]types.GroupFolderBadFormatIDAndGroups) map[int]types.GroupFolder { - var gfs = map[int]types.GroupFolder{} - for k := range g { - i, _ := strconv.Atoi(k) - d := g[k] - gfs[i] = d.FormatGroupFolder() - } - return gfs + q, _ := strconv.Atoi(gf.Quota) + g.Quota = q + g.Size = gf.Size + return g } diff --git a/groupfolders_impl.go b/groupfolders_impl.go new file mode 100644 index 0000000..0eeed84 --- /dev/null +++ b/groupfolders_impl.go @@ -0,0 +1,140 @@ +package gonextcloud + +import ( + "fmt" + "net/http" + "strconv" + + req "github.com/levigross/grequests" +) + +//groupFolders contains all groups Folders available actions +type groupFolders struct { + c *client +} + +//List returns the groups folders +func (g *groupFolders) List() (map[int]GroupFolder, error) { + res, err := g.c.baseRequest(http.MethodGet, routes.groupfolders, nil) + if err != nil { + return nil, err + } + var r GroupFoldersListResponse + res.JSON(&r) + gfs := formatBadIDAndGroups(r.Ocs.Data) + return gfs, nil +} + +//Get returns the group folder details +func (g *groupFolders) Get(id int) (GroupFolder, error) { + res, err := g.c.baseRequest(http.MethodGet, routes.groupfolders, nil, strconv.Itoa(id)) + if err != nil { + return GroupFolder{}, err + } + var r GroupFoldersResponse + res.JSON(&r) + if r.Ocs.Data.ID == 0 { + return GroupFolder{}, fmt.Errorf("%d is not a valid groupfolder's id", id) + } + return r.Ocs.Data.FormatGroupFolder(), nil +} + +//Create creates a group folder +func (g *groupFolders) Create(name string) (id int, err error) { + // TODO: Validate Folder name + ro := &req.RequestOptions{ + Data: map[string]string{ + "mountpoint": name, + }, + } + res, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro) + if err != nil { + return 0, err + } + var r GroupFoldersCreateResponse + res.JSON(&r) + id, _ = strconv.Atoi(r.Ocs.Data.ID) + return id, nil +} + +//Rename renames the group folder +func (g *groupFolders) Rename(groupID int, name string) error { + ro := &req.RequestOptions{ + Data: map[string]string{ + "mountpoint": name, + }, + } + // groupFolders's response does not give any clues about success or failure + _, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(groupID), "mountpoint") + if err != nil { + return err + } + return nil +} + +//TODO func (c *client) GroupFoldersDelete(id int) error { + +//AddGroup adds group to folder +func (g *groupFolders) AddGroup(folderID int, groupName string) error { + ro := &req.RequestOptions{ + Data: map[string]string{ + "group": groupName, + }, + } + // groupFolders's response does not give any clues about success or failure + _, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "groups") + if err != nil { + return err + } + return nil +} + +//RemoveGroup remove a group from the group folder +func (g *groupFolders) RemoveGroup(folderID int, groupName string) error { + // groupFolders's response does not give any clues about success or failure + _, err := g.c.baseRequest(http.MethodDelete, routes.groupfolders, nil, strconv.Itoa(folderID), "groups", groupName) + if err != nil { + return err + } + return nil +} + +//SetGroupPermissions set groups permissions +func (g *groupFolders) SetGroupPermissions(folderID int, groupName string, permission SharePermission) error { + ro := &req.RequestOptions{ + Data: map[string]string{ + "permissions": strconv.Itoa(int(permission)), + }, + } + // groupFolders's response does not give any clues about success or failure + _, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "groups", groupName) + if err != nil { + return err + } + return nil +} + +//SetQuota set quota on the group folder. quota in bytes, use -3 for unlimited +func (g *groupFolders) SetQuota(folderID int, quota int) error { + ro := &req.RequestOptions{ + Data: map[string]string{ + "quota": strconv.Itoa(int(quota)), + }, + } + // groupFolders's response does not give any clues about success or failure + _, err := g.c.baseRequest(http.MethodPost, routes.groupfolders, ro, strconv.Itoa(folderID), "quota") + if err != nil { + return err + } + return nil +} + +func formatBadIDAndGroups(g map[string]GroupFolderBadFormatIDAndGroups) map[int]GroupFolder { + var gfs = map[int]GroupFolder{} + for k := range g { + i, _ := strconv.Atoi(k) + d := g[k] + gfs[i] = d.FormatGroupFolder() + } + return gfs +} diff --git a/groupfolders_test.go b/groupfolders_impl_test.go similarity index 94% rename from groupfolders_test.go rename to groupfolders_impl_test.go index 8d2cd13..9a7d0c7 100644 --- a/groupfolders_test.go +++ b/groupfolders_impl_test.go @@ -1,9 +1,9 @@ package gonextcloud import ( - "github.com/stretchr/testify/assert" - "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" "testing" + + "github.com/stretchr/testify/assert" ) var ( @@ -53,7 +53,7 @@ var ( { "TestGroupFoldersSetGroupPermissions", func(t *testing.T) { - err := c.GroupFolders().SetGroupPermissions(groupID, "admin", types.ReadPermission) + err := c.GroupFolders().SetGroupPermissions(groupID, "admin", ReadPermission) assert.NoError(t, err) }, }, diff --git a/groups.go b/groups_impl.go similarity index 66% rename from groups.go rename to groups_impl.go index 1dec769..73b565a 100644 --- a/groups.go +++ b/groups_impl.go @@ -1,29 +1,29 @@ package gonextcloud import ( - req "github.com/levigross/grequests" - "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" "net/http" + + req "github.com/levigross/grequests" ) -//Groups contains all Groups available actions -type Groups struct { - c *Client +//groups contains all groups available actions +type groups struct { + c *client } //List lists the Nextcloud groups -func (g *Groups) List() ([]string, error) { +func (g *groups) List() ([]string, error) { res, err := g.c.baseRequest(http.MethodGet, routes.groups, nil) if err != nil { return nil, err } - var r types.GroupListResponse + var r GroupListResponse res.JSON(&r) return r.Ocs.Data.Groups, nil } //ListDetails lists the Nextcloud groups -func (g *Groups) ListDetails(search string) ([]types.Group, error) { +func (g *groups) ListDetails(search string) ([]Group, error) { ro := &req.RequestOptions{ Params: map[string]string{ "search": search, @@ -33,24 +33,24 @@ func (g *Groups) ListDetails(search string) ([]types.Group, error) { if err != nil { return nil, err } - var r types.GroupListDetailsResponse + var r GroupListDetailsResponse res.JSON(&r) return r.Ocs.Data.Groups, nil } -//Users list the group's users -func (g *Groups) Users(name string) ([]string, error) { +//users list the group's users +func (g *groups) Users(name string) ([]string, error) { res, err := g.c.baseRequest(http.MethodGet, routes.groups, nil, name) if err != nil { return nil, err } - var r types.UserListResponse + var r UserListResponse res.JSON(&r) return r.Ocs.Data.Users, nil } //Search return the list of groups matching the search string -func (g *Groups) Search(search string) ([]string, error) { +func (g *groups) Search(search string) ([]string, error) { ro := &req.RequestOptions{ Params: map[string]string{"search": search}, } @@ -58,13 +58,13 @@ func (g *Groups) Search(search string) ([]string, error) { if err != nil { return nil, err } - var r types.GroupListResponse + var r GroupListResponse res.JSON(&r) return r.Ocs.Data.Groups, nil } //Create creates a group -func (g *Groups) Create(name string) error { +func (g *groups) Create(name string) error { ro := &req.RequestOptions{ Data: map[string]string{ "groupid": name, @@ -74,22 +74,22 @@ func (g *Groups) Create(name string) error { } //Delete deletes the group -func (g *Groups) Delete(name string) error { +func (g *groups) Delete(name string) error { return g.baseRequest(http.MethodDelete, nil, name) } //SubAdminList lists the group's subadmins -func (g *Groups) SubAdminList(name string) ([]string, error) { +func (g *groups) SubAdminList(name string) ([]string, error) { res, err := g.c.baseRequest(http.MethodGet, routes.groups, nil, name, "subadmins") if err != nil { return nil, err } - var r types.UserListResponse + var r UserListResponse res.JSON(&r) return r.Ocs.Data.Users, nil } -func (g *Groups) baseRequest(method string, ro *req.RequestOptions, subRoute ...string) error { +func (g *groups) baseRequest(method string, ro *req.RequestOptions, subRoute ...string) error { _, err := g.c.baseRequest(method, routes.groups, ro, subRoute...) return err } diff --git a/types/mocks/Apps.go b/mocks/Apps.go similarity index 87% rename from types/mocks/Apps.go rename to mocks/Apps.go index 7118743..1983837 100644 --- a/types/mocks/Apps.go +++ b/mocks/Apps.go @@ -2,8 +2,11 @@ package mocks -import mock "github.com/stretchr/testify/mock" -import types "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" +import ( + "github.com/stretchr/testify/mock" + + "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud" +) // Apps is an autogenerated mock type for the Apps type type Apps struct { @@ -39,14 +42,14 @@ func (_m *Apps) Enable(name string) error { } // Infos provides a mock function with given fields: name -func (_m *Apps) Infos(name string) (types.App, error) { +func (_m *Apps) Infos(name string) (gonextcloud.App, error) { ret := _m.Called(name) - var r0 types.App - if rf, ok := ret.Get(0).(func(string) types.App); ok { + var r0 gonextcloud.App + if rf, ok := ret.Get(0).(func(string) gonextcloud.App); ok { r0 = rf(name) } else { - r0 = ret.Get(0).(types.App) + r0 = ret.Get(0).(gonextcloud.App) } var r1 error diff --git a/types/mocks/AppsConfig.go b/mocks/AppsConfig.go similarity index 100% rename from types/mocks/AppsConfig.go rename to mocks/AppsConfig.go diff --git a/types/mocks/Auth.go b/mocks/Auth.go similarity index 100% rename from types/mocks/Auth.go rename to mocks/Auth.go diff --git a/types/mocks/Client.go b/mocks/Client.go similarity index 55% rename from types/mocks/Client.go rename to mocks/Client.go index 8535d3b..17743e5 100644 --- a/types/mocks/Client.go +++ b/mocks/Client.go @@ -2,8 +2,11 @@ package mocks -import mock "github.com/stretchr/testify/mock" -import types "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" +import ( + "github.com/stretchr/testify/mock" + + "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud" +) // Client is an autogenerated mock type for the Client type type Client struct { @@ -11,15 +14,15 @@ type Client struct { } // Apps provides a mock function with given fields: -func (_m *Client) Apps() types.Apps { +func (_m *Client) Apps() gonextcloud.Apps { ret := _m.Called() - var r0 types.Apps - if rf, ok := ret.Get(0).(func() types.Apps); ok { + var r0 gonextcloud.Apps + if rf, ok := ret.Get(0).(func() gonextcloud.Apps); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(types.Apps) + r0 = ret.Get(0).(gonextcloud.Apps) } } @@ -27,15 +30,15 @@ func (_m *Client) Apps() types.Apps { } // AppsConfig provides a mock function with given fields: -func (_m *Client) AppsConfig() types.AppsConfig { +func (_m *Client) AppsConfig() gonextcloud.AppsConfig { ret := _m.Called() - var r0 types.AppsConfig - if rf, ok := ret.Get(0).(func() types.AppsConfig); ok { + var r0 gonextcloud.AppsConfig + if rf, ok := ret.Get(0).(func() gonextcloud.AppsConfig); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(types.AppsConfig) + r0 = ret.Get(0).(gonextcloud.AppsConfig) } } @@ -43,15 +46,15 @@ func (_m *Client) AppsConfig() types.AppsConfig { } // GroupFolders provides a mock function with given fields: -func (_m *Client) GroupFolders() types.GroupFolders { +func (_m *Client) GroupFolders() gonextcloud.GroupFolders { ret := _m.Called() - var r0 types.GroupFolders - if rf, ok := ret.Get(0).(func() types.GroupFolders); ok { + var r0 gonextcloud.GroupFolders + if rf, ok := ret.Get(0).(func() gonextcloud.GroupFolders); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(types.GroupFolders) + r0 = ret.Get(0).(gonextcloud.GroupFolders) } } @@ -59,15 +62,15 @@ func (_m *Client) GroupFolders() types.GroupFolders { } // Groups provides a mock function with given fields: -func (_m *Client) Groups() types.Groups { +func (_m *Client) Groups() gonextcloud.Groups { ret := _m.Called() - var r0 types.Groups - if rf, ok := ret.Get(0).(func() types.Groups); ok { + var r0 gonextcloud.Groups + if rf, ok := ret.Get(0).(func() gonextcloud.Groups); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(types.Groups) + r0 = ret.Get(0).(gonextcloud.Groups) } } @@ -103,15 +106,15 @@ func (_m *Client) Logout() error { } // Notifications provides a mock function with given fields: -func (_m *Client) Notifications() types.Notifications { +func (_m *Client) Notifications() gonextcloud.Notifications { ret := _m.Called() - var r0 types.Notifications - if rf, ok := ret.Get(0).(func() types.Notifications); ok { + var r0 gonextcloud.Notifications + if rf, ok := ret.Get(0).(func() gonextcloud.Notifications); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(types.Notifications) + r0 = ret.Get(0).(gonextcloud.Notifications) } } @@ -119,15 +122,15 @@ func (_m *Client) Notifications() types.Notifications { } // Shares provides a mock function with given fields: -func (_m *Client) Shares() types.Shares { +func (_m *Client) Shares() gonextcloud.Shares { ret := _m.Called() - var r0 types.Shares - if rf, ok := ret.Get(0).(func() types.Shares); ok { + var r0 gonextcloud.Shares + if rf, ok := ret.Get(0).(func() gonextcloud.Shares); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(types.Shares) + r0 = ret.Get(0).(gonextcloud.Shares) } } @@ -135,15 +138,15 @@ func (_m *Client) Shares() types.Shares { } // Users provides a mock function with given fields: -func (_m *Client) Users() types.Users { +func (_m *Client) Users() gonextcloud.Users { ret := _m.Called() - var r0 types.Users - if rf, ok := ret.Get(0).(func() types.Users); ok { + var r0 gonextcloud.Users + if rf, ok := ret.Get(0).(func() gonextcloud.Users); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(types.Users) + r0 = ret.Get(0).(gonextcloud.Users) } } diff --git a/types/mocks/GroupFolders.go b/mocks/GroupFolders.go similarity index 79% rename from types/mocks/GroupFolders.go rename to mocks/GroupFolders.go index 45241c9..0d6dfb7 100644 --- a/types/mocks/GroupFolders.go +++ b/mocks/GroupFolders.go @@ -2,8 +2,11 @@ package mocks -import mock "github.com/stretchr/testify/mock" -import types "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" +import ( + "github.com/stretchr/testify/mock" + + "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud" +) // GroupFolders is an autogenerated mock type for the GroupFolders type type GroupFolders struct { @@ -46,14 +49,14 @@ func (_m *GroupFolders) Create(name string) (int, error) { } // Get provides a mock function with given fields: id -func (_m *GroupFolders) Get(id int) (types.GroupFolder, error) { +func (_m *GroupFolders) Get(id int) (gonextcloud.GroupFolder, error) { ret := _m.Called(id) - var r0 types.GroupFolder - if rf, ok := ret.Get(0).(func(int) types.GroupFolder); ok { + var r0 gonextcloud.GroupFolder + if rf, ok := ret.Get(0).(func(int) gonextcloud.GroupFolder); ok { r0 = rf(id) } else { - r0 = ret.Get(0).(types.GroupFolder) + r0 = ret.Get(0).(gonextcloud.GroupFolder) } var r1 error @@ -67,15 +70,15 @@ func (_m *GroupFolders) Get(id int) (types.GroupFolder, error) { } // List provides a mock function with given fields: -func (_m *GroupFolders) List() (map[int]types.GroupFolder, error) { +func (_m *GroupFolders) List() (map[int]gonextcloud.GroupFolder, error) { ret := _m.Called() - var r0 map[int]types.GroupFolder - if rf, ok := ret.Get(0).(func() map[int]types.GroupFolder); ok { + var r0 map[int]gonextcloud.GroupFolder + if rf, ok := ret.Get(0).(func() map[int]gonextcloud.GroupFolder); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(map[int]types.GroupFolder) + r0 = ret.Get(0).(map[int]gonextcloud.GroupFolder) } } @@ -118,11 +121,11 @@ func (_m *GroupFolders) Rename(groupID int, name string) error { } // SetGroupPermissions provides a mock function with given fields: folderID, groupName, permission -func (_m *GroupFolders) SetGroupPermissions(folderID int, groupName string, permission types.SharePermission) error { +func (_m *GroupFolders) SetGroupPermissions(folderID int, groupName string, permission gonextcloud.SharePermission) error { ret := _m.Called(folderID, groupName, permission) var r0 error - if rf, ok := ret.Get(0).(func(int, string, types.SharePermission) error); ok { + if rf, ok := ret.Get(0).(func(int, string, gonextcloud.SharePermission) error); ok { r0 = rf(folderID, groupName, permission) } else { r0 = ret.Error(0) diff --git a/types/mocks/Groups.go b/mocks/Groups.go similarity index 89% rename from types/mocks/Groups.go rename to mocks/Groups.go index 8b758da..22c7c1f 100644 --- a/types/mocks/Groups.go +++ b/mocks/Groups.go @@ -2,8 +2,11 @@ package mocks -import mock "github.com/stretchr/testify/mock" -import types "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" +import ( + "github.com/stretchr/testify/mock" + + "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud" +) // Groups is an autogenerated mock type for the Groups type type Groups struct { @@ -62,15 +65,15 @@ func (_m *Groups) List() ([]string, error) { } // ListDetails provides a mock function with given fields: search -func (_m *Groups) ListDetails(search string) ([]types.Group, error) { +func (_m *Groups) ListDetails(search string) ([]gonextcloud.Group, error) { ret := _m.Called(search) - var r0 []types.Group - if rf, ok := ret.Get(0).(func(string) []types.Group); ok { + var r0 []gonextcloud.Group + if rf, ok := ret.Get(0).(func(string) []gonextcloud.Group); ok { r0 = rf(search) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]types.Group) + r0 = ret.Get(0).([]gonextcloud.Group) } } diff --git a/types/mocks/Notifications.go b/mocks/Notifications.go similarity index 78% rename from types/mocks/Notifications.go rename to mocks/Notifications.go index dca767d..ea0be0d 100644 --- a/types/mocks/Notifications.go +++ b/mocks/Notifications.go @@ -2,8 +2,11 @@ package mocks -import mock "github.com/stretchr/testify/mock" -import types "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" +import ( + "github.com/stretchr/testify/mock" + + "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud" +) // Notifications is an autogenerated mock type for the Notifications type type Notifications struct { @@ -81,14 +84,14 @@ func (_m *Notifications) DeleteAll() error { } // Get provides a mock function with given fields: id -func (_m *Notifications) Get(id int) (types.Notification, error) { +func (_m *Notifications) Get(id int) (gonextcloud.Notification, error) { ret := _m.Called(id) - var r0 types.Notification - if rf, ok := ret.Get(0).(func(int) types.Notification); ok { + var r0 gonextcloud.Notification + if rf, ok := ret.Get(0).(func(int) gonextcloud.Notification); ok { r0 = rf(id) } else { - r0 = ret.Get(0).(types.Notification) + r0 = ret.Get(0).(gonextcloud.Notification) } var r1 error @@ -102,15 +105,15 @@ func (_m *Notifications) Get(id int) (types.Notification, error) { } // List provides a mock function with given fields: -func (_m *Notifications) List() ([]types.Notification, error) { +func (_m *Notifications) List() ([]gonextcloud.Notification, error) { ret := _m.Called() - var r0 []types.Notification - if rf, ok := ret.Get(0).(func() []types.Notification); ok { + var r0 []gonextcloud.Notification + if rf, ok := ret.Get(0).(func() []gonextcloud.Notification); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]types.Notification) + r0 = ret.Get(0).([]gonextcloud.Notification) } } diff --git a/types/mocks/Shares.go b/mocks/Shares.go similarity index 68% rename from types/mocks/Shares.go rename to mocks/Shares.go index c74ef1e..95c597f 100644 --- a/types/mocks/Shares.go +++ b/mocks/Shares.go @@ -2,8 +2,11 @@ package mocks -import mock "github.com/stretchr/testify/mock" -import types "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" +import ( + "github.com/stretchr/testify/mock" + + "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud" +) // Shares is an autogenerated mock type for the Shares type type Shares struct { @@ -11,18 +14,18 @@ type Shares struct { } // Create provides a mock function with given fields: path, shareType, permission, shareWith, publicUpload, password -func (_m *Shares) Create(path string, shareType types.ShareType, permission types.SharePermission, shareWith string, publicUpload bool, password string) (types.Share, error) { +func (_m *Shares) Create(path string, shareType gonextcloud.ShareType, permission gonextcloud.SharePermission, shareWith string, publicUpload bool, password string) (gonextcloud.Share, error) { ret := _m.Called(path, shareType, permission, shareWith, publicUpload, password) - var r0 types.Share - if rf, ok := ret.Get(0).(func(string, types.ShareType, types.SharePermission, string, bool, string) types.Share); ok { + var r0 gonextcloud.Share + if rf, ok := ret.Get(0).(func(string, gonextcloud.ShareType, gonextcloud.SharePermission, string, bool, string) gonextcloud.Share); ok { r0 = rf(path, shareType, permission, shareWith, publicUpload, password) } else { - r0 = ret.Get(0).(types.Share) + r0 = ret.Get(0).(gonextcloud.Share) } var r1 error - if rf, ok := ret.Get(1).(func(string, types.ShareType, types.SharePermission, string, bool, string) error); ok { + if rf, ok := ret.Get(1).(func(string, gonextcloud.ShareType, gonextcloud.SharePermission, string, bool, string) error); ok { r1 = rf(path, shareType, permission, shareWith, publicUpload, password) } else { r1 = ret.Error(1) @@ -46,14 +49,14 @@ func (_m *Shares) Delete(shareID int) error { } // Get provides a mock function with given fields: shareID -func (_m *Shares) Get(shareID string) (types.Share, error) { +func (_m *Shares) Get(shareID string) (gonextcloud.Share, error) { ret := _m.Called(shareID) - var r0 types.Share - if rf, ok := ret.Get(0).(func(string) types.Share); ok { + var r0 gonextcloud.Share + if rf, ok := ret.Get(0).(func(string) gonextcloud.Share); ok { r0 = rf(shareID) } else { - r0 = ret.Get(0).(types.Share) + r0 = ret.Get(0).(gonextcloud.Share) } var r1 error @@ -67,15 +70,15 @@ func (_m *Shares) Get(shareID string) (types.Share, error) { } // GetFromPath provides a mock function with given fields: path, reshares, subfiles -func (_m *Shares) GetFromPath(path string, reshares bool, subfiles bool) ([]types.Share, error) { +func (_m *Shares) GetFromPath(path string, reshares bool, subfiles bool) ([]gonextcloud.Share, error) { ret := _m.Called(path, reshares, subfiles) - var r0 []types.Share - if rf, ok := ret.Get(0).(func(string, bool, bool) []types.Share); ok { + var r0 []gonextcloud.Share + if rf, ok := ret.Get(0).(func(string, bool, bool) []gonextcloud.Share); ok { r0 = rf(path, reshares, subfiles) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]types.Share) + r0 = ret.Get(0).([]gonextcloud.Share) } } @@ -90,15 +93,15 @@ func (_m *Shares) GetFromPath(path string, reshares bool, subfiles bool) ([]type } // List provides a mock function with given fields: -func (_m *Shares) List() ([]types.Share, error) { +func (_m *Shares) List() ([]gonextcloud.Share, error) { ret := _m.Called() - var r0 []types.Share - if rf, ok := ret.Get(0).(func() []types.Share); ok { + var r0 []gonextcloud.Share + if rf, ok := ret.Get(0).(func() []gonextcloud.Share); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).([]types.Share) + r0 = ret.Get(0).([]gonextcloud.Share) } } @@ -113,11 +116,11 @@ func (_m *Shares) List() ([]types.Share, error) { } // Update provides a mock function with given fields: shareUpdate -func (_m *Shares) Update(shareUpdate types.ShareUpdate) error { +func (_m *Shares) Update(shareUpdate gonextcloud.ShareUpdate) error { ret := _m.Called(shareUpdate) var r0 error - if rf, ok := ret.Get(0).(func(types.ShareUpdate) error); ok { + if rf, ok := ret.Get(0).(func(gonextcloud.ShareUpdate) error); ok { r0 = rf(shareUpdate) } else { r0 = ret.Error(0) @@ -155,11 +158,11 @@ func (_m *Shares) UpdatePassword(shareID int, password string) error { } // UpdatePermissions provides a mock function with given fields: shareID, permissions -func (_m *Shares) UpdatePermissions(shareID int, permissions types.SharePermission) error { +func (_m *Shares) UpdatePermissions(shareID int, permissions gonextcloud.SharePermission) error { ret := _m.Called(shareID, permissions) var r0 error - if rf, ok := ret.Get(0).(func(int, types.SharePermission) error); ok { + if rf, ok := ret.Get(0).(func(int, gonextcloud.SharePermission) error); ok { r0 = rf(shareID, permissions) } else { r0 = ret.Error(0) diff --git a/types/mocks/Users.go b/mocks/Users.go similarity index 89% rename from types/mocks/Users.go rename to mocks/Users.go index ae975a5..b2e5309 100644 --- a/types/mocks/Users.go +++ b/mocks/Users.go @@ -2,8 +2,11 @@ package mocks -import mock "github.com/stretchr/testify/mock" -import types "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" +import ( + "github.com/stretchr/testify/mock" + + "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud" +) // Users is an autogenerated mock type for the Users type type Users struct { @@ -11,11 +14,11 @@ type Users struct { } // Create provides a mock function with given fields: username, password, user -func (_m *Users) Create(username string, password string, user *types.UserDetails) error { +func (_m *Users) Create(username string, password string, user *gonextcloud.UserDetails) error { ret := _m.Called(username, password, user) var r0 error - if rf, ok := ret.Get(0).(func(string, string, *types.UserDetails) error); ok { + if rf, ok := ret.Get(0).(func(string, string, *gonextcloud.UserDetails) error); ok { r0 = rf(username, password, user) } else { r0 = ret.Error(0) @@ -25,11 +28,11 @@ func (_m *Users) Create(username string, password string, user *types.UserDetail } // CreateBatchWithoutPassword provides a mock function with given fields: users -func (_m *Users) CreateBatchWithoutPassword(users []types.User) error { +func (_m *Users) CreateBatchWithoutPassword(users []gonextcloud.User) error { ret := _m.Called(users) var r0 error - if rf, ok := ret.Get(0).(func([]types.User) error); ok { + if rf, ok := ret.Get(0).(func([]gonextcloud.User) error); ok { r0 = rf(users) } else { r0 = ret.Error(0) @@ -102,15 +105,15 @@ func (_m *Users) Enable(name string) error { } // Get provides a mock function with given fields: name -func (_m *Users) Get(name string) (*types.UserDetails, error) { +func (_m *Users) Get(name string) (*gonextcloud.UserDetails, error) { ret := _m.Called(name) - var r0 *types.UserDetails - if rf, ok := ret.Get(0).(func(string) *types.UserDetails); ok { + var r0 *gonextcloud.UserDetails + if rf, ok := ret.Get(0).(func(string) *gonextcloud.UserDetails); ok { r0 = rf(name) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.UserDetails) + r0 = ret.Get(0).(*gonextcloud.UserDetails) } } @@ -250,15 +253,15 @@ func (_m *Users) List() ([]string, error) { } // ListDetails provides a mock function with given fields: -func (_m *Users) ListDetails() (map[string]types.UserDetails, error) { +func (_m *Users) ListDetails() (map[string]gonextcloud.UserDetails, error) { ret := _m.Called() - var r0 map[string]types.UserDetails - if rf, ok := ret.Get(0).(func() map[string]types.UserDetails); ok { + var r0 map[string]gonextcloud.UserDetails + if rf, ok := ret.Get(0).(func() map[string]gonextcloud.UserDetails); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(map[string]types.UserDetails) + r0 = ret.Get(0).(map[string]gonextcloud.UserDetails) } } @@ -310,11 +313,11 @@ func (_m *Users) SendWelcomeEmail(name string) error { } // Update provides a mock function with given fields: user -func (_m *Users) Update(user *types.UserDetails) error { +func (_m *Users) Update(user *gonextcloud.UserDetails) error { ret := _m.Called(user) var r0 error - if rf, ok := ret.Get(0).(func(*types.UserDetails) error); ok { + if rf, ok := ret.Get(0).(func(*gonextcloud.UserDetails) error); ok { r0 = rf(user) } else { r0 = ret.Error(0) diff --git a/monitoring.go b/monitoring.go index a88dfc2..29dccc4 100644 --- a/monitoring.go +++ b/monitoring.go @@ -1,17 +1,65 @@ package gonextcloud -import ( - "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" - "net/http" -) - -//Monitoring return nextcloud monitoring statistics -func (c *Client) Monitoring() (*types.Monitoring, error) { - res, err := c.baseRequest(http.MethodGet, routes.monitor, nil) - if err != nil { - return nil, err - } - var m types.MonitoringResponse - res.JSON(&m) - return &m.Ocs.Data, nil +type System struct { + Version string `json:"version"` + Theme string `json:"theme"` + EnableAvatars string `json:"enable_avatars"` + EnablePreviews string `json:"enable_previews"` + MemcacheLocal string `json:"memcache.local"` + MemcacheDistributed string `json:"memcache.distributed"` + FilelockingEnabled string `json:"filelocking.enabled"` + MemcacheLocking string `json:"memcache.locking"` + Debug string `json:"debug"` + Freespace int64 `json:"freespace"` + Cpuload []float32 `json:"cpuload"` + MemTotal int `json:"mem_total"` + MemFree int `json:"mem_free"` + SwapTotal int `json:"swap_total"` + SwapFree int `json:"swap_free"` +} + +type Monitoring struct { + Nextcloud struct { + System System `json:"system"` + Storage Storage `json:"storage"` + Shares struct { + NumShares int `json:"num_shares"` + NumSharesUser int `json:"num_shares_user"` + NumSharesGroups int `json:"num_shares_groups"` + NumSharesLink int `json:"num_shares_link"` + NumSharesLinkNoPassword int `json:"num_shares_link_no_password"` + NumFedSharesSent int `json:"num_fed_shares_sent"` + NumFedSharesReceived int `json:"num_fed_shares_received"` + } `json:"shares"` + } `json:"nextcloud"` + Server struct { + Webserver string `json:"webserver"` + Php struct { + Version string `json:"version"` + MemoryLimit int `json:"memory_limit"` + MaxExecutionTime int `json:"max_execution_time"` + UploadMaxFilesize int `json:"upload_max_filesize"` + } `json:"php"` + Database struct { + Type string `json:"type"` + Version string `json:"version"` + Size int `json:"size"` + } `json:"database"` + } `json:"server"` + ActiveUsers ActiveUsers `json:"activeUsers"` +} + +type ActiveUsers struct { + Last5Minutes int `json:"last5minutes"` + Last1Hour int `json:"last1hour"` + Last24Hours int `json:"last24hours"` +} + +type Storage struct { + NumUsers int `json:"num_users"` + NumFiles int `json:"num_files"` + NumStorages int `json:"num_storages"` + NumStoragesLocal int `json:"num_storages_local"` + NumStoragesHome int `json:"num_storages_home"` + NumStoragesOther int `json:"num_storages_other"` } diff --git a/monitoring_impl.go b/monitoring_impl.go new file mode 100644 index 0000000..e2af134 --- /dev/null +++ b/monitoring_impl.go @@ -0,0 +1,16 @@ +package gonextcloud + +import ( + "net/http" +) + +//Monitoring return nextcloud monitoring statistics +func (c *client) Monitoring() (*Monitoring, error) { + res, err := c.baseRequest(http.MethodGet, routes.monitor, nil) + if err != nil { + return nil, err + } + var m MonitoringResponse + res.JSON(&m) + return &m.Ocs.Data, nil +} diff --git a/types/notification.go b/notification.go similarity index 97% rename from types/notification.go rename to notification.go index 931b6a6..5690f63 100644 --- a/types/notification.go +++ b/notification.go @@ -1,4 +1,4 @@ -package types +package gonextcloud import "time" diff --git a/notifications.go b/notifications_impl.go similarity index 72% rename from notifications.go rename to notifications_impl.go index badf7f4..50b1ff7 100644 --- a/notifications.go +++ b/notifications_impl.go @@ -2,19 +2,19 @@ package gonextcloud import ( "errors" - req "github.com/levigross/grequests" - "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" "net/http" "strconv" + + req "github.com/levigross/grequests" ) -//Notifications contains all Notifications available actions -type Notifications struct { - c *Client +//notifications contains all notifications available actions +type notifications struct { + c *client } //List returns all the notifications -func (n *Notifications) List() ([]types.Notification, error) { +func (n *notifications) List() ([]Notification, error) { if err := n.Available(); err != nil { return nil, err } @@ -22,27 +22,27 @@ func (n *Notifications) List() ([]types.Notification, error) { if err != nil { return nil, err } - var r types.NotificationsListResponse + var r NotificationsListResponse res.JSON(&r) return r.Ocs.Data, nil } //Get returns the notification corresponding to the id -func (n *Notifications) Get(id int) (types.Notification, error) { +func (n *notifications) Get(id int) (Notification, error) { if err := n.Available(); err != nil { - return types.Notification{}, err + return Notification{}, err } res, err := n.c.baseRequest(http.MethodGet, routes.notifications, nil, strconv.Itoa(id)) if err != nil { - return types.Notification{}, err + return Notification{}, err } - var r types.NotificationResponse + var r NotificationResponse res.JSON(&r) return r.Ocs.Data, nil } //Delete deletes the notification corresponding to the id -func (n *Notifications) Delete(id int) error { +func (n *notifications) Delete(id int) error { if err := n.Available(); err != nil { return err } @@ -51,7 +51,7 @@ func (n *Notifications) Delete(id int) error { } //DeleteAll deletes all notifications -func (n *Notifications) DeleteAll() error { +func (n *notifications) DeleteAll() error { if err := n.Available(); err != nil { return err } @@ -60,7 +60,7 @@ func (n *Notifications) DeleteAll() error { } //Create creates a notification (if the user is an admin) -func (n *Notifications) Create(userID, title, message string) error { +func (n *notifications) Create(userID, title, message string) error { if err := n.AdminAvailable(); err != nil { return err } @@ -75,7 +75,7 @@ func (n *Notifications) Create(userID, title, message string) error { } //AdminAvailable returns an error if the admin-notifications app is not installed -func (n *Notifications) AdminAvailable() error { +func (n *notifications) AdminAvailable() error { if len(n.c.capabilities.Notifications.AdminNotifications) == 0 { return errors.New("'admin notifications' not available on this instance") } @@ -83,7 +83,7 @@ func (n *Notifications) AdminAvailable() error { } //Available returns an error if the notifications app is not installed -func (n *Notifications) Available() error { +func (n *notifications) Available() error { if len(n.c.capabilities.Notifications.OcsEndpoints) == 0 { return errors.New("notifications not available on this instance") } diff --git a/notifications_test.go b/notifications_impl_test.go similarity index 100% rename from notifications_test.go rename to notifications_impl_test.go diff --git a/types/responses.go b/responses.go similarity index 99% rename from types/responses.go rename to responses.go index e7487e5..07d9f9b 100644 --- a/types/responses.go +++ b/responses.go @@ -1,4 +1,4 @@ -package types +package gonextcloud //Meta type Meta struct { diff --git a/shares.go b/shares.go index c53d889..bdc149f 100644 --- a/shares.go +++ b/shares.go @@ -1,174 +1,53 @@ package gonextcloud -import ( - "fmt" - req "github.com/levigross/grequests" - "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" - "net/http" - "strconv" - "sync" +type ShareType int +type SharePermission int + +const ( + UserShare ShareType = 0 + GroupShare ShareType = 1 + PublicLinkShare ShareType = 3 + FederatedCloudShare ShareType = 6 + + ReadPermission SharePermission = 1 + UpdatePermission SharePermission = 2 + CreatePermission SharePermission = 4 + DeletePermission SharePermission = 8 + ReSharePermission SharePermission = 16 + AllPermissions SharePermission = 31 ) -//Shares contains all Shares available actions -type Shares struct { - c *Client +type ShareUpdate struct { + ShareID int + Permissions SharePermission + Password string + PublicUpload bool + ExpireDate string } -//List list all shares of the logged in user -func (s *Shares) List() ([]types.Share, error) { - res, err := s.c.baseRequest(http.MethodGet, routes.shares, nil) - if err != nil { - return nil, err - } - var r types.SharesListResponse - res.JSON(&r) - return r.Ocs.Data, nil -} - -//GetFromPath return shares from a specific file or folder -func (s *Shares) GetFromPath(path string, reshares bool, subfiles bool) ([]types.Share, error) { - ro := &req.RequestOptions{ - Params: map[string]string{ - "path": path, - "reshares": strconv.FormatBool(reshares), - "subfiles": strconv.FormatBool(subfiles), - }, - } - res, err := s.c.baseRequest(http.MethodGet, routes.shares, ro) - if err != nil { - return nil, err - } - var r types.SharesListResponse - res.JSON(&r) - return r.Ocs.Data, nil -} - -//Get information about a known Share -func (s *Shares) Get(shareID string) (types.Share, error) { - res, err := s.c.baseRequest(http.MethodGet, routes.shares, nil, shareID) - if err != nil { - return types.Share{}, err - } - var r types.SharesListResponse - res.JSON(&r) - return r.Ocs.Data[0], nil -} - -//Create create a share -func (s *Shares) Create( - path string, - shareType types.ShareType, - permission types.SharePermission, - shareWith string, - publicUpload bool, - password string, -) (types.Share, error) { - - if (shareType == types.UserShare || shareType == types.GroupShare) && shareWith == "" { - return types.Share{}, fmt.Errorf("shareWith cannot be empty for ShareType UserShare or GroupShare") - } - ro := &req.RequestOptions{ - Data: map[string]string{ - "path": path, - "shareType": strconv.Itoa(int(shareType)), - "shareWith": shareWith, - "publicUpload": strconv.FormatBool(publicUpload), - "password": password, - "permissions": strconv.Itoa(int(permission)), - }, - } - res, err := s.c.baseRequest(http.MethodPost, routes.shares, ro) - if err != nil { - return types.Share{}, err - } - var r types.SharesResponse - res.JSON(&r) - return r.Ocs.Data, nil -} - -//Delete Remove the given share. -func (s *Shares) Delete(shareID int) error { - _, err := s.c.baseRequest(http.MethodDelete, routes.shares, nil, strconv.Itoa(shareID)) - return err -} - -// Update update share details -// expireDate expireDate expects a well formatted date string, e.g. ‘YYYY-MM-DD’ -func (s *Shares) Update(shareUpdate types.ShareUpdate) error { - errs := make(chan *types.UpdateError) - var wg sync.WaitGroup - wg.Add(4) - go func() { - defer wg.Done() - if err := s.UpdatePassword(shareUpdate.ShareID, shareUpdate.Password); err != nil { - errs <- &types.UpdateError{ - Field: "password", - Error: err, - } - } - }() - go func() { - defer wg.Done() - if err := s.UpdateExpireDate(shareUpdate.ShareID, shareUpdate.ExpireDate); err != nil { - errs <- &types.UpdateError{ - Field: "expireDate", - Error: err, - } - } - }() - go func() { - defer wg.Done() - if err := s.UpdatePermissions(shareUpdate.ShareID, shareUpdate.Permissions); err != nil { - errs <- &types.UpdateError{ - Field: "permissions", - Error: err, - } - } - }() - go func() { - defer wg.Done() - if err := s.UpdatePublicUpload(shareUpdate.ShareID, shareUpdate.PublicUpload); err != nil { - errs <- &types.UpdateError{ - Field: "publicUpload", - Error: err, - } - } - }() - go func() { - wg.Wait() - close(errs) - }() - if err := types.NewUpdateError(errs); err != nil { - return err - } - return nil -} - -//UpdateExpireDate updates the share's expire date -// expireDate expects a well formatted date string, e.g. ‘YYYY-MM-DD’ -func (s *Shares) UpdateExpireDate(shareID int, expireDate string) error { - return s.baseShareUpdate(strconv.Itoa(shareID), "expireDate", expireDate) -} - -//UpdatePublicUpload enable or disable public upload -func (s *Shares) UpdatePublicUpload(shareID int, public bool) error { - return s.baseShareUpdate(strconv.Itoa(shareID), "publicUpload", strconv.FormatBool(public)) -} - -//UpdatePassword updates share password -func (s *Shares) UpdatePassword(shareID int, password string) error { - return s.baseShareUpdate(strconv.Itoa(shareID), "password", password) -} - -//UpdatePermissions update permissions -func (s *Shares) UpdatePermissions(shareID int, permissions types.SharePermission) error { - return s.baseShareUpdate(strconv.Itoa(shareID), "permissions", strconv.Itoa(int(permissions))) -} - -func (s *Shares) baseShareUpdate(shareID string, key string, value string) error { - ro := &req.RequestOptions{ - Data: map[string]string{key: value}, - } - _, err := s.c.baseRequest(http.MethodPut, routes.shares, ro, shareID) - return err +type Share struct { + ID string `json:"id"` + ShareType int `json:"share_type"` + UIDOwner string `json:"uid_owner"` + DisplaynameOwner string `json:"displayname_owner"` + Permissions int `json:"permissions"` + Stime int `json:"stime"` + Parent interface{} `json:"parent"` + Expiration string `json:"expiration"` + Token string `json:"token"` + UIDFileOwner string `json:"uid_file_owner"` + DisplaynameFileOwner string `json:"displayname_file_owner"` + Path string `json:"path"` + ItemType string `json:"item_type"` + Mimetype string `json:"mimetype"` + StorageID string `json:"storage_id"` + Storage int `json:"storage"` + ItemSource int `json:"item_source"` + FileSource int `json:"file_source"` + FileParent int `json:"file_parent"` + FileTarget string `json:"file_target"` + ShareWith string `json:"share_with"` + ShareWithDisplayname string `json:"share_with_displayname"` + MailSend int `json:"mail_send"` + Tags []string `json:"tags"` } diff --git a/shares_impl.go b/shares_impl.go new file mode 100644 index 0000000..0e36774 --- /dev/null +++ b/shares_impl.go @@ -0,0 +1,174 @@ +package gonextcloud + +import ( + "fmt" + "net/http" + "strconv" + "sync" + + req "github.com/levigross/grequests" +) + +//shares contains all shares available actions +type shares struct { + c *client +} + +//List list all shares of the logged in user +func (s *shares) List() ([]Share, error) { + res, err := s.c.baseRequest(http.MethodGet, routes.shares, nil) + if err != nil { + return nil, err + } + var r SharesListResponse + res.JSON(&r) + return r.Ocs.Data, nil +} + +//GetFromPath return shares from a specific file or folder +func (s *shares) GetFromPath(path string, reshares bool, subfiles bool) ([]Share, error) { + ro := &req.RequestOptions{ + Params: map[string]string{ + "path": path, + "reshares": strconv.FormatBool(reshares), + "subfiles": strconv.FormatBool(subfiles), + }, + } + res, err := s.c.baseRequest(http.MethodGet, routes.shares, ro) + if err != nil { + return nil, err + } + var r SharesListResponse + res.JSON(&r) + return r.Ocs.Data, nil +} + +//Get information about a known Share +func (s *shares) Get(shareID string) (Share, error) { + res, err := s.c.baseRequest(http.MethodGet, routes.shares, nil, shareID) + if err != nil { + return Share{}, err + } + var r SharesListResponse + res.JSON(&r) + return r.Ocs.Data[0], nil +} + +//Create create a share +func (s *shares) Create( + path string, + shareType ShareType, + permission SharePermission, + shareWith string, + publicUpload bool, + password string, +) (Share, error) { + + if (shareType == UserShare || shareType == GroupShare) && shareWith == "" { + return Share{}, fmt.Errorf("shareWith cannot be empty for ShareType UserShare or GroupShare") + } + ro := &req.RequestOptions{ + Data: map[string]string{ + "path": path, + "shareType": strconv.Itoa(int(shareType)), + "shareWith": shareWith, + "publicUpload": strconv.FormatBool(publicUpload), + "password": password, + "permissions": strconv.Itoa(int(permission)), + }, + } + res, err := s.c.baseRequest(http.MethodPost, routes.shares, ro) + if err != nil { + return Share{}, err + } + var r SharesResponse + res.JSON(&r) + return r.Ocs.Data, nil +} + +//Delete Remove the given share. +func (s *shares) Delete(shareID int) error { + _, err := s.c.baseRequest(http.MethodDelete, routes.shares, nil, strconv.Itoa(shareID)) + return err +} + +// Update update share details +// expireDate expireDate expects a well formatted date string, e.g. ‘YYYY-MM-DD’ +func (s *shares) Update(shareUpdate ShareUpdate) error { + errs := make(chan *UpdateError) + var wg sync.WaitGroup + wg.Add(4) + go func() { + defer wg.Done() + if err := s.UpdatePassword(shareUpdate.ShareID, shareUpdate.Password); err != nil { + errs <- &UpdateError{ + Field: "password", + Error: err, + } + } + }() + go func() { + defer wg.Done() + if err := s.UpdateExpireDate(shareUpdate.ShareID, shareUpdate.ExpireDate); err != nil { + errs <- &UpdateError{ + Field: "expireDate", + Error: err, + } + } + }() + go func() { + defer wg.Done() + if err := s.UpdatePermissions(shareUpdate.ShareID, shareUpdate.Permissions); err != nil { + errs <- &UpdateError{ + Field: "permissions", + Error: err, + } + } + }() + go func() { + defer wg.Done() + if err := s.UpdatePublicUpload(shareUpdate.ShareID, shareUpdate.PublicUpload); err != nil { + errs <- &UpdateError{ + Field: "publicUpload", + Error: err, + } + } + }() + go func() { + wg.Wait() + close(errs) + }() + if err := NewUpdateError(errs); err != nil { + return err + } + return nil +} + +//UpdateExpireDate updates the share's expire date +// expireDate expects a well formatted date string, e.g. ‘YYYY-MM-DD’ +func (s *shares) UpdateExpireDate(shareID int, expireDate string) error { + return s.baseShareUpdate(strconv.Itoa(shareID), "expireDate", expireDate) +} + +//UpdatePublicUpload enable or disable public upload +func (s *shares) UpdatePublicUpload(shareID int, public bool) error { + return s.baseShareUpdate(strconv.Itoa(shareID), "publicUpload", strconv.FormatBool(public)) +} + +//UpdatePassword updates share password +func (s *shares) UpdatePassword(shareID int, password string) error { + return s.baseShareUpdate(strconv.Itoa(shareID), "password", password) +} + +//UpdatePermissions update permissions +func (s *shares) UpdatePermissions(shareID int, permissions SharePermission) error { + return s.baseShareUpdate(strconv.Itoa(shareID), "permissions", strconv.Itoa(int(permissions))) +} + +func (s *shares) baseShareUpdate(shareID string, key string, value string) error { + ro := &req.RequestOptions{ + Data: map[string]string{key: value}, + } + _, err := s.c.baseRequest(http.MethodPut, routes.shares, ro, shareID) + return err +} diff --git a/types/groupfolders.go b/types/groupfolders.go deleted file mode 100644 index f43bab5..0000000 --- a/types/groupfolders.go +++ /dev/null @@ -1,57 +0,0 @@ -package types - -import "strconv" - -type GroupFolderBadFormatIDAndGroups struct { - ID string `json:"id"` - MountPoint string `json:"mount_point"` - Groups map[string]string `json:"groups"` - Quota string `json:"quota"` - Size int `json:"size"` -} - -type GroupFolderBadFormatGroups struct { - ID int `json:"id"` - MountPoint string `json:"mount_point"` - Groups map[string]string `json:"groups"` - Quota string `json:"quota"` - Size int `json:"size"` -} - -type GroupFolder struct { - ID int `json:"id"` - MountPoint string `json:"mount_point"` - Groups map[string]SharePermission `json:"groups"` - Quota int `json:"quota"` - Size int `json:"size"` -} - -func (gf *GroupFolderBadFormatGroups) FormatGroupFolder() GroupFolder { - g := GroupFolder{} - g.ID = gf.ID - g.MountPoint = gf.MountPoint - g.Groups = map[string]SharePermission{} - for k, v := range gf.Groups { - p, _ := strconv.Atoi(v) - g.Groups[k] = SharePermission(p) - } - q, _ := strconv.Atoi(gf.Quota) - g.Quota = q - g.Size = gf.Size - return g -} - -func (gf *GroupFolderBadFormatIDAndGroups) FormatGroupFolder() GroupFolder { - g := GroupFolder{} - g.ID, _ = strconv.Atoi(gf.ID) - g.MountPoint = gf.MountPoint - g.Groups = map[string]SharePermission{} - for k, v := range gf.Groups { - p, _ := strconv.Atoi(v) - g.Groups[k] = SharePermission(p) - } - q, _ := strconv.Atoi(gf.Quota) - g.Quota = q - g.Size = gf.Size - return g -} diff --git a/types/monitoring.go b/types/monitoring.go deleted file mode 100644 index 51cf346..0000000 --- a/types/monitoring.go +++ /dev/null @@ -1,65 +0,0 @@ -package types - -type System struct { - Version string `json:"version"` - Theme string `json:"theme"` - EnableAvatars string `json:"enable_avatars"` - EnablePreviews string `json:"enable_previews"` - MemcacheLocal string `json:"memcache.local"` - MemcacheDistributed string `json:"memcache.distributed"` - FilelockingEnabled string `json:"filelocking.enabled"` - MemcacheLocking string `json:"memcache.locking"` - Debug string `json:"debug"` - Freespace int64 `json:"freespace"` - Cpuload []float32 `json:"cpuload"` - MemTotal int `json:"mem_total"` - MemFree int `json:"mem_free"` - SwapTotal int `json:"swap_total"` - SwapFree int `json:"swap_free"` -} - -type Monitoring struct { - Nextcloud struct { - System System `json:"system"` - Storage Storage `json:"storage"` - Shares struct { - NumShares int `json:"num_shares"` - NumSharesUser int `json:"num_shares_user"` - NumSharesGroups int `json:"num_shares_groups"` - NumSharesLink int `json:"num_shares_link"` - NumSharesLinkNoPassword int `json:"num_shares_link_no_password"` - NumFedSharesSent int `json:"num_fed_shares_sent"` - NumFedSharesReceived int `json:"num_fed_shares_received"` - } `json:"shares"` - } `json:"nextcloud"` - Server struct { - Webserver string `json:"webserver"` - Php struct { - Version string `json:"version"` - MemoryLimit int `json:"memory_limit"` - MaxExecutionTime int `json:"max_execution_time"` - UploadMaxFilesize int `json:"upload_max_filesize"` - } `json:"php"` - Database struct { - Type string `json:"type"` - Version string `json:"version"` - Size int `json:"size"` - } `json:"database"` - } `json:"server"` - ActiveUsers ActiveUsers `json:"activeUsers"` -} - -type ActiveUsers struct { - Last5Minutes int `json:"last5minutes"` - Last1Hour int `json:"last1hour"` - Last24Hours int `json:"last24hours"` -} - -type Storage struct { - NumUsers int `json:"num_users"` - NumFiles int `json:"num_files"` - NumStorages int `json:"num_storages"` - NumStoragesLocal int `json:"num_storages_local"` - NumStoragesHome int `json:"num_storages_home"` - NumStoragesOther int `json:"num_storages_other"` -} diff --git a/types/shares.go b/types/shares.go deleted file mode 100644 index 7073e94..0000000 --- a/types/shares.go +++ /dev/null @@ -1,53 +0,0 @@ -package types - -type ShareType int -type SharePermission int - -const ( - UserShare ShareType = 0 - GroupShare ShareType = 1 - PublicLinkShare ShareType = 3 - FederatedCloudShare ShareType = 6 - - ReadPermission SharePermission = 1 - UpdatePermission SharePermission = 2 - CreatePermission SharePermission = 4 - DeletePermission SharePermission = 8 - ReSharePermission SharePermission = 16 - AllPermissions SharePermission = 31 -) - -type ShareUpdate struct { - ShareID int - Permissions SharePermission - Password string - PublicUpload bool - ExpireDate string -} - -type Share struct { - ID string `json:"id"` - ShareType int `json:"share_type"` - UIDOwner string `json:"uid_owner"` - DisplaynameOwner string `json:"displayname_owner"` - Permissions int `json:"permissions"` - Stime int `json:"stime"` - Parent interface{} `json:"parent"` - Expiration string `json:"expiration"` - Token string `json:"token"` - UIDFileOwner string `json:"uid_file_owner"` - DisplaynameFileOwner string `json:"displayname_file_owner"` - Path string `json:"path"` - ItemType string `json:"item_type"` - Mimetype string `json:"mimetype"` - StorageID string `json:"storage_id"` - Storage int `json:"storage"` - ItemSource int `json:"item_source"` - FileSource int `json:"file_source"` - FileParent int `json:"file_parent"` - FileTarget string `json:"file_target"` - ShareWith string `json:"share_with"` - ShareWithDisplayname string `json:"share_with_displayname"` - MailSend int `json:"mail_send"` - Tags []string `json:"tags"` -} diff --git a/types/webdav.go b/types/webdav.go deleted file mode 100644 index 4f17573..0000000 --- a/types/webdav.go +++ /dev/null @@ -1,39 +0,0 @@ -package types - -import ( - "io" - "os" - "path/filepath" -) - -// WebDav available methods -type WebDav interface { - // ReadDir reads the contents of a remote directory - ReadDir(path string) ([]os.FileInfo, error) - // Stat returns the file stats for a specified path - Stat(path string) (os.FileInfo, error) - // Remove removes a remote file - Remove(path string) error - // RemoveAll removes remote files - RemoveAll(path string) error - // Mkdir makes a directory - Mkdir(path string, _ os.FileMode) error - // MkdirAll like mkdir -p, but for webdav - MkdirAll(path string, _ os.FileMode) error - // Rename moves a file from A to B - Rename(oldpath, newpath string, overwrite bool) error - // Copy copies a file from A to B - Copy(oldpath, newpath string, overwrite bool) error - // Read reads the contents of a remote file - Read(path string) ([]byte, error) - // ReadStream reads the stream for a given path - ReadStream(path string) (io.ReadCloser, error) - // Write writes data to a given path - Write(path string, data []byte, _ os.FileMode) error - // WriteStream writes a stream - WriteStream(path string, stream io.Reader, _ os.FileMode) error - - // Walk walks the file tree rooted at root, calling walkFn for each file or - // directory in the tree, including root. - Walk(path string, walkFunc filepath.WalkFunc) error -} diff --git a/update_test.go b/update_test.go index b6ac6da..feef13a 100644 --- a/update_test.go +++ b/update_test.go @@ -2,12 +2,12 @@ package gonextcloud import ( "fmt" - "github.com/fatih/structs" - "github.com/stretchr/testify/assert" - "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" "strings" "testing" "time" + + "github.com/fatih/structs" + "github.com/stretchr/testify/assert" ) func TestUserUpdate(t *testing.T) { @@ -23,11 +23,11 @@ func TestUserUpdate(t *testing.T) { if err != nil { t.FailNow() } - user := &types.UserDetails{ + user := &UserDetails{ ID: username, Displayname: strings.ToUpper(username), Email: "some@mail.com", - Quota: types.Quota{ + Quota: Quota{ // Unlimited Quota: -3, }, diff --git a/types/user.go b/user.go similarity index 98% rename from types/user.go rename to user.go index 7e8ebfa..954e3df 100644 --- a/types/user.go +++ b/user.go @@ -1,4 +1,4 @@ -package types +package gonextcloud import "strconv" diff --git a/users.go b/users_impl.go similarity index 76% rename from users.go rename to users_impl.go index 8eca631..734760c 100644 --- a/users.go +++ b/users_impl.go @@ -2,56 +2,56 @@ package gonextcloud import ( "encoding/json" - req "github.com/levigross/grequests" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" - "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" "net/http" "net/url" "path" "strings" "sync" + + req "github.com/levigross/grequests" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" ) -//Users contains all Users available actions -type Users struct { - c *Client +//users contains all users available actions +type users struct { + c *client } // List return the Nextcloud'user list -func (u *Users) List() ([]string, error) { +func (u *users) List() ([]string, error) { res, err := u.c.baseRequest(http.MethodGet, routes.users, nil) //res, err := c.session.Get(u.String(), nil) if err != nil { return nil, err } - var r types.UserListResponse + var r UserListResponse res.JSON(&r) return r.Ocs.Data.Users, nil } //ListDetails return a map of user with details -func (u *Users) ListDetails() (map[string]types.UserDetails, error) { +func (u *users) ListDetails() (map[string]UserDetails, error) { res, err := u.c.baseRequest(http.MethodGet, routes.users, nil, "details") //res, err := c.session.Get(u.String(), nil) if err != nil { return nil, err } - var r types.UserListDetailsResponse + var r UserListDetailsResponse res.JSON(&r) return r.Ocs.Data.Users, nil } // Get return the details about the specified user -func (u *Users) Get(name string) (*types.UserDetails, error) { +func (u *users) Get(name string) (*UserDetails, error) { if name == "" { - return nil, &types.APIError{Message: "name cannot be empty"} + return nil, &APIError{Message: "name cannot be empty"} } res, err := u.c.baseRequest(http.MethodGet, routes.users, nil, name) if err != nil { return nil, err } - var r types.UserResponse + var r UserResponse js := res.String() // Nextcloud does not encode JSON properly js = reformatJSON(js) @@ -62,7 +62,7 @@ func (u *Users) Get(name string) (*types.UserDetails, error) { } // Search returns the users whose name match the search string -func (u *Users) Search(search string) ([]string, error) { +func (u *users) Search(search string) ([]string, error) { ro := &req.RequestOptions{ Params: map[string]string{"search": search}, } @@ -70,14 +70,14 @@ func (u *Users) Search(search string) ([]string, error) { if err != nil { return nil, err } - var r types.UserListResponse + var r UserListResponse res.JSON(&r) return r.Ocs.Data.Users, nil } // Create create a new user -func (u *Users) Create(username string, password string, user *types.UserDetails) error { - // Create base Users +func (u *users) Create(username string, password string, user *UserDetails) error { + // Create base users ro := &req.RequestOptions{ Data: map[string]string{ "userid": username, @@ -97,7 +97,7 @@ func (u *Users) Create(username string, password string, user *types.UserDetails // CreateWithoutPassword create a user without provisioning a password, the email address must be provided to send // an init password email -func (u *Users) CreateWithoutPassword(username, email, displayName, quota, language string, groups ...string) error { +func (u *users) CreateWithoutPassword(username, email, displayName, quota, language string, groups ...string) error { if u.c.version.Major < 14 { return errors.New("unsupported method: requires Nextcloud 14+") } @@ -132,12 +132,12 @@ func (u *Users) CreateWithoutPassword(username, email, displayName, quota, langu } //CreateBatchWithoutPassword create multiple users and send them the init password email -func (u *Users) CreateBatchWithoutPassword(users []types.User) error { +func (u *users) CreateBatchWithoutPassword(users []User) error { var wg sync.WaitGroup errs := make(chan error) for _, us := range users { wg.Add(1) - go func(user types.User) { + go func(user User) { logrus.Debugf("creating user %s", user.Username) defer wg.Done() if err := u.CreateWithoutPassword( @@ -162,12 +162,12 @@ func (u *Users) CreateBatchWithoutPassword(users []types.User) error { } //Delete delete the user -func (u *Users) Delete(name string) error { +func (u *users) Delete(name string) error { return u.baseRequest(http.MethodDelete, nil, name) } //Enable enables the user -func (u *Users) Enable(name string) error { +func (u *users) Enable(name string) error { ro := &req.RequestOptions{ Data: map[string]string{}, } @@ -175,7 +175,7 @@ func (u *Users) Enable(name string) error { } //Disable disables the user -func (u *Users) Disable(name string) error { +func (u *users) Disable(name string) error { ro := &req.RequestOptions{ Data: map[string]string{}, } @@ -183,25 +183,25 @@ func (u *Users) Disable(name string) error { } //SendWelcomeEmail (re)send the welcome mail to the user (return an error if the user has not configured his email) -func (u *Users) SendWelcomeEmail(name string) error { +func (u *users) SendWelcomeEmail(name string) error { return u.baseRequest(http.MethodPost, nil, name, "welcome") } -//Update takes a *types.Users struct to update the user's information -// Updatable fields: Email, Displayname, Phone, Address, Website, Twitter, Quota, Groups -func (u *Users) Update(user *types.UserDetails) error { +//Update takes a *types.users struct to update the user's information +// Updatable fields: Email, Displayname, Phone, Address, Website, Twitter, Quota, groups +func (u *users) Update(user *UserDetails) error { // Get user to update only modified fields original, err := u.Get(user.ID) if err != nil { return err } - errs := make(chan *types.UpdateError) + errs := make(chan *UpdateError) var wg sync.WaitGroup update := func(key string, value string) { defer wg.Done() if err := u.updateAttribute(user.ID, strings.ToLower(key), value); err != nil { - errs <- &types.UpdateError{ + errs <- &UpdateError{ Field: key, Error: err, } @@ -242,7 +242,7 @@ func (u *Users) Update(user *types.UserDetails) error { if user.Quota.Quota != original.Quota.Quota { var value string // If empty - if user.Quota == (types.Quota{}) { + if user.Quota == (Quota{}) { value = "default" } else { value = user.Quota.String() @@ -250,7 +250,7 @@ func (u *Users) Update(user *types.UserDetails) error { wg.Add(1) go update("Quota", value) } - // Groups + // groups // Group removed for _, g := range original.Groups { if !contains(user.Groups, g) { @@ -258,8 +258,8 @@ func (u *Users) Update(user *types.UserDetails) error { go func(gr string) { defer wg.Done() if err := u.GroupRemove(user.ID, gr); err != nil { - errs <- &types.UpdateError{ - Field: "Groups/" + gr, + errs <- &UpdateError{ + Field: "groups/" + gr, Error: err, } } @@ -275,8 +275,8 @@ func (u *Users) Update(user *types.UserDetails) error { go func(gr string) { defer wg.Done() if err := u.GroupAdd(user.ID, gr); err != nil { - errs <- &types.UpdateError{ - Field: "Groups/" + gr, + errs <- &UpdateError{ + Field: "groups/" + gr, Error: err, } } @@ -290,66 +290,66 @@ func (u *Users) Update(user *types.UserDetails) error { close(errs) }() // Warning : we actually need to check the *err - if err := types.NewUpdateError(errs); err != nil { + if err := NewUpdateError(errs); err != nil { return err } return nil } //UpdateEmail update the user's email -func (u *Users) UpdateEmail(name string, email string) error { +func (u *users) UpdateEmail(name string, email string) error { return u.updateAttribute(name, "email", email) } //UpdateDisplayName update the user's display name -func (u *Users) UpdateDisplayName(name string, displayName string) error { +func (u *users) UpdateDisplayName(name string, displayName string) error { return u.updateAttribute(name, "displayname", displayName) } //UpdatePhone update the user's phone -func (u *Users) UpdatePhone(name string, phone string) error { +func (u *users) UpdatePhone(name string, phone string) error { return u.updateAttribute(name, "phone", phone) } //UpdateAddress update the user's address -func (u *Users) UpdateAddress(name string, address string) error { +func (u *users) UpdateAddress(name string, address string) error { return u.updateAttribute(name, "address", address) } //UpdateWebSite update the user's website -func (u *Users) UpdateWebSite(name string, website string) error { +func (u *users) UpdateWebSite(name string, website string) error { return u.updateAttribute(name, "website", website) } //UpdateTwitter update the user's twitter -func (u *Users) UpdateTwitter(name string, twitter string) error { +func (u *users) UpdateTwitter(name string, twitter string) error { return u.updateAttribute(name, "twitter", twitter) } //UpdatePassword update the user's password -func (u *Users) UpdatePassword(name string, password string) error { +func (u *users) UpdatePassword(name string, password string) error { return u.updateAttribute(name, "password", password) } //UpdateQuota update the user's quota (bytes). Set negative quota for unlimited -func (u *Users) UpdateQuota(name string, quota int64) error { - q := types.Quota{Quota: quota} +func (u *users) UpdateQuota(name string, quota int64) error { + q := Quota{Quota: quota} return u.updateAttribute(name, "quota", q.String()) } //GroupList lists the user's groups -func (u *Users) GroupList(name string) ([]string, error) { +func (u *users) GroupList(name string) ([]string, error) { res, err := u.c.baseRequest(http.MethodGet, routes.users, nil, name, "groups") if err != nil { return nil, err } - var r types.GroupListResponse + var r GroupListResponse res.JSON(&r) return r.Ocs.Data.Groups, nil } //GroupAdd adds a the user to the group -func (u *Users) GroupAdd(name string, group string) error { +func (u *users) GroupAdd(name string, group string) error { ro := &req.RequestOptions{ Data: map[string]string{ "groupid": group, @@ -359,7 +359,7 @@ func (u *Users) GroupAdd(name string, group string) error { } //GroupRemove removes the user from the group -func (u *Users) GroupRemove(name string, group string) error { +func (u *users) GroupRemove(name string, group string) error { ro := &req.RequestOptions{ Data: map[string]string{ "groupid": group, @@ -369,7 +369,7 @@ func (u *Users) GroupRemove(name string, group string) error { } //GroupPromote promotes the user as group admin -func (u *Users) GroupPromote(name string, group string) error { +func (u *users) GroupPromote(name string, group string) error { ro := &req.RequestOptions{ Data: map[string]string{ "groupid": group, @@ -379,7 +379,7 @@ func (u *Users) GroupPromote(name string, group string) error { } //GroupDemote demotes the user -func (u *Users) GroupDemote(name string, group string) error { +func (u *users) GroupDemote(name string, group string) error { ro := &req.RequestOptions{ Data: map[string]string{ "groupid": group, @@ -389,7 +389,7 @@ func (u *Users) GroupDemote(name string, group string) error { } //GroupSubAdminList lists the groups where he is subadmin -func (u *Users) GroupSubAdminList(name string) ([]string, error) { +func (u *users) GroupSubAdminList(name string) ([]string, error) { if !u.c.loggedIn() { return nil, errUnauthorized } @@ -399,12 +399,12 @@ func (u *Users) GroupSubAdminList(name string) ([]string, error) { if err != nil { return nil, err } - var r types.BaseResponse + var r BaseResponse res.JSON(&r) return r.Ocs.Data, nil } -func (u *Users) updateAttribute(name string, key string, value string) error { +func (u *users) updateAttribute(name string, key string, value string) error { ro := &req.RequestOptions{ Data: map[string]string{ "key": key, @@ -414,13 +414,13 @@ func (u *Users) updateAttribute(name string, key string, value string) error { return u.baseRequest(http.MethodPut, ro, name) } -func (u *Users) baseRequest(method string, ro *req.RequestOptions, subRoutes ...string) error { +func (u *users) baseRequest(method string, ro *req.RequestOptions, subRoutes ...string) error { _, err := u.c.baseRequest(method, routes.users, ro, subRoutes...) return err } func ignoredUserField(key string) bool { - keys := []string{"Email", "Displayname", "Phone", "Address", "Website", "Twitter", "Quota", "Groups"} + keys := []string{"Email", "Displayname", "Phone", "Address", "Website", "Twitter", "Quota", "groups"} for _, k := range keys { if key == k { return false diff --git a/utils.go b/utils.go index 7363e1a..f56713a 100644 --- a/utils.go +++ b/utils.go @@ -2,15 +2,15 @@ package gonextcloud import ( "encoding/json" - req "github.com/levigross/grequests" - "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" "net/http" "net/url" "path" "strings" + + req "github.com/levigross/grequests" ) -func (c *Client) baseRequest(method string, route *url.URL, ro *req.RequestOptions, subRoutes ...string) (*req.Response, error) { +func (c *client) baseRequest(method string, route *url.URL, ro *req.RequestOptions, subRoutes ...string) (*req.Response, error) { if !c.loggedIn() { return nil, errUnauthorized } @@ -40,12 +40,12 @@ func (c *Client) baseRequest(method string, route *url.URL, ro *req.RequestOptio } // As we cannot read the ReaderCloser twice, we use the string content js := res.String() - var r types.BaseResponse + var r BaseResponse json.Unmarshal([]byte(js), &r) if r.Ocs.Meta.Statuscode == 200 || r.Ocs.Meta.Statuscode == 100 { return res, nil } - err = types.ErrorFromMeta(r.Ocs.Meta) + err = ErrorFromMeta(r.Ocs.Meta) return nil, err } diff --git a/webdav.go b/webdav.go index ff4da1f..c4e792b 100644 --- a/webdav.go +++ b/webdav.go @@ -1,82 +1,39 @@ package gonextcloud import ( + "io" "os" "path/filepath" - "sort" - - "gitlab.bertha.cloud/adphi/gowebdav" ) -type webDav struct { - *gowebdav.Client -} - -func newWebDav(url string, user string, password string) *webDav { - wb := gowebdav.NewClient(url, user, password) - return &webDav{Client: wb} -} - -// Implementation adapted from filepath.Walk - -// Walk walks the file tree rooted at root, calling walkFn for each file or -// directory in the tree, including root. All errors that arise visiting files -// and directories are filtered by walkFn. The files are walked in lexical -// order, which makes the output deterministic but means that for very -// large directories Walk can be inefficient. -// Walk does not follow symbolic links. -func (wd *webDav) Walk(root string, walkFn filepath.WalkFunc) error { - info, err := wd.Stat(root) - if err != nil { - err = walkFn(root, nil, err) - } else { - err = wd.walk(root, info, walkFn) - } - if err == filepath.SkipDir { - return nil - } - return err -} - -// walk recursively descends path, calling walkFn. -func (wd *webDav) walk(path string, info os.FileInfo, walkFn filepath.WalkFunc) error { - if !info.IsDir() { - return walkFn(path, info, nil) - } - fis, err := wd.readDir(path) - err1 := walkFn(path, info, err) - // If err != nil, walk can't walk into this directory. - // err1 != nil means walkFn want walk to skip this directory or stop walking. - // Therefore, if one of err and err1 isn't nil, walk will return. - if err != nil || err1 != nil { - // The caller's behavior is controlled by the return value, which is decided - // by walkFn. walkFn may ignore err and return nil. - // If walkFn returns SkipDir, it will be handled by the caller. - // So walk should return whatever walkFn returns. - return err1 - } - - for _, fi := range fis { - filename := filepath.Join(path, fi.Name()) - err = wd.walk(filename, fi, walkFn) - if err != nil { - if !fi.IsDir() || err != filepath.SkipDir { - return err - } - } - } - return nil -} - -// readDir reads the directory and returns -// a sorted list of directory entries. -func (wd *webDav) readDir(dirname string) ([]os.FileInfo, error) { - fs, err := wd.ReadDir(dirname) - if err != nil { - return nil, err - } - sort.Slice(fs, func(i, j int) bool { - return sort.StringsAreSorted([]string{fs[i].Name(), fs[j].Name()}) - }) - return fs, nil +// WebDav available methods +type WebDav interface { + // ReadDir reads the contents of a remote directory + ReadDir(path string) ([]os.FileInfo, error) + // Stat returns the file stats for a specified path + Stat(path string) (os.FileInfo, error) + // Remove removes a remote file + Remove(path string) error + // RemoveAll removes remote files + RemoveAll(path string) error + // Mkdir makes a directory + Mkdir(path string, _ os.FileMode) error + // MkdirAll like mkdir -p, but for webdav + MkdirAll(path string, _ os.FileMode) error + // Rename moves a file from A to B + Rename(oldpath, newpath string, overwrite bool) error + // Copy copies a file from A to B + Copy(oldpath, newpath string, overwrite bool) error + // Read reads the contents of a remote file + Read(path string) ([]byte, error) + // ReadStream reads the stream for a given path + ReadStream(path string) (io.ReadCloser, error) + // Write writes data to a given path + Write(path string, data []byte, _ os.FileMode) error + // WriteStream writes a stream + WriteStream(path string, stream io.Reader, _ os.FileMode) error + + // Walk walks the file tree rooted at root, calling walkFn for each file or + // directory in the tree, including root. + Walk(path string, walkFunc filepath.WalkFunc) error } diff --git a/webdav_impl.go b/webdav_impl.go new file mode 100644 index 0000000..ff4da1f --- /dev/null +++ b/webdav_impl.go @@ -0,0 +1,82 @@ +package gonextcloud + +import ( + "os" + "path/filepath" + "sort" + + "gitlab.bertha.cloud/adphi/gowebdav" +) + +type webDav struct { + *gowebdav.Client +} + +func newWebDav(url string, user string, password string) *webDav { + wb := gowebdav.NewClient(url, user, password) + return &webDav{Client: wb} +} + +// Implementation adapted from filepath.Walk + +// Walk walks the file tree rooted at root, calling walkFn for each file or +// directory in the tree, including root. All errors that arise visiting files +// and directories are filtered by walkFn. The files are walked in lexical +// order, which makes the output deterministic but means that for very +// large directories Walk can be inefficient. +// Walk does not follow symbolic links. +func (wd *webDav) Walk(root string, walkFn filepath.WalkFunc) error { + info, err := wd.Stat(root) + if err != nil { + err = walkFn(root, nil, err) + } else { + err = wd.walk(root, info, walkFn) + } + if err == filepath.SkipDir { + return nil + } + return err +} + +// walk recursively descends path, calling walkFn. +func (wd *webDav) walk(path string, info os.FileInfo, walkFn filepath.WalkFunc) error { + if !info.IsDir() { + return walkFn(path, info, nil) + } + fis, err := wd.readDir(path) + err1 := walkFn(path, info, err) + // If err != nil, walk can't walk into this directory. + // err1 != nil means walkFn want walk to skip this directory or stop walking. + // Therefore, if one of err and err1 isn't nil, walk will return. + if err != nil || err1 != nil { + // The caller's behavior is controlled by the return value, which is decided + // by walkFn. walkFn may ignore err and return nil. + // If walkFn returns SkipDir, it will be handled by the caller. + // So walk should return whatever walkFn returns. + return err1 + } + + for _, fi := range fis { + filename := filepath.Join(path, fi.Name()) + err = wd.walk(filename, fi, walkFn) + if err != nil { + if !fi.IsDir() || err != filepath.SkipDir { + return err + } + } + } + return nil +} + +// readDir reads the directory and returns +// a sorted list of directory entries. +func (wd *webDav) readDir(dirname string) ([]os.FileInfo, error) { + fs, err := wd.ReadDir(dirname) + if err != nil { + return nil, err + } + sort.Slice(fs, func(i, j int) bool { + return sort.StringsAreSorted([]string{fs[i].Name(), fs[j].Name()}) + }) + return fs, nil +} diff --git a/webdav_test.go b/webdav_impl_test.go similarity index 94% rename from webdav_test.go rename to webdav_impl_test.go index cbdc889..753200d 100644 --- a/webdav_test.go +++ b/webdav_impl_test.go @@ -9,14 +9,12 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - - "gitlab.bertha.cloud/partitio/Nextcloud-Partitio/gonextcloud/types" ) var ( dir string - wd types.WebDav - folders = []string{ + wd WebDav + folders = []string{ "folder1", "folder1/sub1", "folder1/sub1/ssub1",