forked from hy/HyPoint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HyPoint.rb
2471 lines (1969 loc) · 84.2 KB
/
HyPoint.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:
#
# [XX] Text in pulse rate and record it into the Mongo NoSQL database
# [XX] Be able to call in to listen to the most recent checkin
# [XX] Possibly be able to graph the data historically
###############################################################################
# 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'
###############################################################################
# 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
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!] Constants Initialized'
end
if ENV['TWITTER_CONSUMER_KEY'] && ENV['TWITTER_CONSUMER_SECRET'] && \
ENV['TWITTER_ACCESS_TOKEN'] && ENV['TWITTER_ACCESS_TOKEN_SECRET']
begin
require 'twitter'
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!] Twitter Client Configured'
rescue Exception => e; puts "[BAD] Twitter config: #{e.message}"; end
end
if ENV['NEO4J_URL']
begin
note = 'NEO4j CONFIG via ENV var set via heroku addons:add neo4j'
require 'neography'
neo4j_uri = URI ( ENV['NEO4J_URL'] )
$neo = Neography::Rest.new(neo4j_uri.to_s)
http = Net::HTTP.new(neo4j_uri.host, neo4j_uri.port)
verification_req = Net::HTTP::Get.new(neo4j_uri.request_uri)
if neo4j_uri.user
verification_req.basic_auth(neo4j_uri.user, neo4j_uri.password)
end #if
response = http.request(verification_req)
abort "Neo4j down" if response.code != '200'
# console access via: heroku addons:open neo4j
puts("[OK!] Neo #{neo4j_uri},:#{neo4j_uri.user}:#{neo4j_uri.password}")
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!] Mongo Configured-via-URI #{CN.host_port} #{CN.auths}")
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!
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!] Mongo Connection Configured via separated env vars')
rescue Exception => e; puts "[BAD] Mongo config(M): #{e.message}"; end
end
if ENV['REDISTOGO_URL']
begin
note = 'CONFIG via ENV var 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!] Redis #{uri}")
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
puts '[OK!] Twilio Client Configured for: ' + ENV['TWILIO_CALLER_ID']
rescue Exception => e; puts "[BAD] Twilio 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!] SendGrid Options Configured"
rescue Exception => e; puts "[BAD] SendGrid 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!] Google API Configured with Scope Including:'
puts GClient.authorization.scope
rescue Exception => e; puts "[BAD] GoogleAPI 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 . . .
#
#############################################################################
graph "history", :prefix => '/plot' do
puts who = params['From'].to_s
puts ' (' + who.class.to_s + ')'
puts flavor = params['flavor']
cursor = DB['checkins'].find({ flavor => {'$exists' => true},
'ID' => params['From'] })
bg_a = Array.new
cursor.each{ |d|
bg_a.push(d[flavor])
}
bar 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
# Look how easy Redis is to use. . .
# 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
#############################################################################
# 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
get /\/c\/plot[:,\s]*(?<flavor>\w+)[:,\s]*/ix do
flavor = params[:captures][0]
link = SITE + 'plot/history.svg'
link += '?'
link += 'From=' + CGI::escape( params['From'] )
link += '&'
link += 'flavor=' + CGI::escape( flavor.downcase )
msg = "Link to your plot: " + link
send_SMS_to( params['From'], msg )
end #do get
#############################################################################
# User Role Setting and Configuration Routes
#############################################################################
# Authorize from a patient's phone, to enable a caregiver to get updates.
# We will use the to-be-Caller's(Caregiver's) number as the key to map
# to the Patient's phone number, to look up the checkin history...
#
# If we detect a leading '+' then we will +add+ what we expect to be
# a parent / guardian phone number to the auth list mapping...
#
# We sub out whitespace, parens, .'s and -'s from the entered phone number,
# so that (650) 324 - 5687 and 650-324-5687 and 650.324.5687 all work
#
# To insert into db, ensure 11 numerical digits, starting with a leading '+1'
# Since we use auth key as the '_id' save will function as an upsert
#
# Question: what if multiple caregivers inserted?
#############################################################################
get /\/c\/\+1?s*[-\.\(]?(\d{3})[-\.\)]*\s*(\d{3})\s*[\.-]*\s*?(\d{4})\z/x do
puts where = "AUTHORIZE NEW CAREGIVER ROUTE"
begin
authorization_string = ''
params[:captures].each {|match_group| authorization_string += match_group}
authorization_string= '+1' + authorization_string
if authorization_string.match(/\+1\d{10}\z/) == nil
reply_via_SMS( 'Please text, for example: +6505555555 (to add that num)' )
else
doc = {
'_id' => authorization_string,
'PatientID' => params['From'],
'CaregiverID' => authorization_string,
'utc' => @now_f
}
DB['groups'].save(doc) unless authorization_string == params['From']
DB['people'].update({'_id' => params['From']},
{'$set' => {'active_patient' => 'yes'}})
reply_via_SMS('You cannot register as your own parent!') if authorization_string == params['From']
reply_via_SMS( 'You have authorized: ' + authorization_string )
send_SMS_to( authorization_string, 'Authorized for: '+params['From'] )
end #if
rescue Exception => e
msg = 'Could not complete authorization'
reply_via_SMS( msg )
log_exception( e, where )
end
end #do authorization
get /\/c\/\-1?s*[-\.\(]?(\d{3})[-\.\)]*\s*(\d{3})\s*[\.-]*\s*?(\d{4})\z/x do
puts where = "DE-AUTHORIZE A CAREGIVER ROUTE"
begin
authorization_string = ''
params[:captures].each {|match_group| authorization_string += match_group}
authorization_string= '+1' + authorization_string
if authorization_string.match(/\+1\d{10}\z/) == nil
reply_via_SMS( 'Please text, for example: -6505555555' )
else
DB['groups'].remove({'CaregiverID' => authorization_string})
reply_via_SMS( 'You have de-authorized: ' + authorization_string )
send_SMS_to( authorization_string, 'De-Authorized for: '+params['From'] )
end #if
rescue Exception => e
msg = 'Could not complete de-authorization'
reply_via_SMS( msg )
log_exception( e, where )
end
end #do de-authorization
#############################################################################
# USER HELP MENU
#############################################################################
#
# Decide if it's a patient or caregiver who is requesting help and then
# forward them the approp. content. . .
#
#############################################################################
get /\/c\/help/x do
p_msg = 'HELP TOPICS: text Checkins, Config, or Feedback for info on each.'
c_msg = 'info=see settings; low67=low BG threshold at 67; high310=high threshold at 310; goal120=set 7 day goal to 120 pts; week=check stats'
msg = p_msg
msg = c_msg if DB['groups'].find_one({'CaregiverID' => params['From']})
reply_via_SMS( msg )
end # get help
get /\/c\/(help)?checkins/x do
msg_for_patient = 'bg123b = glucose 123 at breakfast; c20d = 20g carbs at dinner; n5L = 5U novolog at lunch; L4 = 4U lantus; score = see points'
reply_via_SMS( msg_for_patient )
end # Checkins help
get /\/c\/(help)?config/x do
msg_for_patient = 'alarm5 = set reminder at 5 hours; +16505551212 = add caregiver at that ph num; info = check settings'
reply_via_SMS( msg_for_patient )
end # Config help
get /\/c\/(help)?feedback/x do
msg_for_patient = 'Have unanswered questions or comments? Text/call 650-275-2901 and leave a message!'
reply_via_SMS( msg_for_patient )
end # Feedback help
#############################################################################
# Stop all msgs and take this user out of all of the collections
# (If either patient or caregiver issues this command, dis-enroll BOTH)
#############################################################################
get /\/c\/stop/ do
puts 'STOP ROUTE'
begin
DB['groups'].remove( {"CaregiverID"=>params['From']} )
DB['groups'].remove( {"PatientID"=>params['From']} )
DB['people'].remove( {"ID"=>params['From']} )
msg = 'OK! -- stopping all interactions and dis-enrolling both parties'
msg +=' (Re-register to re-activate)'
rescue Exception => e
msg = 'Could not stop scheduled texts'
log_exception( e, 'STOP ROUTE' )
end
reply_via_SMS( msg )
end #do resign
#############################################################################
# Delete all checkin data for this user in the system
#############################################################################
get /\/c\/delete/ do
puts 'DELETE ROUTE'
begin
authorization_string = params['From']
if authorization_string.match(/\+1\d{10}\z/) == nil
msg = 'Phone Number should be of the form: +16505551234'
else
DB['checkins'].remove({'ID' => authorization_string})
msg = 'Wiped out checkin history for: '+authorization_string
end
rescue Exception => e
msg = 'Could not delete all checkins'
log_exception( e, 'DELETE ROUTE' )
end
reply_via_SMS( msg )
end #do reset
#############################################################################
# Remove a caregiver from the groups collection to stop notices to them
#############################################################################
get /\/c\/resign/ do
puts 'CAREGIVER RESIGNATION ROUTE'
begin
DB['groups'].remove( {"CaregiverID"=>params['From']} )
msg = 'Stopped your notifications. '
msg += '(Type: ' + params['From'] + ' from patient phone to re-activate)'
rescue Exception => e
msg = 'Could not resign caregiver from updates'
log_exception( e, 'CAREGIVER RESIGNATION ROUTE' )
end
reply_via_SMS( msg )
end #do resign
#############################################################################
# Set a new goal and notify both patient and caregiver
#############################################################################
get /\/c\/goal[\s:\.,-=]*?(\d{2,4})\z/ do
puts "GOAL SETTING ROUTE"
begin
goal_f = Float(params[:captures][0])
ph_num = patient_ph_num_assoc_wi_caller
doc = {
'ID' => ph_num,
'Who' => params['From'],
'goal' => goal_f,
'utc' => @now_f
}
DB['checkins'].insert(doc)
msg = 'New 7-day goal of: ' + goal_f.to_s + ' -- Go for it!'
rescue Exception => e
msg = 'Could not update goal for '+ ph_num.to_s
log_exception( e, 'GOAL SETTING ROUTE' )
end
reply_via_SMS( msg )
ct_msg = 'New goal of: ' + goal_f.to_s
send_SMS_to( ph_num, ct_msg ) if ph_num != params['From']
end # do goal
#############################################################################
# Routes enabling either patient or caregiver to change the various settings
#############################################################################
get /\/c\/(hi)g?h?[\s:\.,-=]*(\d{3})\z/ do
begin
key = params[:captures][0]
puts "SETTINGS ROUTE FOR: " + key
new_f = Float(params[:captures][1])
ph_num = patient_ph_num_assoc_wi_caller
record = DB['people'].find_one({'_id' => ph_num})
id = record['_id']
DB['people'].update({'_id' => id},
{"$set" => {key => new_f}})
msg = 'New '+key.to_s+': ' + new_f.to_s + ' mg_per_dL'
rescue Exception => e
msg = 'Could not update setting for '+key.to_s
log_exception( e, 'HI SETTING ROUTE' )
end
send_SMS_to( ph_num, msg ) if ph_num != params['From']
reply_via_SMS( msg )
end #do hi settings
get /\/c\/(lo)w?[\s:\.,-=]*(\d{2})\z/ do
begin
key = params[:captures][0]
puts "SETTINGS ROUTE FOR: " + key
new_f = Float(params[:captures][1])
ph_num = patient_ph_num_assoc_wi_caller
record = DB['people'].find_one({'_id' => ph_num})
id = record['_id']
DB['people'].update({'_id' => id},
{"$set" => {key => new_f}})
msg = 'New '+key.to_s+': ' + new_f.to_s + ' mg_per_dL'
rescue Exception => e
msg = 'Could not update setting for '+key.to_s
log_exception( e, 'LO SETTING ROUTE' )
end
send_SMS_to( ph_num, msg ) if ph_num != params['From']
reply_via_SMS( msg )
end #do hi settings
get /\/c\/age[\s:\.,-=]*(\d{2})\z/ do
begin
key = params[:captures][0]
puts "SETTINGS ROUTE FOR: " + key
new_f = Float(params[:captures][1])
ph_num = patient_ph_num_assoc_wi_caller
record = DB['people'].find_one({'_id' => ph_num})
id = record['_id']
DB['people'].update({'_id' => id},
{"$set" => {key => new_f}})
msg = 'New '+key.to_s+': ' + new_f.to_s + ' years'
rescue Exception => e
msg = 'Could not update setting for '+key.to_s
log_exception( e, 'AGE SETTING ROUTE' )
end
send_SMS_to( ph_num, msg ) if ph_num != params['From']
reply_via_SMS( msg )
end #do hi settings
get /\/c\/(alarm)[\s:\.,-=]*(\d{1})\z/ do
begin
key = params[:captures][0]
puts "SETTINGS ROUTE FOR: " + key
new_f = Float(params[:captures][1])
ph_num = patient_ph_num_assoc_wi_caller
record = DB['people'].find_one({'_id' => ph_num})
id = record['_id']
DB['people'].update({'_id' => id},
{"$set" => {'alarm' => new_f}})
DB['people'].update({'_id' => id},
{"$set" => {'timer' => new_f}})
msg = 'New alarm threshold: ' + new_f.to_s + ' hours.'
rescue Exception => e
msg = 'Could not update setting for '+key.to_s
log_exception( e, 'ALARM SETTING ROUTE' )
end
send_SMS_to( ph_num, msg ) if ph_num != params['From']
reply_via_SMS( msg )
end #do hi settings
#############################################################################