forked from mrmattwilkins/google-contacts-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
contacts.py
executable file
·388 lines (335 loc) · 11.3 KB
/
contacts.py
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
#!/usr/bin/env python3
import pickle
import os.path
import dateutil.parser
from time import sleep
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/contacts']
# The user field that we store a key in to uniquely identify a person across
# accounts
SYNC_TAG = 'csync-uid'
# all personFields, I don't know to programmatically get these, I just got them
# from
# https://developers.google.com/people/api/rest/v1/people.connections/list
all_person_fields = [
'addresses',
'ageRanges',
'biographies',
'birthdays',
'calendarUrls',
'clientData',
'coverPhotos',
'emailAddresses',
'events',
'externalIds',
'genders',
'imClients',
'interests',
'locales',
'locations',
'memberships',
'metadata',
'miscKeywords',
'names',
'nicknames',
'occupations',
'organizations',
'phoneNumbers',
'photos',
'relations',
'sipAddresses',
'skills',
'urls',
'userDefined'
]
all_update_person_fields = [
'addresses',
'biographies',
'birthdays',
'clientData',
'emailAddresses',
'events',
'externalIds',
'genders',
'imClients',
'interests',
'locales',
'locations',
'memberships',
'miscKeywords',
'names',
'nicknames',
'occupations',
'organizations',
'phoneNumbers',
'relations',
'sipAddresses',
'urls',
'userDefined'
]
class Contacts():
def __init__(self, keyfile, credfile):
creds = None
# The file token.pickle stores the user's access and refresh tokens,
# and is created automatically when the authorization flow completes
# for the first time.
if os.path.exists(credfile):
with open(credfile, 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
keyfile, SCOPES
)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open(credfile, 'wb') as token:
pickle.dump(creds, token)
creds = creds
self.service = build('people', 'v1', credentials=creds)
self.get_info()
def __strip_body(self, body):
"""Return a person body without coverPhotos/photos/metadata
and some other things
We need just this info about a person when we do an update or add, the
photos field doesn't work with People API at the moment, and you don't
pass metadata for add/update.
Parameters
----------
body: dict
A dict returned from people api. Looks something like
{
'resourceName': 'people/blah',
'etag': 'blah',
'metadata': {
'sources': [
{
'type': 'CONTACT',
'id': 'blah',
'etag': 'blah',
'updateTime': '2016-06-05T18:56:16.972001Z'
}
],
'objectType': 'PERSON'
},
'names': [
{
'metadata':
{
'primary': True,
'source': {'type': 'CONTACT', 'id': 'blah'}
},
'displayName': 'John Smith',
'familyName': 'Smith',
'givenName': 'John',
'displayNameLastFirst': 'Smith, John',
'unstructuredName': 'John Smith'
}
],
'photos': [
blah
]
blah
}
Returns
-------
dict:
Like body but without resourceName, etag, coverPhotos, photos and
metadata fields. Also no metadata in each field (eg
['names'][0]['metadata']). So the above example would be stripped
to
{
'names': [
{
'displayName': 'John Smith',
'familyName': 'Smith',
'givenName': 'John',
'displayNameLastFirst': 'Smith, John',
'unstructuredName': 'John Smith'
}
],
blah
}
"""
# keep all_person_fields, but not photos/metadata
bad = set(['metadata', 'coverPhotos', 'photos'])
tokeep = set(all_person_fields) - bad
ret = {k: v for k, v in body.items() if k in tokeep}
# all the other fields are lists of dicts, we must drop the metadata
# key from any of those dicts
for k, v in ret.items():
for i in v:
i.pop('metadata', None)
# for some reason some of my contacts have more than one name. remove
# anything except the first. same problem with genders.
ret['names'] = [ret['names'][0]]
if 'genders' in ret:
ret['genders'] = [ret['genders'][0]]
return ret
def get_info(self):
"""Store a dict of contact info
Returns
-------
dict:
A dict of dicts tag, etag, updated, name
{
'rn0':
{
'etag': str
'tag': the csync_id (possibly None for newly added)
'updated': datetime,
'name': the display name
},
'rn1':
{
'etag': str
'tag': the csync_id (possibly None for newly added)
'updated': datetime,
'name': the display name
},
...
}
"""
self.info = {}
for p in self.get_all_contacts():
tagls = [
kv['value']
for kv in p.get('clientData', {})
if kv.get('key', None) == SYNC_TAG
]
if not ('names' in p or 'organizations' in p):
continue
self.info[p['resourceName']] = {
'etag': p['etag'],
'tag': tagls[0] if tagls else None,
'updated': dateutil.parser.isoparse(
p['metadata']['sources'][0]['updateTime']
),
'name': (
p['names'][0]['displayName']
if 'names' in p else p['organizations'][0]['name']
)
}
def get_all_contacts(
self, fields=['names', 'organizations', 'clientData', 'metadata']
):
"""Return a list of all the contacts."""
# Keep getting 1000 connections until the nextPageToken becomes None
connections_list = []
next_page_token = ''
while True:
if not (next_page_token is None):
# Call the People API
results = self.service.people().connections().list(
resourceName='people/me',
pageSize=1000,
personFields=','.join(fields),
pageToken=next_page_token
).execute()
connections_list += results.get('connections', [])
next_page_token = results.get('nextPageToken')
else:
break
return connections_list
def tag_to_rn(self, tag):
"""Return the resourceName for this tag, or None"""
rn = [rn for rn, v in self.info.items() if v['tag'] == tag]
if not rn:
return None
assert(len(rn) == 1)
return rn[0]
def name_to_rn(self, name):
"""Return the resourceName for this name, or None"""
rn = [
rn
for rn, v in self.info.items()
if v['name'].lower() == name.lower()
]
if not rn:
return None
assert(len(rn) == 1)
return rn[0]
def delete(self, tag: str, verbose=False):
"""Delete a person
Parameters
----------
tag: str
This is a tag to delete
"""
# need to find the resource name
rn = self.tag_to_rn(tag)
if rn is None:
return
if verbose:
print(f"{self.info[rn]['name']} ", end='')
self.service.people().deleteContact(resourceName=rn).execute()
def update_tag(self, rn: str, tag: str):
"""Update the tag for a contact
Parameters
---------
rn: str
The resource name of person to add tag to
tag: str
The tag to add. No check on uniques is made, but it better be
"""
# get the current clientData
try:
p = self.service.people().get(
resourceName=rn,
personFields='clientData'
).execute()
# the clientData without the tag dict
wout = [
i
for i in p.get('clientData', [])
if i.get('key', None) != SYNC_TAG
]
wout.append({'key': SYNC_TAG, 'value': tag})
self.service.people().updateContact(
resourceName=rn,
updatePersonFields='clientData',
body={'etag': self.info[rn]['etag'], 'clientData': wout}
).execute()
except HttpError as e:
# added a little sleep to avoid 429 HTTP error because rate limit
sleep(1)
self.update_tag(rn, tag)
def add(self, body):
"""Add a person with this body
Parameters
----------
body: dict
Maps all_person_fields to lists of dicts with info in them.
"""
new_contact = self.service.people().createContact(
body=body
).execute()
return new_contact
def update(self, tag: str, body: dict, verbose=False):
rn = self.tag_to_rn(tag)
if rn is not None:
try:
body.update({'etag': self.info[rn]['etag']})
self.service.people().updateContact(
resourceName=rn,
updatePersonFields=','.join(all_update_person_fields),
body=body
).execute()
except HttpError as e:
# added a little sleep to avoid 429 HTTP error because rate limit
sleep(1)
self.update(tag, body, verbose)
def get(self, rn):
"""Return a person body, stripped of resourceName/etag etc"""
p = self.service.people().get(
resourceName=rn,
personFields=','.join(all_person_fields)
).execute()
return self.__strip_body(p)