-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdexcomClient.js
265 lines (220 loc) · 8.98 KB
/
dexcomClient.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
'use strict';
import GLib from 'gi://GLib';
import Soup from 'gi://Soup';
import Gio from 'gi://Gio';
export class DexcomClient {
constructor(username, password, region = 'ous', unit = 'mg/dL') {
this._username = username;
this._password = password;
this._region = region.toLowerCase();
// Update base URLs and handling
this._baseUrls = {
'us': 'https://share2.dexcom.com',
'non-us': 'https://shareous1.dexcom.com',
'non_us': 'https://shareous1.dexcom.com',
'ous': 'https://shareous1.dexcom.com'
};
// Set base URL based on region
this._baseUrl = this._baseUrls[this._region] || this._baseUrls['ous'];
this._applicationId = 'd89443d2-327c-4a6f-89e5-496bbb0317db';
this._agent = 'Dexcom Share/3.0.2.11';
this._sessionId = null;
this._accountId = null;
this._unit = unit;
// Configure session
this._session = new Soup.Session();
this._session.timeout = 30;
// Debug info
console.log('DexcomClient initialized:', {
region: this._region,
baseUrl: this._baseUrl,
unit: this._unit
});
}
// Helper function to encode URI components safely
_encodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, c =>
'%' + c.charCodeAt(0).toString(16).toUpperCase()
);
}
// Helper function to build query string
_buildQueryString(params) {
return Object.keys(params)
.map(key => `${this._encodeURIComponent(key)}=${this._encodeURIComponent(params[key])}`)
.join('&');
}
// Update _makeRequest method
async _makeRequest(url, method = 'GET', data = null, params = null) {
try {
if (params) {
const queryString = Object.entries(params)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
url = `${url}?${queryString}`;
}
const message = new Soup.Message({
method,
uri: GLib.Uri.parse(url, GLib.UriFlags.NONE)
});
// Set headers
const headers = message.get_request_headers();
headers.append('Content-Type', 'application/json; charset=utf-8');
headers.append('Accept', 'application/json');
headers.append('User-Agent', this._agent);
// Add request body if provided and method is not GET
if (data && method !== 'GET') {
const jsonStr = JSON.stringify(data);
const bytes = new TextEncoder().encode(jsonStr);
message.set_request_body_from_bytes('application/json', new GLib.Bytes(bytes));
console.log(`Request body: ${jsonStr}`);
} else {
console.log('GET request - no body required');
}
const response = await this._session.send_and_read_async(message,
GLib.PRIORITY_DEFAULT, null);
const status = message.get_status();
const responseText = new TextDecoder().decode(response.get_data());
if (status === 200) {
try {
return JSON.parse(responseText);
} catch {
return responseText.replace(/^"|"$/g, '');
}
}
// Handle error responses
throw new Error(`Request failed with status ${status}: ${responseText}`);
} catch (error) {
console.error('Request failed:', error);
throw error;
}
}
async authenticate() {
try {
// Validate credentials
if (!this._username || !this._password) {
throw new Error('Username and password are required');
}
// Step 1: Authentication
const authUrl = `${this._baseUrl}/ShareWebServices/Services/General/AuthenticatePublisherAccount`;
const authPayload = {
accountName: this._username,
password: this._password,
applicationId: this._applicationId
};
console.log('Attempting authentication...');
this._accountId = await this._makeRequest(authUrl, 'POST', authPayload);
// Validate accountId
if (!this._accountId || typeof this._accountId !== 'string') {
throw new Error('Invalid account ID received');
}
// Step 2: Login
const loginUrl = `${this._baseUrl}/ShareWebServices/Services/General/LoginPublisherAccountById`;
const loginPayload = {
accountId: this._accountId,
password: this._password,
applicationId: this._applicationId
};
this._sessionId = await this._makeRequest(loginUrl, 'POST', loginPayload);
// Validate sessionId
if (!this._sessionId || this._sessionId === '00000000-0000-0000-0000-000000000000') {
throw new Error('Invalid session ID received');
}
console.log('Authentication successful');
return this._sessionId;
} catch (error) {
console.error('Authentication error:', error);
this._sessionId = null;
this._accountId = null;
throw error;
}
}
async getLatestGlucose() {
try {
if (!this._sessionId) {
await this.authenticate();
}
const url = `${this._baseUrl}/ShareWebServices/Services/Publisher/ReadPublisherLatestGlucoseValues`;
const params = {
sessionId: this._sessionId,
minutes: 1440,
maxCount: 1
};
console.log('Fetching latest glucose reading...');
const readings = await this._makeRequest(url, 'GET', null, params); // Changed to GET method
if (!Array.isArray(readings) || readings.length === 0) {
console.log('No readings available');
throw new Error('No readings available');
}
const reading = this._formatReading(readings[0]);
console.log('Latest reading:', reading);
return reading;
} catch (error) {
if (error.message.includes('SessionIdNotFound')) {
console.log('Session expired, re-authenticating...');
this._sessionId = null;
return this.getLatestGlucose();
}
throw error;
}
}
_formatReading(reading) {
// Calculate value based on unit
let value = reading.Value;
if (this._unit === 'mmol/L') {
value = (reading.Value / 18.0).toFixed(1);
}
// Calculate delta more accurately
let delta = 0;
if (this._previousReading && this._previousReading.Value !== reading.Value) {
const prevValue = this._unit === 'mmol/L' ?
(this._previousReading.Value / 18.0) :
this._previousReading.Value;
delta = value - prevValue;
} else {
// If trend is downward, estimate a negative delta
if (reading.Trend === 'SingleDown') {
delta = -2.0;
} else if (reading.Trend === 'DoubleDown') {
delta = -4.0;
} else if (reading.Trend === 'FortyFiveDown') {
delta = -1.0;
} else if (reading.Trend === 'SingleUp') {
delta = 2.0;
} else if (reading.Trend === 'DoubleUp') {
delta = 4.0;
} else if (reading.Trend === 'FortyFiveUp') {
delta = 1.0;
}
}
// Store current reading for next delta calculation
this._previousReading = {...reading};
// Normalize trend value
const trend = this._normalizeTrend(reading.Trend);
return {
value: value,
unit: this._unit,
trend: trend,
timestamp: new Date(parseInt(reading.WT.match(/\d+/)[0])),
delta: delta.toFixed(1)
};
}
// Helper function to normalize trend values
_normalizeTrend(trend) {
const trendMap = {
'NONE': 'NONE',
'DOUBLEUP': 'DOUBLE_UP',
'SINGLEUP': 'SINGLE_UP',
'FORTYFIVEUP': 'FORTY_FIVE_UP',
'FLAT': 'FLAT',
'FORTYFIVEDOWN': 'FORTY_FIVE_DOWN',
'SINGLEDOWN': 'SINGLE_DOWN',
'DOUBLEDOWN': 'DOUBLE_DOWN',
'NOTCOMPUTABLE': 'NOT_COMPUTABLE',
'RATEOUTOFRANGE': 'RATE_OUT_OF_RANGE'
};
const normalizedTrend = String(trend).toUpperCase()
.replace(/\s+/g, '')
.replace(/-/g, '');
return trendMap[normalizedTrend] || trend;
}
}