]> code.delx.au - monosys/blob - mail/abook2mutt/ab2mutt.m
449234e8a9e84acf5b0491de1c7786b7a42b0188
[monosys] / mail / abook2mutt / ab2mutt.m
1 /* Copyright 2008 James Bunton <jamesbunton@fastmail.fm>
2 * Licensed for distribution under the GPL version 2.
3 *
4 * Dump the contents of the OSX address book as a Mutt alias file
5 */
6
7
8 #import <Foundation/Foundation.h>
9 #import <AddressBook/AddressBook.h>
10
11
12 void
13 NSPrint(NSString* format, ...)
14 {
15 va_list args;
16 va_start(args, format);
17 NSString* string = [[NSString alloc] initWithFormat:format arguments:args];
18 va_end(args);
19 [string writeToFile:@"/dev/stdout" atomically:NO encoding:NSUTF8StringEncoding error:nil];
20 [string release];
21 }
22
23
24 @interface NSString (james)
25 -(NSString*) keepOnlyCharacterSet:(NSCharacterSet*)keepChars;
26 @end
27 @implementation NSString (james)
28 -(NSString*)
29 keepOnlyCharacterSet:(NSCharacterSet*)keepChars;
30 {
31 NSMutableString* ret = [[NSMutableString alloc] init];
32 NSScanner* scanner = [NSScanner scannerWithString:self];
33 NSString* temp;
34 while(![scanner isAtEnd]) {
35 if([scanner scanCharactersFromSet:keepChars intoString:&temp]) {
36 [ret appendString:temp];
37 } else {
38 [scanner setScanLocation:1+[scanner scanLocation]];
39 }
40 }
41 return [ret autorelease];
42 }
43 @end
44
45
46 void
47 printMuttAlias(NSString* key, NSString* firstName, NSString* lastName, ABMultiValue* emails)
48 {
49 key = [[key lowercaseString] keepOnlyCharacterSet:[NSCharacterSet lowercaseLetterCharacterSet]];
50
51 for(unsigned int i = 0; i < [emails count]; ++i) {
52 NSString* keySuffix = @"";
53 if(i > 0) {
54 keySuffix = [NSString stringWithFormat:@"%d", i];
55 }
56 NSPrint(@"alias %@%@ \"%@ %@\" <%@>\n", key, keySuffix, firstName, lastName, [emails valueAtIndex:i]);
57 }
58 }
59
60 int
61 main()
62 {
63 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
64
65 for(ABPerson* person in [[ABAddressBook sharedAddressBook] people]) {
66 NSString* firstName = [[person valueForProperty:kABFirstNameProperty] description];
67 NSString* lastName = [[person valueForProperty:kABLastNameProperty] description];
68 NSString* nickName = [[person valueForProperty:kABNicknameProperty] description];
69 // WTF does ABMultiValue exist for? No fast enumeration? What's wrong with NSArray?!
70 ABMultiValue* emails = [person valueForProperty:kABEmailProperty];
71
72 if([emails count] == 0) {
73 continue;
74 }
75
76 // Generate an entry for Nick and FirstLast
77 if([nickName length] > 0) {
78 printMuttAlias(nickName, firstName, lastName, emails);
79 }
80 if([firstName length] > 0 && [lastName length] > 0) {
81 NSString* key = [NSString stringWithFormat:@"%@%@", firstName, lastName];
82 printMuttAlias(key, firstName, lastName, emails);
83 }
84 }
85
86 [pool release];
87
88 return 0;
89 }
90