This repository has been archived by the owner on Aug 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
237 lines (220 loc) · 6.19 KB
/
index.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
const moment = require('moment')
const bluebird = require('bluebird')
const cheerio = require('cheerio')
const {
log,
BaseKonnector,
saveBills,
request,
retry,
errors
} = require('cozy-konnector-libs')
let rq = request({
cheerio: true,
json: false,
jar: true,
// debug: true,
headers: {}
})
module.exports = new BaseKonnector(function fetch(fields) {
return retry(getToken, {
interval: 5000,
throw_original: true
})
.then(token => logIn(token, fields))
.then(() =>
retry(fetchBillsAttempts, {
interval: 5000,
throw_original: true,
// do not retry if we get the LOGIN_FAILED error code
predicate: err => err.message !== 'LOGIN_FAILED'
})
)
.then(entries =>
saveBills(entries, fields.folderPath, {
timeout: Date.now() + 60 * 1000,
identifiers: 'sfr'
})
)
.catch(err => {
// Connector is not in error if there is not entry in the end
// It may be simply an empty account
if (err.message === 'NO_ENTRY') return []
throw err
})
})
// Procedure to get the login token
function getToken() {
log('info', 'Logging in on Sfr RED Website...')
return rq(
'https://www.sfr.fr/cas/login?service=https://www.red-by-sfr.fr/accueil/j_spring_cas_security_check&theme=espaceclientred#redclicid=X_Menu_EspaceClient'
)
.then($ => {
if ($('.g-recaptcha').length) {
throw new Error(errors.CHALLENGE_ASKED)
}
return $
})
.then($ => $('input[name=lt]').val())
.then(token => {
log('debug', token, 'TOKEN')
if (!token) throw new Error('BAD_TOKEN')
return token
})
}
function logIn(token, fields) {
return rq({
method: 'POST',
url:
'https://www.sfr.fr/cas/login?domain=espaceclientred&service=https://www.red-by-sfr.fr/accueil/j_spring_cas_security_check#sfrclicid=EC_mire_Me-Connecter',
form: {
lt: token,
execution: 'e1s1',
_eventId: 'submit',
username: fields.login,
password: fields.password,
identifier: ''
}
})
.then($ => {
// check that the login is OK
const badLogin = $('#username').length > 0
if (badLogin) throw new Error('bad login')
})
.catch(err => {
log('warn', err.message, 'Error while logging in')
throw new Error('LOGIN_FAILED')
})
}
function fetchBillsAttempts() {
return fetchBillingInfo()
.then(parsePage)
.then(entries => {
if (entries.length === 0) throw new Error('NO_ENTRY')
return entries
})
}
function fetchBillingInfo() {
log('info', 'Fetching bill info')
return rq({
url: 'https://espace-client-red.sfr.fr/facture-mobile/consultation',
resolveWithFullResponse: true,
maxRedirects: 5 // avoids infinite redirection to facture-fixe if any
}).then(response => {
// check that the page was not redirected to another sfr service
if (
response.request.uri.path !== '/facture-mobile/consultation' ||
response.request.uri.hostname !== 'espace-client-red.sfr.fr'
) {
// this is the case where the user identified himself with other sfr login
log('error', 'This is not red mobile identifier')
throw new Error('LOGIN_FAILED')
}
return response.body
})
}
function parsePage($) {
const result = []
moment.locale('fr')
const baseURL = 'https://espace-client-red.sfr.fr'
const firstBill = $($('.sr-container-main > .sr-container-wrapper-m').get(0))
const firstBillUrl = $('#lien-telecharger-pdf').attr('href')
if (firstBillUrl) {
// The year is not provided, but we assume this is the current year or that
// it will be provided if different from the current year
let firstBillDate = firstBill
.find('.sr-container-content span > span')
.get(0)
firstBillDate = $(firstBillDate)
.text()
.trim()
firstBillDate = moment(firstBillDate, 'D MMM YYYY')
const price = firstBill
.find('.sr-text-25B')
.text()
.replace('€', '')
.replace(',', '.')
const bill = {
date: firstBillDate.toDate(),
amount: parseFloat(price),
fileurl: `${baseURL}${firstBillUrl}`,
filename: getFileName(firstBillDate),
vendor: 'SFR RED MOBILE'
}
result.push(bill)
} else {
log('info', 'wrong url for first PDF bill.')
}
let trs = Array.from($('table.sr-multi-payment tbody tr'))
function getMoreBills() {
// find some more rows if any
return rq(`${baseURL}/facture-mobile/consultation/plusDeFactures`)
.then($ => $('tr'))
.then($trs => {
if ($trs.length > trs.length) {
trs = Array.from($trs)
return getMoreBills()
} else return Promise.resolve()
})
}
return getMoreBills()
.then(() => {
return bluebird.mapSeries(trs, tr => {
let link = $(tr)
.find('td')
.eq(1)
.find('a')
if (link.length === 1) {
link = baseURL + link.attr('href')
return rq(link).then($ =>
$('.sr-container-wrapper-m')
.eq(0)
.html()
)
} else {
return false
}
})
})
.then(list => list.filter(item => item))
.then(list =>
list.map(item => {
const $ = cheerio.load(item)
const fileurl = $('#lien-duplicata-pdf-').attr('href')
const fields = $('.sr-container-content')
.eq(0)
.find('span:not(.sr-text-grey-14)')
const date = moment(
fields
.eq(0)
.text()
.trim(),
'DD MMMM YYYY'
)
const price = fields
.eq(1)
.text()
.trim()
.replace('€', '')
.replace(',', '.')
if (price) {
const bill = {
date: date.toDate(),
amount: parseFloat(price),
fileurl: `${baseURL}${fileurl}`,
filename: getFileName(date),
vendor: 'SFR RED MOBILE'
}
return bill
} else return null
})
)
.then(list => list.filter(item => item))
.then(bills => {
if (result.length) bills.unshift(result[0])
return bills
})
}
function getFileName(date) {
return `${date.format('YYYY_MM')}_SfrRed.pdf`
}