/
instagram_api.go
79 lines (64 loc) · 1.66 KB
/
instagram_api.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
package api
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"github.com/ailinykh/pullanusbot/v2/core"
)
// CreateInstagramAPI
func CreateInstagramAPI(l core.ILogger, cookie string) InstAPI {
return &InstagramAPI{l, cookie}
}
type InstAPI interface {
GetReel(string) (*IgReel, error)
}
// Instagram API
type InstagramAPI struct {
l core.ILogger
cookie string
}
func (api *InstagramAPI) GetReel(urlString string) (*IgReel, error) {
body, err := api.getContent(urlString, map[string]string{
"sec-fetch-mode": "navigate",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36",
"cookie": api.cookie,
"accept": "text/html",
})
if err != nil {
api.l.Error(err)
return nil, err
}
// os.WriteFile("instagram-reel.html", body, 0644)
r := regexp.MustCompile(`"xdt_api__v1__media__shortcode__web_info":(.*)\},"extensions"`)
match := r.FindSubmatch(body)
if len(match) < 2 {
return nil, fmt.Errorf("parse HTML failed: %s", urlString)
}
// os.WriteFile("instagram-reel.json", match[1], 0644)
var reel IgReel
err = json.Unmarshal(match[1], &reel)
if err != nil {
api.l.Error(err)
return nil, err
}
return &reel, nil
}
func (api *InstagramAPI) getContent(urlString string, headers map[string]string) ([]byte, error) {
req, err := http.NewRequest("GET", urlString, nil)
for k, v := range headers {
req.Header.Set(k, v)
}
if err != nil {
api.l.Error(err)
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
api.l.Error(err)
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}