Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
auxlife authored Dec 31, 2016
1 parent 9cf2b50 commit 3b60d08
Show file tree
Hide file tree
Showing 5 changed files with 433 additions and 0 deletions.
34 changes: 34 additions & 0 deletions db.inc.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php
ini_set ('error_reporting', E_ALL);
ini_set ('display_errors', '1');
error_reporting (E_ALL|E_STRICT);


$dbc = mysqli_init();

function ConnectDB() {
$GLOBALS['dbc'] = mysqli_init();
mysqli_ssl_set($GLOBALS['dbc'],'dbcrt/client-key.pem', 'dbcrt/client-cert.pem', 'dbcrt/ca-cert.pem', 'dbcrt/ca.pem', NULL) ;
mysqli_real_connect($GLOBALS['dbc'], /*HOST*/, /*USERNAME*/, /*PASSWORD*/, 'xdrip', 3306, NULL, MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT);
if (!$GLOBALS['dbc'])
die('Could not connect to MySQL: ' . mysqli_connect_error() );
else
mysqli_set_charset($GLOBALS['dbc'], 'utf8');
return TRUE;
}
function DisconnectDB() {
return mysqli_close($GLOBALS['dbc']);
}
function InsertValue($DateString, $Type, $Value, $Payload) {
$query = "INSERT INTO `Data` (`DateString`, `Type`, `Value`, `Payload`, `Uploaded`) VALUES ('".$DateString."', '".$Type."', ".$Value.", '".$Payload."', NULL);";
return mysqli_query($GLOBALS['dbc'],$query);
}
function ConfirmUpload($Payload) {
$query = "UPDATE `Data` SET `Uploaded` = '".date('Y-m-d H:i:s')."' WHERE `Data`.`Payload` = '".$Payload."'";
return mysqli_query($GLOBALS['dbc'],$query);
}

function RunQuery($query) {
return mysqli_query($GLOBALS['dbc'],$query);
}
?>
75 changes: 75 additions & 0 deletions dbload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php
include_once "tidepool.inc.php";
error_reporting(E_ALL);

function sortByDate($a, $b) {
return $a['date'] - $b['date'];
}
function RandomString($Length)
{
$characters = str_split('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',1);
$randstring = array();
for ($i = 0; $i < $Length; $i++) {
$randstring[] = $characters[rand(0, count($characters)-1)];
}
return implode($randstring);
}
rename("v1/dexcom.data" , "v1/data.old");
$file = file_get_contents("v1/data.old");
$file = str_replace('[','',$file);
$file = explode("]",$file);
$json = array();
$data = array();
foreach ($file as $point) {
$json = explode("},",$point);
foreach ($json as $value) {
$value = $value."}";
if(substr( $value, 0, 25 ) === '{"device":"xDrip-DexcomG5'){
$data[] = json_decode($value, true);
}
}
}
unset($file,$json);
$array = array();
foreach ($data as $entry) {
if($entry["type"] == "sgv"){
switch($entry["noise"]){
case 0:
$entry["noise"] = "NONE";
break;
case 1:
$entry["noise"] = "CLEAN";
break;
case 2:
$entry["noise"] = "LIGHT";
break;
case 3:
$entry["noise"] = "MEDIUM";
break;
case 4:
$entry["noise"] = "HEAVY";
break;
case 6:
$entry["noise"] = "MAX";
break;
default:
$entry["noise"] = "NOT_COMPUTED";
}
$array[$entry["dateString"].$entry["type"].$entry["sgv"]] = $entry;
}
if($entry["type"] == "mbg")
$array[$entry["dateString"].$entry["type"].$entry["mbg"]] = $entry;
}
unset ($data);

