#!/usr/bin/env python

import requests
import json
from datetime import datetime, timedelta
from keen.client import KeenClient
from config import spire, keen

DAYS_AGO = 2
USER = 'tyin'

def main():
    print '[INFO] Getting raw spire data...'
    date = (datetime.today()-timedelta(days=DAYS_AGO)).strftime('%Y-%m-%d')
    breaths = get_spire(spire['breath'], date)
    print '[INFO] Uploading raw spire data...'
    client = KeenClient(
        project_id = keen['project_id'],
        read_key = keen['read_key'],
        write_key = keen['write_key']
    )
    data = {}
    data['breaths'] = [{'timestamp': b['timestamp'], 'value':b['value']} for b in breaths['data']]
    data['metadata'] = breaths['metadata']
    data['metadata']['min'] = min([b['value'] for b in breaths['data']])
    data['metadata']['max'] = max([b['value'] for b in breaths['data']])
    data['id'] = USER + date
    client.add_event('sessions', data)
    print '[INFO] Uploaded raw spire data for ' + date

def get_spire(what, date):
    url = spire['url'] + what + date
    token = spire['token']
    headers = {'Authorization': 'Bearer ' + token}
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    data = None
    try:
        data = response.json()
    except ValueError as e:
        print '[ERROR] ' + e
    return data

if __name__ == '__main__':
    main()

@@ -360,16 +360,64 @@
 , date)%0A
+    steps = get_spire(spire%5B'step'%5D, date)%0A    %0A
     prin
@@ -432,33 +432,30 @@
 %5D Uploading 
-raw spire
+breath
  data...'%0A  
@@ -452,24 +452,31 @@
 ata...'%0A    
+breath_
 client = Kee
@@ -511,16 +511,26 @@
 = keen%5B'
+breath'%5D%5B'
 project_
@@ -560,16 +560,26 @@
 = keen%5B'
+breath'%5D%5B'
 read_key
@@ -608,16 +608,26 @@
 = keen%5B'
+breath'%5D%5B'
 write_ke
@@ -644,26 +644,42 @@
     
-data = %7B%7D%0A    data
+keen_breaths = %7B%7D%0A    keen_breaths
 %5B'br
@@ -765,28 +765,36 @@
 data'%5D%5D%0A    
-data
+keen_breaths
 %5B'metadata'%5D
@@ -816,28 +816,36 @@
 adata'%5D%0A    
-data
+keen_breaths
 %5B'metadata'%5D
@@ -901,20 +901,28 @@
 %5D%5D)%0A    
-data
+keen_breaths
 %5B'metada
@@ -982,20 +982,28 @@
 %5D%5D)%0A    
-data
+keen_breaths
 %5B'id'%5D =
@@ -1052,13 +1052,22 @@
 s', 
-data)
+keen_breaths)%0A
 %0A   
@@ -1091,14 +1091,482 @@
 load
-ed raw
+ing step data...'%0A    breath_client = KeenClient(%0A        project_id = keen%5B'steps'%5D%5B'project_id'%5D,%0A        read_key = keen%5B'steps'%5D%5B'read_key'%5D,%0A        write_key = keen%5B'steps'%5D%5B'write_key'%5D%0A    )%0A    keen_steps = %7B%7D%0A    keen_steps%5B'steps'%5D = %5B%7B'timestamp': s%5B'timestamp'%5D, 'value':s%5B'value'%5D%7D for s in steps%5B'data'%5D%5D%0A    keen_steps%5B'metadata'%5D = steps%5B'metadata'%5D%0A    keen_steps%5B'id'%5D = USER + date%0A    client.add_event('sessions', keen_steps)%0A%0A    print '%5BINFO%5D Uploaded
  spi

add steps data