github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/model/instance/manager.go (about) 1 package instance 2 3 import ( 4 "fmt" 5 "net/url" 6 7 "github.com/cozy/cozy-stack/pkg/config/config" 8 "github.com/cozy/cozy-stack/pkg/manager" 9 ) 10 11 // ManagerURLKind is an enum type for the different kinds of manager URLs. 12 type ManagerURLKind int 13 14 const ( 15 // ManagerTOSURL is the kind for changes of TOS URL. 16 ManagerTOSURL ManagerURLKind = iota 17 // ManagerPremiumURL is the kind for changing the account type of the 18 // instance. 19 ManagerPremiumURL 20 // ManagerBlockedURL is the kind for a redirection of a blocked instance. 21 ManagerBlockedURL 22 ) 23 24 // ManagerURL returns an external string for the given ManagerURL kind. It is 25 // used for redirecting the user to a manager URL. 26 func (i *Instance) ManagerURL(k ManagerURLKind) (string, error) { 27 if i.UUID == "" { 28 return "", nil 29 } 30 31 config, ok := i.SettingsContext() 32 if !ok { 33 return "", nil 34 } 35 36 base, ok := config["manager_url"].(string) 37 if !ok { 38 return "", nil 39 } 40 41 baseURL, err := url.Parse(base) 42 if err != nil { 43 return "", err 44 } 45 46 var path string 47 switch k { 48 case ManagerPremiumURL: 49 path = fmt.Sprintf("/cozy/instances/%s/premium", url.PathEscape(i.UUID)) 50 case ManagerTOSURL: 51 path = fmt.Sprintf("/cozy/instances/%s/tos", url.PathEscape(i.UUID)) 52 case ManagerBlockedURL: 53 path = fmt.Sprintf("/cozy/instances/%s/blocked", url.PathEscape(i.UUID)) 54 default: 55 panic("unknown ManagerURLKind") 56 } 57 baseURL.Path = path 58 59 return baseURL.String(), nil 60 } 61 62 // APIManagerClient returns a client to talk to the manager via its API. 63 func APIManagerClient(inst *Instance) *manager.APIClient { 64 clouderies := config.GetConfig().Clouderies 65 if clouderies == nil { 66 return nil 67 } 68 69 var cloudery config.ClouderyConfig 70 cloudery, ok := clouderies[inst.ContextName] 71 if !ok { 72 cloudery, ok = clouderies[config.DefaultInstanceContext] 73 } 74 if !ok { 75 return nil 76 } 77 78 api := cloudery.API 79 if api.URL == "" || api.Token == "" { 80 return nil 81 } 82 83 return manager.NewAPIClient(api.URL, api.Token) 84 }