forked from tidev/titanium-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContactsModule.m
596 lines (517 loc) · 18.8 KB
/
ContactsModule.m
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
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#ifdef USE_TI_CONTACTS
#import <AddressBookUI/AddressBookUI.h>
#import "ContactsModule.h"
#import "TiContactsPerson.h"
#import "TiContactsGroup.h"
#import "TiApp.h"
#import "TiBase.h"
#pragma Backwards compatibility for pre-iOS 6.0
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_6_0
//TODO: Should we warn that they need to update to the latest XCode is this is happening?
#define kABAuthorizationStatusNotDetermined 0
#define kABAuthorizationStatusRestricted 1
#define kABAuthorizationStatusDenied 2
#define kABAuthorizationStatusAuthorized 3
#endif
@implementation ContactsModule
void CMExternalChangeCallback (ABAddressBookRef notifyAddressBook,CFDictionaryRef info,void *context)
{
DebugLog(@"Got External Change Callback");
ContactsModule* theModule = (ContactsModule*) context;
theModule->reloadAddressBook = YES;
[theModule fireEvent:@"reload" withObject:nil];
}
// We'll force the address book to only be accessed on the main thread, for consistency. Otherwise
// we could run into cross-thread memory issues.
-(ABAddressBookRef)addressBook
{
if (![NSThread isMainThread]) {
return NULL;
}
if (reloadAddressBook && (addressBook != NULL) ) {
[self releaseAddressBook];
addressBook = NULL;
}
reloadAddressBook = NO;
if (addressBook == NULL) {
if (iOS6API) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
#endif
} else {
addressBook = ABAddressBookCreate();
}
if (addressBook == NULL) {
DebugLog(@"[WARN] Could not create an address book. Make sure you have gotten permission first.");
} else {
ABAddressBookRegisterExternalChangeCallback(addressBook, CMExternalChangeCallback, self);
}
}
return addressBook;
}
-(void)releaseAddressBook
{
TiThreadPerformOnMainThread(^{
ABAddressBookUnregisterExternalChangeCallback(addressBook, CMExternalChangeCallback, self);
CFRelease(addressBook);
}, YES);
}
-(void)startup
{
[super startup];
addressBook = NULL;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
if (ABAddressBookGetAuthorizationStatus != NULL) {
iOS6API = YES;
}
#endif
}
-(void)dealloc
{
RELEASE_TO_NIL(picker)
RELEASE_TO_NIL(cancelCallback)
RELEASE_TO_NIL(selectedPersonCallback)
RELEASE_TO_NIL(selectedPropertyCallback)
if (addressBook != NULL) {
[self releaseAddressBook];
}
[super dealloc];
}
-(void)removeRecord:(ABRecordRef)record
{
CFErrorRef error;
if (!ABAddressBookRemoveRecord([self addressBook], record, &error)) {
CFStringRef errorStr = CFErrorCopyDescription(error);
NSString* str = [NSString stringWithString:(NSString*)errorStr];
CFRelease(errorStr);
NSString* kind = (ABRecordGetRecordType(record) == kABPersonType) ? @"person" : @"group";
[self throwException:[NSString stringWithFormat:@"Failed to remove %@: %@",kind,str]
subreason:nil
location:CODELOCATION];
}
}
#pragma mark Public API
-(void) requestAuthorization:(id)args
{
ENSURE_SINGLE_ARG(args, KrollCallback);
KrollCallback * callback = args;
NSString * error = nil;
int code = 0;
bool doPrompt = NO;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
if(iOS6API){
long int permissions = ABAddressBookGetAuthorizationStatus();
switch (permissions) {
case kABAuthorizationStatusNotDetermined:
doPrompt = YES;
break;
case kABAuthorizationStatusAuthorized:
break;
case kABAuthorizationStatusDenied:
code = kABAuthorizationStatusDenied;
error = @"The user has denied access to the address book";
case kABAuthorizationStatusRestricted:
code = kABAuthorizationStatusRestricted;
error = @"The user is unable to allow access to the address book";
default:
break;
}
}
#endif
if (!doPrompt) {
NSDictionary * propertiesDict = [TiUtils dictionaryWithCode:code message:error];
NSArray * invocationArray = [[NSArray alloc] initWithObjects:&propertiesDict count:1];
[callback call:invocationArray thisObject:self];
[invocationArray release];
return;
}
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
TiThreadPerformOnMainThread(^(){
ABAddressBookRef ourAddressBook = [self addressBook];
ABAddressBookRequestAccessWithCompletion(ourAddressBook, ^(bool granted, CFErrorRef error) {
NSError * errorObj = (NSError *)error;
NSDictionary * propertiesDict = [TiUtils dictionaryWithCode:[errorObj code] message:[TiUtils messageFromError:errorObj]];
KrollEvent * invocationEvent = [[KrollEvent alloc] initWithCallback:callback eventObject:propertiesDict thisObject:self];
[[callback context] enqueue:invocationEvent];
});
}, NO);
#endif
}
-(NSNumber*) contactsAuthorization
{
long int result = kABAuthorizationStatusAuthorized;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
if (iOS6API) { //5.1 and before: We always had permission.
result = ABAddressBookGetAuthorizationStatus();
}
#endif
return [NSNumber numberWithLong:result];
}
-(void)save:(id)unused
{
ENSURE_UI_THREAD(save, unused)
CFErrorRef error;
ABAddressBookRef ourAddressBook = [self addressBook];
if (ourAddressBook == NULL) {
return;
}
if (!ABAddressBookSave(ourAddressBook, &error)) {
CFStringRef errorStr = CFErrorCopyDescription(error);
NSString* str = [NSString stringWithString:(NSString*)errorStr];
CFRelease(errorStr);
[self throwException:[NSString stringWithFormat:@"Unable to save address book: %@",str]
subreason:nil
location:CODELOCATION];
}
}
-(void)revert:(id)unused
{
ENSURE_UI_THREAD(revert, unused)
ABAddressBookRef ourAddressBook = [self addressBook];
if (ourAddressBook == NULL) {
return;
}
ABAddressBookRevert(ourAddressBook);
}
-(void)showContacts:(id)args
{
ENSURE_SINGLE_ARG(args, NSDictionary)
ENSURE_UI_THREAD(showContacts, args);
RELEASE_TO_NIL(cancelCallback)
RELEASE_TO_NIL(selectedPersonCallback)
RELEASE_TO_NIL(selectedPropertyCallback)
RELEASE_TO_NIL(picker)
cancelCallback = [[args objectForKey:@"cancel"] retain];
selectedPersonCallback = [[args objectForKey:@"selectedPerson"] retain];
selectedPropertyCallback = [[args objectForKey:@"selectedProperty"] retain];
picker = [[ABPeoplePickerNavigationController alloc] init];
[picker setPeoplePickerDelegate:self];
animated = [TiUtils boolValue:@"animated" properties:args def:YES];
NSArray* fields = [args objectForKey:@"fields"];
ENSURE_TYPE_OR_NIL(fields, NSArray)
if (fields != nil) {
NSMutableArray* pickerFields = [NSMutableArray arrayWithCapacity:[fields count]];
for (id field in fields) {
id property = nil;
if ((property = [[TiContactsPerson contactProperties] objectForKey:field]) ||
(property = [[TiContactsPerson multiValueProperties] objectForKey:field])) {
[pickerFields addObject:property];
}
}
[picker setDisplayedProperties:pickerFields];
}
[[TiApp app] showModalController:picker animated:animated];
}
// OK to do outside main thread
-(TiContactsPerson*)getPersonByID:(id)arg
{
ENSURE_SINGLE_ARG(arg, NSObject)
__block int idNum = [TiUtils intValue:arg];
__block BOOL validId = NO;
dispatch_sync(dispatch_get_main_queue(),^{
ABAddressBookRef ourAddressBook = [self addressBook];
if (ourAddressBook == NULL) {
return;
}
ABRecordRef record = NULL;
record = ABAddressBookGetPersonWithRecordID(ourAddressBook, idNum);
if (record != NULL)
{
validId = YES;
}
});
if (validId == YES)
{
return [[[TiContactsPerson alloc] _initWithPageContext:[self executionContext] recordId:idNum module:self] autorelease];
}
return NULL;
}
-(TiContactsGroup*)getGroupByID:(id)arg
{
ENSURE_SINGLE_ARG(arg, NSObject)
__block int idNum = [TiUtils intValue:arg];
__block BOOL validId = NO;
dispatch_sync(dispatch_get_main_queue(),^{
ABAddressBookRef ourAddressBook = [self addressBook];
if (ourAddressBook == NULL) {
return;
}
ABRecordRef record = NULL;
record = ABAddressBookGetGroupWithRecordID(ourAddressBook, idNum);
if (record != NULL)
{
validId = YES;
}
});
if (validId == YES)
{
return [[[TiContactsGroup alloc] _initWithPageContext:[self executionContext] recordId:idNum module:self] autorelease];
}
return NULL;
}
-(NSArray*)getPeopleWithName:(id)arg
{
ENSURE_SINGLE_ARG(arg, NSString)
if (![NSThread isMainThread]) {
__block id result;
TiThreadPerformOnMainThread(^{result = [[self getPeopleWithName:arg] retain];}, YES);
return [result autorelease];
}
ABAddressBookRef ourAddressBook = [self addressBook];
if (ourAddressBook == NULL) {
return nil;
}
CFArrayRef peopleRefs = ABAddressBookCopyPeopleWithName(ourAddressBook, (CFStringRef)arg);
if (peopleRefs == NULL) {
return nil;
}
CFIndex count = CFArrayGetCount(peopleRefs);
NSMutableArray* people = [NSMutableArray arrayWithCapacity:count];
for (CFIndex i=0; i < count; i++) {
ABRecordRef ref = CFArrayGetValueAtIndex(peopleRefs, i);
ABRecordID id_ = ABRecordGetRecordID(ref);
TiContactsPerson* person = [[[TiContactsPerson alloc] _initWithPageContext:[self executionContext] recordId:id_ module:self] autorelease];
[people addObject:person];
}
CFRelease(peopleRefs);
return people;
}
-(NSArray*)getAllPeople:(id)unused
{
if (![NSThread isMainThread]) {
__block id result = nil;
TiThreadPerformOnMainThread(^{result = [[self getAllPeople:unused] retain];}, YES);
return [result autorelease];
}
ABAddressBookRef ourAddressBook = [self addressBook];
if (ourAddressBook == NULL) {
return nil;
}
CFArrayRef peopleRefs = ABAddressBookCopyArrayOfAllPeople(ourAddressBook);
if (peopleRefs == NULL) {
return nil;
}
CFIndex count = CFArrayGetCount(peopleRefs);
NSMutableArray* people = [NSMutableArray arrayWithCapacity:count];
for (CFIndex i=0; i < count; i++) {
ABRecordRef ref = CFArrayGetValueAtIndex(peopleRefs, i);
ABRecordID id_ = ABRecordGetRecordID(ref);
TiContactsPerson* person = [[[TiContactsPerson alloc] _initWithPageContext:[self executionContext] recordId:id_ module:self] autorelease];
[people addObject:person];
}
CFRelease(peopleRefs);
return people;
}
-(NSArray*)getAllGroups:(id)unused
{
if (![NSThread isMainThread]) {
__block id result = nil;
TiThreadPerformOnMainThread(^{result = [[self getAllGroups:unused] retain];}, YES);
return [result autorelease];
}
ABAddressBookRef ourAddressBook = [self addressBook];
if (ourAddressBook == NULL) {
return nil;
}
CFArrayRef groupRefs = ABAddressBookCopyArrayOfAllGroups(ourAddressBook);
if (groupRefs == NULL) {
return nil;
}
CFIndex count = CFArrayGetCount(groupRefs);
NSMutableArray* groups = [NSMutableArray arrayWithCapacity:count];
for (CFIndex i=0; i < count; i++) {
ABRecordRef ref = CFArrayGetValueAtIndex(groupRefs, i);
ABRecordID id_ = ABRecordGetRecordID(ref);
TiContactsGroup* group = [[[TiContactsGroup alloc] _initWithPageContext:[self executionContext] recordId:id_ module:self] autorelease];
[groups addObject:group];
}
CFRelease(groupRefs);
return groups;
}
-(TiContactsPerson*)createPerson:(id)arg
{
ENSURE_SINGLE_ARG_OR_NIL(arg, NSDictionary)
if (![NSThread isMainThread]) {
__block id result = nil;
TiThreadPerformOnMainThread(^{result = [[self createPerson:arg] retain];}, YES);
return [result autorelease];
}
ABAddressBookRef ourAddressBook = [self addressBook];
if (ourAddressBook == NULL) {
[self throwException:@"Cannot access address book"
subreason:nil
location:CODELOCATION];
}
if (ABAddressBookHasUnsavedChanges(ourAddressBook)) {
[self throwException:@"Cannot create a new entry with unsaved changes"
subreason:nil
location:CODELOCATION];
return nil;
}
ABRecordRef record = ABPersonCreate();
[(id)record autorelease];
CFErrorRef error;
if (!ABAddressBookAddRecord(ourAddressBook, record, &error)) {
CFStringRef errorStr = CFErrorCopyDescription(error);
NSString* str = [NSString stringWithString:(NSString*)errorStr];
CFRelease(errorStr);
[self throwException:[NSString stringWithFormat:@"Failed to add person: %@",str]
subreason:nil
location:CODELOCATION];
return nil;
}
[self save:nil];
ABRecordID id_ = ABRecordGetRecordID(record);
TiContactsPerson* newPerson = [[[TiContactsPerson alloc] _initWithPageContext:[self executionContext] recordId:id_ module:self] autorelease];
[newPerson setValuesForKeysWithDictionary:arg];
if (arg != nil) {
// Have to save initially so properties can be set; have to save again to commit changes
[self save:nil];
}
return newPerson;
}
-(void)removePerson:(id)arg
{
ENSURE_SINGLE_ARG(arg,TiContactsPerson)
ENSURE_UI_THREAD(removePerson,arg)
[self removeRecord:[arg record]];
}
-(TiContactsGroup*)createGroup:(id)arg
{
ENSURE_SINGLE_ARG_OR_NIL(arg, NSDictionary)
if (![NSThread isMainThread]) {
__block id result = nil;
TiThreadPerformOnMainThread(^{result = [[self createGroup:arg] retain];}, YES);
return [result autorelease];
}
ABAddressBookRef ourAddressBook = [self addressBook];
if (ourAddressBook == NULL) {
[self throwException:@"Cannot access address book"
subreason:nil
location:CODELOCATION];
}
if (ABAddressBookHasUnsavedChanges(ourAddressBook)) {
[self throwException:@"Cannot create a new entry with unsaved changes"
subreason:nil
location:CODELOCATION];
}
ABRecordRef record = ABGroupCreate();
[(id)record autorelease];
CFErrorRef error;
if (!ABAddressBookAddRecord(ourAddressBook, record, &error)) {
CFStringRef errorStr = CFErrorCopyDescription(error);
NSString* str = [NSString stringWithString:(NSString*)errorStr];
CFRelease(errorStr);
[self throwException:[NSString stringWithFormat:@"Failed to add group: %@",str]
subreason:nil
location:CODELOCATION];
}
[self save:nil];
ABRecordID id_ = ABRecordGetRecordID(record);
TiContactsGroup* newGroup = [[[TiContactsGroup alloc] _initWithPageContext:[self executionContext] recordId:id_ module:self] autorelease];
[newGroup setValuesForKeysWithDictionary:arg];
if (arg != nil) {
// Have to save initially so properties can be set; have to save again to commit changes
[self save:nil];
}
return newGroup;
}
-(void)removeGroup:(id)arg
{
ENSURE_SINGLE_ARG(arg,TiContactsGroup)
ENSURE_UI_THREAD(removePerson,arg)
[self removeRecord:[arg record]];
}
#pragma mark Properties
MAKE_SYSTEM_NUMBER(CONTACTS_KIND_PERSON,[[(NSNumber*)kABPersonKindPerson retain] autorelease])
MAKE_SYSTEM_NUMBER(CONTACTS_KIND_ORGANIZATION,[[(NSNumber*)kABPersonKindOrganization retain] autorelease])
MAKE_SYSTEM_PROP(CONTACTS_SORT_FIRST_NAME,kABPersonSortByFirstName);
MAKE_SYSTEM_PROP(CONTACTS_SORT_LAST_NAME,kABPersonSortByLastName);
MAKE_SYSTEM_PROP(AUTHORIZATION_UNKNOWN, kABAuthorizationStatusNotDetermined);
MAKE_SYSTEM_PROP(AUTHORIZATION_RESTRICTED, kABAuthorizationStatusRestricted);
MAKE_SYSTEM_PROP(AUTHORIZATION_DENIED, kABAuthorizationStatusDenied);
MAKE_SYSTEM_PROP(AUTHORIZATION_AUTHORIZED, kABAuthorizationStatusAuthorized);
#pragma mark Picker delegate functions
-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
[[TiApp app] hideModalController:picker animated:animated];
if (cancelCallback) {
[self _fireEventToListener:@"cancel" withObject:nil listener:cancelCallback thisObject:nil];
}
}
-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
if (selectedPersonCallback) {
ABRecordID id_ = ABRecordGetRecordID(person);
TiContactsPerson* person = [[[TiContactsPerson alloc] _initWithPageContext:[self executionContext] recordId:id_ module:self] autorelease];
[self _fireEventToListener:@"selectedPerson"
withObject:[NSDictionary dictionaryWithObject:person forKey:@"person"]
listener:selectedPersonCallback
thisObject:nil];
[[TiApp app] hideModalController:picker animated:animated];
return NO;
}
return YES;
}
-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
if (selectedPropertyCallback) {
ABRecordID id_ = ABRecordGetRecordID(person);
TiContactsPerson* personObject = [[[TiContactsPerson alloc] _initWithPageContext:[self executionContext] recordId:id_ module:self] autorelease];
NSString* propertyName = nil;
id value = [NSNull null];
id label = [NSNull null];
if (identifier == kABMultiValueInvalidIdentifier) {
propertyName = [[[TiContactsPerson contactProperties] allKeysForObject:[NSNumber numberWithInt:property]] objectAtIndex:0];
// Contacts is poorly-designed enough that we should worry about receiving NULL values for properties which are actually assigned.
CFTypeRef val = ABRecordCopyValue(person, property);
if (val != NULL) {
value = [[(id)val retain] autorelease]; // Force toll-free bridging & autorelease
CFRelease(val);
}
}
else {
propertyName = [[[TiContactsPerson multiValueProperties] allKeysForObject:[NSNumber numberWithInt:property]] objectAtIndex:0];
ABMultiValueRef multival = ABRecordCopyValue(person, property);
CFIndex index = ABMultiValueGetIndexForIdentifier(multival, identifier);
CFTypeRef val = ABMultiValueCopyValueAtIndex(multival, index);
if (val != NULL) {
value = [[(id)val retain] autorelease]; // Force toll-free bridging & autorelease
CFRelease(val);
}
CFStringRef CFlabel = ABMultiValueCopyLabelAtIndex(multival, index);
NSArray* labelKeys = [[TiContactsPerson multiValueLabels] allKeysForObject:(NSString*)CFlabel];
if ([labelKeys count] > 0) {
label = [NSString stringWithString:[labelKeys objectAtIndex:0]];
}
else {
// Hack for Exchange and other 'cute' setups where there is no label associated with a multival property;
// in this case, force it to be the property name.
if (CFlabel != NULL) {
label = [NSString stringWithString:(NSString*)CFlabel];
}
// There may also be cases where we get a property from the system that we can't handle, because it's undocumented or not in the map.
else if (propertyName != nil) {
label = [NSString stringWithString:propertyName];
}
}
if (CFlabel != NULL) {
CFRelease(CFlabel);
}
CFRelease(multival);
}
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:personObject,@"person",propertyName,@"property",value,@"value",label,@"label",nil];
[self _fireEventToListener:@"selectedProperty" withObject:dict listener:selectedPropertyCallback thisObject:nil];
[[TiApp app] hideModalController:picker animated:animated];
return NO;
}
return YES;
}
@end
#endif