forked from yatsenkolesh/instagram-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinstagram.js
221 lines (202 loc) · 5.8 KB
/
instagram.js
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
/**
* @author Alex Yatsenko
* @link https://github.com/yatsenkolesh/instagram-nodejs
*/
"use-strict";
const fetch = require('node-fetch');
const formData = require('form-data');
module.exports = class Instagram
{
/**
* Constructor
*/
constructor(csrfToken, sessionId)
{
this.csrfToken = csrfToken
this.sessionId = sessionId
this.userAgent = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2900.1 Iron Safari/537.36'
this.userIdFollowers = {};
this.timeoutForCounter = 300
this.timeoutForCounterValue = 300
this.receivePromises = {}
}
/**
* User data by username
* @param {String} username
* @return {Object} Promise
*/
getUserDataByUsername(username)
{
return fetch('https://www.instagram.com/'+username+'/?__a=1').then(res => res.text().then(function(data)
{
return data;
}))
}
/**
* User followers list
* @param {Int} userId
* @param {String} command
* @param {String} Params
* @return {Object} array followers list
*/
getUserFollowers(userId, command, params, followersCounter, selfSelf)
{
const self = this
if((typeof self.receivePromises[userId] !== 'undefined' && self.receivePromises[userId] != 0) && !selfSelf)
return 0
command = !command ? 'first' : command
params = !params ? 20 : params
let queryString = 'followed_by.'+command+'('+params+') {';
let postBody= 'ig_user('+userId+') {'+queryString+'count,\
page_info {\
end_cursor,\
has_next_page\
},\
nodes {\
id,\
is_verified,\
followed_by_viewer,\
requested_by_viewer,\
full_name,\
profile_pic_url,\
username\
}\
}\
}'
let form = new formData();
form.append('q', postBody)
if(!this.userIdFollowers[userId])
this.userIdFollowers[userId] = []
self.receivePromises[userId] = 1
return fetch('https://www.instagram.com/query/',
{
'method' : 'post',
'body' : form,
'headers' :
{
'referer': 'https://www.instagram.com/',
'origin' : 'https://www.instagram.com',
'user-agent' : this.userAgent,
'x-instagram-ajax' : '1',
'x-requested-with' : 'XMLHttpRequest',
'x-csrftoken' : this.csrfToken,
cookie :' sessionid='+this.sessionId+'; csrftoken='+this.csrfToken
}
}).then(res =>
res.text().then(function(html)
{
//prepare convert to json
let json = html
console.log(json)
// console.log(json)
try
{
json = JSON.parse(json)
}
catch(e)
{
console.log('Session error')
return JSON.parse('{}');
}
if(json.status == 'ok')
self.userIdFollowers[userId] = self.userIdFollowers[userId].concat(json.followed_by.nodes)
else
console.log('Error handle user followers with id: ' + userId)
if(json.followed_by.page_info.has_next_page)
{
return new Promise((resolve) =>
{
let after = json.followed_by.page_info.end_cursor
if(json.followed_by.count > self.timeoutForCounter || json.status != 'ok')
setTimeout(() =>
{
resolve(self.getUserFollowers(userId, 'after', after + ',20',1,1 ))
}, self.timeoutForCounterValue)
else
resolve(self.getUserFollowers(userId, 'after', after + ',20',1,1))
},
(reject) =>
console.log('Error handle response from instagram server(get followers request)')
)
}
else
{
self.receivePromises[userId] = 0
return self.userIdFollowers[userId]
}
}).
catch((e) =>
{
console.log('Instagram returned:' + e)
})
)
}
/**
* Get csrf token
* @return {Object} Promise
*/
getCsrfToken()
{
return fetch('https://www.instagram.com',
{
'method' : 'get',
'headers' :
{
'referer': 'https://www.instagram.com/',
'origin' : 'https://www.instagram.com',
'user-agent' : this.userAgent,
}
}).then(
t =>
{
let cookies = t.headers._headers['set-cookie']
for(let i in cookies)
{
if(cookies[i].split('=')[0] == 'csrftoken')
return cookies[i].split(';')[0].replace('csrftoken=','')
}
}
).catch(() =>
console.log('Failed to get instagram csrf token')
)
}
/**
* Session id by usrname and password
* @param {String} username
* @param {String} password
* @return {Object} Promise
*/
auth(username, password)
{
let form = new formData();
form.append('username', username)
form.append('password', password)
return fetch('https://www.instagram.com/accounts/login/ajax/',
{
'method' : 'post',
'body' : form,
'headers' :
{
'referer': 'https://www.instagram.com/',
'origin' : 'https://www.instagram.com',
'user-agent' : this.userAgent,
'x-instagram-ajax' : '1',
'x-requested-with' : 'XMLHttpRequest',
'x-csrftoken': this.csrfToken,
cookie: 'csrftoken=' + this.csrfToken
}
}).then(
t =>
{
let cookies = t.headers._headers['set-cookie']
for(let i in cookies)
{
if(cookies[i].split('=')[0] == 'sessionid')
return cookies[i].split(';')[0].replace('sessionid=','')
}
}
).catch(() =>
console.log('Instagram authentication failed')
)
}
}