-
Notifications
You must be signed in to change notification settings - Fork 1
/
TheApp.rb
4649 lines (3677 loc) · 156 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
# ADD: Conf call, grat. hotline, friend-connector
# Serve CSV:
# https://gist.github.com/hy/6746a9fe455ec906dce4
#
# http://stackoverflow.com/questions/936249/stop-tracking-and-ignore-changes-to-a-file-in-git
# Cautionary Note:
# In May 2014, a gem was pulled, leading to:
# Could not find jwt-0.1.12 in any of the sources
# !
# ! Failed to install gems via Bundler.
# !
# Explanation of what happened and how to fix: (specify old version in gemfile)
# http://stackoverflow.com/questions/23526673/cannot-push-to-heroku-bundler-fails
# http://www.sitepoint.com/uno-use-sinatra-implement-rest-api/
# TODO List:
# [--] Waterfall the environment variables and other config (API keys etc.) as
# follows: read-from-ENV, then read-from-Mongo-and-overwrite conflicts
# [--] This means that Mongo config vars over-ride ENV ones
# [--] Then write a Makefile rule that syncs the local ENV *to* the mongo vars
# [XX] Switch DB to: https://app.mongohq.com/stephen-a-racunas-gmail-com/mongo/production/users
# [XX] 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 'haml'
require 'sinatra/graph'
require 'time'
require 'net/http'
require 'net/https'
require 'uri'
require 'json'
require 'pony'
require 'haml'
require 'httparty'
require 'csv'
###############################################################################
# Optional Requires (Not essential for base version)
###############################################################################
#require 'rest-client'
#require 'aws-sdk'
# 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
TWILIO_CALLER_ID = ENV['TWILIO_CALLER_ID']
# INDIA_CALLER_ID = '+917022216711'
# THIS IS NOW KATY'S NUMBER SO WILL WANT TO SWITCH THAT OUT
# SHAHED:
INDIA_CALLER_ID = '+918001030479'
# Indira (Kolkata NE work phone number)
KOLKATA_CALLER_ID = '+919830661199'
# For backup purposes, var's are here: (in prod, we read from Redis!)
AUDIO = 'http://grass-roots-science.info/audio/'
KOLKATA_ENGLISH_AUDIO = AUDIO + 'Kolkata_English_.mp3'
KOLKATA_HINDI_AUDIO = AUDIO + 'Kolkata_Hindi_.mp3'
KOLKATA_BENGALI_AUDIO = AUDIO + 'Kolkata_Bengali_.mp3'
KOLKATA_ENGLISH_CHOICE = AUDIO + 'RepeatInEnglishPress1.mp3'
KOLKATA_HINDI_CHOICE = AUDIO + 'RepeatInHindiPress2.mp3'
KOLKATA_BENGALI_CHOICE = AUDIO + 'RepeatInBengaliPress3.mp3'
# Language choices and estimated date-of-birth will be stored in a profile coll
# Pull env and constants from db as an option
PTS_FOR_BG = 5
PTS_FOR_INS = 5
PTS_FOR_CARB = 5
PTS_FOR_LANTUS = 5
PTS_BONUS_FOR_LABELS = 5
PTS_BONUS_FOR_TIMING = 5
DEFAULT_POINTS = 5
DEFAULT_SCORE = 0
DEFAULT_GOAL = 500.0
DEFAULT_PANIC = 24
DEFAULT_KET = 301.0
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
puts "[OK!] [6] Twilio Configured for: #{$twilio_account.incoming_phone_numbers.list.first.phone_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 before using 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!] [8] SendGrid Options Configured"
@@services_available[:sendgrid] = true
rescue Exception => e; puts "[BAD] SendGrid config: #{e.message}"; end
end
# Assuming by now we have SOME kind of connection to Mongo, we can fetch consts
# from there instead of hardcoding them locally.
# Assuming these are stored per-site-name, we fetch via:
puts 'Constants stored in Mongo:'
puts CM = DB[SITE].find_one()
# Over time, perhaps duplicate the consts section in this collection,
# backed up as a file at: ~/Dropbox/HyWay/constants.json and a redis file ?
puts 'Constants stored in Redis:'
puts CR = REDIS.get(SITE)
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_s = params['flavor']
search_clause = { flavor_s => {'$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_s])
}
line flavor_s, 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
# USUSALLY, (for incoming calls and texts) we will have a valid "From" param
# and onboarding is straightforwardly the correct thing to do
# HOWEVER, for outgoing calls, "From" is . . . the app itself!
if ((params['From'] != nil) && (params['From'] != TWILIO_CALLER_ID ))
@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 '/' do
'!!!!!!!!!!!!!!!!!!!!!!!! SERVER READY !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
end
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
# Based on https://gist.github.com/szabcsee/8523329,
get '/upload' do
haml :upload
end
# Handle POST-request (Receive and save the uploaded file)
post '/upload' do
fname = './tmp/' + params['thefile'][:filename]
File.open(fname, "w") do |f|
f.write(params['thefile'][:tempfile].read)
end
File.open(fname, "r") do |f|
puts f.read
# Roughly:
# [1] Pull out the extra lines at the top and bottom
# [2] Do some basic data integrity checks
# [3] Insert into Mongo
end
# CSV.foreach(fname, :headers => true) do |csv_obj|
# puts csv_obj['first'] #just to verify that parsing is working well
# DB[:prospects].insert( :first => cvs_obj['first'], :owner => csv_obj['owner'] )
# end
return "Successfully uploaded and parsed!"
end
post '/set_nh_msg' do
puts what_we_received = params['cmd']
DB['nh_msg'].remove()
DB['nh_msg'].insert({'words' => what_we_received})
puts DB['nh_msg'].find_one({})['words']
redirect 'http://serene-forest-4377.herokuapp.com/nh.noora_tracking.list'
end
get '/nh.*.list*' do
collection_to_list = (params[:splat][0]).downcase
if params[:splat][1].include?('.current') then
scope = { 'Discharge' => ''}
end
a = Array.new
DB[collection_to_list].find(scope).each { |row|
if row['CCphone'] != '' then
row['id'] = '+' + row['CCphone'].to_s
row['search_string'] = 'cardiothoracic ' + row['Surgery'].to_s
a.push(row)
end
}
@msg_suggest = 'Suggested Message goes here'
@label = collection_to_list.upcase + " LIST:"
@foo = a
erb :list
end # end get '/*.list' do
get '/nh.*.count' do
collection_to_list = (params[:splat][0]).downcase
scope = {}
puts "Getting numbers for: " + collection_to_list
@number = DB[collection_to_list].find().count()
erb :number
end #get
## Serve data as CSV file
get '/checkins.csv' do
collection_name = 'checkins'
cursor = DB[collection_name].find()
content_type 'application/csv'
attachment collection_name + ".csv"
keys = ["Phone", "mg/dL", "tag", "utc_time"]
csv_string = CSV.generate do |csv|
csv << keys
cursor.each{ |d|
csv << d.values
}
end
end
## This part starting to work
## Serve data as CSV file
get /(?<field_name>\w*)_(?<collection_name>\w*)(?<extension>_as_csv)/ix do
first_param = params[:captures][0]
field_name = first_param
field_name = "" if first_param == "all"
collection_name = params[:captures][1]
cursor = DB[collection_name].find()
# change this to:
content_type 'application/csv'
attachment collection_name + ".csv"
keys = ["heading1", "heading2", "heading3", "heading4"]
values1 = ["row1", "of1", "CSV1", "data1"]
values2 = ["row2", "of2", "CSV2", "data2"]
csv_string = CSV.generate do |csv|
csv << keys
cursor.each{ |d|
csv << d.values
}
end
end
## These may not yet work
post '/nh_sched' do
file_data = params[:file].read
csv_rows = CSV.parse(file_data, headers: true)
csv_rows.each do |row|
DB['outgoing'].insert( JSON.pretty_generate(row) )
end
end
get /TestLiberiaCall(?<ph_num>.*)/ do
# make a new outgoing call
$twilio_account.calls.create(
# :From => '+17244489427',
:From => INDIA_CALLER_ID,
# :From => '+16154427792',
# gather does not seem to work with this +1615 number?
:To => params['ph'],
:Url => SITE + 'handle_liberia_call',
:StatusCallbackMethod => 'GET',
:StatusCallback => SITE + 'status_callback_for_liberia'
)
end #get Call
# To accumulate stats:
# count up the number of responses to each question
# and also keep an array of which numbers answered each question how
post '/handle_liberia_call' do
Twilio::TwiML::Response.new do |r|
r.Gather :numDigits => '1', :action => '/gather_lib_1' do |g|
g.Play 'http://grass-roots-science.info/audio/libIntro2.mp3'
g.Play 'http://grass-roots-science.info/audio/libQ1.mp3'
end
end.text
end #handle_liberia_call
post '/gather_lib_1' do
puts '/GATHER_LIB_1 \n WITH PARAMS= ' + params.to_s
d = DB['liberia'].find_one({'Phone Number' => params['To'].to_i})
d['A1'] = params['Digits'].to_s
DB['liberia'].update({'Phone Number' => params['To'].to_i}, d)
count_s = 'libQ1A' + params['Digits'].to_s
key = count_s +'_voters'
value = params['To']
REDIS.sadd key, value
REDIS.incr count_s
response = Twilio::TwiML::Response.new do |r|
r.Gather :numDigits => '1', :action => '/gather_lib_2' do |g|
g.Play 'http://grass-roots-science.info/audio/libQ2.mp3'
end
end
response.text do |format|
format.xml { render :xml => response.text }
end #do response.text
end
post '/gather_lib_2' do
puts '/GATHER_LIB_2 \n WITH PARAMS= ' + params.to_s
d = DB['liberia'].find_one({'Phone Number' => params['To'].to_i})
d['A2'] = params['Digits'].to_s
DB['liberia'].update({'Phone Number' => params['To'].to_i}, d)
count_s = 'libQ2A' + params['Digits'].to_s
key = count_s +'_voters'
value = params['To']
REDIS.sadd key, value
REDIS.incr count_s
response = Twilio::TwiML::Response.new do |r|
r.Gather :numDigits => '1', :action => '/gather_lib_3' do |g|
g.Play 'http://grass-roots-science.info/audio/libQ3.mp3'
end
end
response.text do |format|
format.xml { render :xml => response.text }
end #do response.text
end
post '/gather_lib_3' do
puts '/GATHER_LIB_3 \n WITH PARAMS= ' + params.to_s
d = DB['liberia'].find_one({'Phone Number' => params['To'].to_i})
d['A3'] = params['Digits'].to_s
DB['liberia'].update({'Phone Number' => params['To'].to_i}, d)
count_s = 'libQ3A' + params['Digits'].to_s
key = count_s +'_voters'
value = params['To']
REDIS.sadd key, value
REDIS.incr count_s
response = Twilio::TwiML::Response.new do |r|
r.Play 'http://grass-roots-science.info/audio/libWrap2.mp3'
end
response.text do |format|
format.xml { render :xml => response.text }
end #do response.text
end
get /OldStyleTestCall(?<ph_num>.*)/ do
puts params['ph']
# make a new outgoing call
@call = $twilio_account.calls.create(
:From => INDIA_CALLER_ID,
:To => params['ph'],
:Url => SITE + 'call-handler',
:StatusCallbackMethod => 'GET',
:StatusCallback => SITE + 'status_callback_for_outgoing_calls'
)
# Auto-redirects to :url => [call-handler, below]
end #get Call
get /OneKolkataCall(?<ph_num>.*)/ do
puts params['ph']
# make a new outgoing call
@call = $twilio_account.calls.create(
:From => KOLKATA_CALLER_ID,
:To => params['ph'],
:Url => SITE + 'handle_k_call',
:StatusCallbackMethod => 'GET',
:StatusCallback => SITE + 'status_callback_for_kolkata'
)
# Auto-redirects to :url => [call-handler, below]
end #get TestKolkataCall
# To handle a kolkata call,
# [1] get the set of valid language options from the db
# [2] if we can't find that, guess what it might be (l)
# [3] make a new person profile, with language defaulting to Bengali
# [4] see if we can find that person's profile already from a prev call
# [5] if not, no worries, we have the Bengali default
# [6] if so, assign if there is a valid language pref in their profile
# [7] (otherwise should remain the string 'Bengali' by default)
# [8] construct approp. audio URL based on our best estimate of language
post '/handle_k_call' do
c = DB['kolkata_languages'].find({})
l = c.first() if (c.count == 1)
l = {'1'=>'English', '2'=>'Hindi', '3'=>'Bengali'} if (c.count != 1)
p = Hash.new()
p['_id'] = params['To']
p['Language'] = 'Bengali'
f = DB['people'].find({'_id' => params['To']})
lang_pref = nil
lang_pref = f.first['Language'] if (f.count == 1)
p['Language'] = lang_pref if l.has_value?(lang_pref)
audio = AUDIO + 'Kolkata_'
audio = audio + p['Language']
audio = audio + '_.mp3'
Twilio::TwiML::Response.new do |r|
r.Gather :numDigits=>'1',:action=>'/gather_k',:timeout=>'12' do |g|
g.Play audio
g.Play KOLKATA_BENGALI_CHOICE
g.Play KOLKATA_HINDI_CHOICE
g.Play KOLKATA_ENGLISH_CHOICE
end #Gather
end.text
end #handle_kolkata_call
post '/gather_k' do
puts '/GATHER_K_RESPONSE \n WITH PARAMS= ' + params.to_s
#Store language pref in Mongo profile
l = DB['kolkata_languages'].find_one({})
p = DB['people'].find_one({'_id' => params['To']})
p['Language'] = l[params['Digits']]
DB['people'].update({:_id => p['_id']}, p, { :upsert => true })
if params['Digits'] == '1'
response = Twilio::TwiML::Response.new do |r|
r.Play KOLKATA_ENGLISH_AUDIO
end
elsif params['Digits'] == '3'
response = Twilio::TwiML::Response.new do |r|
r.Play KOLKATA_BENGALI_AUDIO
end
elsif params['Digits'] == '2'
response = Twilio::TwiML::Response.new do |r|
r.Play KOLKATA_BENGALI_AUDIO
end
else
response = Twilio::TwiML::Response.new do |r|
r.Say 'We do not know what you want to hear.'
end
end
response.text do |format|
format.xml { render :xml => response.text }
end #do response.text
end #gather_k do
post '/handle_kolkata_call' do
puts d = DB['kolkata'].find_one({'Called number' => params['To'].to_i})
if d == nil
@Language = 'Bengali'
elseif d['Language'] == nil
@Language = 'Bengali'
else
@Language = d['Language']
end #if
puts in_proper_language_and_scope = {'Language'=>@Language}
@toRepeatInHindiPress = REDIS.get 'ToRepeatInHindiPress'
@toRepeatInBengaliPress = REDIS.get 'ToRepeatInBengaliPress'
#To get this audio from Abhik's voicemail, tried:
#http://www.macroplant.com/iexplorer/tutorials/how-to-access-voicemail-on-iphone
#(seemed to work OK)
Twilio::TwiML::Response.new do |r|
r.Gather :numDigits => '1', :action => '/gather_kolkata' do |g|
# :timeout => '9'
g.Play d['audio'] +'.mp3'
g.Play @toRepeatInHindiPress
g.Say 'two', :voice => 'woman'
g.Play @toRepeatInBengaliPress
g.Say 'three', :voice => 'woman'
end
end.text
end #handle_kolkata_call
post '/gather_kolkata' do
puts '/GATHER_KOLKATA_RESPONSE \n WITH PARAMS= ' + params.to_s
r = DB['kolkata'].find_one({'Mobile number' => params['To'].to_i})
old_link = r['last_content_delivered']
link_segments = old_link.split('_')
if params['Digits'] == '1'
link_segments[1] = 'English'
new_link = link_segments.join('_')
r['Language'] = link_segments[1]
r['last_time_called'] = Time.now.to_f
r['audio'] = new_link
r['last_content_delivered'] = new_link
DB['kolkata'].update({"_id" => r["_id"]}, r)
response = Twilio::TwiML::Response.new do |r|
r.Play new_link +'1.mp3'
r.Play new_link +'2.mp3'
r.Play new_link +'3.mp3'
r.Play new_link +'4.mp3'
r.Play new_link +'5.mp3'
end
elsif params['Digits'] == '3'
link_segments[1] = 'Bengali'
new_link = link_segments.join('_')
r['Language'] = link_segments[1]
r['last_time_called'] = Time.now.to_f
r['audio'] = new_link
r['last_content_delivered'] = new_link
DB['kolkata'].update({"_id" => r["_id"]}, r)
response = Twilio::TwiML::Response.new do |r|
r.Play new_link +'1.mp3'
r.Play new_link +'2.mp3'
r.Play new_link +'3.mp3'