This repository has been archived by the owner on Jun 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.rb
136 lines (101 loc) · 2.36 KB
/
app.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
require 'rubygems'
require 'sinatra'
require 'algoliasearch'
require 'dotenv'
require 'yaml'
require 'nationbuilder'
Dotenv.load
Algolia.init :application_id => ENV['ALGOLIA_APP_ID'],
:api_key => ENV['ALGOLIA_ADMIN_KEY']
before do
# Parse JSON in body
if request.body.size > 0
request.body.rewind
@params = JSON.parse request.body.read
end
end
helpers do
def config
YAML.load_file(File.join(settings.root, 'config.yml'))
end
def valid_token?
return params['token'] === ENV['NATIONBUILDER_WEBHOOK_TOKEN']
end
def check_token!
unless valid_token?
halt 403, 'Bad token'
end
end
def algolia_index
Algolia::Index.new ENV['ALGOLIA_INDEX']
end
def person_filtered
params['payload']['person'].select do |key, value|
config['allowed_keys'].include? key
end
end
end
get '/' do
'Hello World'
end
post '/people/created' do
check_token!
person = person_filtered
person_without_id = p.tap { |p| p.delete('id') }
logger.info person.inspect
index = algolia_index
res = index.add_object(person_without_id, person['id'])
'OK'
end
post '/people/changed' do
check_token!
person = person_filtered
index = algolia_index
# Delete if banned
unless person['banned_at'].nil?
puts '> delete (banned)'
index.delete_object(person['id'])
halt 200
end
# Emails as array
person['emails'] = []
(1..5).each do |i|
person['emails'] << person["email#{i}"]
person.delete("email#{i}")
end
person['emails'] = person['emails'].compact.uniq
# Geoloc
unless person['primary_address'].nil? or person['primary_address']['lat'].nil? or person['primary_address']['lng'].nil?
person['_geoloc'] = {
lat: person['primary_address']['lat'],
lng: person['primary_address']['lng']
}
end
# Tags
person['_tags'] = person['tags']
person.delete('tags')
# Set id
person['objectID'] = person['id']
person.delete('id')
logger.info person.inspect
index.save_object(person)
'OK'
end
post '/people/merged' do
check_token!
logger.info params.inspect
person = person_filtered
logger.info person.inspect
'OK'
end
post '/people/deleted' do
check_token!
person = person_filtered
logger.info person.inspect
if person['id'].nil? or person['id'].empty?
halt
end
index = algolia_index
index.delete_object(person['id'])
'OK'
end