summaryrefslogtreecommitdiff
path: root/internal/platforms/linkedin/preview.go
blob: 54c24ba9dd113c4c49aab6d517f04b5d0cbd3e45 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package linkedin

import (
	"context"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"path/filepath"

	"codeberg.org/snonux/gos/internal/colour"
	"codeberg.org/snonux/gos/internal/config"
	"codeberg.org/snonux/gos/internal/oi"
	"golang.org/x/net/html"
)

var (
	errNoTitleElementFound = errors.New("no title element found")
	errNoImageElementFound = errors.New("no image element found")
)

type preview struct {
	title, thumbnailURL, thumbnailDownloadPath, url string
}

func NewPreview(ctx context.Context, args config.Args, urls []string) (preview, error) {
	var (
		p   preview
		err error
	)
	if len(urls) == 0 {
		return p, nil
	}
	p.url = urls[0]

	if p.title, p.thumbnailURL, err = extractFromURL(ctx, urls[0]); err != nil {
		if errors.Is(err, errNoTitleElementFound) || p.title == "" {
			colour.Infoln("Setting title to", urls[0])
			p.title = urls[0]
		}
		if errors.Is(err, errNoImageElementFound) {
			colour.Infoln("URL", urls[0], "is without any image, that's fine, though.")
		}
		if !errors.Is(err, errNoTitleElementFound) && !errors.Is(err, errNoImageElementFound) {
			colour.Infoln("Skipping LinkedIn preview metadata for", urls[0], "due to", err)
			return p, nil
		}
	}

	if p.thumbnailURL != "" {
		if p.thumbnailDownloadPath, err = p.DownloadImage(args.CacheDir); err != nil {
			colour.Infoln("Skipping LinkedIn preview image for", urls[0], "due to", err)
			p.thumbnailDownloadPath = ""
			return p, nil
		}
		colour.Infoln("Downloaded preview image to ", p.thumbnailDownloadPath)
	}
	return p, nil
}

func (p preview) String() string {
	if p.thumbnailURL != "" {
		return fmt.Sprintf("Title: %s; URL: %s, Image: %s", p.title, p.url, p.thumbnailURL)
	}
	return fmt.Sprintf("Title: %s; URL: %s", p.title, p.url)
}

func (p preview) TitleAndURL() (string, string, bool) {
	return p.title, p.url, p.url != "" && p.title != ""
}

func (p preview) Thumbnail() (string, bool) {
	return p.thumbnailDownloadPath, p.thumbnailDownloadPath != ""
}

func (p preview) DownloadImage(destPath string) (string, error) {
	// Skip data URIs - they can't be downloaded and don't provide meaningful images
	if u, err := url.Parse(p.thumbnailURL); err == nil && u.Scheme == "data" {
		colour.Infoln("Skipping data URI image, using article metadata instead")
		return "", nil
	}

	if err := oi.EnsureDir(destPath); err != nil {
		return "", err
	}
	resp, err := http.Get(p.thumbnailURL)
	if err != nil {
		return "", err
	}
	defer func() {
		if err := resp.Body.Close(); err != nil {
			// Log the error but don't fail the operation since we've already read the data
			colour.Errorln("Error closing response body:", err)
		}
	}()

	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.thumbnailURL))
	out, err := os.Create(destFile)
	if err != nil {
		return destFile, fmt.Errorf("%s: %w", destFile, err)
	}
	defer func() {
		if err := out.Close(); err != nil {
			// Log the error but don't fail the operation since we've already written the data
			colour.Errorln("Error closing output file:", err)
		}
	}()

	_, 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)
	traverse = func(n *html.Node) {
		if n.Type == html.ElementNode && n.Data == "title" {
			if n.FirstChild != nil {
				title = n.FirstChild.Data
			}
			return
		}
		for c := n.FirstChild; c != nil; c = c.NextSibling {
			traverse(c)
		}
	}
	traverse(n)
	if title == "" {
		return "", errNoTitleElementFound
	}
	return title, nil
}

func findFirstImage(n *html.Node) (string, error) {
	var imageURL string
	var traverse func(*html.Node) bool
	traverse = func(n *html.Node) bool {
		if n.Type == html.ElementNode && n.Data == "img" {
			for _, attr := range n.Attr {
				if attr.Key == "src" {
					imageURL = attr.Val
					return true // Stop searching when the first image's URL is found
				}
			}
		}
		for c := n.FirstChild; c != nil; c = c.NextSibling {
			if traverse(c) {
				return true
			}
		}
		return false
	}
	if !traverse(n) {
		return "", errNoImageElementFound
	}
	return imageURL, nil
}

func resolveURL(baseURL, rawURL string) (string, error) {
	base, err := url.Parse(baseURL)
	if err != nil {
		return "", fmt.Errorf("failed to parse base URL: %w", err)
	}
	u, err := url.Parse(rawURL)
	if err != nil {
		return "", fmt.Errorf("failed to parse raw URL: %w", err)
	}
	return base.ResolveReference(u).String(), nil
}

func extractFromURL(ctx context.Context, url string) (string, string, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return "", "", fmt.Errorf("failed to create request: %w", err)
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", "", fmt.Errorf("failed to get URL: %w", err)
	}
	defer func() {
		if err := resp.Body.Close(); err != nil {
			// Log the error but don't fail the operation since we've already read the data
			colour.Errorln("Error closing response body:", err)
		}
	}()

	if resp.StatusCode != http.StatusOK {
		return "", "", fmt.Errorf("failed to get a successful response: %v", resp.StatusCode)
	}

	return extract(url, resp.Body)
}

func extract(url string, htmlBody io.Reader) (string, string, error) {
	doc, err := html.Parse(htmlBody)
	if err != nil {
		return "", "", fmt.Errorf("failed to parse HTML: %w", err)
	}

	var errs error
	title, err := findTitle(doc)
	if err != nil {
		errs = errors.Join(errs, err)
	}

	imageURL, err := findFirstImage(doc)
	if err != nil {
		errs = errors.Join(errs, err)
	} else if imageURL != "" {
		if imageURL, err = resolveURL(url, imageURL); err != nil {
			errs = errors.Join(errs, err)
		}
	}

	return title, imageURL, errs
}