-
Notifications
You must be signed in to change notification settings - Fork 1
/
linkedin.go
326 lines (301 loc) · 7.9 KB
/
linkedin.go
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package external
import (
"bytes"
"encoding/json"
"fmt"
"github.com/PuerkitoBio/goquery"
"github.com/bitesinbyte/ferret/pkg/config"
"io"
"mime/multipart"
"net/http"
"net/url"
"os"
"strings"
)
const (
LinkedinCreatePostUrl = "https://api.linkedin.com/v2/posts"
LinkedinProfileUrl = "https://api.linkedin.com/v2/userinfo"
LinkedinImageUrl = "https://api.linkedin.com/rest/images?action=initializeUpload"
)
type Linkedin struct {
}
func (m Linkedin) Post(configData config.Config, post Post) error {
var accessToken = fmt.Sprintf("Bearer %s", os.Getenv("LINKEDIN_ACCESS_TOKEN"))
err, userInfo := fetchProfile(accessToken)
if err != nil {
return err
}
content := fmt.Sprintf("Just posted a new blog\n\n%s", post.HashTags)
err = createPost(configData, post, content, userInfo.Sub, accessToken)
return err
}
func createPost(configData config.Config, post Post, content string, authorId string, accessToken string) error {
err, thumbnail := getThumbnail(configData, post.Link, authorId, accessToken)
if err != nil {
return err
}
body, err := json.Marshal(linkedinPost{
Author: fmt.Sprintf("urn:li:person:%s", authorId),
Commentary: content,
ContentLandingPage: post.Link,
Visibility: "PUBLIC",
Distribution: struct {
FeedDistribution string `json:"feedDistribution"`
}{
FeedDistribution: "MAIN_FEED",
},
Content: struct {
Article postArticleContent `json:"article"`
}{
Article: postArticleContent{
Source: post.Link,
Thumbnail: thumbnail,
Title: post.Title,
Description: post.Description,
},
},
LifecycleState: "PUBLISHED",
ContentCallToActionLabel: "SEE_MORE",
})
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodPost, LinkedinCreatePostUrl, bytes.NewBuffer(body))
if err != nil {
return err
}
req.Header.Set("Authorization", accessToken)
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
panic(err)
}
}(resp.Body)
if resp.StatusCode != http.StatusCreated {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
return nil
}
type postArticleContent struct {
Source string `json:"source"`
Title string `json:"title"`
Description string `json:"description"`
Thumbnail string `json:"thumbnail"`
}
type linkedinPost struct {
Author string `json:"author"`
Commentary string `json:"commentary"`
Visibility string `json:"visibility"`
ContentLandingPage string `json:"contentLandingPage"`
Distribution struct {
FeedDistribution string `json:"feedDistribution"`
} `json:"distribution"`
Content struct {
Article postArticleContent `json:"article"`
} `json:"content"`
LifecycleState string `json:"lifecycleState"`
IsReshareDisabledByAuthor bool `json:"isReshareDisabledByAuthor"`
ContentCallToActionLabel string `json:"contentCallToActionLabel"`
}
// thumbnail
type initializeUploadResponse struct {
Value struct {
UploadUrlExpiresAt int64 `json:"uploadUrlExpiresAt"`
UploadUrl string `json:"uploadUrl"`
Image string `json:"image"`
} `json:"value"`
}
type initializeUploadRequest struct {
InitializeUploadRequest struct {
Owner string `json:"owner"`
} `json:"initializeUploadRequest"`
}
func getThumbnail(configData config.Config, articleUrl string, userId string, accessToken string) (error, string) {
err, initializeUpload := initializeUpload(accessToken, userId)
if err != nil {
return err, ""
}
err = uploadImage(articleUrl, configData, initializeUpload)
if err != nil {
return err, ""
}
return nil, initializeUpload.Value.Image
}
func getMetaOgHasRelativePath(imageUrl string, configData config.Config) string {
_, err := url.ParseRequestURI(imageUrl)
if err == nil {
return imageUrl
}
if configData.DoesMetaOgHasRelativePath {
imageUrl = configData.BaseUrl + imageUrl
}
_, err = url.ParseRequestURI(imageUrl)
if err != nil {
return ""
}
return imageUrl
}
func uploadImage(articleUrl string, configData config.Config, initializeUpload *initializeUploadResponse) error {
imageUrl, err := getOGImageURL(articleUrl, configData)
if err != nil {
return err
}
resp, err := http.Get(imageUrl)
if err != nil {
return err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
panic(err)
}
}(resp.Body)
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", imageUrl)
if err != nil {
return err
}
_, err = io.Copy(part, resp.Body)
if err != nil {
return err
}
err = writer.Close()
if err != nil {
return err
}
req, err := http.NewRequest("PUT", initializeUpload.Value.UploadUrl, body)
if err != nil {
return err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
client := &http.Client{}
resp, err = client.Do(req)
if err != nil {
return err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
panic(err)
}
}(resp.Body)
if resp.StatusCode != http.StatusCreated {
return fmt.Errorf("HTTP request failed with status code %d", resp.StatusCode)
}
return nil
}
// GetOGImageURL retrieves the og:image URL from the HTTP header of a given URL
func getOGImageURL(url string, configData config.Config) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
panic(err)
}
}(resp.Body)
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("HTTP request failed with status code %d", resp.StatusCode)
}
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return "", err
}
var ogImageURL string
doc.Find("meta").Each(func(i int, s *goquery.Selection) {
property, _ := s.Attr("property")
content, _ := s.Attr("content")
if strings.ToLower(property) == "og:image" {
ogImageURL = content
}
})
ogImageURL = getMetaOgHasRelativePath(ogImageURL, configData)
if ogImageURL == "" {
return "", fmt.Errorf("og:image tag not found in HTML head section")
}
return ogImageURL, nil
}
func initializeUpload(accessToken string, userId string) (error, *initializeUploadResponse) {
request := initializeUploadRequest{
InitializeUploadRequest: struct {
Owner string `json:"owner"`
}{
Owner: fmt.Sprintf("urn:li:person:%s", userId),
},
}
body, err := json.Marshal(request)
if err != nil {
return err, nil
}
req, err := http.NewRequest(http.MethodPost, LinkedinImageUrl, bytes.NewBuffer(body))
if err != nil {
return err, nil
}
req.Header.Set("Authorization", accessToken)
req.Header.Set("LinkedIn-Version", "202401")
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return err, nil
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
panic(err)
}
}(resp.Body)
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode), nil
}
var uploadResponse initializeUploadResponse
body, err = io.ReadAll(resp.Body)
if err != nil {
return err, nil
}
if err := json.Unmarshal(body, &uploadResponse); err != nil {
panic(err)
}
return nil, &uploadResponse
}
type userInfo struct {
Sub string `json:"sub"`
}
func fetchProfile(accessToken string) (error, *userInfo) {
req, err := http.NewRequest(http.MethodGet, LinkedinProfileUrl, nil)
if err != nil {
return err, nil
}
req.Header.Set("Authorization", accessToken)
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return err, nil
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode), nil
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
panic(err)
}
}(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return err, nil
}
var data userInfo
err = json.Unmarshal(body, &data)
if err != nil {
return err, nil
}
return nil, &data
}