Class: RubyFitbit

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-fitbit.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(email, pass) ⇒ RubyFitbit

Returns a new instance of RubyFitbit.



11
12
13
14
15
16
17
# File 'lib/ruby-fitbit.rb', line 11

def initialize(email, pass)
  @email = email
  @pass = pass
  @agent = WWW::Mechanize.new #{|a| a.log = Logger.new(STDERR) } #turn on if debugging
  @logged_in = false 
  @cached_data = {}
end

Instance Attribute Details

#logged_inObject (readonly)

TODO change tests so reader isn’t needed



9
10
11
# File 'lib/ruby-fitbit.rb', line 9

def logged_in
  @logged_in
end

Instance Method Details

#get_activity_score_data(date = Time.now) ⇒ Object



202
203
204
# File 'lib/ruby-fitbit.rb', line 202

def get_activity_score_data(date = Time.now)
  get_graph_data('intradayActiveScore',date)
end

#get_aggregated_data(start_date = Time.now, end_date = Time.now) ⇒ Object



151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/ruby-fitbit.rb', line 151

def get_aggregated_data(start_date = Time.now, end_date = Time.now) 
  data = {}
  formatted_date = get_fitbit_date_format(end_date)
  data[formatted_date] = get_data(end_date)
  
  date = end_date + (24 * 60 * 60)
  while date < start_date
    formatted_date = get_fitbit_date_format(date)
    data[formatted_date] = get_data(date)
    date = date + (24 * 60 * 60)
  end

  data
end

#get_avg_data(start_date = Time.now, end_date = Time.now) ⇒ Object



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
# File 'lib/ruby-fitbit.rb', line 166

def get_avg_data(start_date = Time.now, end_date = Time.now) 
  data = {}
  data['calories'] = 0
  data['steps'] = 0
  data['miles_walked'] = 0
  # TODO these aren't numbers but times need to convert all to minutes and then back
  #data['sedentary_active'] = 0
  #data['lightly_active'] = 0
  #data['fairly_active'] = 0
  #data['very_active'] = 0
  days = 0
  
  days_data = get_aggregated_data(start_date, end_date) 
  days_data.keys.each do |key|
    days += 1
    current_data = days_data[key]
    data.keys.each do |stat|
      data[stat] += current_data[stat].to_f
    end
  end

  data.keys.each do |key|
    data[key] = (data[key]/days)
  end

  data
end

#get_calorie_data(date = Time.now) ⇒ Object



198
199
200
# File 'lib/ruby-fitbit.rb', line 198

def get_calorie_data(date = Time.now)
  get_graph_data('intradayCaloriesBurned',date)
end

#get_data(date = Time.now) ⇒ Object



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
# File 'lib/ruby-fitbit.rb', line 124

def get_data(date = Time.now)
  

  date = get_fitbit_date_format(date).gsub('-','/')
  return @cached_data[date] if @cached_data[date]

  page = @agent.get "https://www.fitbit.com/#{date}"

  calories = page.search("//div[@class='data']").search("span").children[0].text
  steps = page.search("//div[@class='data']").search("span").children[2].text.strip
  miles_walked = page.search("//div[@class='data']").search("span").children[3].text.strip
  sedentary_active = page.search("//div[@class='sedentary caption']/div[@class='number']").text.strip
  lightly_active = page.search("//div[@class='lightly caption']/div[@class='number']").text.strip
  fairly_active = page.search("//div[@class='caption fairly']/div[@class='number']").text.strip
  very_active = page.search("//div[@class='caption very']/div[@class='number']").text.strip
  data = {}
  data['calories'] = calories.to_i
  data['steps'] = steps.to_i
  data['miles_walked'] = miles_walked.to_f
  data['sedentary_active'] = sedentary_active
  data['lightly_active'] = lightly_active
  data['fairly_active'] = fairly_active
  data['very_active'] = very_active
  @cached_data[date] = data
  data
end

#get_eaten_calories(date = Time.now) ⇒ Object



113
114
115
116
117
118
119
120
121
122
# File 'lib/ruby-fitbit.rb', line 113

def get_eaten_calories(date = Time.now)
  

  date = get_fitbit_date_format(date).gsub('-','/')
  page = @agent.get "https://www.fitbit.com/foods/log/#{date}"
  calories_data = page.search("//div[@id='dailyTotals']").first
  calories_xml = calories_data.to_xml
  calories_text = calories_data.text
  {:calories_xml => calories_xml, :calories_text => calories_text}
end

#get_fitbit_date_format(date) ⇒ Object



235
236
237
238
# File 'lib/ruby-fitbit.rb', line 235

