-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
289 lines (223 loc) · 6.18 KB
/
app.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
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
'use strict';
const rp = require('request-promise'),
$ = require('cheerio'),
request = require('request'),
moment = require('moment'),
fs = require('fs'),
_ = require('lodash');
const extractCookies = require('./util/extractCookies.js');
const LOGIN_COOKIE_FILENAME = 'logincookie.json';
const USER_INFO_FILENAME = 'user.json';
const MAX_TRIES = 900;
let commonInfo = {
userId:undefined,
flattenCookie: undefined
};
function persist(obj, filename) {
fs.writeFileSync(filename, JSON.stringify(obj), 'utf8');
}
function getObjectFromFile(filename) {
try {
return JSON.parse(fs.readFileSync(filename, 'utf8'));
}
catch(err) {
return undefined;
}
}
function requestFor(obj) {
let baseConfig = {
resolveWithFullResponse: true,
encoding: 'binary'
};
let config = Object.assign(baseConfig, obj);
return rp(config);
}
function requestForWithCookies(obj, flattenedCookies) {
let cookie = request.cookie(flattenedCookies);
let jar = request.jar();
jar.setCookie(cookie, 'http://boxcheckin.com.br');
let options = {
jar: jar,
resolveWithFullResponse: true,
encoding: 'binary'
};
let config = Object.assign(options, obj);
return rp(config);
}
const endpoints = {
base: 'http://boxcheckin.com.br',
login: 'Account/LogOn',
profile: 'Perfil',
checkInList: 'CheckIn/Index/?tipo_checkin=NOR',
checkIn: 'Create/?id_horario=1470&dt=26/10/2016&tipo_checkin=NOR'
};
function login(user, password) {
let data = {
url: `${endpoints.base}/${endpoints.login}`,
method: 'POST',
form: {
'UserName': user,
'Password': password,
'send': 'Entrar'
},
simple: false
};
console.log('step 1 - login');
return requestFor(data)
.then((result) => {
console.log('step 1 - fim login', result.statusCode);
if(result.complete && result.statusCode === 302) {
return getCookiesFromHeader(result.headers);
}
else throw 'error on login';
}).catch((err) => {
console.log('error on login', err);
});
}
function getCookiesFromHeader(headers) {
if (_.isObject(headers)) {
return extractCookies(headers['set-cookie']);
}
return {};
}
function openProfile(cookies) {
let data = {
url: `${endpoints.base}/${endpoints.profile}`,
followAllRedirects: true,
method: 'GET'
};
return requestForWithCookies(data, cookies).then((result) => {
let url = result.req.path.split('/');
let userId = url[url.length - 1];
console.log('userid = ' + userId);
return userId;
});
}
function getAvailableCheckins() {
let data = {
url: `${endpoints.base}/${endpoints.checkInList}`,
followAllRedirects: true,
method: 'GET',
transform: function(result) {
return $.load(result);
}
};
return requestForWithCookies(data, commonInfo.flattenCookie)
.then((jq) => {
let table = jq('table#dt_a tbody');
let trs = $('tr', table);
let result = [];
_.each(trs, (row) => {
let columns = $('td',row);
if(columns.length >= 2) {
result.push({
hour: $(columns[1]).text(),
link: $('a', columns[columns.length - 1]).attr('href')
});
}
});
return result;
});
}
function checkIn(targetUrl) {
let data = {
url: `${endpoints.base}/${targetUrl}`,
followAllRedirects: true,
method: 'POST',
form: {
id_aluno: commonInfo.userId,
data: moment().format('DD/MM/YYYY')
}
};
return requestForWithCookies(data, commonInfo.flattenCookie).then((result) => {
console.log('checkin done!');
}).catch((err) => {
console.log('fail to checkin');
});
}
function loadPersisted() {
let info = getObjectFromFile(LOGIN_COOKIE_FILENAME);
if(!info || !info.userId || !info.flattenCookie) {
return Promise.reject();
}
commonInfo = info;
console.log('loaded info from file');
return Promise.resolve();
};
//post com login para http://boxcheckin.com.br/Account/LogOn
/**
* UserName:jjlameira@gmail.com
Password:123456
send:Entrar
*/
//para pegar o id do aluno, http://boxcheckin.com.br/Aluno/Edit/126
// get http://boxcheckin.com.br/CheckIn/Index/?tipo_checkin=NOR
/**
* pegar a url do horario, para descobrir o id_horario e data
* /CheckIn/Create/?id_horario=1470&dt=26/10/2016&tipo_checkin=NOR
*/
/**
* post para CheckIn/Create/?id_horario=1470&dt=26/10/2016&tipo_checkin=NOR
*
* id_aluno:126
token_gympass:
* data:26/10/2016
*/
let userInfo = getObjectFromFile(USER_INFO_FILENAME);
if(!userInfo || !userInfo.login || !userInfo.password || !userInfo.target_hour)
{
console.log('error on user info file read');
return;
}
loadPersisted().catch(() => {
return login(userInfo.login, userInfo.password)
.then((result) => {
let flattenedCookies = _.join(_.values({
a:result['.ASPXAUTH'],
b:result['ARRAffinity'],
c:result['ASP.NET_SessionId']}), ';');
commonInfo.flattenCookie = flattenedCookies;
return flattenedCookies;
})
.then(openProfile)
.then((result) => commonInfo.userId = result)
.then(() => {
persist(commonInfo, LOGIN_COOKIE_FILENAME);
});
}).then(tryTocheckIn)
.catch(() => {
console.log('start to try between 500 seconds');
var counter = 0, dismissed = false;
return new Promise((resolve, reject) => {
let intervalId = setInterval(() => tryTocheckIn().then(() => {
clearInterval(intervalId);
console.log('finished!gratz!');
resolve();
}).catch(() => {
++counter;
console.log(`tried ${counter} times`);
if(counter > MAX_TRIES) {
if (!dismissed) {
console.log(`tried ${MAX_TRIES} times. dismiss`);
dismissed = true;
clearInterval(intervalId);
}
resolve();
}
}), 1000);
});
}).then(() => {
console.log('program finished.');
process.exit(0);
});
function tryTocheckIn(){
return getAvailableCheckins()
.then((availableHours) => {
let target = _.find(availableHours, (el) => el.hour === userInfo.target_hour);
if(!target) {
console.log('target hour not available');
throw 'target hour not available';
}
return target.link;
}).then(checkIn);
}