processImageFile handles a single image file (URL or base64) and returns the path to the temporary file
(file string, generatedContentDir string)
| 258 | |
| 259 | // processImageFile handles a single image file (URL or base64) and returns the path to the temporary file |
| 260 | func processImageFile(file string, generatedContentDir string) string { |
| 261 | fileData := []byte{} |
| 262 | var err error |
| 263 | |
| 264 | // check if file is an URL, if so download it and save it to a temporary file |
| 265 | if strings.HasPrefix(file, "http://") || strings.HasPrefix(file, "https://") { |
| 266 | out, err := downloadFile(file) |
| 267 | if err != nil { |
| 268 | xlog.Error("Failed downloading file", "error", err, "file", file) |
| 269 | return "" |
| 270 | } |
| 271 | defer os.RemoveAll(out) |
| 272 | |
| 273 | fileData, err = os.ReadFile(out) |
| 274 | if err != nil { |
| 275 | xlog.Error("Failed reading downloaded file", "error", err, "file", out) |
| 276 | return "" |
| 277 | } |
| 278 | } else { |
| 279 | // base 64 decode the file and write it somewhere that we will cleanup |
| 280 | fileData, err = base64.StdEncoding.DecodeString(file) |
| 281 | if err != nil { |
| 282 | xlog.Error("Failed decoding base64 file", "error", err) |
| 283 | return "" |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | // Create a temporary file |
| 288 | outputFile, err := os.CreateTemp(generatedContentDir, "b64") |
| 289 | if err != nil { |
| 290 | xlog.Error("Failed creating temporary file", "error", err) |
| 291 | return "" |
| 292 | } |
| 293 | |
| 294 | // write the decoded result |
| 295 | writer := bufio.NewWriter(outputFile) |
| 296 | _, err = writer.Write(fileData) |
| 297 | if err != nil { |
| 298 | outputFile.Close() |
| 299 | xlog.Error("Failed writing to temporary file", "error", err) |
| 300 | return "" |
| 301 | } |
| 302 | if err := writer.Flush(); err != nil { |
| 303 | outputFile.Close() |
| 304 | xlog.Error("Failed flushing to temporary file", "error", err) |
| 305 | return "" |
| 306 | } |
| 307 | outputFile.Close() |
| 308 | |
| 309 | return outputFile.Name() |
| 310 | } |