forked from hy/HyWay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTheApp.rb
2944 lines (2336 loc) · 101 KB
/
TheApp.rb
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# TODO List:
# [--] http://www.wooptoot.com/file-upload-with-sinatra
# [--] Pick a consistent http client?
# http://www.slideshare.net/HiroshiNakamura/rubyhttp-clients-comparison
# MAILGUN on Heroku with rest-client references:
# https://github.com/rest-client/rest-client
# https://github.com/worldlywisdom/mazuma/blob/master/modules/mailer.rb
# http://documentation.mailgun.com/quickstart.html#sending-messages
# TrueVault
# TrueVault Ruby adapter: https://github.com/marks/truevault.rb
# TrueVault endpoints will look like:
# https://api.truevault.com/v1/vaults/<vault_id>/documents/<document_id>
# What we have done so far . . .
# [--] Go to https://proximity.gimbal.com/developer/transmitters
# [--] Name first beacon Hy1, factory code: 7NBP-BY85C
# [--] Key to Lat: 37.785525, Lon: -122.397581
# [--] TURN ON BLUETOOTH
# [--] Add a rule at: https://proximity.gimbal.com/developer/rules/new
# [--] More analytics: plot trend,
# [--] plot intervals (times between events),
# [--] Add a "____ help(s)(ed) ____ _____" route so folks can discover and then
# prototype their own reminder texts . . .
# [--] Consider ID key to int ne: String ('+17244489427' --> 17244489427)
# [--] Enable and Test broadcast to all caregivers
# [--] Enable and Test broadcast to all patients
# [--] Enable and Test broadcast to everyone
# [--] Enable and Test broadcast to dev's
# [--] Enable a way for parents to invite other parents
# [--] Think of a way for kids to interact in anonymous ways with other kids
###############################################################################
# Ruby Gem Core Requires -- this first grouping is essential
# (Deploy-to: Heroku Cedar Stack)
###############################################################################
require 'rubygems' if RUBY_VERSION < '1.9'
require 'sinatra/base'
require 'erb'
require 'sinatra/graph'
require 'net/http'
require 'uri'
require 'json'
require 'pony'
require 'haml'
require 'rest-client'
require 'httparty'
###############################################################################
# Optional Requires (Not essential for base version)
###############################################################################
# require 'temporals'
# require 'ri_cal'
# require 'tzinfo'
# If will be needed, Insert these into Gemfile:
# gem 'ri_cal'
# gem 'tzinfo'
# require 'yaml'
###############################################################################
# App Skeleton: General Implementation Comments
###############################################################################
#
# Here I do the 'Top-Level' Configuration, Options-Setting, etc.
#
# I enable static, logging, and sessions as Sinatra config. options
# (See http://www.sinatrarb.com/configuration.html re: enable/set)
#
# I am going to use MongoDB to log events, so I also proceed to declare
# all Mongo collections as universal resources at this point to make them
# generally available throughout the app, encouraging a paradigm treating
# them as if they were hooks into a filesystem
#
# Redis provides fast cache; SendGrid: email; Google API --> calendar access
#
# I am also going to include the Twilio REST Client for SMS ops and phone ops,
# and so I configure that as well. Neo4j is included for relationship
# tracking and management.
#
# Conventions:
# In the params[] hash, capitalized params are auto- or Twilio- generated
# Lower-case params are ones that I put into the params[] hash via this code
#
###############################################################################
class TheApp < Sinatra::Base
register Sinatra::Graph
enable :static, :logging, :sessions
set :public_folder, File.dirname(__FILE__) + '/static'
configure :development do
SITE = 'http://localhost:3000'
puts '____________CONFIGURING FOR LOCAL SITE: ' + SITE + '____________'
end
configure :production do
SITE = ENV['SITE']
puts '____________CONFIGURING FOR REMOTE SITE: ' + SITE + '____________'
end
@@services_available = {:twitter => false,
:graphene => false,
:mongo => false,
:redis => false,
:twilio => false,
:google => false,
:dropbox => false,
:sendgrid => false
}
configure do
begin
PTS_FOR_BG = 10
PTS_FOR_INS = 5
PTS_FOR_CARB = 5
PTS_FOR_LANTUS = 20
PTS_BONUS_FOR_LABELS = 5
PTS_BONUS_FOR_TIMING = 10
DEFAULT_POINTS = 2
DEFAULT_SCORE = 0
DEFAULT_GOAL = 500.0
DEFAULT_PANIC = 24
DEFAULT_HI = 300.0
DEFAULT_LO = 70.0
ONE_HOUR = 60.0 * 60.0
ONE_DAY = 24.0 * ONE_HOUR
ONE_WEEK = 7.0 * ONE_DAY
puts '[OK!] [1] Constants Initialized'
end
if ENV['TWITTER_CONSUMER_KEY'] && ENV['TWITTER_CONSUMER_SECRET'] && \
ENV['TWITTER_ACCESS_TOKEN'] && ENV['TWITTER_ACCESS_TOKEN_SECRET']
begin
require 'oauth'
consumer = OAuth::Consumer.new(ENV['TWITTER_CONSUMER_KEY'],
ENV['TWITTER_CONSUMER_SECRET'],
{ :site => "http://api.twitter.com",
:scheme => :header })
token_hash = {:oauth_token => ENV['TWITTER_ACCESS_TOKEN'],
:oauth_token_secret => ENV['TWITTER_ACCESS_TOKEN_SECRET']}
$twitter_handle = OAuth::AccessToken.from_hash(consumer, token_hash )
puts '[OK!] [2.1] Twitter Oauth Client Configured'
require 'twitter'
# Refer to https://github.com/sferik/twitter for usage
$twitter_client = Twitter::REST::Client.new do |config|
config.consumer_key = ENV['TWITTER_CONSUMER_KEY']
config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET']
config.access_token = ENV['TWITTER_ACCESS_TOKEN']
config.access_token_secret = ENV['TWITTER_ACCESS_TOKEN_SECRET']
end
puts '[OK!] [2.2] Twitter REST Client Configured'
@@services_available[:twitter] = true
rescue Exception => e; puts "[BAD] Twitter config: #{e.message}"; end
end
if ENV['GRAPHENEDB_URL']
begin
# NEO4j CONFIG via ENV var set via $ heroku addons:add graphenedb
# heroku addons:open graphenedb
# Heroku automatically sets up the GRAPHENEDB_URL environment variable
uri = URI.parse(ENV['GRAPHENEDB_URL'])
require 'neography'
$neo = Neography::Rest.new(ENV["GRAPHENEDB_URL"])
Neography.configure do |conf|
conf.server = uri.host
conf.port = uri.port
conf.authentication = 'basic'
conf.username = uri.user
conf.password = uri.password
end
query_results = $neo.execute_query("start n=node(*) return n limit 1")
puts('[OK!] [3] Graphene ' + query_results.to_s)
@@services_available[:graphene] = true
rescue Exception => e; puts "[BAD] Neo4j config: #{e.message}"; end
end
if ENV['MONGODB_URI']
begin
require 'mongo'
require 'bson' #Do NOT 'require bson_ext' just put it in Gemfile!
CN = Mongo::Connection.new
DB = CN.db
puts("[OK!] [4] Mongo Configured-via-URI #{CN.host_port} #{CN.auths}")
@@services_available[:mongo] = true
rescue Exception => e; puts "[BAD] Mongo config(1): #{e.message}"; end
end
if ENV['MONGO_URL'] and not ENV['MONGODB_URI']
begin
require 'mongo'
require 'bson' #Do NOT 'require bson_ext' just put it in Gemfile!
raise 'MONGO_URL provided, but one of MONGO_PORT, MONGO_USER_ID, or MONGO_PASSWORD is not present' unless ( ENV['MONGO_PORT'] && ENV['MONGO_USER_ID'] && ENV['MONGO_PASSWORD'])
CN = Mongo::Connection.new(ENV['MONGO_URL'], ENV['MONGO_PORT'])
DB = CN.db(ENV['MONGO_DB_NAME'])
auth = DB.authenticate(ENV['MONGO_USER_ID'], ENV['MONGO_PASSWORD'])
puts("[OK!] [4] Mongo Connection Configured via separated env vars")
@@services_available[:mongo] = true
rescue Exception => e
puts "[BAD] Mongo config(2): #{e.message}"
end
end
if ENV['MONGOLAB_URI'] and not ENV['MONGODB_URI'] and not ENV['MONGO_URL']
# To add mongo Lab to heroku, run: $ heroku addons:add mongolab
# To check out the settings, run: $ heroku addons:open mongolab
begin
require 'mongo'
mongo_uri = ENV['MONGOLAB_URI']
# The following parsing code comes from https://devcenter.heroku.com/articles/mongolab#connecting-to-your-mongodb-instance
db_name = mongo_uri[%r{/([^/\?]+)(\?|$)}, 1]
client = Mongo::MongoClient.from_uri(mongo_uri)
DB = client.db(db_name)
puts("[OK!] [4] Mongo Connection Configured via MongoLab environment variable")
@@services_available[:mongo] = true
rescue Exception => e
puts "[BAD] Mongo config(3): #{e.message}"
end
end
if ENV['MONGOHQ_URL'] and not ENV['MONGOLAB_URI'] and not ENV['MONGODB_URI'] and not ENV['MONGO_URL']
# This environment variable is set up by using the MongoHQ addon. Run: $ heroku addons:add mongolab
# To check out the settings, run: $ heroku addons:open mongolab
# Following https://devcenter.heroku.com/articles/mongohq for setup
begin
require 'mongo'
require 'uri'
db = URI.parse(ENV['MONGOHQ_URL'])
db_name = db.path.gsub(/^\//, '')
db_connection = Mongo::Connection.new(db.host, db.port).db(db_name)
db_connection.authenticate(db.user, db.password) unless (db.user.nil? || db.user.nil?)
DB = db_connection
puts("[OK!] [4] Mongo Connection Configured via MongoHQ environment variable")
@@services_available[:mongo] = true
rescue Exception => e
puts "[BAD] Mongo config(3): #{e.message}"
end
end
if ENV['REDISTOGO_URL']
begin
# Environment variable is set via $ heroku addons:add redistogo
require 'hiredis'
require 'redis'
uri = URI.parse(ENV['REDISTOGO_URL'])
REDIS = Redis.new(:host => uri.host, :port => uri.port,
:password => uri.password)
REDIS.set('CacheStatus', "[OK!] [5] Redis #{uri}")
@@services_available[:redis] = true
puts REDIS.get('CacheStatus')
rescue Exception => e; puts "[BAD] Redis config: #{e.message}"; end
end
if ENV['TWILIO_ACCOUNT_SID'] && ENV['TWILIO_AUTH_TOKEN']
begin
require 'twilio-ruby'
require 'builder'
$t_client = Twilio::REST::Client.new(
ENV['TWILIO_ACCOUNT_SID'], ENV['TWILIO_AUTH_TOKEN'] )
$twilio_account = $t_client.account
@@twilio_incoming_number = ENV['TWILIO_CALLER_ID']
@@twilio_incoming_number ||= $twilio_account.incoming_phone_numbers.list.first.phone_number
puts "[OK!] [6] Twilio Configured for: #{@@twilio_incoming_number}"
@@services_available[:twilio] = true
rescue Exception => e; puts "[BAD] Twilio config: #{e.message}"; end
end
# Store the calling route in GClient.authorization.state
# That way, if we have to redirect to authorize, we know how to get back
# to where we left off...
if ENV['GOOGLE_ID'] && ENV['GOOGLE_SECRET']
begin
require 'google/api_client'
options = {:application_name => ENV['APP'],
:application_version => ENV['APP_BASE_VERSION']}
GClient = Google::APIClient.new(options)
GClient.authorization.client_id = ENV['GOOGLE_ID']
GClient.authorization.client_secret = ENV['GOOGLE_SECRET']
GClient.authorization.redirect_uri = SITE + 'oauth2callback'
GClient.authorization.scope = [
'https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/tasks'
]
GClient.authorization.state = 'configuration'
RedirectURL = GClient.authorization.authorization_uri.to_s
GCal = GClient.discovered_api('calendar', 'v3')
puts '[OK!] [7] Google API Configured with Scope Including:'
puts GClient.authorization.scope
@@services_available[:google] = true
rescue Exception => e; puts "[BAD] GoogleAPI config: #{e.message}"; end
end
# remember to include rest-client in preparation for mailgun (!!!)
if ENV['MAILGUN_API_KEY'] && ENV['MAILGUN_DOMAIN']
begin
require 'rest-client'
require 'multimap'
puts 'Config block, mailgun section . . .'
puts "https://api:#{ENV['MAILGUN_API_KEY']}"\
"@api.mailgun.net/v2/samples.mailgun.org/messages"
RestClient.post "https://api:#{ENV['MAILGUN_API_KEY']}"\
"@#{ENV['MAILGUN_DOMAIN']}",
:from => 'Mailgun Sandbox <[email protected]>',
:to => "[email protected]",
:subject => "Hello",
:text => "Testing Mailgun awesomness thanks to code from Ben!"
puts '[OK!] [8] Mailgun test email sent (hopefully)'
rescue Exception => e; puts "[BAD] Mailgun test: #{e.message}"; end
end
# Access tokens from https://www.dropbox.com/developers/core/start/ruby
if ENV['DROPBOX_ACCESS_TOKEN']
begin
require 'dropbox_sdk'
$dropbox_handle = DropboxClient.new(ENV['DROPBOX_ACCESS_TOKEN'])
@@services_available[:dropbox] = true
puts '[OK!] [9] Dropbox Client Configured'
rescue Exception => e; puts "[BAD] Dropbox config: #{e.message}"; end
end
if ENV['SENDGRID_USERNAME'] && ENV['SENDGRID_PASSWORD']
begin
Pony.options = {
:via => :smtp,
:via_options => {
:address => 'smtp.sendgrid.net',
:port => '587',
:domain => 'heroku.com',
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:authentication => :plain,
:enable_starttls_auto => true
}
}
puts "[OK!] [10] SendGrid Options Configured"
@@services_available[:sendgrid] = true
rescue Exception => e; puts "[BAD] SendGrid config: #{e.message}"; end
end
end #configure
#############################################################################
# Sample Analytics
#############################################################################
#
# Plot everyone's BG values in the db so far.
#
# PLEASE NOTE: This route is Illustrative-Only; not meant
# to scale . . .
#
#############################################################################
# For Example, to view this graph, nav to:
# http://something-something-number.herokuapp.com/plot/history.svg
graph "history", :prefix => '/plot' do
puts who = params['From'].to_s
puts ' (' + who.class.to_s + ')'
puts flavor = params['flavor']
search_clause = { flavor => {'$exists' => true}, 'ID' => params['From'] }
count = DB['checkins'].find(search_clause).count
num_to_skip = (count > 20 ? count-20 : 0)
cursor = DB['checkins'].find(search_clause).skip(num_to_skip)
bg_a = Array.new
cursor.each{ |d|
bg_a.push(d[flavor])
}
line flavor, bg_a
end
#############################################################################
# Routing Code Filters
#############################################################################
#
# It's generally safer to use custom helpers explicitly in each route.
# (Rather than overuse the default before and after filters. . .)
#
# This is especially true since there are many different kinds of routing
# ops going on: Twilio routes, web routes, etc. and assumptions that are
# valid for one type of route may be invalid for others . . .
#
# So in the "before" filter, we just print diagnostics & set a timetamp
# It is worth noting that @var's changed or set in the before filter are
# available in the routes . . .
#
# A stub for the "after" filter is also included
# The after filter could possibly also be used to do command bifurcation
#
# Before every route, print route diagnostics & set the timetamp
# Look up user in db. If not in db, insert them with default params.
# This will ensure that at least default data will be available for every
# user, even brand-new ones. If someone IS brand-new, send disclaimer.
#
#############################################################################
before do
puts where = 'BEFORE FILTER'
begin
print_diagnostics_on_route_entry
@these_variables_will_be_available_in_all_routes = true
@now_f = Time.now.to_f
if params['From'] != nil
@this_user = DB['people'].find_one('_id' => params['From'])
if (@this_user == nil)
onboard_a_brand_new_user
@this_user = DB['people'].find_one('_id' => params['From'])
end #if
puts @this_user
end #if params
rescue Exception => e; log_exception( e, where ); end
end
after do
puts where = 'AFTER FILTER'
begin
rescue Exception => e; log_exception( e, where ); end
end
#############################################################################
# Routing Code Notes
#############################################################################
# Some routes must "write" TwiML, which can be done in a number of ways.
#
# The cleanest-looking way is via erb, and Builder and raw XML in-line are
# also options that have their uses. Please note that these cannot be
# readily combined -- if there is Builder XML in a route with erb at the
# end, the erb will take precedence and the earlier functionality is voided
#
# In the case of TwiML erb, my convention is to list all of the instance
# variables referenced in the erb directly before the erb call... this
# serves as a sort of "parameter list" for the erb that is visible from
# within the routing code
#############################################################################
get '/test' do
'Server is up! '
end
get '/services' do
response_string = ""
@@services_available.each do |service, status|
response_string = response_string + "#{service.to_s} is <b>#{status ? '<font color="blue">up</font>' : '<font color="red">down </font>' } </b><br>"
end
response_string
end
get '/sushi.json' do
content_type :json
return {:sushi => ["Maguro", "Hamachi", "Uni", "Saba", "Ebi", "Sake", "Tai"]}.to_json
end
get '/questions.json' do
content_type :json
return {:questions => ["Is [your baby] ready to eat?", "How hungry do you think [your baby] is?", "What is telling you [your baby] needs to eat?", "How did you know [your baby] was finished?", "Did [your baby] eat enough at this feed?"]}.to_json
end
# Shift to MongoDB when we have the time . . .
# Also, think about if we would need to put this into TrueVault, and,
# how much of that would we want to do and when?
# Three types of data: text, audio, video
# There will be intro text, and different types of Yes and No
# There may be a correct and an incorrect answer (T/F)
# Screen Title, then:
# Question text, audio clip / video poss. a
# Text for the "True" button, text for the "False" button
# Where to go if you got it right (link)
# Where to go if you get it wrong (link)
# For now let us just put something reasonable in json as an example
get '/example1.json' do
content_type :json
return {:question => ["Is there pain and swelling when you move your arm?"], :options => ["True", "False"], :correct_answer => "True", :if_correct_go => "http://serene-forest-4377.herokuapp.com/here", :if_wrong_go => "http://serene-forest-4377.herokuapp.com/there", :tags => ["Arm", "Pain", "Move", "Owies"]}.to_json
end
# For now serve some static content from the default pub folder
get '/here' do
send_file File.join(settings.public_folder,'broken_arm.gif')
end
get '/there' do
send_file File.join(settings.public_folder,'looks_broken_but_sprained.jpg')
end
get '/TestEO' do
puts temperature = params['temperature']
puts proximityRSSI = params['proximityRSSI']
puts battery = params['battery']
puts identifier = params['identifier']
end
get '/forgot' do
puts number = params['To']
puts "BAD PHONE NUMBER" if number.match(/\+1\d{10}\z/)==nil
puts msg = 'Can you please pick up the ' + params['What']
send_SMS_to( params['To'], params['What'] )
end
get '/ouch' do
send_SMS_to( '+17244489427', 'Ouch mom, too hot!' )
# send_SMS_to( params['To'], params['What'] )
end
# Let's give whatever we receive in the params to REDIS.set
get '/redisify' do
puts 'setting: ' + params['key']
puts 'to: ' + params['value']
REDIS.set(params['key'], params['value'])
end
# REDIS.get fetches it back. . .
get '/getfromredis' do
puts @value = REDIS.get(params['key'])
end
#############################################################################
# Other Physical Environment Sensing Examples
#############################################################################
#
# Sensor can detect vibration, magnetic proximity and/or moisture
#
#############################################################################
get '/magswitch_is_opened' do
puts where = "MAGNETIC SWITCH SENSOR OPENING ROUTE"
the_time_now = Time.now
event = {
'ID' => '+17244489427',
'utc' => the_time_now.to_f,
'flavor' => 'fridge',
'fridge' => 1.0,
'value_s' => '1.0',
'Who' => 'ZergLoaf BlueMeat',
'When' => the_time_now.strftime("%A %B %d at %I:%M %p"),
'Where' => where,
'What' => 'Door Magnet Sensor on fridge opened',
'Why' => 'Fridge main door opening'
}
puts DB['checkins'].insert( event, {:w => 1} )
end
get '/magswitch_is_closed' do
end
# Vibration sensor currently set at 63 milli-g sensitivity for freezer door
get '/vibration_sensor_starts_shaking' do
puts where = "VIBRATION SENSOR STARTS SHAKING ROUTE"
the_time_now = Time.now
event = {
'ID' => '+17244489427',
'utc' => the_time_now.to_f,
'flavor' => 'fridge',
'fridge' => 1.0,
'value_s' => '1.0',
'When' => the_time_now.strftime("%A %B %d at %I:%M %p"),
'Who' => 'ZergLoaf BlueMeat',
'Where' => where,
'What' => 'Vibration Sensor on top of fridge moved',
'Why' => 'Possible freezer door opening'
}
puts DB['checkins'].insert( event, {:w => 1} )
end
get '/vibration_sensor_stops_shaking' do
puts "VIBRATION SENSOR STOPS SHAKING ROUTE"
end
#############################################################################
# Voice Route to handle incoming phone call
#############################################################################
# Handle an incoming voice-call via TwiML
#
# At the moment this has two main use cases:
# [1] Allow a patient to verify their last check in
# [2] Avoid worry by making the last time and reading available to family
#
# Accordingly, first we look up the phone number to see who is calling
# If they have a patient in the system, we play info for that patient
# If they are a patient and have data we speak their last report
#
#############################################################################
get '/voice_request' do
puts "VOICE REQUEST ROUTE"
patient_ph_num = patient_ph_num_assoc_wi_caller
# last_level = last_glucose_lvl_for(patient_ph_num)
last_level = last_checkin_for(patient_ph_num)
if (last_level == nil)
@flavor_text = 'you'
@number_as_string = 'never '
@time_of_last_checkin = 'texted in.'
else
@number_as_string = last_level['value_s']
@flavor_text = last_level['flavor']
interval_in_hours = (Time.now.to_f - last_level['utc']) / ONE_HOUR
@time_of_last_checkin = speakable_hour_interval_for( interval_in_hours )
end #if
speech_text = 'Hi! The last checkin for'
speech_text += ' '
speech_text += @flavor_text
speech_text += ' '
speech_text += 'was'
speech_text += ' '
speech_text += @number_as_string
speech_text += ' '
speech_text += @time_of_last_checkin
response = Twilio::TwiML::Response.new do |r|
r.Pause :length => 1
r.Say speech_text, :voice => 'woman'
r.Pause :length => 1
r.Hangup
end #do response
response.text do |format|
format.xml { render :xml => response.text }
end #do response.text
end #do get
#############################################################################
# EXTERNALLY-TRIGGERED EVENT AND ALARM ROUTES
#############################################################################
#
# Whenever we are to check for alarm triggering, someone will 'ping' us,
# activating one of the following routes. . .
#
# Every ten minutes, check to see if we need to text anybody.
# We do this by polling the 'textbacks' collection for msgs over 12 min old
# If we need to send SMS, send them the text and remove the textback request
#
#############################################################################
get '/ten_minute_heartbeat' do
puts where = 'HEARTBEAT'
begin
REDIS.incr('Heartbeats')
cursor = DB['textbacks'].find()
cursor.each { |r|
if ( Time.now.to_f > (60.0 * 12.0 + r['utc']) )
send_SMS_to( r['ID'], r['msg'] )
DB['textbacks'].remove({'ID' => r['ID']})
end #if
}
h = REDIS.get('Heartbeats')
puts ".................HEARTBEAT #{h} COMPLETE.........................."
rescue Exception => e
msg = 'Could not complete ten minute heartbeat'
log_exception( e, where )
end
Time.now.to_s # <-- Must return a string for all get req's
end #do tick
get '/hourly_ping' do
puts where = 'HOURLY PING'
a = Array.new
begin
REDIS.incr('HoursOfUptime')
#DO HOURLY CHECKS HERE
h = REDIS.get('HoursOfUptime')
puts "------------------HOURLY PING #{h} COMPLETE ----------------------"
rescue Exception => e
msg = 'Could not complete hourly ping'
log_exception( e, where )
end
"One Hour Passes"+a.to_s # <-- Must return a string for all get req's
end #do get ping
get '/daily_refresh' do
puts where = 'DAILY REFRESH'
a = Array.new
begin
REDIS.incr('DaysOfUptime')
#DO DAILY UPKEEP TASKS HERE
d = REDIS.get('DaysOfUptime')
puts "==================DAILY REFRESH #{d} COMPLETE ===================="
rescue Exception => e
msg = 'Could not complete daily refresh'
log_exception( e, where )
end
"One Day Passes"+a.to_s # <-- Must return a string for all get req's
end
#############################################################################
# Google API routes
#
# Auth-Per-Transaction example:
#
# https://code.google.com/p/google-api-ruby-client/
# source/browse/calendar/calendar.rb?repo=samples
# https://code.google.com/p/google-api-ruby-client/wiki/OAuth2
#
# Refresh Token example:
#
# http://pastebin.com/cWjqw9A6
#
#
#############################################################################
get '/insert' do
where = 'ROUTE PATH: ' + request.path_info
begin
GClient.authorization.state = request.path_info
ensure_session_has_GoogleAPI_refresh_token_else_redirect()
puts cursor = DB['sample'].find({'location' => 'TestLand' })
insert_into_gcal_from_mongo( cursor )
GClient.authorization.state = '*route completed*'
rescue Exception => e; log_exception( e, where ); end
end
get '/quick_add' do
where = 'ROUTE PATH: ' + request.path_info
begin
GClient.authorization.state = request.path_info
ensure_session_has_GoogleAPI_refresh_token_else_redirect()
puts cursor = DB['sample'].find({'location' => 'TestLand' })
quick_add_into_gcal_from_mongo( cursor )
GClient.authorization.state = '*route completed*'
rescue Exception => e; log_exception( e, where ); end
end
get '/delete_all_APP_events' do
where = 'ROUTE PATH: ' + request.path_info
begin
GClient.authorization.state = request.path_info
ensure_session_has_GoogleAPI_refresh_token_else_redirect()
page_token = nil
result = GClient.execute(:api_method => GCal.events.list,
:parameters => {'calendarId' => 'primary', 'q' => 'APP_gen_event'})
events = result.data.items
puts events
events.each { |e|
GClient.execute(:api_method => GCal.events.delete,
:parameters => {'calendarId' => 'primary', 'eventId' => e.id})
puts 'DELETED EVENT wi. ID=' + e.id
}
rescue Exception => e; log_exception( e, where ); end
end #delete all APP-generated events
get '/list' do
ensure_session_has_GoogleAPI_refresh_token_else_redirect()
calendar = GClient.execute(:api_method => GCal.calendars.get,
:parameters => {'calendarId' => 'primary' })
print JSON.parse( calendar.body )
return calendar.body
end
# Request authorization
get '/oauth2authorize' do
where = 'ROUTE PATH: ' + request.path_info
begin
redirect user_credentials.authorization_uri.to_s, 303
rescue Exception => e; log_exception( e, where ); end
end
get '/oauth2callback' do
where = 'ROUTE PATH: ' + request.path_info
begin
GClient.authorization.code = params[:code]
results = GClient.authorization.fetch_access_token!
session[:refresh_token] = results['refresh_token']
redirect GClient.authorization.state
rescue Exception => e; log_exception( e, where ); end
end
#############################################################################
# SMS_request (via Twilio)
#############################################################################
#
# SMS routing essentially follows a command-line interface interaction model
#
# I get the SMS body, sender, and intended recipient (the intended recipient
# should obviously be this app's own phone number).
#
# I first archive the SMS message in the db, regardless of what else is done
#
# I then use the command as a route in this app, prefixed by '/c/'
#
# At this point, I could just feed the content to the routes... that's a bit
# dangerous, security-wise, though... so I will prepend with 'c' to keep
# arbitrary interactions from routing right into the internals of the app!
#
# So, all-in-all: add protective wrapper, downcase the message content,
# remove all of the whitespace from the content, . . .
# and then prepend with the security tag and forward to the routing
#
#############################################################################
get '/SMS_request' do
puts where = 'SMS REQUEST ROUTE'
begin
the_time_now = Time.now
puts info_about_this_SMS_to_log_in_db = {
'Who' => params['From'],
'utc' => the_time_now.to_f,
'When' => the_time_now.strftime("%A %B %d at %I:%M %p"),
'What' => params['Body']
}
puts DB['log'].insert(info_about_this_SMS_to_log_in_db, {:w => 1 })
# w == 1 means SAFE == TRUE
# can specify at the collection level, op level, and init level
c_handler = '/c/'+(params['Body']).downcase.gsub(/\s+/, "")
puts "SINATRA: Will try to use c_handler = "+c_handler
redirect to(c_handler)
rescue Exception => e; log_exception( e, where ); end
end #do get
#############################################################################
# Command routes are defined by their separators
# Command routes are downcased before they come here, in SMS_request
#
# Un-caught routes fall through to default routing
#
# Roughly, detect all specific commands first
# Then, detect more complex phrases
# Then, detect numerical reporting
# Finally, fall through to the default route
# Exceptions can occur in: numerical matching
# So, there must also be an exception route...
#############################################################################
get '/c/' do
puts "BLANK SMS ROUTE"
send_SMS_to( params['From'], 'Received blank SMS, . . . ?' )
end #do get
get '/c/hello*' do
puts "GREETINGS ROUTE"
send_SMS_to( params['From'], 'Hello, and Welcome!' )
end #do get
#############################################################################
# Free-Text Q&A: Questions from patients
#############################################################################
get /\/c\/q[:,\s]*(?<question>).*/ix do
puts "Got a FREETEXT Question to forward!!!"
q_text = params[:captures][0]
# Store the question, originating phone number, and overall question ord
the_time_now = Time.now
question = {
'utc' => the_time_now.to_f,
'Who' => params['From'],
'What' => q_text,
'When' => the_time_now.strftime("%A %B %d at %I:%M %p")
}
puts DB['questions'].insert( question, {:w => 1} )
puts q_text
# Use some method to generate a unique Question ID, ideally just ordinal?
ordinal = 1
# For now, put in a placeholder at q1 and don't increment it (yet)
# Also for now, put JOYCE_CELL == Steve_cell
JOYCE_CELL = '+17244489427'
fwd_text = 'M'+ordinal.to_s+': '+q_text
send_SMS_to(JOYCE_CELL, fwd_text)
end #do get
#############################################################################
# Free-Text Q&A: Replies from Joyce
#############################################################################
get /\/c\/r(?<replytonum>\d*)[:]+[\s]+(?<replytext>\S.*)/ix do
puts "Got a FREETEXT Response from Joyce to forward!!!"
replytonum = params[:captures][0].to_i
replytext = params[:captures][1].to_s
# Look up the ordinal in the db and send Joyce's reply the right phone num
# description of how to use ordinal as primary key: