-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgoogle_contacts_api.rb
More file actions
260 lines (213 loc) · 7.42 KB
/
google_contacts_api.rb
File metadata and controls
260 lines (213 loc) · 7.42 KB
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
require 'xmlsimple'
require 'pp'
#require 'pry-byebug'
require_relative "./google_api_client"
module GoogleContactsApi
def self.create config=nil
return GoogleContactsApi.new config
end
class Atom
def initialize
@_h = {}
end
def children
@_h.select do |k, v|
v.class == Array
end
end
end
class ContactAtom < Atom
def initialize
super
@_h.merge!({'xmlns:atom' => 'http://www.w3.org/2005/Atom', 'xmlns:gd' => 'http://schemas.google.com/g/2005'})
@_h['atom:category']=[]
@_h['atom:category']<<{'scheme' => 'http://schemas.google.com/g/2005#kind',
'term' => 'http://schemas.google.com/contact/2008#contact'}
end
def to_s
@_h.to_s
end
def to_atom
x={'atom:entry' => []}
x['atom:entry'] << @_h
XmlSimple.xml_out(x, {'KeepRoot' => true})
end
def add_name(options)
if @_h['gd:name'].nil?
@_h["title"]=[{'type'=> 'text', 'content' => options[:fullName]}]
@_h['gd:name'] = []
@_h['gd:name'] << {'gd:givenName' => [options[:givenName]], 'gd:familyName' => [options[:familyName]]
}
end
self
end
def add_organization(options)
@_h['gd:organization'] ||= []
@_h['gd:organization'] <<
{'rel' => "http://schemas.google.com/g/2005#work", 'primary' => 'true',
'gd:orgName' => [options[:organization_name]]}
self
end
def add_email(options)
@_h['gd:email'] ||= []
@_h['gd:email'] << {'rel' => options[:rel], 'primary' => options[:primary].to_s, 'address' => options[:address],
'displayName' => options[:displayName]}
self
end
def add_phone(options)
@_h['gd:phoneNumber'] ||= []
@_h['gd:phoneNumber'] << {'rel' => options[:rel], 'primary' => options[:primary].to_s, 'content' => options[:number]}
self
end
end
class GoogleContactsApi < GoogleApiClient::GoogleApiClient
attr_reader :contact_list
attr_accessor :batch_endpoint
def initialize config
super config
@endpoint= config['endpoint'] || '/m8/feeds/contacts/cclr.org/full'
@host = config['host'] || 'https://www.google.com'
@batch_endpoint = config['batch_endpoint'] || '/m8/feeds/contacts/cclr.org/private/full/batch'
@contact_list = nil
end
def contact_list_info
mesg = ''
mesg += "#{@contact_list.size} entries.\n"
# mesg += @contact_list.to_s
mesg += pp(@contact_list)
mesg
end
def fetch_all_contacts
self.authenticate
contact_resp = all_contacts_data
@atom_body = contact_resp.body
@contact_list = atom_to_array contact_resp.body
end
def fetch_one_contact(id_url)
self.authenticate
execute_hash = {uri: id_url, # "https://www.google.com/m8/feeds/contacts/cclr.org/full",
headers: { 'GData-Version' => '3.0', 'Content-Type' => 'application/atom+xml'}}
resp = @client.execute execute_hash
puts resp.body
end
def new_contact_atom
return ContactAtom.new
end
def delete_all_contacts(atom_entries)
return '' if atom_entries['entry'].nil?
x.each do |contact|
delete_ept = (contact['link'].select { |l| l['rel']=='edit' })[0]['href']
puts ">>> Deleting #{delete_ept}"
self.delete_data(delete_ept)
end
end
def send_batch(entries, command='create')
# entries is assumed to be an object of class ContactAtom
batches = []
counter = 0
batch_id = 1
current_batch = initialize_batch
current_batch['feed'][0]['entry'] = []
entries.each do |entry|
counter += 1
child = {'category' => [{'scheme' => 'http://schemas.google.com/g/2005#kind', 'term' => 'http://schemas.google.com/g/2008#contact'}],
'batch:id' => ["#{command}"], 'batch:operation' => [{'type' => "#{command == 'delete' ? command : 'insert'}"}]}
if command == 'delete'
child.merge!({'gd:etag' => 'deleteContactEtag'})
end
batch_id += 1
if command == 'create'
if entry.class==ContactAtom
child.merge!(entry.children.delete_if { |k, v| k == 'atom:category' })
else
child.merge! entry
end
elsif command == 'delete'
child.merge!({'gd:etag' => "#{entry['gd$etag']}", 'id' => [entry['link'][1]['href']]})
end
if child['atom:category'] # There won't be any, if we didn't run an insert.
child.delete 'atom:category'
end
current_batch['feed'][0]['entry'] << child
if counter % 100 == 0
batches << current_batch
puts ">>> Created a batch"
current_batch = initialize_batch
current_batch['feed'][0]['entry'] = []
end
end
if current_batch['feed'][0]['entry'].size > 0
batches << current_batch
# puts current_batch.to_s
end
batches.each_with_index do |b, i|
feed_post = XmlSimple.xml_out(b, {'KeepRoot' => true});
feed_post = "<?xml version='1.0' encoding='UTF-8'?>\n#{feed_post}"
puts ">>> Sending batch #{i} with #{b['feed'][0]['entry'].size} entries; xml size = #{feed_post.length}"
resp = self.post_data(feed_post, endpoint: @host + @batch_endpoint, headers: {'Content-Type' => 'application/atom+xml'})
print_errors resp
end
# TODO Return a response at the end of this.
end
private
def all_contacts_data
if 1
execute_hash = {uri: @host + @endpoint, # "https://www.google.com/m8/feeds/contacts/cclr.org/full",
parameters: { 'alt' => 'json',
'max-results' => '100000' },
headers: { 'GData-Version' => '3.0', 'Content-Type' => 'application/atom+xml'}}
@client.execute execute_hash
else
# Pre Google OAuth 2.0
@client.retrieve_data(@endpoint, @headers)
end
end
def print_errors resp
bd=resp.body
t=XmlSimple.xml_in bd
errs = t["entry"].select do |status_ent|
status_ent["status"][0]['code'] != '201' and status_ent["status"][0]['code'] != '200'
end
$stderr.write("#{errs.count} errors found.\n")
end
def initialize_batch
_h = {}
_h['feed'] = []
_h['feed'] << {'xmlns' => 'http://www.w3.org/2005/Atom', 'xmlns:gContact' => 'http://schemas.google.com/contact/2008',
'xmlns:gd' => 'http://schemas.google.com/g/2005', 'xmlns:batch' => 'http://schemas.google.com/gdata/batch'}
_h
end
def atom_xml(elt_array)
str = ''
elt_array.each do |elt|
str += "<#{elt[0]} "
if elt[1][:attr]
elt[1][:attr].each do |attr_key, attr_value|
str += "#{attr_key}='#{attr_value}' "
end
end
str += " > "
if elt[1][:children]
str += atom_xml(elt[1][:children])
end
# Not checking that a tag has both children and value, which is not allowed.
if elt[1][:value]
str += " #{elt[1][:value]} "
end
# Returning str
str += " </#{elt[0]}> "
end
str
end
def atom_to_array(atom_str)
#return XmlSimple.xml_in(atom_str)
JSON.parse(atom_str)['feed']['entry']
end
def get_feed(uri, headers=nil)
uri = URI.parse(uri)
Net::HTTP.start(uri.host, uri.port) do |http|
http.get(uri.path, headers)
end
end
end
end