From 7a63e78baf3fe9f769ad4a0569baf8ca71363cfe Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Fri, 8 Nov 2024 22:48:51 +0200 Subject: can download preview image for linkedin --- internal/platforms/linkedin/linkedin.go | 8 ++++++++ internal/platforms/linkedin/preview.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) (limited to 'internal/platforms/linkedin') diff --git a/internal/platforms/linkedin/linkedin.go b/internal/platforms/linkedin/linkedin.go index a8f7a13..1d57a9e 100644 --- a/internal/platforms/linkedin/linkedin.go +++ b/internal/platforms/linkedin/linkedin.go @@ -58,6 +58,14 @@ func post(ctx context.Context, args config.Args, sizeLimit int, en entry.Entry) return err } + var filePath string + if prev.imageURL != "" { + if filePath, err = prev.DownloadImage(args.CacheDir); err != nil { + return err + } + log.Println("Downloaded preview image to ", filePath) + } + question := fmt.Sprintf("Do you want to post this message to Linkedin (%v)?", prev) if err := prompt.FileAction(question, content, en.Path); err != nil { return err diff --git a/internal/platforms/linkedin/preview.go b/internal/platforms/linkedin/preview.go index 765a487..2e40798 100644 --- a/internal/platforms/linkedin/preview.go +++ b/internal/platforms/linkedin/preview.go @@ -8,7 +8,10 @@ import ( "log" "net/http" "net/url" + "os" + "path/filepath" + "codeberg.org/snonux/gos/internal/oi" "golang.org/x/net/html" ) @@ -48,6 +51,35 @@ func (p preview) Empty() bool { return p.url == "" } +func (p preview) DownloadImage(destPath string) (string, error) { + if err := oi.EnsureDir(destPath); err != nil { + return "", err + } + resp, err := http.Get(p.imageURL) + if err != nil { + return "", err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("bad status while trying to download image: %s", resp.Status) + } + + destFile := fmt.Sprintf("%s/%s", destPath, filepath.Base(p.imageURL)) + out, err := os.Create(destFile) + if err != nil { + return destFile, fmt.Errorf("%s: %w", destFile, err) + } + defer out.Close() + + _, err = io.Copy(out, resp.Body) + if err != nil { + return destFile, err + } + + return destFile, nil +} + func findTitle(n *html.Node) (string, error) { var title string var traverse func(*html.Node) -- cgit v1.2.3