-
Notifications
You must be signed in to change notification settings - Fork 0
/
garmin-connect-new.php
383 lines (316 loc) · 12.9 KB
/
garmin-connect-new.php
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
<?php
/**
* garmin-connect.php
*
* LICENSE: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @author David Wilcock <[email protected]> - original file author. See https://github.com/10REM/php-garmin-connect
* @author Karen Attfield <[email protected]> - stripped down file and minor modifications
* @package
*/
require_once('garmin-connect/connector.php');
require 'garmin-connect/exceptions/unexpected-response-code-exception.php';
class Garmin_Connect
{
/**
* @var string
*/
private $strUsername = '';
/**
* @var string
*/
private $strPassword = '';
/**
* @var Garmin_Connect\Connector|null
*/
private $objConnector = null;
/**
* Performs some essential setup
*
* @param array $arrCredentials
* @throws Exception
*/
public function __construct(array $arrCredentials = array())
{
// if (!isset($arrCredentials['username'])) {
// throw new Exception("Username credential missing");
// }
// $this->strUsername = $arrCredentials['username'];
// unset($arrCredentials['username']);
// $intIdentifier = md5($this->strUsername);
// $this->objConnector = new \Connector($intIdentifier);
// // If we can validate the cached auth, we don't need to do anything else
// // if ($this->checkCookieAuth()) {
// // return;
// // }
// if (!isset($arrCredentials['password'])) {
// throw new Exception("Password credential missing");
// }
// $this->strPassword = $arrCredentials['password'];
// unset($arrCredentials['password']);
// print_r('we are constructing');
// $this->authorize($this->strUsername, $this->strPassword);
if (!isset($arrCredentials['username'])) {
throw new Exception("Username credential missing");
}
$this->strUsername = $arrCredentials['username'];
unset($arrCredentials['username']);
$intIdentifier = md5($this->strUsername);
// Initialize the Connector instance with the unique identifier
$this->objConnector = new \Connector($intIdentifier);
if (!isset($arrCredentials['password'])) {
throw new Exception("Password credential missing");
}
$this->strPassword = $arrCredentials['password'];
unset($arrCredentials['password']);
// Call the authorize function to perform authentication
$this->authorize($this->strUsername, $this->strPassword);
}
/**
* Try to read the username from the API - if successful, it means we have a valid cookie, and we don't need to auth
*
* @return bool
* @throws Unexpected_Response_Code_Exception
*/
// private function checkCookieAuth()
// {
// if (strlen(trim($this->getUsername())) == 0) {
// $this->objConnector->cleanupSession();
// $this->objConnector->refreshSession();
// return false;
// }
// return true;
// }
/**
* Because there doesn't appear to be a nice "API" way to authenticate with Garmin Connect, we have to effectively spoof
* a browser session using some pretty high-level scraping techniques. The connector object does all of the HTTP
* work, and is effectively a wrapper for CURL-based session handler (via CURLs in-built cookie storage).
*
* @param string $strUsername
* @param string $strPassword
* @throws Authentication_Exception
* @throws Unexpected_Response_Code_Exception
*/
// private function authorize($strUsername, $strPassword)
// {
// print_r('anything');
// $arrParams = array(
// 'service' => 'https://connect.garmin.com/modern/',
// 'webhost' => 'https://connect.garmin.com',
// 'source' => 'https://connect.garmin.com/en-UK/signin',
// 'clientId' => 'GarminConnect',
// 'gauthHost' => 'https://sso.garmin.com/sso',
// 'consumeServiceTicket' => 'false'
// );
// $strResponse = $this->objConnector->get("https://sso.garmin.com/sso/login", $arrParams, true);
// print_r('str response is');
// print_r($strResponse);
// $strSigninUrl = "https://sso.garmin.com/sso/login?" . http_build_query($arrParams);
// if ($this->objConnector->getLastResponseCode() != 200) {
// throw new Exception(sprintf(
// "SSO prestart error (code: %d, message: %s)",
// $this->objConnector->getLastResponseCode(),
// $strResponse
// ));
// }
// // preg_match("/name=\"_csrf\" value=\"(.*)\"/", $strResponse, $arrCsrfMatches);
// // if (!isset($arrCsrfMatches[1])) {
// // throw new Exception("Unable to find CSRF input in login form");
// // }
// $arrData = array(
// "username" => $strUsername,
// "password" => $strPassword,
// "_eventId" => "submit",
// "embed" => "true",
// "displayNameRequired" => "false",
// // "_csrf" => $arrCsrfMatches[1],
// );
// print_r('come on over');
// $strResponse = $this->objConnector->post("https://sso.garmin.com/sso/login", $arrParams, $arrData, true, $strSigninUrl);
// print_r('lalala');
// print_r($strResponse);
// print_r('oh??');
// preg_match("/ticket=([^\"]+)\"/", $strResponse, $arrMatches);
// if (!isset($arrMatches[1])) {
// $strMessage = "Garmin authentication failed - please check your credentials";
// preg_match("/locked/", $strResponse, $arrLocked);
// if (isset($arrLocked[0])) {
// $strMessage = "Authentication failed, and it looks like your account has been locked. Please access https://connect.garmin.com to unlock";
// }
// // $this->objConnector->cleanupSession();
// throw new Exception($strMessage);
// }
// $strTicket = rtrim($arrMatches[0], '"');
// $arrParams = array(
// 'ticket' => $strTicket
// );
// $this->objConnector->post('https://connect.garmin.com/modern/', $arrParams, null, false);
// if ($this->objConnector->getLastResponseCode() != 302) {
// throw new Exception($this->objConnector->getLastResponseCode());
// }
// // should only exist if the above response WAS a 302 ;)
// $arrCurlInfo = $this->objConnector->getCurlInfo();
// $strRedirectUrl = $arrCurlInfo['redirect_url'];
// $this->objConnector->get($strRedirectUrl, null, true);
// if (!in_array($this->objConnector->getLastResponseCode(), array(200, 302))) {
// throw new Exception($this->objConnector->getLastResponseCode());
// }
// // Fires up a fresh CuRL instance, because of our reliance on Cookies requiring "a new page load" as it were ...
// $this->objConnector->refreshSession();
// }
private function authorize($strUsername, $strPassword)
{
$arrParams = array(
'service' => 'https://connect.garmin.com/modern/',
'webhost' => 'https://connect.garmin.com',
'source' => 'https://connect.garmin.com/en-UK/signin',
'clientId' => 'GarminConnect',
'gauthHost' => 'https://sso.garmin.com/sso',
'consumeServiceTicket' => 'false'
);
// Perform initial GET request
// $strResponse = $this->objConnector->get("https://sso.garmin.com/sso/login", $arrParams, true);
// if ($this->objConnector->getLastResponseCode() != 200) {
// throw new Exception(sprintf(
// "SSO prestart error (code: %d, message: %s)",
// $this->objConnector->getLastResponseCode(),
// $strResponse
// ));
// }
// Perform initial GET request
$strResponse = $this->objConnector->get("https://sso.garmin.com/sso/login", $arrParams, true);
//print_r($strResponse);
if ($this->objConnector->getLastResponseCode() != 200) {
// Log the error
error_log('SSO prestart error. Response code: ' . $this->objConnector->getLastResponseCode());
// Handle the error
throw new Exception(sprintf(
"SSO prestart error (code: %d, message: %s)",
$this->objConnector->getLastResponseCode(),
$strResponse
));
}
preg_match("/name=\"_csrf\" value=\"(.*)\"/", $strResponse, $arrCsrfMatches);
if (!isset($arrCsrfMatches[1])) {
throw new Exception("Unable to find CSRF input in login form");
}
$arrData = array(
"username" => $strUsername,
"password" => $strPassword,
"_eventId" => "submit",
"embed" => "true",
"displayNameRequired" => "false",
"_csrf" => $arrCsrfMatches[1],
);
// Perform POST request for login
$strResponse = $this->objConnector->post("https://sso.garmin.com/sso/login", $arrParams, $arrData, true, null);
//print_r($strResponse);
preg_match("/ticket=([^\"]+)\"/", $strResponse, $arrMatches);
if (!isset($arrMatches[1])) {
$strMessage = "Garmin authentication failed - please check your credentials";
preg_match("/\blocked\b/", $strResponse, $arrLocked);
if (isset($arrLocked[0])) {
print_r($strResponse);
$strMessage = "Authentication failed, and it looks like your account has been locked. Please access https://connect.garmin.com to unlock";
}
throw new Exception($strMessage);
}
$strTicket = rtrim($arrMatches[0], '"');
print_r($arrMatches[0]);
$arrParams = array(
'ticket' => $strTicket
);
// Perform POST request to connect.garmin.com
$this->objConnector->post('https://connect.garmin.com/modern/', $arrParams, null, false);
if ($this->objConnector->getLastResponseCode() != 302) {
throw new Exception($this->objConnector->getLastResponseCode());
}
// Fetch the location header from the response
$response_headers = $this->objConnector->getResponseHeaders();
$strRedirectUrl = isset($response_headers['location']) ? $response_headers['location'] : '';
if (empty($strRedirectUrl)) {
throw new Exception("Redirect URL not found in the response headers");
}
// Now use $strRedirectUrl to perform the follow-up request
$this->objConnector->get($strRedirectUrl, null, true);
if (!in_array($this->objConnector->getLastResponseCode(), array(200, 302))) {
throw new Exception($this->objConnector->getLastResponseCode());
}
// // Fetch redirect URL and follow it
// $arrCurlInfo = $this->objConnector->getCurlInfo();
// $strRedirectUrl = $arrCurlInfo['redirect_url'];
// $this->objConnector->get($strRedirectUrl, null, true);
// if (!in_array($this->objConnector->getLastResponseCode(), array(200, 302))) {
// throw new Exception($this->objConnector->getLastResponseCode());
// }
}
/**
* Gets a list of activities within a date range
*
* @param string $startDate
* @param string $endDate
* @param string $strActivityType
* @return mixed
* @throws Exception
*/
public function getActivityListByDate($startDate = '', $endDate = '', $strActivityType = null)
{
$arrParams = array();
if ('' !== $startDate) {
$arrParams['startDate'] = $startDate;
}
else {
return;
}
if ('' !== $endDate) {
$arrParams['endDate'] = $endDate;
}
if (null !== $strActivityType) {
$arrParams['activityType'] = $strActivityType;
}
$strResponse = $this->objConnector->get(
'https://connect.garmin.com/modern/proxy/activitylist-service/activities/search/activities',
$arrParams
);
if ($this->objConnector->getLastResponseCode() != 200) {
print_r('yeps');
throw new Exception($this->objConnector->getLastResponseCode());
}
$objResponse = json_decode($strResponse);
return $objResponse;
}
/**
* @return mixed
* @throws Unexpected_Response_Code_Exception
*/
public function getUser()
{
$strResponse = $this->objConnector->get('https://connect.garmin.com/modern/currentuser-service/user/info');
if ($this->objConnector->getLastResponseCode() != 200) {
throw new MapGarminActivities\Garmin_Connect\exceptions\Unexpected_Response_Code_Exception($this->objConnector->getLastResponseCode());
}
print_r('<pre>');
print_r($strResponse);
print_r('</pre>');
$objResponse = json_decode($strResponse);
return $objResponse;
}
/**
* @return mixed
* @throws Unexpected_Response_Code_Exception
*/
public function getUsername()
{
$objUser = $this->getUser();
if (!$objUser) {
return null;
}
return $objUser->username;
}
}