github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/model/remote/list.go (about) 1 package remote 2 3 import ( 4 "encoding/json" 5 "net/http" 6 "os" 7 "strings" 8 "time" 9 10 "github.com/cozy/cozy-stack/model/instance" 11 "github.com/cozy/cozy-stack/pkg/config/config" 12 "github.com/cozy/httpcache" 13 ) 14 15 var listClient = &http.Client{ 16 Timeout: 20 * time.Second, 17 Transport: httpcache.NewMemoryCacheTransport(32), 18 } 19 20 // https://docs.github.com/en/rest/repos/contents#get-repository-content 21 const listURL = "https://api.github.com/repos/cozy/cozy-doctypes/contents/" 22 23 type listEntries struct { 24 Name string `json:"name"` 25 Type string `json:"type"` 26 } 27 28 // ListDoctypes returns the list of the known remote doctypes. 29 func ListDoctypes(inst *instance.Instance) ([]string, error) { 30 var doctypes []string 31 if config.GetConfig().Doctypes == "" { 32 req, err := http.NewRequest(http.MethodGet, listURL, nil) 33 if err != nil { 34 return nil, err 35 } 36 res, err := listClient.Do(req) 37 if err != nil { 38 log.Warnf("cannot list doctypes: %s", err) 39 return nil, ErrNotFoundRemote 40 } 41 defer res.Body.Close() 42 var entries []listEntries 43 if err := json.NewDecoder(res.Body).Decode(&entries); err != nil { 44 return nil, err 45 } 46 for _, entry := range entries { 47 if entry.Type != "dir" { 48 continue 49 } 50 if entry.Name == "docs" || strings.HasPrefix(entry.Name, ".") { 51 continue 52 } 53 doctypes = append(doctypes, entry.Name) 54 } 55 } else { 56 entries, err := os.ReadDir(config.GetConfig().Doctypes) 57 if err != nil { 58 return nil, err 59 } 60 for _, entry := range entries { 61 if !entry.IsDir() { 62 continue 63 } 64 name := entry.Name() 65 if name == "docs" || strings.HasPrefix(name, ".") { 66 continue 67 } 68 doctypes = append(doctypes, name) 69 } 70 } 71 return doctypes, nil 72 }