|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "net/http" |
| 8 | + "os" |
| 9 | + "path/filepath" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +// remotePackage matches the JSON returned by GET /api/packages. |
| 14 | +type remotePackage struct { |
| 15 | + Name string `json:"name"` |
| 16 | + Desc string `json:"desc"` |
| 17 | + Category string `json:"category"` |
| 18 | + Type string `json:"type"` |
| 19 | + Installer string `json:"installer"` // "formula", "cask", or "npm" |
| 20 | +} |
| 21 | + |
| 22 | +type remotePackagesResponse struct { |
| 23 | + Packages []remotePackage `json:"packages"` |
| 24 | +} |
| 25 | + |
| 26 | +const ( |
| 27 | + packagesCacheFile = "packages-cache.json" |
| 28 | + packagesCacheTTL = 24 * time.Hour |
| 29 | +) |
| 30 | + |
| 31 | +// packagesCacheEntry is the on-disk cache format. |
| 32 | +type packagesCacheEntry struct { |
| 33 | + FetchedAt time.Time `json:"fetched_at"` |
| 34 | + Packages []remotePackage `json:"packages"` |
| 35 | +} |
| 36 | + |
| 37 | +// RefreshPackagesFromRemote fetches packages from the server and merges them |
| 38 | +// into the global Categories slice. Safe to call multiple times; it is a no-op |
| 39 | +// if the cache is fresh. Falls back to the embedded packages.yaml silently. |
| 40 | +func RefreshPackagesFromRemote() { |
| 41 | + pkgs, err := loadRemotePackages() |
| 42 | + if err != nil || len(pkgs) == 0 { |
| 43 | + return // keep embedded fallback |
| 44 | + } |
| 45 | + mergeRemotePackages(pkgs) |
| 46 | +} |
| 47 | + |
| 48 | +func loadRemotePackages() ([]remotePackage, error) { |
| 49 | + // Try disk cache first. |
| 50 | + if pkgs, err := readPackagesCache(); err == nil { |
| 51 | + return pkgs, nil |
| 52 | + } |
| 53 | + |
| 54 | + // Fetch from server. |
| 55 | + pkgs, err := fetchRemotePackages() |
| 56 | + if err != nil { |
| 57 | + return nil, err |
| 58 | + } |
| 59 | + |
| 60 | + // Write cache (best-effort). |
| 61 | + _ = writePackagesCache(pkgs) |
| 62 | + return pkgs, nil |
| 63 | +} |
| 64 | + |
| 65 | +func fetchRemotePackages() ([]remotePackage, error) { |
| 66 | + apiURL := getAPIBase() + "/api/packages" |
| 67 | + client := &http.Client{Timeout: 8 * time.Second} |
| 68 | + |
| 69 | + resp, err := client.Get(apiURL) |
| 70 | + if err != nil { |
| 71 | + return nil, fmt.Errorf("fetch packages: %w", err) |
| 72 | + } |
| 73 | + defer resp.Body.Close() |
| 74 | + |
| 75 | + if resp.StatusCode != 200 { |
| 76 | + return nil, fmt.Errorf("fetch packages: status %d", resp.StatusCode) |
| 77 | + } |
| 78 | + |
| 79 | + var result remotePackagesResponse |
| 80 | + if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&result); err != nil { |
| 81 | + return nil, fmt.Errorf("parse packages: %w", err) |
| 82 | + } |
| 83 | + |
| 84 | + return result.Packages, nil |
| 85 | +} |
| 86 | + |
| 87 | +// cacheDir returns the directory for cache files. It is a variable so tests |
| 88 | +// can replace it with a temp directory. |
| 89 | +var cacheDir = func() string { |
| 90 | + home, _ := os.UserHomeDir() |
| 91 | + return filepath.Join(home, ".openboot") |
| 92 | +} |
| 93 | + |
| 94 | +func readPackagesCache() ([]remotePackage, error) { |
| 95 | + data, err := os.ReadFile(filepath.Join(cacheDir(), packagesCacheFile)) |
| 96 | + if err != nil { |
| 97 | + return nil, err |
| 98 | + } |
| 99 | + |
| 100 | + var entry packagesCacheEntry |
| 101 | + if err := json.Unmarshal(data, &entry); err != nil { |
| 102 | + return nil, err |
| 103 | + } |
| 104 | + |
| 105 | + if time.Since(entry.FetchedAt) > packagesCacheTTL { |
| 106 | + return nil, fmt.Errorf("cache expired") |
| 107 | + } |
| 108 | + |
| 109 | + return entry.Packages, nil |
| 110 | +} |
| 111 | + |
| 112 | +func writePackagesCache(pkgs []remotePackage) error { |
| 113 | + dir := cacheDir() |
| 114 | + if err := os.MkdirAll(dir, 0700); err != nil { |
| 115 | + return err |
| 116 | + } |
| 117 | + |
| 118 | + entry := packagesCacheEntry{ |
| 119 | + FetchedAt: time.Now(), |
| 120 | + Packages: pkgs, |
| 121 | + } |
| 122 | + data, err := json.Marshal(entry) |
| 123 | + if err != nil { |
| 124 | + return err |
| 125 | + } |
| 126 | + |
| 127 | + return os.WriteFile(filepath.Join(dir, packagesCacheFile), data, 0600) |
| 128 | +} |
| 129 | + |
| 130 | +// categoryMap maps server category names to display info. |
| 131 | +var categoryMap = map[string]struct { |
| 132 | + Name string |
| 133 | + Icon string |
| 134 | +}{ |
| 135 | + "essential": {Name: "Essential", Icon: "⚡"}, |
| 136 | + "development": {Name: "Development", Icon: "🛠"}, |
| 137 | + "productivity": {Name: "Productivity", Icon: "🚀"}, |
| 138 | + "optional": {Name: "Optional", Icon: "📦"}, |
| 139 | +} |
| 140 | + |
| 141 | +// mergeRemotePackages converts remote packages into Categories format and |
| 142 | +// merges them with the embedded data. Remote packages take precedence. |
| 143 | +func mergeRemotePackages(pkgs []remotePackage) { |
| 144 | + // Build a set of existing package names from embedded data. |
| 145 | + existing := make(map[string]bool) |
| 146 | + for _, cat := range Categories { |
| 147 | + for _, pkg := range cat.Packages { |
| 148 | + existing[pkg.Name] = true |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + // Group new remote packages by category. |
| 153 | + byCat := make(map[string][]Package) |
| 154 | + for _, rp := range pkgs { |
| 155 | + if existing[rp.Name] { |
| 156 | + // Update description in existing categories if remote has a better one. |
| 157 | + updateDescription(rp.Name, rp.Desc) |
| 158 | + // Update installer type flags. |
| 159 | + updateInstallerFlags(rp.Name, rp.Installer) |
| 160 | + continue |
| 161 | + } |
| 162 | + pkg := Package{ |
| 163 | + Name: rp.Name, |
| 164 | + Description: rp.Desc, |
| 165 | + IsCask: rp.Installer == "cask", |
| 166 | + IsNpm: rp.Installer == "npm", |
| 167 | + } |
| 168 | + byCat[rp.Category] = append(byCat[rp.Category], pkg) |
| 169 | + } |
| 170 | + |
| 171 | + // Append new packages to existing categories or create new ones. |
| 172 | + catIndex := make(map[string]int) |
| 173 | + for i, cat := range Categories { |
| 174 | + // Map existing category names to server categories. |
| 175 | + switch cat.Name { |
| 176 | + case "Essential": |
| 177 | + catIndex["essential"] = i |
| 178 | + case "Development", "Git & GitHub", "DevOps", "Database": |
| 179 | + catIndex["development"] = i |
| 180 | + case "Productivity", "Browsers": |
| 181 | + catIndex["productivity"] = i |
| 182 | + case "NPM Global": |
| 183 | + catIndex["development"] = i // npm goes with development |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | + for serverCat, newPkgs := range byCat { |
| 188 | + if idx, ok := catIndex[serverCat]; ok { |
| 189 | + Categories[idx].Packages = append(Categories[idx].Packages, newPkgs...) |
| 190 | + } else { |
| 191 | + info := categoryMap[serverCat] |
| 192 | + if info.Name == "" { |
| 193 | + info = struct { |
| 194 | + Name string |
| 195 | + Icon string |
| 196 | + }{Name: serverCat, Icon: "📦"} |
| 197 | + } |
| 198 | + Categories = append(Categories, Category{ |
| 199 | + Name: info.Name, |
| 200 | + Icon: info.Icon, |
| 201 | + Packages: newPkgs, |
| 202 | + }) |
| 203 | + } |
| 204 | + } |
| 205 | +} |
| 206 | + |
| 207 | +func updateDescription(name, desc string) { |
| 208 | + if desc == "" { |
| 209 | + return |
| 210 | + } |
| 211 | + for i := range Categories { |
| 212 | + for j := range Categories[i].Packages { |
| 213 | + if Categories[i].Packages[j].Name == name && Categories[i].Packages[j].Description == "" { |
| 214 | + Categories[i].Packages[j].Description = desc |
| 215 | + } |
| 216 | + } |
| 217 | + } |
| 218 | +} |
| 219 | + |
| 220 | +func updateInstallerFlags(name, installer string) { |
| 221 | + for i := range Categories { |
| 222 | + for j := range Categories[i].Packages { |
| 223 | + if Categories[i].Packages[j].Name == name { |
| 224 | + switch installer { |
| 225 | + case "cask": |
| 226 | + Categories[i].Packages[j].IsCask = true |
| 227 | + case "npm": |
| 228 | + Categories[i].Packages[j].IsNpm = true |
| 229 | + } |
| 230 | + } |
| 231 | + } |
| 232 | + } |
| 233 | +} |
0 commit comments