def get_fitbit_date_format(date)
  #fitbit date format expects like so: 2010-06-24
  date = date.strftime("%Y-%m-%d")
end

#get_food_items(food = "Coffe") ⇒ Object



106
107
108
109
110
111
# File 'lib/ruby-fitbit.rb', line 106

def get_food_items(food="Coffe")
  
  result = @agent.get "http://www.fitbit.com/solr/food/select?q=#{food}&wt=foodjson&qt=food"
  foods = JSON.parse(result.body).first[1]["foods"]
  foods
end

#get_graph_data(graph_type = 'intradaySteps', date = Time.now, data_version = '2108') ⇒ Object



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
# File 'lib/ruby-fitbit.rb', line 206

def get_graph_data(graph_type = 'intradaySteps', date = Time.now, data_version = '2108')
  

  date = get_fitbit_date_format(date)

  params = {:userId => @userId,
    :type => graph_type,
    :version => "amchart",
    :dataVersion => data_version,
    :chart_Type => "column2d",
    :period => "1d",
    :dateTo => date}

  params = WWW::Mechanize::Util.build_query_string(params)
  uri = "http://www.fitbit.com/graph/getGraphData?#{params}"

  page = @agent.get uri
  doc = Nokogiri::HTML(page.content)
  minutes_segment = 0
  chart_data = {}
  doc.xpath('//data/chart/graphs/graph/value').each do |ele|
    moment = Time.parse(date)+(5*60*minutes_segment)
    minutes_segment += 1
    chart_data[moment] = ele.child.text
  end 

  chart_data
end

#get_steps_data(date = Time.now) ⇒ Object



194
195
196
# File 'lib/ruby-fitbit.rb', line 194

def get_steps_data(date = Time.now)
  get_graph_data('intradaySteps',date)
end

#get_unit_id_for_unit(unit) ⇒ Object



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
# File 'lib/ruby-fitbit.rb', line 77

def get_unit_id_for_unit(unit)
  unit_id   = nil
  unit_type = unit.match(/\d+ (.*)/)[1]

  type_map = {'oz' => '226',
              'lb' => '180',
              'gram' => '147',
              'kilogram' => '389',
              'roll' => '290',
              'serving' => '304',
              'link' => '188',
              'piece' => '251',
              'fl oz' => '128',
              'ml' => '209',
              'tsp' => '364',
              'tbsp' => '349',
              'cup' => '91',
              'pint' => '256',
              'slice' => '311',
              'liter' => '189',
              'quart' => '279',
              'entree' => '117',
              'portion' => '270'
  }

  unit_id   = type_map[unit_type]
  unit_id
end

#loginObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/ruby-fitbit.rb', line 19

def 
  unless @logged_in
    page = @agent.get 'https://www.fitbit.com/login'
    
    form = page.forms.first
    form.email = @email
    form.password = @pass
    
    page = @agent.submit(form, form.buttons.first)
    
    @userId = page.search("//div[@class='accountLinks']").search("a")[0]['href'].gsub('/user/','')
    # @agent.cookie_jar.jar["www.fitbit.com"]['/']['uid'].value
    # @agent.cookie_jar.jar["www.fitbit.com"]['/']['sid'].value

    @logged_in = true
  end
end

#submit_food_log(options = {}) ⇒ Object



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
# File 'lib/ruby-fitbit.rb', line 37

def submit_food_log(options = {})
  

  date = options.fetch(:date) {Time.now}
  date = get_fitbit_date_format(date)
  meal_type = options.fetch(:meal_type){'7'}
  food_id = options[:food_id]
  food = options[:food]
  raise "food_id or food required to submit food log" unless food_id || food
  unless food_id
    food_recommendation = get_food_items(food)
    if food_recommendation.length > 0
      food_recommendation = food_recommendation.first
      food = food_recommendation['name']
      food_id = food_recommendation['id']
    end
  end

  unit_id = options[:unit_id]
  unit = options[:unit]
  raise "unit_id or unit required to submit food log" unless unit_id || unit
  unless unit_id
    unit_id = get_unit_id_for_unit(unit)
  end

  page = @agent.get 'http://www.fitbit.com/foods/log'

  form = page.forms[1]

  form.action="/foods/log/foodLog?apiFormat=htmljson&log=on&date=#{date}"
  form.foodId = food_id
  form.foodselectinput = food
  form.unitId = unit_id
  form.quantityselectinput = unit
  form.quantityConsumed = unit
  form.mealTypeId = meal_type
  
  result = @agent.submit(form, form.buttons.first)
end