-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackup.php
executable file
·83 lines (74 loc) · 2.82 KB
/
backup.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
#!/usr/bin/php
<?php
include_once 'Fitbit.php';
include_once 'config.php';
$date = date("Y-m-d");
$period = new DatePeriod(
new DateTime(Config::$start_date),
new DateInterval('P1D'),
new DateTime(date("Y-m-d"))
);
$p2 = array();
foreach ($period as $key => $value) {
array_push($p2, $value->format('Y-m-d'));
}
$m = new PHPFitBit(Config::$client_id, Config::$client_secret, Config::$redirect_url);
$t = json_decode(file_get_contents("token.json"), true);
$m->set_tokens($t['access_token'], $t['refresh_token']);
function logs($msg)
{
$log = fopen(Config::$log, "ab");
$ts = gmdate("Y-m-d\TH:i:s\Z");
$ent = $ts . ": " . $msg . "\n";
fwrite($log, $ent);
fclose($log);
echo $ent;
}
function get_data($df)
{
$m = new PHPFitBit(Config::$client_id, Config::$client_secret, Config::$redirect_url);
$t = json_decode(file_get_contents("token.json"), true);
$m->set_tokens($t['access_token'], $t['refresh_token']);
$ep = array("activities/calories", "activities/caloriesBMR", "activities/steps", "activities/distance", "activities/floors", "activities/elevation", "activities/minutesSedentary", "activities/minutesLightlyActive", "activities/minutesFairlyActive", "activities/minutesVeryActive", "activities/activityCalories");
foreach ($ep as $i) {
$done = false;
$p = '/user/-/' . $i . '/date/' . $df . '/1d.json';
$aa = str_replace('activities/', "", $i);
$fn = $aa . "_" . $df . ".json";
while (!$done) {
$t = json_decode(file_get_contents("token.json"), true);
$m->set_tokens($t['access_token'], $t['refresh_token']);
$d2 = $m->get($p);
$done = ratecheck($m->headers, $m->last_http);
file_put_contents("./backup/" . $fn, json_encode($d2, JSON_PRETTY_PRINT));
logs("Writing file " . $fn);
}
}
}
function ratecheck($h, $r)
{
$resert = (int) $h['Fitbit-Rate-Limit-Reset'];
$cur = (int) $h["Fitbit-Rate-Limit-Remaining"];
if ($cur <= 10 || $r != 200) {
if ($r == 401) {
$m = new PHPFitBit(Config::$client_id, Config::$client_secret, Config::$redirect_url);
$t = json_decode(file_get_contents("token.json"), true);
$m->set_tokens($t['access_token'], $t['refresh_token']);
$t2 = $m->refresh();
file_put_contents("token.json", json_encode($t2));
sleep(10);
logs("Token Expired refreshing auth token. Wating 10 sec.");
return false;
}else{
logs("Sleeping for " . ($resert + 60) . " Sec at rate limit. Responce Code:" . $r . " Requests remaining:" . $cur);
sleep($resert + 60);
return false;
}
} else {
logs("Rate limit left " . $cur . " Keeping going");
return true;
}
}
foreach ($p2 as $p) {
get_data($p);
}