github.com/cs3org/reva/v2@v2.27.7/pkg/siteacc/data/siteinfo.go (about) 1 // Copyright 2018-2020 CERN 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // In applying this license, CERN does not waive the privileges and immunities 16 // granted to it by virtue of its status as an Intergovernmental Organization 17 // or submit itself to any jurisdiction. 18 19 package data 20 21 import ( 22 "encoding/json" 23 "sort" 24 25 "github.com/cs3org/reva/v2/pkg/mentix/utils/network" 26 "github.com/pkg/errors" 27 ) 28 29 // SiteInformation holds the most basic information about a site. 30 type SiteInformation struct { 31 ID string 32 Name string 33 FullName string 34 } 35 36 // QueryAvailableSites uses Mentix to query a list of all available (registered) sites. 37 func QueryAvailableSites(mentixHost, dataEndpoint string) ([]SiteInformation, error) { 38 mentixURL, err := network.GenerateURL(mentixHost, dataEndpoint, network.URLParams{}) 39 if err != nil { 40 return nil, errors.Wrap(err, "unable to generate Mentix URL") 41 } 42 43 data, err := network.ReadEndpoint(mentixURL, nil, true) 44 if err != nil { 45 return nil, errors.Wrap(err, "unable to read the Mentix endpoint") 46 } 47 48 // Decode the data into a simplified, reduced data type 49 type siteData struct { 50 Sites []SiteInformation 51 } 52 sites := siteData{} 53 if err := json.Unmarshal(data, &sites); err != nil { 54 return nil, errors.Wrap(err, "error while decoding the JSON data") 55 } 56 57 // Sort the sites alphabetically by their names 58 sort.Slice(sites.Sites, func(i, j int) bool { 59 return sites.Sites[i].Name < sites.Sites[j].Name 60 }) 61 62 return sites.Sites, nil 63 } 64 65 // QuerySiteName uses Mentix to query the name of a site given by its ID. 66 func QuerySiteName(siteID string, fullName bool, mentixHost, dataEndpoint string) (string, error) { 67 sites, err := QueryAvailableSites(mentixHost, dataEndpoint) 68 if err != nil { 69 return "", err 70 } 71 72 index := len(sites) 73 for i, site := range sites { 74 if site.ID == siteID { 75 index = i 76 break 77 } 78 } 79 80 if index != len(sites) { 81 if fullName { 82 return sites[index].FullName, nil 83 } 84 85 return sites[index].Name, nil 86 } 87 88 return "", errors.Errorf("no site with ID %v found", siteID) 89 }