usort($array, 'sortByDate');
ConnectDB();
foreach ($array as $entry) {
if($entry["type"] == "sgv")
echo InsertValue($entry["dateString"], $entry["type"], $entry["sgv"] , '"payload":{"internalTime":"'.GetDeviceTime($entry["dateString"]).'","delta":'.$entry["delta"].',"noiseMode":"'.$entry["noise"].'","trend":"'. $entry["direction"].'","value"'.ConvertToMmol($entry["sgv"]).'}');
if($entry["type"] == "mbg")
echo InsertValue($entry["dateString"], $entry["type"], $entry["mbg"] , '"payload":{"subType":"manual","time":"'.GetUTCTime($entry["dateString"]).'","timezoneOffset":'.GetUtcOffset().',"type":"smbg","units":"mmol/L","value":'.ConvertToMmol($entry["mbg"]).'}');
}
DisconnectDB();
rename("v1/data.old", "v1/olddata/".RandomString(12).".".RandomString(4));
?>
13 changes: 13 additions & 0 deletions dbupload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php
include_once "tidepool.inc.php";
error_reporting(E_ALL);
Login();
ConnectDB();
$results = RunQuery("SELECT * FROM `Data` WHERE `Uploaded` IS NULL ORDER BY `Data`.`DateString` ASC");
while ($row = mysqli_fetch_array($results)){
echo UploadBG($row["DateString"],$row["Type"],$row["Value"],$row["Payload"]);
ConfirmUpload($row["Payload"]);
}
DisconnectDB();
Logout();
?>
226 changes: 226 additions & 0 deletions tidepool.inc.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,226 @@
<?php
include_once "db.inc.php";
if(!set_time_limit(0))
die("Could not set infinite script timeout.");
error_reporting(E_ALL);
ini_set('display_errors', 'On');
date_default_timezone_set('America/Los_Angeles');
$baseurl = 'https://api.tidepool.org';
$loginHash = /*BASE64 of EMAIL:PASSWORD*/;
$deviceId = /*DEXCOM SERIAL*/;
$sessionStart = date(DATE_ATOM);
$sessionToken = FALSE;
$sessionData = array();
$UTCoffset = -480;

function CheckFile($filename) {
if(!file_exists($filename))
touch($filename);
return TRUE;
}

function Kill($string) {
echo '<h1><font color="red">Fatal Error!!</font><h1><br>'.$string;
die();
}

function ConvertToMgDl($value) {
return $value * 18.018018;
}

function ConvertToMmol($value) {
return $value / 18.018018;
}

function GetDeviceTime($value) {
$DT = strtotime($value);
return date('Y-m-d',$DT).'T'.date('H:i:s',$DT);
}

function GetUtcTime($value) {
$DT = strtotime($value);
$DT = $DT + ($GLOBALS['UTCoffset'] * -60);
return date('Y-m-d',$DT).'T'.date('H:i:s',$DT).".000Z";
}

function GetUtcOffset() {
return $GLOBALS['UTCoffset'];
}

