forked from xartyx/minimed-connect-to-nightscout
-
Notifications
You must be signed in to change notification settings - Fork 1
/
carelink.js
179 lines (157 loc) · 4.51 KB
/
carelink.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
/* jshint node: true */
"use strict";
var _ = require('lodash'),
common = require('common'),
request = require('request');
var logger = require('./logger');
var DEFAULT_MAX_RETRY_DURATION = module.exports.defaultMaxRetryDuration = 512;
var CARELINK_SECURITY_URL = 'https://carelink.minimed.eu/patient/j_security_check';
var CARELINK_AFTER_LOGIN_URL = 'https://carelink.minimed.eu/patient/main/login.do';
var CARELINK_JSON_BASE_URL = 'https://carelink.minimed.eu/patient/connect/ConnectViewerServlet?cpSerialNumber=NONE&msgType=last24hours&requestTime=';
var CARELINK_LOGIN_COOKIE = '_WL_AUTHCOOKIE_JSESSIONID';
var carelinkJsonUrlNow = function() {
return CARELINK_JSON_BASE_URL + Date.now();
};
function reqOptions(extra) {
var defaults = {
jar: true,
followRedirect: false,
headers: {
Host: 'carelink.minimed.eu',
Connection: 'keep-alive',
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:41.0) Gecko/20100101 Firefox/41.0',
'Accept-Encoding': 'gzip,deflate,sdch',
'Accept-Language': 'en-US,en;q=0.8'
}
};
return _.merge(defaults, extra);
}
function haveLoginCookie(jar) {
return _.some(jar.getCookies(CARELINK_SECURITY_URL), {key: CARELINK_LOGIN_COOKIE});
}
function responseAsError(response) {
if (!(response.statusCode >= 200 && response.statusCode < 400)) {
return new Error(
"Bad response from CareLink: " +
JSON.stringify(_.merge(response, {'body': '<redacted>'}))
);
} else {
return null;
}
}
function checkResponseThen(fn) {
return function(err, response) {
err = err || responseAsError(response);
fn.apply(this, [err].concat(Array.prototype.slice.call(arguments, 1)));
};
}
function retryDurationOnAttempt(n) {
return Math.pow(2, n);
}
function totalDurationAfterNextRetry(n) {
var sum = 0;
for(var i = 0; i <= n; i++) {
sum += retryDurationOnAttempt(i);
}
return sum;
}
var Client = exports.Client = function (options) {
if (!(this instanceof Client)) {
return new Client(arguments[0]);
}
var jar = request.jar();
if (options.maxRetryDuration === undefined) {
options.maxRetryDuration = DEFAULT_MAX_RETRY_DURATION;
}
function doLogin(next) {
logger.log('POST ' + CARELINK_SECURITY_URL);
request.post(
CARELINK_SECURITY_URL,
reqOptions({
jar: jar,
qs: {j_username: options.username, j_password: options.password}
}),
checkResponseThen(next)
);
}
function doFetchCookie(response, next) {
logger.log('GET ' + CARELINK_AFTER_LOGIN_URL);
request.get(
CARELINK_AFTER_LOGIN_URL,
reqOptions({jar: jar}),
checkResponseThen(next)
);
}
function getConnectData(response, next, retryCount) {
var url = carelinkJsonUrlNow();
logger.log('GET ' + url);
var resp = request.get(
url,
reqOptions({jar: jar, gzip: true}),
checkResponseThen(function(err, response) {
if (err) {
logger.log(err);
if (retryCount === undefined ) {
retryCount = 0;
} else if (totalDurationAfterNextRetry(retryCount) >= options.maxRetryDuration) {
logger.log('Retried for too long (' + totalDurationAfterNextRetry(retryCount - 1) + ' seconds).');
next(err);
}
var timeout = retryDurationOnAttempt(retryCount);
logger.log('Trying again in ' + timeout + ' second(s)...');
setTimeout(function() {
getConnectData(response, next, retryCount + 1);
}, 1000 * timeout);
} else {
next(null, response);
}
})
);
}
function parseData(response, next) {
var parsed;
try {
parsed = JSON.parse(response.body);
} catch (e) {
next(e);
}
next(null, parsed);
}
function firstFetch(callback) {
common.step(
[
doLogin,
doFetchCookie,
getConnectData,
parseData,
callback.bind(null, null),
],
callback
);
}
function fetchLoggedIn(callback) {
common.step(
[
getConnectData,
parseData,
callback.bind(null, null),
],
function onError(err) {
logger.log('Fetch JSON failed; logging in again');
firstFetch(callback);
}
);
}
function fetch(callback) {
if (haveLoginCookie(jar)) {
fetchLoggedIn(callback);
} else {
logger.log('Logging in to CareLink');
firstFetch(callback);
}
}
return {
fetch: fetch
};
};