Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial implementation of /me/drives/sharedByMe endpoint #7239

Merged
merged 6 commits into from
Nov 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions services/graph/pkg/service/v0/driveitems.go
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,13 @@ func cs3ResourceToDriveItem(res *storageprovider.ResourceInfo) (*libregraph.Driv
lastModified := cs3TimestampToTime(res.Mtime)
driveItem.LastModifiedDateTime = &lastModified
}
if res.ParentId != nil {
parentRef := libregraph.NewItemReference()
parentRef.SetDriveType(res.Space.SpaceType)
parentRef.SetDriveId(storagespace.FormatStorageID(res.ParentId.StorageId, res.ParentId.SpaceId))
parentRef.SetId(storagespace.FormatResourceID(*res.ParentId))
driveItem.ParentReference = parentRef
}
if res.Type == storageprovider.ResourceType_RESOURCE_TYPE_FILE && res.MimeType != "" {
// We cannot use a libregraph.File here because the openapi codegenerator autodetects 'File' as a go type ...
driveItem.File = &libregraph.OpenGraphFile{
Expand Down
2 changes: 0 additions & 2 deletions services/graph/pkg/service/v0/educationclasses_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
libregraph "github.com/owncloud/libre-graph-api-go"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/ocis-pkg/shared"
"github.com/owncloud/ocis/v2/services/graph/mocks"
"github.com/owncloud/ocis/v2/services/graph/pkg/config"
Expand Down Expand Up @@ -85,7 +84,6 @@ var _ = Describe("EducationClass", func() {
service.EventsPublisher(&eventsPublisher),
service.WithIdentityBackend(identityBackend),
service.WithIdentityEducationBackend(identityEducationBackend),
service.Logger(log.NewLogger(log.Level("debug"))),
)
})

Expand Down
8 changes: 7 additions & 1 deletion services/graph/pkg/service/v0/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ type Service interface {
GetDrives(w http.ResponseWriter, r *http.Request)
GetSingleDrive(w http.ResponseWriter, r *http.Request)
GetAllDrives(w http.ResponseWriter, r *http.Request)
GetSharedByMe(w http.ResponseWriter, r *http.Request)
CreateDrive(w http.ResponseWriter, r *http.Request)
UpdateDrive(w http.ResponseWriter, r *http.Request)
DeleteDrive(w http.ResponseWriter, r *http.Request)
Expand Down Expand Up @@ -199,6 +200,9 @@ func NewService(opts ...Option) (Graph, error) {

m.Route(options.Config.HTTP.Root, func(r chi.Router) {
r.Use(middleware.StripSlashes)
r.Route("/v1beta1", func(r chi.Router) {
r.Get("/me/drives/sharedByMe", svc.GetSharedByMe)
})
r.Route("/v1.0", func(r chi.Router) {
r.Route("/extensions/org.libregraph", func(r chi.Router) {
r.Get("/tags", svc.GetTags)
Expand All @@ -212,7 +216,9 @@ func NewService(opts ...Option) (Graph, error) {
r.Route("/me", func(r chi.Router) {
r.Get("/", svc.GetMe)
r.Get("/drive", svc.GetUserDrive)
r.Get("/drives", svc.GetDrives)
r.Route("/drives", func(r chi.Router) {
r.Get("/", svc.GetDrives)
})
r.Get("/drive/root/children", svc.GetRootDriveChildren)
r.Post("/changePassword", svc.ChangeOwnPassword)
})
Expand Down
242 changes: 242 additions & 0 deletions services/graph/pkg/service/v0/sharedbyme.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
package svc

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

group "github.com/cs3org/go-cs3apis/cs3/identity/group/v1beta1"
rpc "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
collaboration "github.com/cs3org/go-cs3apis/cs3/sharing/collaboration/v1beta1"
link "github.com/cs3org/go-cs3apis/cs3/sharing/link/v1beta1"
storageprovider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/cs3org/reva/v2/pkg/share"
"github.com/cs3org/reva/v2/pkg/storagespace"
revautils "github.com/cs3org/reva/v2/pkg/utils"
"github.com/go-chi/render"
libregraph "github.com/owncloud/libre-graph-api-go"
"github.com/owncloud/ocis/v2/services/graph/pkg/service/v0/errorcode"
)

type driveItemsByResourceID map[string]libregraph.DriveItem

// GetSharedByMe implements the Service interface (/me/drives/sharedByMe endpoint)
func (g Graph) GetSharedByMe(w http.ResponseWriter, r *http.Request) {
rhafer marked this conversation as resolved.
Show resolved Hide resolved
g.logger.Debug().Msg("Calling GetRootDriveChildren")
ctx := r.Context()

driveItems := make(driveItemsByResourceID)
var err error
driveItems, err = g.listUserShares(ctx, driveItems)
if err != nil {
errorcode.RenderError(w, r, err)
return
}

driveItems, err = g.listPublicShares(ctx, driveItems)
if err != nil {
errorcode.RenderError(w, r, err)
return
}

res := make([]libregraph.DriveItem, 0, len(driveItems))
for _, v := range driveItems {
res = append(res, v)
}

render.Status(r, http.StatusOK)
render.JSON(w, r, &ListResponse{Value: res})
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we sort the response list so we have reproducible return values?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know. Should we? I don't think we're doing that elsewhere. Somehow I think we shouldn't. It would only result in clients expecting the results to be returned in a specific order.

}

func (g Graph) listUserShares(ctx context.Context, driveItems driveItemsByResourceID) (driveItemsByResourceID, error) {
gatewayClient, err := g.gatewaySelector.Next()
if err != nil {
g.logger.Error().Err(err).Msg("could not select next gateway client")
return driveItems, errorcode.New(errorcode.GeneralException, err.Error())
}

filters := []*collaboration.Filter{
share.UserGranteeFilter(),
share.GroupGranteeFilter(),
}
lsUserSharesRequest := collaboration.ListSharesRequest{
Filters: filters,
}

lsUserSharesResponse, err := gatewayClient.ListShares(ctx, &lsUserSharesRequest)
if err != nil {
return driveItems, errorcode.New(errorcode.GeneralException, err.Error())
}
if statusCode := lsUserSharesResponse.GetStatus().GetCode(); statusCode != rpc.Code_CODE_OK {
return driveItems, errorcode.New(cs3StatusToErrCode(statusCode), lsUserSharesResponse.Status.Message)
}
driveItems, err = g.cs3UserSharesToDriveItems(ctx, lsUserSharesResponse.Shares, driveItems)
if err != nil {
return driveItems, errorcode.New(errorcode.GeneralException, err.Error())
}
return driveItems, nil
}

func (g Graph) listPublicShares(ctx context.Context, driveItems driveItemsByResourceID) (driveItemsByResourceID, error) {

gatewayClient, err := g.gatewaySelector.Next()
if err != nil {
g.logger.Error().Err(err).Msg("could not select next gateway client")
return driveItems, errorcode.New(errorcode.GeneralException, err.Error())
}

filters := []*link.ListPublicSharesRequest_Filter{}

req := link.ListPublicSharesRequest{
Filters: filters,
}

lsPublicSharesResponse, err := gatewayClient.ListPublicShares(ctx, &req)
if err != nil {
return driveItems, errorcode.New(errorcode.GeneralException, err.Error())
}
if statusCode := lsPublicSharesResponse.GetStatus().GetCode(); statusCode != rpc.Code_CODE_OK {
return driveItems, errorcode.New(cs3StatusToErrCode(statusCode), lsPublicSharesResponse.Status.Message)
}
driveItems, err = g.cs3PublicSharesToDriveItems(ctx, lsPublicSharesResponse.Share, driveItems)
if err != nil {
return driveItems, errorcode.New(errorcode.GeneralException, err.Error())
}
return driveItems, nil

}

func (g Graph) cs3UserSharesToDriveItems(ctx context.Context, shares []*collaboration.Share, driveItems driveItemsByResourceID) (driveItemsByResourceID, error) {
for _, s := range shares {
g.logger.Debug().Interface("CS3 UserShare", s).Msg("Got Share")
resIDStr := storagespace.FormatResourceID(*s.ResourceId)
item, ok := driveItems[resIDStr]
if !ok {
itemptr, err := g.getDriveItem(ctx, storageprovider.Reference{ResourceId: s.ResourceId})
if err != nil {
g.logger.Debug().Err(err).Interface("Share", s.ResourceId).Msg("could not stat share, skipping")
continue
}
item = *itemptr
}
perm := libregraph.Permission{}
perm.SetRoles([]string{})
perm.SetId(s.Id.OpaqueId)
grantedTo := libregraph.SharePointIdentitySet{}
switch s.Grantee.Type {
case storageprovider.GranteeType_GRANTEE_TYPE_USER:
gatewayClient, err := g.gatewaySelector.Next()
if err != nil {
g.logger.Error().Err(err).Msg("could not select next gateway client")
return driveItems, errorcode.New(errorcode.GeneralException, err.Error())
}
user := libregraph.NewIdentityWithDefaults()
user.SetId(s.Grantee.GetUserId().GetOpaqueId())
cs3User, err := revautils.GetUser(s.GetGrantee().GetUserId(), gatewayClient)
switch {
case revautils.IsErrNotFound(err):
g.logger.Warn().Str("userid", s.Grantee.GetUserId().GetOpaqueId()).Msg("User not found by id")
// User does not seem to exist anymore, don't add a permission for this
continue
case err != nil:
return driveItems, errorcode.New(errorcode.GeneralException, err.Error())
default:
user.SetDisplayName(cs3User.GetDisplayName())
grantedTo.SetUser(*user)
}
case storageprovider.GranteeType_GRANTEE_TYPE_GROUP:
gatewayClient, err := g.gatewaySelector.Next()
if err != nil {
g.logger.Error().Err(err).Msg("could not select next gateway client")
return driveItems, errorcode.New(errorcode.GeneralException, err.Error())
}
req := group.GetGroupRequest{
GroupId: s.Grantee.GetGroupId(),
}
res, err := gatewayClient.GetGroup(ctx, &req)
if err != nil {
return driveItems, errorcode.New(errorcode.GeneralException, err.Error())
}
grp := libregraph.NewIdentityWithDefaults()
grp.SetId(s.Grantee.GetGroupId().GetOpaqueId())
switch res.Status.Code {
case rpc.Code_CODE_OK:
cs3Group := res.GetGroup()
grp.SetDisplayName(cs3Group.GetDisplayName())
grantedTo.SetGroup(*grp)
case rpc.Code_CODE_NOT_FOUND:
g.logger.Warn().Str("groupid", s.Grantee.GetGroupId().GetOpaqueId()).Msg("Group not found by id")
rhafer marked this conversation as resolved.
Show resolved Hide resolved
// Group does not seem to exist anymore, don't add a permission for this
continue
default:
return driveItems, errorcode.New(errorcode.GeneralException, res.Status.Message)
}
}

// set expiration date
if s.GetExpiration() != nil {
perm.SetExpirationDateTime(cs3TimestampToTime(s.GetExpiration()))
}

perm.SetGrantedToV2(grantedTo)
item.Permissions = append(item.Permissions, perm)
driveItems[resIDStr] = item
}
return driveItems, nil
}

func (g Graph) cs3PublicSharesToDriveItems(ctx context.Context, shares []*link.PublicShare, driveItems driveItemsByResourceID) (driveItemsByResourceID, error) {
for _, s := range shares {
g.logger.Debug().Interface("CS3 PublicShare", s).Msg("Got Share")
resIDStr := storagespace.FormatResourceID(*s.ResourceId)
item, ok := driveItems[resIDStr]
if !ok {
itemptr, err := g.getDriveItem(ctx, storageprovider.Reference{ResourceId: s.ResourceId})
if err != nil {
g.logger.Debug().Err(err).Interface("Share", s.ResourceId).Msg("could not stat share, skipping")
continue
}
item = *itemptr
}
perm := libregraph.Permission{}
perm.SetRoles([]string{})
perm.SetId(s.Id.OpaqueId)
link := libregraph.SharingLink{}
webURL, err := url.Parse(g.config.Spaces.WebDavBase)
if err != nil {
g.logger.Error().
Err(err).
Str("url", g.config.Spaces.WebDavBase).
Msg("failed to parse webURL base url")
return driveItems, err
}

webURL.Path = path.Join(webURL.Path, "s", s.GetToken())
link.SetWebUrl(webURL.String())
perm.SetLink(link)
// set expiration date
if s.GetExpiration() != nil {
perm.SetExpirationDateTime(cs3TimestampToTime(s.GetExpiration()))
}

item.Permissions = append(item.Permissions, perm)
driveItems[resIDStr] = item
}

return driveItems, nil
}

func cs3StatusToErrCode(code rpc.Code) (errcode errorcode.ErrorCode) {
switch code {
case rpc.Code_CODE_UNAUTHENTICATED:
errcode = errorcode.Unauthenticated
case rpc.Code_CODE_PERMISSION_DENIED:
errcode = errorcode.AccessDenied
case rpc.Code_CODE_NOT_FOUND:
errcode = errorcode.ItemNotFound
default:
errcode = errorcode.GeneralException
}
return errcode
}
Loading