function DownloadAllData() { // not working
$Querystring = 'METAQUERY WHERE emails CONTAINS ' . implode($GLOBALS['sessionData']['emails']) . 'QUERY TYPE IN basal, bolus, cbg, cgmSettings, deviceEvent, deviceMeta, pumpSettings, settings, smbg';
$url = $GLOBALS['baseurl'] . '/query/data';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('x-tidepool-session-token: ' . $GLOBALS['sessionToken'],'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $Querystring);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);
curl_close($ch);
file_put_contents("data_download.json", $response);
return $response;
}

function UploadBG($date, $type, $value) {
if($type == "sgv") {
$JSONstring = '{"uploadId":"'.GetUploadID().'","deviceId":"'.$GLOBALS['deviceId'].'","deviceTime":"'.GetDeviceTime($date).'","time":"'.GetUtcTime($date).'","timezoneOffset":'.$GLOBALS['UTCoffset'].',"type":"cbg","units":"mmol/L","value":'.ConvertToMmol($value).'}';
return UploadData($JSONstring);
}
if($type == "mbg") {
$JSONstring = '{"uploadId":"'.GetUploadID().'","deviceId":"'.$GLOBALS['deviceId'].'","deviceTime":"'.GetDeviceTime($date).'","time":"'.GetUtcTime($date).'","timezoneOffset":'.$GLOBALS['UTCoffset'].',"type":"smbg","subType":"manual","units":"mmol/L","value":'.ConvertToMmol($value).'}';
return UploadData($JSONstring);
}

}

function UploadData($JSONstring) {
$url = 'https://uploads.tidepool.org/data';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('x-tidepool-session-token: ' . $GLOBALS['sessionToken'],'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $JSONstring);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);
curl_close($ch);
if(GetHttpStatus($response) != 200)
{
Kill("Sorry the upload failed.<br>Request:<br>".$JSONstring."<br>Response:<br>".$response);
}
return TRUE;
}

function GetGroupIds(){ // needs repair
$url = $GLOBALS['baseurl'] . '/access/groups/' . $GLOBALS['sessionData']['userid'];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('x-tidepool-session-token: ' . $GLOBALS['sessionToken']));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}

function GetUploadID() {
return 'upid_' . substr(md5($GLOBALS['deviceId'] . '_' . $GLOBALS['sessionStart']),0, 12);
}

function GetHttpStatus($string) {
$StatusStart = 'HTTP/1.1 ';
$StatusEnd = PHP_EOL;
return SubString($string, $StatusStart, $StatusEnd);
}

function ExtractToken($string) {
$TokenStart = 'x-tidepool-session-token: ';
$TokenEnd = PHP_EOL;
return SubString($string, $TokenStart, $TokenEnd);
}

function GetJSON($string) {
$JSONStart = '{';
$JSONEnd = '}';
return '{' . SubString($string, $JSONStart, $JSONEnd) . '}';
}

function SubString($string, $start, $end) {
$string = substr($string, strpos($string, $start) + strlen($start));
return substr($string,0,strpos($string, $end));
}

function IsTokenValid() {
if($GLOBALS['sessionToken'] != FALSE)
{
$url = $GLOBALS['baseurl'] . '/auth/login';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('x-tidepool-session-token: ' . $GLOBALS['sessionToken']));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);
curl_close($ch);
if(GetHttpStatus($response) == 200)
{
$GLOBALS['sessionStart'] = date(DATE_ATOM);
return TRUE;
}
$GLOBALS['sessionToken'] = FALSE;
return FALSE;
}
return FALSE;
}

function LoadToken() {
if(!file_exists("tidepool.auth"))
return FALSE;
$response = file_get_contents("tidepool.auth");
$GLOBALS['sessionData'] = json_decode(GetJSON($response), true);
$GLOBALS['sessionToken'] = ExtractToken($response);
$GLOBALS['sessionStart'] = date(DATE_ATOM);
if(!IsTokenValid())
{
unlink("tidepool.auth");
return FALSE;
}
return TRUE;
}

function Login() {
if($GLOBALS['sessionToken'] == FALSE)
{
if(LoadToken())
return TRUE;
$url = $GLOBALS['baseurl'] . '/auth/login';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $GLOBALS['loginHash']));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);
curl_close($ch);
if(GetHttpStatus($response) != 200)
{
Kill("Sorry the login failed.<br>Response:<br>".$response);
}
$GLOBALS['sessionData'] = json_decode(GetJSON($response), true);
$GLOBALS['sessionToken'] = ExtractToken($response);
$GLOBALS['sessionStart'] = date(DATE_ATOM);
file_put_contents("tidepool.auth", $response);
return TRUE;
}
if(IsTokenValid())
return TRUE;
else
return Login();
return FALSE;
}

function Logout() {
LoadToken();
$url = $GLOBALS['baseurl'] . '/auth/logout';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('x-tidepool-session-token: ' . $GLOBALS['sessionToken']));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$response = curl_exec($ch);
curl_close($ch);
if(GetHttpStatus($response) != 200)
{
Kill("Sorry the logout failed.<br>Response:<br>".$response);
}
$GLOBALS['sessionToken'] = FALSE;
unlink("tidepool.auth");
return TRUE;
}

function GetToken() {
return $GLOBALS['sessionToken'];
}
?>
Loading

0 comments on commit 3b60d08

Please sign in to comment.