-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClient.js
More file actions
301 lines (256 loc) · 9.92 KB
/
Client.js
File metadata and controls
301 lines (256 loc) · 9.92 KB
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
'use strict';
const EventEmitter = require('events');
const puppeteer = require('puppeteer');
const Util = require('./util/Util');
const { InstagramURL, UserAgent, DefaultOptions, Events, Selectors } = require('./util/Constants');
const igRaid = require('./util/igRaid');
const { ExposeStore } = require('./util/Injected');
const Message = require('./structures/Message');
const User = require('./structures/User');
class Client extends EventEmitter {
constructor(options = {}) {
super();
this.options = Util.mergeDefault(DefaultOptions, options);
this.pupBrowser = null;
this.pupPage = null;
}
async initialize() {
const browser = await puppeteer.launch(this.options.puppeteer);
const page = (await browser.pages())[0];
page.setUserAgent(UserAgent);
/**
* Making Browser available on scope
* @event Client#ready
*/
const that = this;
this.pupBrowser = browser;
this.pupPage = page;
/**
* Checking if session is alredy registered previously
*/
if (this.options.session) {
await page.setCookie(...this.options.session);
this.emit(Events.AUTHENTICATED);
/**
* Navigating to Instagram Home Page -
* It's important access initial instagram address for security issues and
* not be tracked as an crawler (param when sessionAuth)
*/
await page.goto(InstagramURL);
} else {
/**
* Navigating to Instagram Home Page -
* It's important access initial instagram address for security issues and
* not be tracked as an crawler (param when sessionAuth)
*/
await page.goto(InstagramURL);
/**
* Processing login steps,
* (1) - Open login form and wait fields load
* (2) - Fill userInformation
* (3) - Click Login Button
* (4) - Wait page navigation load
*/
await page.waitForSelector(Selectors.USERNAME, { timeout: 6000 });
await page.focus(Selectors.USERNAME);
await page.keyboard.type(this.options.credentials.username);
await page.focus(Selectors.PASSWORD);
await page.keyboard.type(this.options.credentials.password);
await page.click(Selectors.SUBMIT_LOGIN);
/**
* bypassing 2Factor autentication using aconecpt of another lib
* more info: https://github.com/joaomirandasa/headless2FA
* Here, this concept as used in addition to eventEmitter
*/
try {
await page.waitForSelector(Selectors.PAGE_LOADED, { timeout: 6000 });
await page.click(Selectors.BUTTON_BYPASS);
this.emit(Events.AUTHENTICATION_2FA);
var token2FA = await new Promise((resolve, reject) => {
that.on(Events.AUTHENTICATION_ANSWER, resolve);
});
await page.focus(Selectors.SECURITY_CODE);
await page.keyboard.type(token2FA);
await page.click(Selectors.SECURITY_CODE_2);
} catch (error) {
console.log("* 2Factor not detected *");
return true;
}
/**
* Checking if login procedue goes wrong
* verify if error message of credentials among other thing is showed
*/
try {
await page.waitForSelector(Selectors.TROUBLES, { timeout: 10000 });
this.emit(Events.AUTHENTICATION_FAILURE, 'Unable to log in. Are the session details valid?');
browser.close();
} catch (error) {
/**
* Getting Session information from browser
*/
const localStorage = JSON.parse(await page.evaluate(() => {
return JSON.stringify(window.localStorage);
}));
/**
* Getting Session information from browser
*/
const _sharedData = JSON.parse(await page.evaluate(() => {
return JSON.stringify(window._sharedData);
}));
/**
* Getting cookies to storage with session info
*/
const cookies = await page.cookies();
/**
* Emitted when authentication is successful
* @event Client#authenticated
* @param {object} session Object containing session information. Can be used to restore the session.
*/
this.emit(Events.AUTHENTICATED, {
localStorage: localStorage,
_sharedData: _sharedData,
cookies: cookies
});
/**
* Closing notification popUp if appear
*/
// await this._closeNotificationPopUp();
try {
await this.pupPage.waitForSelector(Selectors.NOTIFICATION_APPEAR, { timeout: 5000 });
await this.pupPage.click(Selectors.NOTIFICATION_CLOSE);
} catch (error) {
return true;
}
}
}
/**
* Waiting feed page load properlly guided by selector browser
*/
await page.waitForSelector(Selectors.ALREDY_LOADED, { timeout: 600000 });
/**
* (1) - Navigating to inbox page
* (2) - Wait inbox page load propperly guided by class and secure by timeout in case of something goes wrong
*/
await page.goto(InstagramURL+'direct/inbox/');
await page.waitForSelector(Selectors.INBOX, { timeout: 60000 });
/**
* Closing notification popUp if appear
*/
// await this._closeNotificationPopUp();
try {
await this.pupPage.waitForSelector(Selectors.NOTIFICATION_APPEAR, { timeout: 5000 });
await this.pupPage.click(Selectors.NOTIFICATION_CLOSE);
} catch (error) {
console.log("* popup not detected *");
}
/**
* Exposing functions from InjectedFile
*/
await page.evaluate(ExposeStore, igRaid.toString());
/**
* Register eventEmitter for Event
* @event Client#onAddMessageEvent
* @param {object} message object guided by constructor message.
*/
await page.exposeFunction('onAddMessageEvent', async msg => {
const self = this;
/*
* Important forEach - an event fired can contains more
* than one action or message, usefull for group
* simultaneous actions
*/
msg.data.forEach(function(dataItem){
const message = {
thread_id: msg.thread_id,
mutation_token: ( msg.mutation_token ? msg.mutation_token : null ),
body: new Message(self, dataItem).body,
user: new User(self, msg.user)
};
if(message.body.op == 'add'){
self.emit(Events.MESSAGE_RECEIVED, message);
} else {
self.emit(Events.MESSAGE_REVOKED_EVERYONE, message);
}
});
});
/**
* Exposing functions and connecting to eventEmitter
*/
await page.evaluate(() => {
window.openInsta.messageSync( window.onAddMessageEvent );
});
/**
* Emitted when the client has initialized and is ready to receive messages.
* @event Client#ready
*/
this.emit(Events.READY);
if(this.options.restartOnCrash) {
this.pupPage.on('error', async error => {
console.error('Page Crashed! Restarting...', error);
});
}
};
/**
* Closes the client
*/
async destroy() {
await this.pupBrowser.close();
};
/**
* Send like into an DM
* @param {string} thread_id
* @param {boolean} isTyping
* @param {object} options
* @returns {Promise<Like>} Like that was just sent
*/
async indicateTyping(thread_id, isTyping, options = {}) {
const newTyping = await this.pupPage.evaluate(async (thread_id, isTyping, options) => {
let typing;
typing = await window.openInsta.indicateTyping(thread_id, isTyping, options);
return typing
}, thread_id, isTyping, options);
return newTyping;
};
/**
* Send a message into an DM
* @param {string} thread_id
* @param {string|MessageMedia|Location} content
* @param {object} options
* @returns {Promise<Message>} Message that was just sent
*/
async sendMessage(thread_id, message, options = {}) {
const newMessage = await this.pupPage.evaluate(async (thread_id, message, options) => {
let msg;
msg = await window.openInsta.sendTextMessage(thread_id, message, options);
return msg
}, thread_id, message, options);
return newMessage;
};
/**
* Send like into an DM
* @param {string} thread_id
* @param {object} options
* @returns {Promise<Like>} Like that was just sent
*/
async sendLike(thread_id, options = {}) {
const newLike = await this.pupPage.evaluate(async (thread_id, options) => {
let like;
like = await window.openInsta.sendLike(thread_id, options);
return like
}, thread_id, options);
return newLike;
};
/**
* Get all current chat instances
* @returns {Promise<Array<Chat>>}
*/
async getInbox() {
const inbox = await this.pupPage.evaluate(async () => {
let inboxFetch;
inboxFetch = await window.openInsta.getInbox();
return inboxFetch;
});
return inbox;
};
}
module.exports = Client;