This repository has been archived by the owner on Mar 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
instagram.go
216 lines (175 loc) · 4.77 KB
/
instagram.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
// gostagram is an unofficial go client for
// the instagram api.
//
// note: there's two way to get the
// access token, using oauth2 golang library
// or using curl (both ways need a local server
// to get the token).
package gostagram
import (
"encoding/json"
"errors"
"fmt"
"net/url"
"strings"
"github.com/parnurzeal/gorequest"
)
const (
apiUrl = "https://api.instagram.com/v1/"
version = "1.0.0"
userAgent = "gostagram/v1"
)
var (
ClientSecretNotSetError = errors.New("Client secret not set for signed request.")
WrongInstagramEndpointError = errors.New("Wrong instagram endpoint.")
)
type Parameters map[string]string
type bodyData map[string]interface{}
type httpResponse map[string]interface{}
// Instagram client.
type Client struct {
clientId string // necesary to create subcriptions.
clientSecret string // necesary to send signed request.
access_token string
signedRequest bool
}
func NewClient(access_token string) *Client {
return &Client{
clientId: "",
clientSecret: "",
access_token: access_token,
signedRequest: false,
}
}
func (c *Client) SetClientId(id string) {
c.clientId = id
}
func (c *Client) SetClientSecret(cs string) {
c.clientSecret = cs
}
func (c *Client) SetSignedRequest(sr bool) {
c.signedRequest = sr
}
func (c Client) newRequest(method, uri string, res *httpResponse, dataToSend ...bodyData) error {
if c.signedRequest && len(c.clientSecret) == 0 {
return ClientSecretNotSetError
} else if c.signedRequest {
// if you plan to use signed request,
// you should check 'Enforce signed requests'
// option at instagram client settings.
//
// Right here, endpoint and query parameters are extracted
// from the url, to generate a hash and add it to the current url.
//
// Check this https://www.instagram.com/developer/secure-api-requests/
// for more information, about it.
tmpUrl, err := url.Parse(uri)
if err != nil {
return err
}
// deleting /v1 from endpoint.
endpoint := strings.Replace(tmpUrl.EscapedPath(), "/v1", "", 1)
// if endpoint ends in '/' character
// should be deleted to correctly generate signed request.
if endpoint[len(endpoint)-1] == '/' {
endpoint = endpoint[0 : len(endpoint)-1]
}
params := make(Parameters)
for paramName, paramValue := range tmpUrl.Query() {
params[paramName] = paramValue[0]
}
sig, err := c.generateSignature(endpoint, params)
if err != nil {
return err
}
uri = uri + "&sig=" + sig
}
// set gostagram user agent.
request := gorequest.New().Set("User-Agent", userAgent)
switch method {
case gorequest.POST:
request = request.Post(uri).Type("form")
// if there's some data to send,
// add it to the body.
if dataToSend != nil && len(dataToSend) > 0 {
request = request.SendMap(dataToSend[0])
}
break
case gorequest.GET:
request = request.Get(uri).Type("json")
break
case gorequest.DELETE:
request = request.Delete(uri).Type("json")
break
}
_, body, errs := request.EndBytes()
json.Unmarshal(body, &res)
if len(errs) > 0 {
return errs[0]
}
// checking if exists response content,
// if not, endpoint may be wrong.
if len(*res) > 0 {
var code int
var errorType string = ""
var errorMessage string = ""
// some responses may come with some
// meta information and some don't.
if (*res)["meta"] != nil {
meta := (*res)["meta"].(map[string]interface{})
code = int(meta["code"].(float64))
if code != 200 {
errorType = meta["error_type"].(string)
errorMessage = meta["error_message"].(string)
}
} else {
code = int((*res)["code"].(float64))
if code != 200 {
errorType = (*res)["error_type"].(string)
errorMessage = (*res)["error_message"].(string)
}
}
// if response code, ins't 200,
// an error need be returned with it's
// respective error message.
if code != 200 {
return fmt.Errorf("[%s]: %s", errorType, errorMessage)
}
} else {
return WrongInstagramEndpointError
}
return nil
}
func (c Client) get(url string) (*interface{}, *interface{}, error) {
var res httpResponse
err := c.newRequest(gorequest.GET, url, &res)
if err != nil {
return nil, nil, err
}
tmp := res["data"]
// check if response has pagination,
// if it has, return it along response data.
tmpPagination := res["pagination"]
if tmpPagination != nil {
return &tmp, &tmpPagination, nil
}
return &tmp, nil, nil
}
func (c Client) post(url string, dataToSend ...bodyData) (*interface{}, error) {
var res httpResponse
err := c.newRequest(gorequest.POST, url, &res, dataToSend...)
if err != nil {
return nil, err
}
tmp := res["data"]
return &tmp, nil
}
func (c Client) delete(url string) (*interface{}, error) {
var res httpResponse
err := c.newRequest(gorequest.DELETE, url, &res)
if err != nil {
return nil, err
}
tmp := res["data"]
return &tmp, nil
}