package officeconvertclient import ( "context" "fmt" "io" "net/http" "os" "path/filepath" "strings" officeconvertapiv1 "gitea.auvem.com/end/officeconvert/gen/go/officeconvertapi/v1" ) // DownloadedArtifact records a downloaded slide image destination path. type DownloadedArtifact struct { SlideIndex int32 LocalPath string } // DownloadArtifacts fetches all slide image URLs from a slide deck into outputDir. func (c *Client) DownloadArtifacts( ctx context.Context, slideDeck *officeconvertapiv1.SlideDeck, outputDir string, ) ([]DownloadedArtifact, error) { if slideDeck == nil { return nil, fmt.Errorf("slide deck is nil") } if err := os.MkdirAll(outputDir, 0o755); err != nil { return nil, fmt.Errorf("create output directory: %w", err) } downloaded := make([]DownloadedArtifact, 0, len(slideDeck.Slides)) for _, slide := range slideDeck.Slides { localPath := filepath.Join(outputDir, fmt.Sprintf("slide-%04d%s", slide.Index, inferImageExt(slide.ImageUrl))) if err := c.downloadFile(ctx, slide.ImageUrl, localPath); err != nil { return nil, err } downloaded = append(downloaded, DownloadedArtifact{ SlideIndex: slide.Index, LocalPath: localPath, }) } return downloaded, nil } func (c *Client) downloadFile(ctx context.Context, sourceURL string, destinationPath string) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, sourceURL, nil) if err != nil { return fmt.Errorf("build download request: %w", err) } res, err := c.httpClient.Do(req) if err != nil { return fmt.Errorf("download artifact: %w", err) } defer res.Body.Close() if res.StatusCode < 200 || res.StatusCode >= 300 { return fmt.Errorf("download failed with status %d", res.StatusCode) } file, err := os.Create(destinationPath) if err != nil { return fmt.Errorf("create artifact file: %w", err) } defer file.Close() if _, err := io.Copy(file, res.Body); err != nil { return fmt.Errorf("write artifact file: %w", err) } return nil } func inferImageExt(imageURL string) string { switch { case strings.Contains(imageURL, ".jpeg") || strings.Contains(imageURL, ".jpg"): return ".jpg" case strings.Contains(imageURL, ".webp"): return ".webp" default: return ".png" } }