code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
// // XMPPSRVResolver.h // // Originally created by Eric Chamberlain on 6/15/10. // Based on SRVResolver by Apple, Inc. // #import <Foundation/Foundation.h> #import <dns_sd.h> extern NSString *const XMPPSRVResolverErrorDomain; @interface XMPPSRVResolver : NSObject { id delegate; dispatch_queue_t delegateQueue; dispatch_queue_t resolverQueue; NSString *srvName; NSTimeInterval timeout; BOOL resolveInProgress; NSMutableArray *results; DNSServiceRef sdRef; int sdFd; dispatch_source_t sdReadSource; dispatch_source_t timeoutTimer; } /** * The delegate & delegateQueue are mandatory. * The resolverQueue is optional. If NULL, it will automatically create it's own internal queue. **/ - (id)initWithdDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)dq resolverQueue:(dispatch_queue_t)rq; @property (readonly) NSString *srvName; @property (readonly) NSTimeInterval timeout; - (void)startWithSRVName:(NSString *)aSRVName timeout:(NSTimeInterval)aTimeout; - (void)stop; + (NSString *)srvNameFromXMPPDomain:(NSString *)xmppDomain; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol XMPPSRVResolverDelegate - (void)srvResolver:(XMPPSRVResolver *)sender didResolveRecords:(NSArray *)records; - (void)srvResolver:(XMPPSRVResolver *)sender didNotResolveDueToError:(NSError *)error; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @interface XMPPSRVRecord : NSObject { UInt16 priority; UInt16 weight; UInt16 port; NSString *target; NSUInteger sum; NSUInteger srvResultsIndex; } + (XMPPSRVRecord *)recordWithPriority:(UInt16)priority weight:(UInt16)weight port:(UInt16)port target:(NSString *)target; - (id)initWithPriority:(UInt16)priority weight:(UInt16)weight port:(UInt16)port target:(NSString *)target; @property (nonatomic, readonly) UInt16 priority; @property (nonatomic, readonly) UInt16 weight; @property (nonatomic, readonly) UInt16 port; @property (nonatomic, readonly) NSString *target; @end
04081337-xmpp
Utilities/XMPPSRVResolver.h
Objective-C
bsd
2,398
/* File: RFImageToDataTransformer.m Abstract: A value transformer, which transforms a UIImage or NSImage object into an NSData object. Based on Apple's UIImageToDataTransformer Copyright (C) 2010 Apple Inc. All Rights Reserved. Copyright (C) 2011 RF.com All Rights Reserved. */ #import "RFImageToDataTransformer.h" #if TARGET_OS_IPHONE #import <UIKit/UIKit.h> #else #endif @implementation RFImageToDataTransformer + (BOOL)allowsReverseTransformation { return YES; } + (Class)transformedValueClass { return [NSData class]; } - (id)transformedValue:(id)value { #if TARGET_OS_IPHONE return UIImagePNGRepresentation(value); #else return [(NSImage *)value TIFFRepresentation]; #endif } - (id)reverseTransformedValue:(id)value { #if TARGET_OS_IPHONE return [[[UIImage alloc] initWithData:value] autorelease]; #else return [[[NSImage alloc] initWithData:value] autorelease]; #endif } @end
04081337-xmpp
Utilities/RFImageToDataTransformer.m
Objective-C
bsd
917
#import "GCDMulticastDelegate.h" #import <libkern/OSAtomic.h> /** * How does this class work? * * In theory, this class is very straight-forward. * It provides a way for multiple delegates to be called, each on its own delegate queue. * * In other words, any delegate method call to this class * will get forwarded (dispatch_async'd) to each added delegate. * * Important note concerning thread-safety: * * This class is designed to be used from within a single dispatch queue. * In other words, it is NOT thread-safe, and should only be used from within the external dedicated dispatch_queue. **/ @interface GCDMulticastDelegate (PrivateAPI) - (NSInvocation *)duplicateInvocation:(NSInvocation *)origInvocation; @end @interface GCDMulticastDelegateEnumerator (PrivateAPI) - (id)initWithDelegateList:(GCDMulticastDelegateListNode *)delegateList; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void GCDMulticastDelegateListNodeRetain(GCDMulticastDelegateListNode *node) { OSAtomicIncrement32Barrier(&node->retainCount); } static void GCDMulticastDelegateListNodeRelease(GCDMulticastDelegateListNode *node) { int32_t newRetainCount = OSAtomicDecrement32Barrier(&node->retainCount); if (newRetainCount == 0) { free(node); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation GCDMulticastDelegate - (id)init { if ((self = [super init])) { delegateList = NULL; } return self; } - (void)addDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue { if (delegate == nil) return; if (delegateQueue == NULL) return; GCDMulticastDelegateListNode *node = malloc(sizeof(GCDMulticastDelegateListNode)); node->delegate = delegate; node->delegateQueue = delegateQueue; node->retainCount = 1; dispatch_retain(delegateQueue); // Remember: The delegateList is a linked list of MulticastDelegateListNode objects. // Each node object is allocated and placed in the list. // It is not deallocated until it is later removed from the linked list. if (delegateList == NULL) { node->prev = NULL; node->next = NULL; } else { node->prev = NULL; node->next = delegateList; node->next->prev = node; } delegateList = node; } - (void)removeDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue { if (delegate == nil) return; GCDMulticastDelegateListNode *node = delegateList; while (node != NULL) { if (delegate == node->delegate) { if ((delegateQueue == NULL) || (delegateQueue == node->delegateQueue)) { // Remove the node from the list. // This is done by editing the pointers of the node's neighbors to skip it. // // In other words: // node->prev->next = node->next // node->next->prev = node->prev // // We also want to properly update our delegateList pointer, // which always points to the "first" element in the list. (Most recently added.) if(node->prev != NULL) node->prev->next = node->next; else delegateList = node->next; if(node->next != NULL) node->next->prev = node->prev; node->prev = NULL; node->next = NULL; dispatch_release(node->delegateQueue); node->delegate = nil; node->delegateQueue = NULL; GCDMulticastDelegateListNodeRelease(node); break; } } else { node = node->next; } } } - (void)removeDelegate:(id)delegate { [self removeDelegate:delegate delegateQueue:NULL]; } - (void)removeAllDelegates { GCDMulticastDelegateListNode *node = delegateList; while (node != NULL) { GCDMulticastDelegateListNode *next = node->next; node->prev = NULL; node->next = NULL; dispatch_release(node->delegateQueue); node->delegate = nil; node->delegateQueue = NULL; GCDMulticastDelegateListNodeRelease(node); node = next; } delegateList = NULL; } - (NSUInteger)count { NSUInteger count = 0; GCDMulticastDelegateListNode *node; for (node = delegateList; node != NULL; node = node->next) { count++; } return count; } - (NSUInteger)countOfClass:(Class)aClass { NSUInteger count = 0; GCDMulticastDelegateListNode *node; for (node = delegateList; node != NULL; node = node->next) { if ([node->delegate isKindOfClass:aClass]) { count++; } } return count; } - (NSUInteger)countForSelector:(SEL)aSelector { NSUInteger count = 0; GCDMulticastDelegateListNode *node; for (node = delegateList; node != NULL; node = node->next) { if ([node->delegate respondsToSelector:aSelector]) { count++; } } return count; } - (GCDMulticastDelegateEnumerator *)delegateEnumerator { return [[[GCDMulticastDelegateEnumerator alloc] initWithDelegateList:delegateList] autorelease]; } - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { GCDMulticastDelegateListNode *node; for (node = delegateList; node != NULL; node = node->next) { NSMethodSignature *result = [node->delegate methodSignatureForSelector:aSelector]; if (result != nil) { return result; } } // This causes a crash... // return [super methodSignatureForSelector:aSelector]; // This also causes a crash... // return nil; return [[self class] instanceMethodSignatureForSelector:@selector(doNothing)]; } - (void)forwardInvocation:(NSInvocation *)origInvocation { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // All delegates MUST be invoked ASYNCHRONOUSLY. GCDMulticastDelegateListNode *node = delegateList; if (node != NULL) { // Recall that new delegates are added to the beginning of the linked list. // The last delegate in the list is the first delegate that was added, so it will be the first that's invoked. // We're going to be moving backwards through the linked list as we invoke the delegates. // // Loop through the linked list so we can get a reference to the last delegate in the list. while (node->next != NULL) { node = node->next; } SEL selector = [origInvocation selector]; while (node != NULL) { id delegate = node->delegate; if ([delegate respondsToSelector:selector]) { NSInvocation *dupInvocation = [self duplicateInvocation:origInvocation]; dispatch_async(node->delegateQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [dupInvocation invokeWithTarget:delegate]; [pool drain]; }); } node = node->prev; } } [pool release]; } - (void)doesNotRecognizeSelector:(SEL)aSelector { // Prevent NSInvalidArgumentException } - (void)doNothing {} - (void)dealloc { [self removeAllDelegates]; [super dealloc]; } - (NSInvocation *)duplicateInvocation:(NSInvocation *)origInvocation { NSMethodSignature *methodSignature = [origInvocation methodSignature]; NSInvocation *dupInvocation = [NSInvocation invocationWithMethodSignature:methodSignature]; [dupInvocation setSelector:[origInvocation selector]]; NSUInteger i, count = [methodSignature numberOfArguments]; for (i = 2; i < count; i++) { const char *type = [methodSignature getArgumentTypeAtIndex:i]; if (*type == *@encode(BOOL)) { BOOL value; [origInvocation getArgument:&value atIndex:i]; [dupInvocation setArgument:&value atIndex:i]; } else if (*type == *@encode(char) || *type == *@encode(unsigned char)) { char value; [origInvocation getArgument:&value atIndex:i]; [dupInvocation setArgument:&value atIndex:i]; } else if (*type == *@encode(short) || *type == *@encode(unsigned short)) { short value; [origInvocation getArgument:&value atIndex:i]; [dupInvocation setArgument:&value atIndex:i]; } else if (*type == *@encode(int) || *type == *@encode(unsigned int)) { int value; [origInvocation getArgument:&value atIndex:i]; [dupInvocation setArgument:&value atIndex:i]; } else if (*type == *@encode(long) || *type == *@encode(unsigned long)) { long value; [origInvocation getArgument:&value atIndex:i]; [dupInvocation setArgument:&value atIndex:i]; } else if (*type == *@encode(long long) || *type == *@encode(unsigned long long)) { long long value; [origInvocation getArgument:&value atIndex:i]; [dupInvocation setArgument:&value atIndex:i]; } else if (*type == *@encode(double)) { double value; [origInvocation getArgument:&value atIndex:i]; [dupInvocation setArgument:&value atIndex:i]; } else if (*type == *@encode(float)) { float value; [origInvocation getArgument:&value atIndex:i]; [dupInvocation setArgument:&value atIndex:i]; } else if (*type == '@') { id value; [origInvocation getArgument:&value atIndex:i]; [dupInvocation setArgument:&value atIndex:i]; } else { NSString *selectorStr = NSStringFromSelector([origInvocation selector]); NSString *format = @"Argument %lu to method %@ - Type(%c) not supported"; NSString *reason = [NSString stringWithFormat:format, (unsigned long)(i - 2), selectorStr, *type]; [[NSException exceptionWithName:NSInvalidArgumentException reason:reason userInfo:nil] raise]; } } [dupInvocation retainArguments]; return dupInvocation; } @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation GCDMulticastDelegateEnumerator - (id)initWithDelegateList:(GCDMulticastDelegateListNode *)delegateList { if ((self = [super init])) { numDelegates = 0; currentDelegateIndex = 0; // The delegate enumerator will provide a snapshot of the current delegate list. // // So, technically, delegates could be added/removed from the list while we're enumerating. GCDMulticastDelegateListNode *node = delegateList; // First we loop through the linked list so we can: // // - Get a count of the number of delegates // - Get a reference to the last delegate in the list // // Recall that new delegates are added to the beginning of the linked list. // The last delegate in the list is the first delegate that was added, so it will be the first that's invoked. // We're going to be moving backwards through the linked list as we add the delegates to our array. if (node != NULL) { numDelegates++; while (node->next != NULL) { numDelegates++; node = node->next; } // Note: The node variable is now pointing to the last node in the list. } // We're now going to create an array of all the nodes. // // Note: We're creating an array of pointers. // Each pointer points to the dynamically allocated struct. // We also retain each node, to prevent it from disappearing while we're enumerating the list. size_t ptrSize = sizeof(node); delegates = malloc(ptrSize * numDelegates); // Remember that delegates is a pointer to an array of pointers. // It's going to look something like this in memory: // // delegates ---> |ptr1|ptr2|ptr3|...| // // So delegates points to ptr1. // And due to pointer arithmetic, delegates+1 points to ptr2. NSUInteger i; for (i = 0; i < numDelegates; i++) { memcpy(delegates + i, &node, ptrSize); GCDMulticastDelegateListNodeRetain(node); node = node->prev; } } return self; } - (NSUInteger)count { return numDelegates; } - (NSUInteger)countOfClass:(Class)aClass { NSUInteger count = 0; NSUInteger index = 0; while (index < numDelegates) { GCDMulticastDelegateListNode *node = *(delegates + index); if ([node->delegate isKindOfClass:aClass]) { count++; } index++; } return count; } - (NSUInteger)countForSelector:(SEL)aSelector { NSUInteger count = 0; NSUInteger index = 0; while (index < numDelegates) { GCDMulticastDelegateListNode *node = *(delegates + index); if ([node->delegate respondsToSelector:aSelector]) { count++; } index++; } return count; } - (BOOL)getNextDelegate:(id *)delPtr delegateQueue:(dispatch_queue_t *)dqPtr { while (currentDelegateIndex < numDelegates) { GCDMulticastDelegateListNode *node = *(delegates + currentDelegateIndex); currentDelegateIndex++; if (node->delegate) { if (delPtr) *delPtr = node->delegate; if (dqPtr) *dqPtr = node->delegateQueue; return YES; } } return NO; } - (BOOL)getNextDelegate:(id *)delPtr delegateQueue:(dispatch_queue_t *)dqPtr ofClass:(Class)aClass { while (currentDelegateIndex < numDelegates) { GCDMulticastDelegateListNode *node = *(delegates + currentDelegateIndex); currentDelegateIndex++; if ([node->delegate isKindOfClass:aClass]) { if (delPtr) *delPtr = node->delegate; if (dqPtr) *dqPtr = node->delegateQueue; return YES; } } return NO; } - (BOOL)getNextDelegate:(id *)delPtr delegateQueue:(dispatch_queue_t *)dqPtr forSelector:(SEL)aSelector { while (currentDelegateIndex < numDelegates) { GCDMulticastDelegateListNode *node = *(delegates + currentDelegateIndex); currentDelegateIndex++; if ([node->delegate respondsToSelector:aSelector]) { if (delPtr) *delPtr = node->delegate; if (dqPtr) *dqPtr = node->delegateQueue; return YES; } } return NO; } - (void)dealloc { NSUInteger i; for (i = 0; i < numDelegates; i++) { GCDMulticastDelegateListNode *node = *(delegates + i); GCDMulticastDelegateListNodeRelease(node); } free(delegates); [super dealloc]; } @end
04081337-xmpp
Utilities/GCDMulticastDelegate.m
Objective-C
bsd
13,953
#import <Foundation/Foundation.h> #if TARGET_OS_IPHONE #import "DDXML.h" #endif @interface NSXMLElement (XMPP) + (NSXMLElement *)elementWithName:(NSString *)name xmlns:(NSString *)ns; - (id)initWithName:(NSString *)name xmlns:(NSString *)ns; - (NSXMLElement *)elementForName:(NSString *)name; - (NSXMLElement *)elementForName:(NSString *)name xmlns:(NSString *)xmlns; - (NSString *)xmlns; - (void)setXmlns:(NSString *)ns; - (NSString *)prettyXMLString; - (NSString *)compactXMLString; - (void)addAttributeWithName:(NSString *)name stringValue:(NSString *)string; - (int)attributeIntValueForName:(NSString *)name; - (BOOL)attributeBoolValueForName:(NSString *)name; - (float)attributeFloatValueForName:(NSString *)name; - (double)attributeDoubleValueForName:(NSString *)name; - (NSString *)attributeStringValueForName:(NSString *)name; - (NSNumber *)attributeNumberIntValueForName:(NSString *)name; - (NSNumber *)attributeNumberBoolValueForName:(NSString *)name; - (int)attributeIntValueForName:(NSString *)name withDefaultValue:(int)defaultValue; - (BOOL)attributeBoolValueForName:(NSString *)name withDefaultValue:(BOOL)defaultValue; - (float)attributeFloatValueForName:(NSString *)name withDefaultValue:(float)defaultValue; - (double)attributeDoubleValueForName:(NSString *)name withDefaultValue:(double)defaultValue; - (NSString *)attributeStringValueForName:(NSString *)name withDefaultValue:(NSString *)defaultValue; - (NSNumber *)attributeNumberIntValueForName:(NSString *)name withDefaultValue:(int)defaultValue; - (NSNumber *)attributeNumberBoolValueForName:(NSString *)name withDefaultValue:(BOOL)defaultValue; - (NSMutableDictionary *)attributesAsDictionary; - (void)addNamespaceWithPrefix:(NSString *)prefix stringValue:(NSString *)string; - (NSString *)namespaceStringValueForPrefix:(NSString *)prefix; - (NSString *)namespaceStringValueForPrefix:(NSString *)prefix withDefaultValue:(NSString *)defaultValue; @end
04081337-xmpp
Categories/NSXMLElement+XMPP.h
Objective-C
bsd
1,942
#import <Foundation/Foundation.h> @interface NSNumber (XMPP) + (NSNumber *)numberWithPtr:(const void *)ptr; - (id)initWithPtr:(const void *)ptr; + (BOOL)parseString:(NSString *)str intoSInt64:(SInt64 *)pNum; + (BOOL)parseString:(NSString *)str intoUInt64:(UInt64 *)pNum; + (BOOL)parseString:(NSString *)str intoNSInteger:(NSInteger *)pNum; + (BOOL)parseString:(NSString *)str intoNSUInteger:(NSUInteger *)pNum; + (UInt8)extractUInt8FromData:(NSData *)data atOffset:(unsigned int)offset; + (UInt16)extractUInt16FromData:(NSData *)data atOffset:(unsigned int)offset andConvertFromNetworkOrder:(BOOL)flag; + (UInt32)extractUInt32FromData:(NSData *)data atOffset:(unsigned int)offset andConvertFromNetworkOrder:(BOOL)flag; @end
04081337-xmpp
Categories/NSNumber+XMPP.h
Objective-C
bsd
733
#import "NSXMLElement+XMPP.h" @implementation NSXMLElement (XMPP) /** * Quick method to create an element **/ + (NSXMLElement *)elementWithName:(NSString *)name xmlns:(NSString *)ns { NSXMLElement *element = [NSXMLElement elementWithName:name]; [element setXmlns:ns]; return element; } - (id)initWithName:(NSString *)name xmlns:(NSString *)ns { if ([self initWithName:name]) { [self setXmlns:ns]; } return self; } /** * This method returns the first child element for the given name (as an NSXMLElement). * If no child elements exist for the given name, nil is returned. **/ - (NSXMLElement *)elementForName:(NSString *)name { NSArray *elements = [self elementsForName:name]; if([elements count] > 0) { return [elements objectAtIndex:0]; } else { // There is a bug in the NSXMLElement elementsForName: method. // Consider the following XML fragment: // // <query xmlns="jabber:iq:private"> // <x xmlns="some:other:namespace"></x> // </query> // // Calling [query elementsForName:@"x"] results in an empty array! // // However, it will work properly if you use the following: // [query elementsForLocalName:@"x" URI:@"some:other:namespace"] // // The trouble with this is that we may not always know the xmlns in advance, // so in this particular case there is no way to access the element without looping through the children. // // This bug was submitted to apple on June 1st, 2007 and was classified as "serious". // // --!!-- This bug does NOT exist in DDXML --!!-- return nil; } } /** * This method returns the first child element for the given name and given xmlns (as an NSXMLElement). * If no child elements exist for the given name and given xmlns, nil is returned. **/ - (NSXMLElement *)elementForName:(NSString *)name xmlns:(NSString *)xmlns { NSArray *elements = [self elementsForLocalName:name URI:xmlns]; if([elements count] > 0) { return [elements objectAtIndex:0]; } else { return nil; } } /** * Returns the common xmlns "attribute", which is only accessible via the namespace methods. * The xmlns value is often used in jabber elements. **/ - (NSString *)xmlns { return [[self namespaceForPrefix:@""] stringValue]; } - (void)setXmlns:(NSString *)ns { // If we use setURI: then the xmlns won't be displayed in the XMLString. // Adding the namespace this way works properly. [self addNamespace:[NSXMLNode namespaceWithName:@"" stringValue:ns]]; } /** * Shortcut to get a pretty (formatted) string representation of the element. **/ - (NSString *)prettyXMLString { return [self XMLStringWithOptions:(NSXMLNodePrettyPrint | NSXMLNodeCompactEmptyElement)]; } /** * Shortcut to get a compact string representation of the element. **/ - (NSString *)compactXMLString { return [self XMLStringWithOptions:NSXMLNodeCompactEmptyElement]; } /** * Shortcut to avoid having to use NSXMLNode everytime **/ - (void)addAttributeWithName:(NSString *)name stringValue:(NSString *)string { [self addAttribute:[NSXMLNode attributeWithName:name stringValue:string]]; } /** * The following methods return the corresponding value of the attribute with the given name. **/ - (int)attributeIntValueForName:(NSString *)name { return [[self attributeStringValueForName:name] intValue]; } - (BOOL)attributeBoolValueForName:(NSString *)name { return [[self attributeStringValueForName:name] boolValue]; } - (float)attributeFloatValueForName:(NSString *)name { return [[self attributeStringValueForName:name] floatValue]; } - (double)attributeDoubleValueForName:(NSString *)name { return [[self attributeStringValueForName:name] doubleValue]; } - (NSString *)attributeStringValueForName:(NSString *)name { return [[self attributeForName:name] stringValue]; } - (NSNumber *)attributeNumberIntValueForName:(NSString *)name { return [NSNumber numberWithInt:[self attributeIntValueForName:name]]; } - (NSNumber *)attributeNumberBoolValueForName:(NSString *)name { return [NSNumber numberWithBool:[self attributeBoolValueForName:name]]; } /** * The following methods return the corresponding value of the attribute with the given name. * If the attribute does not exist, the given defaultValue is returned. **/ - (int)attributeIntValueForName:(NSString *)name withDefaultValue:(int)defaultValue { NSXMLNode *attr = [self attributeForName:name]; return (attr) ? [[attr stringValue] intValue] : defaultValue; } - (BOOL)attributeBoolValueForName:(NSString *)name withDefaultValue:(BOOL)defaultValue { NSXMLNode *attr = [self attributeForName:name]; return (attr) ? [[attr stringValue] boolValue] : defaultValue; } - (float)attributeFloatValueForName:(NSString *)name withDefaultValue:(float)defaultValue { NSXMLNode *attr = [self attributeForName:name]; return (attr) ? [[attr stringValue] floatValue] : defaultValue; } - (double)attributeDoubleValueForName:(NSString *)name withDefaultValue:(double)defaultValue { NSXMLNode *attr = [self attributeForName:name]; return (attr) ? [[attr stringValue] doubleValue] : defaultValue; } - (NSString *)attributeStringValueForName:(NSString *)name withDefaultValue:(NSString *)defaultValue { NSXMLNode *attr = [self attributeForName:name]; return (attr) ? [attr stringValue] : defaultValue; } - (NSNumber *)attributeNumberIntValueForName:(NSString *)name withDefaultValue:(int)defaultValue { return [NSNumber numberWithInt:[self attributeIntValueForName:name withDefaultValue:defaultValue]]; } - (NSNumber *)attributeNumberBoolValueForName:(NSString *)name withDefaultValue:(BOOL)defaultValue { return [NSNumber numberWithBool:[self attributeBoolValueForName:name withDefaultValue:defaultValue]]; } /** * Returns all the attributes in a dictionary. **/ - (NSMutableDictionary *)attributesAsDictionary { NSArray *attributes = [self attributes]; NSMutableDictionary *result = [NSMutableDictionary dictionaryWithCapacity:[attributes count]]; NSUInteger i; for(i = 0; i < [attributes count]; i++) { NSXMLNode *node = [attributes objectAtIndex:i]; [result setObject:[node stringValue] forKey:[node name]]; } return result; } /** * Shortcut to avoid having to use NSXMLNode everytime **/ - (void)addNamespaceWithPrefix:(NSString *)prefix stringValue:(NSString *)string { [self addNamespace:[NSXMLNode namespaceWithName:prefix stringValue:string]]; } /** * Just to make your code look a little bit cleaner. **/ - (NSString *)namespaceStringValueForPrefix:(NSString *)prefix { return [[self namespaceForPrefix:prefix] stringValue]; } - (NSString *)namespaceStringValueForPrefix:(NSString *)prefix withDefaultValue:(NSString *)defaultValue { NSXMLNode *namespace = [self namespaceForPrefix:prefix]; return (namespace) ? [namespace stringValue] : defaultValue; } @end
04081337-xmpp
Categories/NSXMLElement+XMPP.m
Objective-C
bsd
6,746
#import "NSData+XMPP.h" #import <CommonCrypto/CommonDigest.h> @implementation NSData (XMPP) static char encodingTable[64] = { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P', 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f', 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v', 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' }; - (NSData *)md5Digest { unsigned char result[CC_MD5_DIGEST_LENGTH]; CC_MD5([self bytes], (CC_LONG)[self length], result); return [NSData dataWithBytes:result length:CC_MD5_DIGEST_LENGTH]; } - (NSData *)sha1Digest { unsigned char result[CC_SHA1_DIGEST_LENGTH]; CC_SHA1([self bytes], (CC_LONG)[self length], result); return [NSData dataWithBytes:result length:CC_SHA1_DIGEST_LENGTH]; } - (NSString *)hexStringValue { NSMutableString *stringBuffer = [NSMutableString stringWithCapacity:([self length] * 2)]; const unsigned char *dataBuffer = [self bytes]; int i; for (i = 0; i < [self length]; ++i) { [stringBuffer appendFormat:@"%02x", (unsigned long)dataBuffer[i]]; } return [[stringBuffer copy] autorelease]; } - (NSString *)base64Encoded { const unsigned char *bytes = [self bytes]; NSMutableString *result = [NSMutableString stringWithCapacity:[self length]]; unsigned long ixtext = 0; unsigned long lentext = [self length]; long ctremaining = 0; unsigned char inbuf[3], outbuf[4]; unsigned short i = 0; unsigned short charsonline = 0, ctcopy = 0; unsigned long ix = 0; while( YES ) { ctremaining = lentext - ixtext; if( ctremaining <= 0 ) break; for( i = 0; i < 3; i++ ) { ix = ixtext + i; if( ix < lentext ) inbuf[i] = bytes[ix]; else inbuf [i] = 0; } outbuf [0] = (inbuf [0] & 0xFC) >> 2; outbuf [1] = ((inbuf [0] & 0x03) << 4) | ((inbuf [1] & 0xF0) >> 4); outbuf [2] = ((inbuf [1] & 0x0F) << 2) | ((inbuf [2] & 0xC0) >> 6); outbuf [3] = inbuf [2] & 0x3F; ctcopy = 4; switch( ctremaining ) { case 1: ctcopy = 2; break; case 2: ctcopy = 3; break; } for( i = 0; i < ctcopy; i++ ) [result appendFormat:@"%c", encodingTable[outbuf[i]]]; for( i = ctcopy; i < 4; i++ ) [result appendString:@"="]; ixtext += 3; charsonline += 4; } return [NSString stringWithString:result]; } - (NSData *)base64Decoded { const unsigned char *bytes = [self bytes]; NSMutableData *result = [NSMutableData dataWithCapacity:[self length]]; unsigned long ixtext = 0; unsigned long lentext = [self length]; unsigned char ch = 0; unsigned char inbuf[4], outbuf[3]; short i = 0, ixinbuf = 0; BOOL flignore = NO; BOOL flendtext = NO; while( YES ) { if( ixtext >= lentext ) break; ch = bytes[ixtext++]; flignore = NO; if( ( ch >= 'A' ) && ( ch <= 'Z' ) ) ch = ch - 'A'; else if( ( ch >= 'a' ) && ( ch <= 'z' ) ) ch = ch - 'a' + 26; else if( ( ch >= '0' ) && ( ch <= '9' ) ) ch = ch - '0' + 52; else if( ch == '+' ) ch = 62; else if( ch == '=' ) flendtext = YES; else if( ch == '/' ) ch = 63; else flignore = YES; if( ! flignore ) { short ctcharsinbuf = 3; BOOL flbreak = NO; if( flendtext ) { if( ! ixinbuf ) break; if( ( ixinbuf == 1 ) || ( ixinbuf == 2 ) ) ctcharsinbuf = 1; else ctcharsinbuf = 2; ixinbuf = 3; flbreak = YES; } inbuf [ixinbuf++] = ch; if( ixinbuf == 4 ) { ixinbuf = 0; outbuf [0] = ( inbuf[0] << 2 ) | ( ( inbuf[1] & 0x30) >> 4 ); outbuf [1] = ( ( inbuf[1] & 0x0F ) << 4 ) | ( ( inbuf[2] & 0x3C ) >> 2 ); outbuf [2] = ( ( inbuf[2] & 0x03 ) << 6 ) | ( inbuf[3] & 0x3F ); for( i = 0; i < ctcharsinbuf; i++ ) [result appendBytes:&outbuf[i] length:1]; } if( flbreak ) break; } } return [NSData dataWithData:result]; } @end
04081337-xmpp
Categories/NSData+XMPP.m
Objective-C
bsd
3,856
#import <Foundation/Foundation.h> @interface NSData (XMPP) - (NSData *)md5Digest; - (NSData *)sha1Digest; - (NSString *)hexStringValue; - (NSString *)base64Encoded; - (NSData *)base64Decoded; @end
04081337-xmpp
Categories/NSData+XMPP.h
Objective-C
bsd
203
#import "NSNumber+XMPP.h" @implementation NSNumber (XMPP) + (NSNumber *)numberWithPtr:(const void *)ptr { return [[[NSNumber alloc] initWithPtr:ptr] autorelease]; } - (id)initWithPtr:(const void *)ptr { return [self initWithLong:(long)ptr]; } + (BOOL)parseString:(NSString *)str intoSInt64:(SInt64 *)pNum { if(str == nil) { *pNum = 0; return NO; } errno = 0; // On both 32-bit and 64-bit machines, long long = 64 bit *pNum = strtoll([str UTF8String], NULL, 10); if(errno != 0) return NO; else return YES; } + (BOOL)parseString:(NSString *)str intoUInt64:(UInt64 *)pNum { if(str == nil) { *pNum = 0; return NO; } errno = 0; // On both 32-bit and 64-bit machines, unsigned long long = 64 bit *pNum = strtoull([str UTF8String], NULL, 10); if(errno != 0) return NO; else return YES; } + (BOOL)parseString:(NSString *)str intoNSInteger:(NSInteger *)pNum { if(str == nil) { *pNum = 0; return NO; } errno = 0; // On LP64, NSInteger = long = 64 bit // Otherwise, NSInteger = int = long = 32 bit *pNum = strtol([str UTF8String], NULL, 10); if(errno != 0) return NO; else return YES; } + (BOOL)parseString:(NSString *)str intoNSUInteger:(NSUInteger *)pNum { if(str == nil) { *pNum = 0; return NO; } errno = 0; // On LP64, NSUInteger = unsigned long = 64 bit // Otherwise, NSUInteger = unsigned int = unsigned long = 32 bit *pNum = strtoul([str UTF8String], NULL, 10); if(errno != 0) return NO; else return YES; } + (UInt8)extractUInt8FromData:(NSData *)data atOffset:(unsigned int)offset { // 8 bits = 1 byte if([data length] < offset + 1) return 0; UInt8 *pResult = (UInt8 *)([data bytes] + offset); UInt8 result = *pResult; return result; } + (UInt16)extractUInt16FromData:(NSData *)data atOffset:(unsigned int)offset andConvertFromNetworkOrder:(BOOL)flag { // 16 bits = 2 bytes if([data length] < offset + 2) return 0; UInt16 *pResult = (UInt16 *)([data bytes] + offset); UInt16 result = *pResult; if(flag) return ntohs(result); else return result; } + (UInt32)extractUInt32FromData:(NSData *)data atOffset:(unsigned int)offset andConvertFromNetworkOrder:(BOOL)flag { // 32 bits = 4 bytes if([data length] < offset + 4) return 0; UInt32 *pResult = (UInt32 *)([data bytes] + offset); UInt32 result = *pResult; if(flag) return ntohl(result); else return result; } @end
04081337-xmpp
Categories/NSNumber+XMPP.m
Objective-C
bsd
2,415
#import "XMPPMessage+XEP0045.h" #import "NSXMLElement+XMPP.h" @implementation XMPPMessage(XEP0045) - (BOOL)isGroupChatMessage { return [[[self attributeForName:@"type"] stringValue] isEqualToString:@"groupchat"]; } - (BOOL)isGroupChatMessageWithBody { if ([self isGroupChatMessage]) { NSString *body = [[self elementForName:@"body"] stringValue]; return ((body != nil) && ([body length] > 0)); } return NO; } @end
04081337-xmpp
Extensions/XEP-0045/XMPPMessage+XEP0045.m
Objective-C
bsd
433
// // XMPPRoom // A chat room. XEP-0045 Implementation. // #import <Foundation/Foundation.h> #import "XMPP.h" #import "XMPPRoomOccupant.h" @interface XMPPRoom : XMPPModule { NSString *roomName; NSString *nickName; NSString *subject; NSString *invitedUser; BOOL _isJoined; NSMutableDictionary *occupants; } - (id)initWithRoomName:(NSString *)roomName nickName:(NSString *)nickName; - (id)initWithRoomName:(NSString *)roomName nickName:(NSString *)nickName dispatchQueue:(dispatch_queue_t)queue; @property (readonly) NSString *roomName; @property (readonly) NSString *nickName; @property (readonly) NSString *subject; @property (readonly, assign) BOOL isJoined; @property (readonly) NSDictionary *occupants; @property (readwrite, copy) NSString *invitedUser; - (void)createOrJoinRoom; - (void)joinRoom; - (void)leaveRoom; - (void)chageNickForRoom:(NSString *)name; - (void)inviteUser:(XMPPJID *)jid withMessage:(NSString *)invitationMessage; - (void)acceptInvitation; - (void)rejectInvitation; - (void)rejectInvitationWithMessage:(NSString *)reasonForRejection; - (void)sendMessage:(NSString *)msg; @end @protocol XMPPRoomDelegate <NSObject> @optional - (void)xmppRoomDidCreate:(XMPPRoom *)sender; - (void)xmppRoomDidEnter:(XMPPRoom *)sender; - (void)xmppRoomDidLeave:(XMPPRoom *)sender; - (void)xmppRoom:(XMPPRoom *)sender didReceiveMessage:(XMPPMessage *)message fromNick:(NSString *)nick; - (void)xmppRoom:(XMPPRoom *)sender didChangeOccupants:(NSDictionary *)occupants; @end
04081337-xmpp
Extensions/XEP-0045/XMPPRoom.h
Objective-C
bsd
1,499
// // XMPPRoomOccupant // A chat room. XEP-0045 Implementation. // #import "XMPPRoomOccupant.h" @implementation XMPPRoomOccupant + (XMPPRoomOccupant *)occupantWithJID:(XMPPJID *)aJid nick:(NSString *)aNick role:(NSString *)aRole { return [[[XMPPRoomOccupant alloc] initWithJID:aJid nick:aNick role:aRole] autorelease]; } @dynamic jid; @dynamic role; @dynamic nick; - (id)initWithJID:(XMPPJID *)aJid nick:(NSString *)aNick role:(NSString *)aRole { if ((self = [super init])) { jid = [aJid copy]; nick = [aNick copy]; role = [aRole copy]; } return self; } - (void)dealloc { [jid release]; [nick release]; [role release]; [super dealloc]; } // Why are these here? // Why not just let @synthesize do it for us? // // Since these variables are readonly, their getters should act like nonatomic getters. // However, using the label nonatomic on their property definitions is misleading, // and might cause some to assume this class isn't thread-safe when, in fact, it is. - (XMPPJID *)jid { return jid; } - (NSString *)nick { return nick; } - (NSString *)role { return role; } @end
04081337-xmpp
Extensions/XEP-0045/XMPPRoomOccupant.m
Objective-C
bsd
1,107
// // XMPPRoomOccupant // A chat room. XEP-0045 Implementation. // #import <Foundation/Foundation.h> @class XMPPJID; @interface XMPPRoomOccupant : NSObject { XMPPJID *jid; NSString *nick; NSString *role; } + (XMPPRoomOccupant *)occupantWithJID:(XMPPJID *)aJid nick:(NSString *)aNick role:(NSString *)aRole; - (id)initWithJID:(XMPPJID *)aJid nick:(NSString *)aNick role:(NSString *)aRole; @property (readonly) XMPPJID *jid; @property (readonly) NSString *nick; @property (readonly) NSString *role; @end
04081337-xmpp
Extensions/XEP-0045/XMPPRoomOccupant.h
Objective-C
bsd
512
#import "XMPPRoom.h" #import "XMPPMessage+XEP0045.h" #import "XMPPLogging.h" // Log levels: off, error, warn, info, verbose // Log flags: trace #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; // | XMPP_LOG_FLAG_TRACE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif static NSString *const XMPPMUCNamespaceName = @"http://jabber.org/protocol/muc"; static NSString *const XMPPMUCUserNamespaceName = @"http://jabber.org/protocol/muc#user"; static NSString *const XMPPMUCOwnerNamespaceName = @"http://jabber.org/protocol/muc#owner"; @interface XMPPRoom () @property (readwrite, assign) BOOL isJoined; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPRoom @dynamic roomName; @dynamic nickName; @dynamic subject; @dynamic isJoined; @dynamic occupants; @dynamic invitedUser; - (id)init { // This will cause a crash - it's designed to. // Only the init methods listed in XMPPRoom.h are supported. return [self initWithRoomName:nil nickName:nil dispatchQueue:NULL]; } - (id)initWithDispatchQueue:(dispatch_queue_t)queue { // This will cause a crash - it's designed to. // Only the init methods listed in XMPPRoom.h are supported. return [self initWithRoomName:nil nickName:nil dispatchQueue:NULL]; } - (id)initWithRoomName:(NSString *)aRoomName nickName:(NSString *)aNickName { return [self initWithRoomName:aRoomName nickName:aNickName dispatchQueue:NULL]; } - (id)initWithRoomName:(NSString *)aRoomName nickName:(NSString *)aNickName dispatchQueue:(dispatch_queue_t)queue { NSParameterAssert(aRoomName != nil); NSParameterAssert(aNickName != nil); if ((self = [super initWithDispatchQueue:queue])) { roomName = [aRoomName copy]; nickName = [aNickName copy]; occupants = [[NSMutableDictionary alloc] init]; XMPPLogTrace2(@"%@: init -> roomName(%@) nickName(%@)", [self class], roomName, nickName); } return self; } - (BOOL)activate:(XMPPStream *)aXmppStream { if ([super activate:aXmppStream]) { // Custom code goes here (if needed) return YES; } return NO; } - (void)deactivate { XMPPLogTrace(); if (self.isJoined) { [self leaveRoom]; } [super deactivate]; } - (void)dealloc { [roomName release]; [nickName release]; [subject release]; [invitedUser release]; [occupants release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Properties //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSString *)roomName { if (dispatch_get_current_queue() == moduleQueue) { return roomName; } else { // This variable is readonly - set in init method and never changed. return [[roomName retain] autorelease]; } } - (NSString *)nickName { if (dispatch_get_current_queue() == moduleQueue) { return nickName; } else { // This variable is readonly - set in init method and never changed. return [[nickName retain] autorelease]; } } - (NSString *)subject { if (dispatch_get_current_queue() == moduleQueue) { return subject; } else { __block NSString *result; dispatch_sync(moduleQueue, ^{ result = [subject retain]; }); return [result autorelease]; } } - (BOOL)isJoined { if (dispatch_get_current_queue() == moduleQueue) { return _isJoined; } else { __block BOOL result; dispatch_sync(moduleQueue, ^{ result = _isJoined; }); return result; } } - (void)setIsJoined:(BOOL)newIsJoined { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); if (_isJoined != newIsJoined) { _isJoined = newIsJoined; if (newIsJoined) [multicastDelegate xmppRoomDidEnter:self]; else [multicastDelegate xmppRoomDidLeave:self]; } } - (NSDictionary *)occupants { if (dispatch_get_current_queue() == moduleQueue) { return occupants; } else { __block NSDictionary *result; dispatch_sync(moduleQueue, ^{ result = [occupants copy]; }); return [result autorelease]; } } - (NSString *)invitedUser { if (dispatch_get_current_queue() == moduleQueue) { return invitedUser; } else { __block NSString *result; dispatch_sync(moduleQueue, ^{ result = [invitedUser retain]; }); return [result autorelease]; } } - (void)setInvitedUser:(NSString *)newInvitedUser { if (dispatch_get_current_queue() == moduleQueue) { if (![invitedUser isEqual:newInvitedUser]) { [invitedUser release]; invitedUser = [newInvitedUser retain]; } } else { NSString *newInvitedUserCopy = [newInvitedUser copy]; dispatch_async(moduleQueue, ^{ if (![invitedUser isEqual:newInvitedUserCopy]) { [invitedUser release]; invitedUser = [newInvitedUserCopy retain]; } }); [newInvitedUserCopy release]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Room Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)createOrJoinRoom { dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPLogTrace(); // <presence to='darkcave@chat.shakespeare.lit/firstwitch'> // <x xmlns='http://jabber.org/protocol/muc'/> // </presence> NSString *to = [NSString stringWithFormat:@"%@/%@", roomName, nickName]; NSXMLElement *x = [NSXMLElement elementWithName:@"x" xmlns:XMPPMUCNamespaceName]; XMPPPresence *presence = [XMPPPresence presence]; [presence addAttributeWithName:@"to" stringValue:to]; [presence addChild:x]; [xmppStream sendElement:presence]; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (void)sendInstantRoomConfig { dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPLogTrace(); // <iq type='set' // from='crone1@shakespeare.lit/desktop' // id='create1' // to='darkcave@chat.shakespeare.lit'> // <query xmlns='http://jabber.org/protocol/muc#owner'> // <x xmlns='jabber:x:data' type='submit'/> // </query> // </iq> NSXMLElement *x = [NSXMLElement elementWithName:@"x" xmlns:@"jabber:x:data"]; [x addAttributeWithName:@"type" stringValue:@"submit"]; NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:XMPPMUCOwnerNamespaceName]; [query addChild:x]; XMPPIQ *iq = [XMPPIQ iq]; [iq addAttributeWithName:@"id" stringValue:[NSString stringWithFormat:@"inroom-cr%@", roomName]]; [iq addAttributeWithName:@"to" stringValue:roomName]; [iq addAttributeWithName:@"type" stringValue:@"set"]; [iq addChild:query]; [xmppStream sendElement:iq]; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (void)joinRoom { dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPLogTrace(); // <presence to='darkcave@chat.shakespeare.lit/thirdwitch'/> NSString *to = [NSString stringWithFormat:@"%@/%@", roomName, nickName]; XMPPPresence *presence = [XMPPPresence presence]; [presence addAttributeWithName:@"to" stringValue:to]; [xmppStream sendElement:presence]; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (void)leaveRoom { dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPLogTrace(); // <presence type='unavailable' to='darkcave@chat.shakespeare.lit/thirdwitch'/> NSString *to = [NSString stringWithFormat:@"%@/%@", roomName, nickName]; XMPPPresence *presence = [XMPPPresence presence]; [presence addAttributeWithName:@"to" stringValue:to]; [presence addAttributeWithName:@"type" stringValue:@"unavailable"]; [xmppStream sendElement:presence]; self.isJoined = NO; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } /** * Changes the nickname for room by joining room again with new nick. **/ - (void)chageNickForRoom:(NSString *)newNickName { NSString *newNickNameCopy = [newNickName copy]; dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPLogTrace(); if (![nickName isEqual:newNickNameCopy]) { [nickName release]; nickName = [newNickNameCopy retain]; [self joinRoom]; } [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); [newNickNameCopy release]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark RoomInvite Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)inviteUser:(XMPPJID *)jid withMessage:(NSString *)inviteMessageStr { dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPLogTrace(); // <message to='darkcave@chat.shakespeare.lit'> // <x xmlns='http://jabber.org/protocol/muc#user'> // <invite to='hecate@shakespeare.lit'> // <reason> // Hey Hecate, this is the place for all good witches! // </reason> // </invite> // </x> // </message> NSXMLElement *reason = [NSXMLElement elementWithName:@"reason" stringValue:inviteMessageStr]; NSXMLElement *invite = [NSXMLElement elementWithName:@"invite"]; [invite addAttributeWithName:@"to" stringValue:[jid full]]; [invite addChild:reason]; NSXMLElement *x = [NSXMLElement elementWithName:@"x" xmlns:XMPPMUCUserNamespaceName]; [x addChild:invite]; XMPPMessage *message = [XMPPMessage message]; [message addAttributeWithName:@"to" stringValue:roomName]; [message addChild:x]; [xmppStream sendElement:message]; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (void)acceptInvitation { dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPLogTrace(); // Just need to send presence to room to accept it. We are done. [self joinRoom]; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (void)rejectInvitation { [self rejectInvitationWithMessage:nil]; } - (void)rejectInvitationWithMessage:(NSString *)rejectMessageStr { dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPLogTrace(); // <message to='darkcave@chat.shakespeare.lit'> // <x xmlns='http://jabber.org/protocol/muc#user'> // <decline to='crone1@shakespeare.lit'> // <reason> // Sorry, I'm too busy right now. // </reason> // </decline> // </x> // </message> NSXMLElement *reason = nil; if (rejectMessageStr) { reason = [NSXMLElement elementWithName:@"reason" stringValue:rejectMessageStr]; } NSXMLElement *decline = [NSXMLElement elementWithName:@"decline"]; [decline addAttributeWithName:@"to" stringValue:invitedUser]; if (reason) { [decline addChild:reason]; } NSXMLElement *x = [NSXMLElement elementWithName:@"x" xmlns:XMPPMUCUserNamespaceName]; [x addChild:decline]; NSXMLElement *message = [XMPPMessage message]; [message addAttributeWithName:@"to" stringValue:roomName]; [message addChild:x]; [xmppStream sendElement:message]; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Message Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)sendMessage:(NSString *)msg { if ([msg length] == 0) return; dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPLogTrace(); // <message type='groupchat' to='darkcave@chat.shakespeare.lit/firstwitch'> // <body>I'll give thee a wind.</body> // </message> NSXMLElement *body = [NSXMLElement elementWithName:@"body" stringValue:msg]; XMPPMessage *message = [XMPPMessage message]; [message addAttributeWithName:@"to" stringValue:roomName]; [message addAttributeWithName:@"type" stringValue:@"groupchat"]; [message addChild:body]; [xmppStream sendElement:message]; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPStream Delegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)onDidChangeOccupants { // We cannot directly pass our NSMutableDictionary *occupants // to the delegates as NSMutableDictionary is not thread-safe. // // And even if it was, we don't want this dictionary changing on them. // That's what this delegate method is for. // // So we create an immutable copy of the dictionary to send to the delegates. // And we don't have to worry about the XMPPRoomOccupant objects changing as they are immutable. NSDictionary *occupantsCopy = [[occupants copy] autorelease]; [multicastDelegate xmppRoom:self didChangeOccupants:occupantsCopy]; } - (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence { // This method must be invoked on the moduleQueue NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); NSArray *components = [[presence fromStr] componentsSeparatedByString:@"/"]; NSString *aRoomName = [components count] > 0 ? [components objectAtIndex:0] : nil; NSString *aNickName = [components count] > 1 ? [components objectAtIndex:1] : nil; if (![aRoomName isEqualToString:roomName]) return; XMPPLogTrace2(@"%@: didReceivePresence: ROOM: %@", [self class], roomName); NSXMLElement *priorityElement = [presence elementForName:@"priority"]; if (priorityElement) XMPPLogVerbose(@"%@: didReceivePresence: priority:%@", [self class], [priorityElement stringValue]); NSXMLElement *x = [presence elementForName:@"x" xmlns:XMPPMUCUserNamespaceName]; NSXMLElement *xItem = [x elementForName:@"item"]; NSString *jidStr = [xItem attributeStringValueForName:@"jid"]; NSString *role = [xItem attributeStringValueForName:@"role"]; NSString *newNick = [xItem attributeStringValueForName:@"nick"]; XMPPLogVerbose(@"%@: didReceivePresence: nick:%@ role:%@ newnick:%@ jid:%@", [self class], aNickName, role, newNick, jidStr); if (newNick) { // We are joined, getting presence for room self.isJoined = YES; // Handle nick Change having "nick" in <item> element. [occupants removeObjectForKey:aNickName]; // Add new room occupant XMPPJID *jid = [XMPPJID jidWithString:jidStr]; XMPPRoomOccupant *occupant = [XMPPRoomOccupant occupantWithJID:jid nick:newNick role:role]; [occupants setObject:occupant forKey:newNick]; [self onDidChangeOccupants]; return; } else if (aNickName) { if ([[presence type] isEqualToString:@"unavailable"]) { if ([aNickName isEqualToString:nickName]) { // We got presence from our nick to us about leaving. self.isJoined = NO; [occupants removeAllObjects]; [self onDidChangeOccupants]; } else { // We're getting presence from the room, so that means we are joined self.isJoined = YES; // This is about some one else leaving the Room. // Remove them and notify delegate. [occupants removeObjectForKey:aNickName]; [self onDidChangeOccupants]; } } else { // We're getting presence from the room, so that means we are joined self.isJoined = YES; // This is about some sort of available presence. i don't mind even if they are busy. // if the user is there. no need to notify. let's check that. XMPPRoomOccupant *occupant = [occupants objectForKey:aNickName]; if (!occupant) { XMPPJID *jid = [XMPPJID jidWithString:jidStr]; occupant = [XMPPRoomOccupant occupantWithJID:jid nick:aNickName role:role]; [occupants setObject:occupant forKey:aNickName]; [self onDidChangeOccupants]; } } } } - (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message { // This method must be invoked on the moduleQueue NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); // Check if its group chat, and make sure it's for this Room if ([message isGroupChatMessageWithBody]) { NSArray *components = [[message fromStr] componentsSeparatedByString:@"/"]; NSString *aRoomName = [components count] > 0 ? [components objectAtIndex:0] : nil; NSString *aNickName = [components count] > 1 ? [components objectAtIndex:1] : nil; if (![aRoomName isEqualToString:roomName]) return; if (aNickName == nil) { // Todo - A proper implementation... // NSString *body = [[message elementForName:@"body"] stringValue]; // // if ([body isEqualToString:@"This room is locked from entry until configuration is confirmed."]) // { // [self sendInstantRoomConfig]; // return; // } // // if ([body isEqualToString:@"This room is now unlocked."]) // { // [multicastDelegate xmppRoomDidCreate:self]; // return; // } } [multicastDelegate xmppRoom:self didReceiveMessage:message fromNick:aNickName]; } } @end
04081337-xmpp
Extensions/XEP-0045/XMPPRoom.m
Objective-C
bsd
18,217
#import <Foundation/Foundation.h> #import "XMPPMessage.h" @interface XMPPMessage(XEP0045) - (BOOL)isGroupChatMessage; - (BOOL)isGroupChatMessageWithBody; @end
04081337-xmpp
Extensions/XEP-0045/XMPPMessage+XEP0045.h
Objective-C
bsd
163
#import "XMPPTransports.h" #import "XMPP.h" @implementation XMPPTransports @synthesize xmppStream; - (id)initWithStream:(XMPPStream *)stream { if ((self = [super init])) { xmppStream = [stream retain]; } return self; } - (void)dealloc { [xmppStream release]; [super dealloc]; } /** * Registration process * @see: http://www.xmpp.org/extensions/xep-0100.html#usecases-jabber-register-pri **/ - (void)queryGatewayDiscoveryIdentityForLegacyService:(NSString *)service { XMPPJID *myJID = xmppStream.myJID; NSString *toValue = [NSString stringWithFormat:@"%@.%@", service, [myJID domain]]; // <iq type="get" from="myFullJID" to="service.domain" id="disco1"> // <query xmlns="http://jabber.org/protocol/disco#info"/> // </iq> NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"http://jabber.org/protocol/disco#info"]; NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"]; [iq addAttributeWithName:@"type" stringValue:@"get"]; [iq addAttributeWithName:@"from" stringValue:[myJID full]]; [iq addAttributeWithName:@"to" stringValue:toValue]; [iq addAttributeWithName:@"id" stringValue:@"disco1"]; [iq addChild:query]; [xmppStream sendElement:iq]; } - (void)queryGatewayAgentInfo { XMPPJID *myJID = xmppStream.myJID; // <iq type="get" from="myFullJID" to="domain" id="agent1"> // <query xmlns="jabber:iq:agents"/> // </iq> NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:agents"]; NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"]; [iq addAttributeWithName:@"type" stringValue:@"get"]; [iq addAttributeWithName:@"from" stringValue:[myJID full]]; [iq addAttributeWithName:@"to" stringValue:[myJID domain]]; [iq addAttributeWithName:@"id" stringValue:@"agent1"]; [iq addChild:query]; [xmppStream sendElement:iq]; } - (void)queryRegistrationRequirementsForLegacyService:(NSString *)service { XMPPJID *myJID = xmppStream.myJID; NSString *toValue = [NSString stringWithFormat:@"%@.%@", service, [myJID domain]]; // <iq type="get" from="myFullJID" to="service.domain" id="reg1"> // <query xmlns="jabber:iq:register"/> // </iq> NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:register"]; NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"]; [iq addAttributeWithName:@"type" stringValue:@"get"]; [iq addAttributeWithName:@"from" stringValue:[myJID full]]; [iq addAttributeWithName:@"to" stringValue:toValue]; [iq addAttributeWithName:@"id" stringValue:@"reg1"]; [iq addChild:query]; [xmppStream sendElement:iq]; } - (void)registerLegacyService:(NSString *)service username:(NSString *)username password:(NSString *)password { XMPPJID *myJID = xmppStream.myJID; NSString *toValue = [NSString stringWithFormat:@"%@.%@", service, [myJID domain]]; // <iq type="set" from="myFullJID" to="service.domain" id="reg2"> // <query xmlns="jabber:iq:register"> // <username>username</username> // <password>password</password> // </query> // </iq> NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:register"]; [query addChild:[NSXMLElement elementWithName:@"username" stringValue:username]]; [query addChild:[NSXMLElement elementWithName:@"password" stringValue:password]]; NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"]; [iq addAttributeWithName:@"type" stringValue:@"set"]; [iq addAttributeWithName:@"from" stringValue:[myJID full]]; [iq addAttributeWithName:@"to" stringValue:toValue]; [iq addAttributeWithName:@"id" stringValue:@"reg2"]; [iq addChild:query]; [xmppStream sendElement:iq]; } /** * Unregistration process * @see: http://www.xmpp.org/extensions/xep-0100.html#usecases-jabber-unregister-pri **/ - (void)unregisterLegacyService:(NSString *)service { XMPPJID *myJID = xmppStream.myJID; NSString *toValue = [NSString stringWithFormat:@"%@.%@", service, [myJID domain]]; // <iq type="set" from="myFullJID" to="service.domain" id="unreg1"> // <query xmlns="jabber:iq:register"> // <remove/> // </query> // </iq> NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:register"]; [query addChild:[NSXMLElement elementWithName:@"remove"]]; NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"]; [iq addAttributeWithName:@"type" stringValue:@"set"]; [iq addAttributeWithName:@"from" stringValue:[myJID full]]; [iq addAttributeWithName:@"to" stringValue:toValue]; [iq addAttributeWithName:@"id" stringValue:@"unreg1"]; [iq addChild:query]; [xmppStream sendElement:iq]; } @end
04081337-xmpp
Extensions/XEP-0100/XMPPTransports.m
Objective-C
bsd
4,580
#import <Foundation/Foundation.h> @class XMPPStream; @interface XMPPTransports : NSObject { XMPPStream *xmppStream; } - (id)initWithStream:(XMPPStream *)xmppStream; @property (nonatomic, readonly) XMPPStream *xmppStream; - (void)queryGatewayDiscoveryIdentityForLegacyService:(NSString *)service; - (void)queryGatewayAgentInfo; - (void)queryRegistrationRequirementsForLegacyService:(NSString *)service; - (void)registerLegacyService:(NSString *)service username:(NSString *)username password:(NSString *)password; - (void)unregisterLegacyService:(NSString *)service; @end
04081337-xmpp
Extensions/XEP-0100/XMPPTransports.h
Objective-C
bsd
579
#import <Foundation/Foundation.h> #import <SystemConfiguration/SystemConfiguration.h> #import "XMPPModule.h" #define DEFAULT_XMPP_RECONNECT_DELAY 2.0 #define DEFAULT_XMPP_RECONNECT_TIMER_INTERVAL 20.0 @protocol XMPPReconnectDelegate; /** * XMPPReconnect handles automatically reconnecting to the xmpp server due to accidental disconnections. * That is, a disconnection that is not the result of calling disconnect on the xmpp stream. * * Accidental disconnections may happen for a variety of reasons. * The most common are general connectivity issues such as disconnection from a WiFi access point. * * However, there are several of issues that occasionaly occur. * There are some routers on the market that disconnect TCP streams after a period of inactivity. * In addition to this, there have been iPhone revisions where the OS networking stack would pull the same crap. * These issue have been largely overcome due to the keepalive implementation in XMPPStream. * * Regardless of how the disconnect happens, the XMPPReconnect class can help to automatically re-establish * the xmpp stream so as to have minimum impact on the user (and hopefully they don't even notice). * * Once a stream has been opened and authenticated, this class will detect any accidental disconnections. * If one occurs, an attempt will be made to automatically reconnect after a short delay. * This delay is configurable via the reconnectDelay property. * At the same time the class will begin monitoring the network for reachability changes. * When the reachability of the xmpp host has changed, a reconnect may be tried again. * In addition to all this, a timer may optionally be used to attempt a reconnect periodically. * The timer is started if the initial reconnect fails. * This reconnect timer is fully configurable (may be enabled/disabled, and it's timeout may be changed). * * In all cases, prior to attempting a reconnect, * this class will invoke the shouldAttemptAutoReconnect delegate method. * The delegate may use this opportunity to optionally decline the auto reconnect attempt. * * Auto reconnect may be disabled at any time via the autoReconnect property. * * Note that auto reconnect will only occur for a stream that has been opened and authenticated. * So it will do nothing, for example, if there is no internet connectivity when your application * first launches, and the xmpp stream is unable to connect to the host. * In cases such as this it may be desireable to start monitoring the network for reachability changes. * This way when internet connectivity is restored, one can immediately connect the xmpp stream. * This is possible via the manualStart method, * which will trigger the class into action just as if an accidental disconnect occurred. **/ @interface XMPPReconnect : XMPPModule { Byte flags; Byte config; NSTimeInterval reconnectDelay; dispatch_source_t reconnectTimer; NSTimeInterval reconnectTimerInterval; SCNetworkReachabilityRef reachability; int reconnectTicket; #if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_5 SCNetworkConnectionFlags previousReachabilityFlags; #else SCNetworkReachabilityFlags previousReachabilityFlags; #endif } /** * Whether auto reconnect is enabled or disabled. * * The default value is YES (enabled). * * Note: Altering this property will only affect future accidental disconnections. * For example, if autoReconnect was true, and you disable this property after an accidental disconnection, * this will not stop the current reconnect process. * In order to stop a current reconnect process use the stop method. * * Similarly, if autoReconnect was false, and you enable this property after an accidental disconnection, * this will not start a reconnect process. * In order to start a reconnect process use the manualStart method. **/ @property (nonatomic, assign) BOOL autoReconnect; /** * When the accidental disconnection first happens, * a short delay may be used before attempting the reconnection. * * The default value is DEFAULT_XMPP_RECONNECT_DELAY (defined at the top of this file). * * To disable this feature, set the value to zero. * * Note: NSTimeInterval is a double that specifies the time in seconds. **/ @property (nonatomic, assign) NSTimeInterval reconnectDelay; /** * A reconnect timer may optionally be used to attempt a reconnect periodically. * The timer will be started after the initial reconnect delay. * * The default value is DEFAULT_XMPP_RECONNECT_TIMER_INTERVAL (defined at the top of this file). * * To disable this feature, set the value to zero. * * Note: NSTimeInterval is a double that specifies the time in seconds. **/ @property (nonatomic, assign) NSTimeInterval reconnectTimerInterval; /** * As opposed to using autoReconnect, this method may be used to manually start the reconnect process. * This may be useful, for example, if one needs network monitoring in order to setup the inital xmpp connection. * Or if one wants autoReconnect but only in very limited situations which they prefer to control manually. * * After invoking this method one can expect the class to act as if an accidental disconnect just occurred. * That is, a reconnect attempt will be tried after reconnectDelay seconds, * and the class will begin monitoring the network for changes in reachability to the xmpp host. * * A manual start of the reconnect process will effectively end once the xmpp stream has been opened. * That is, if you invoke manualStart and the xmpp stream is later opened, * then future disconnections will not result in an auto reconnect process (unless the autoReconnect property applies). * * This method does nothing if the xmpp stream is not disconnected. **/ - (void)manualStart; /** * Stops the current reconnect process. * * This method will stop the current reconnect process regardless of whether the * reconnect process was started due to the autoReconnect property or due to a call to manualStart. * * Stopping the reconnect process does NOT prevent future auto reconnects if the property is enabled. * That is, if the autoReconnect property is still enabled, and the xmpp stream is later opened, authenticated and * accidentally disconnected, this class will still attempt an automatic reconnect. * * Stopping the reconnect process does NOT prevent future calls to manualStart from working. * * It only stops the CURRENT reconnect process. **/ - (void)stop; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol XMPPReconnectDelegate @optional /** * This method may be used to fine tune when we * should and should not attempt an auto reconnect. * * For example, if on the iPhone, one may want to prevent auto reconnect when WiFi is not available. **/ #if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_5 - (void)xmppReconnect:(XMPPReconnect *)sender didDetectAccidentalDisconnect:(SCNetworkConnectionFlags)connectionFlags; - (BOOL)xmppReconnect:(XMPPReconnect *)sender shouldAttemptAutoReconnect:(SCNetworkConnectionFlags)connectionFlags; #else - (void)xmppReconnect:(XMPPReconnect *)sender didDetectAccidentalDisconnect:(SCNetworkReachabilityFlags)connectionFlags; - (BOOL)xmppReconnect:(XMPPReconnect *)sender shouldAttemptAutoReconnect:(SCNetworkReachabilityFlags)reachabilityFlags; #endif @end
04081337-xmpp
Extensions/Reconnect/XMPPReconnect.h
Objective-C
bsd
7,586
#import "XMPPReconnect.h" #import "XMPPStream.h" #import "XMPPLogging.h" #import "NSXMLElement+XMPP.h" #define IMPOSSIBLE_REACHABILITY_FLAGS 0xFFFFFFFF // Log levels: off, error, warn, info, verbose #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_VERBOSE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif enum XMPPReconnectFlags { kShouldReconnect = 1 << 0, // If set, disconnection was accidental, and autoReconnect may be used kMultipleChanges = 1 << 1, // If set, there have been reachability changes during a connection attempt kManuallyStarted = 1 << 2, // If set, we were started manually via manualStart method kQueryingDelegates = 1 << 3, // If set, we are awaiting response(s) from the delegate(s) }; enum XMPPReconnectConfig { kAutoReconnect = 1 << 0, // If set, automatically attempts to reconnect after a disconnection }; #if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_5 // SCNetworkConnectionFlags was renamed to SCNetworkReachabilityFlags in 10.6 typedef SCNetworkConnectionFlags SCNetworkReachabilityFlags; #endif @interface XMPPReconnect (PrivateAPI) - (void)setupReconnectTimer; - (void)teardownReconnectTimer; - (void)setupNetworkMonitoring; - (void)teardownNetworkMonitoring; - (void)maybeAttemptReconnect; - (void)maybeAttemptReconnectWithTicket:(int)ticket; - (void)maybeAttemptReconnectWithReachabilityFlags:(SCNetworkReachabilityFlags)reachabilityFlags; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPReconnect @dynamic autoReconnect; @synthesize reconnectDelay; @synthesize reconnectTimerInterval; - (id)init { return [self initWithDispatchQueue:NULL]; } - (id)initWithDispatchQueue:(dispatch_queue_t)queue { if ((self = [super initWithDispatchQueue:queue])) { flags = 0; config = kAutoReconnect; reconnectDelay = DEFAULT_XMPP_RECONNECT_DELAY; reconnectTimerInterval = DEFAULT_XMPP_RECONNECT_TIMER_INTERVAL; reconnectTicket = 0; previousReachabilityFlags = IMPOSSIBLE_REACHABILITY_FLAGS; } return self; } - (void)dealloc { dispatch_block_t block = ^{ [self teardownReconnectTimer]; [self teardownNetworkMonitoring]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_sync(moduleQueue, block); [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Configuration and Flags //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)autoReconnect { __block BOOL result; dispatch_block_t block = ^{ result = (config & kAutoReconnect) ? YES : NO; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_sync(moduleQueue, block); return result; } - (void)setAutoReconnect:(BOOL)flag { dispatch_block_t block = ^{ if (flag) config |= kAutoReconnect; else config &= ~kAutoReconnect; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (BOOL)shouldReconnect { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked private method outside moduleQueue"); return (flags & kShouldReconnect) ? YES : NO; } - (void)setShouldReconnect:(BOOL)flag { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked private method outside moduleQueue"); if (flag) flags |= kShouldReconnect; else flags &= ~kShouldReconnect; } - (BOOL)multipleReachabilityChanges { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked private method outside moduleQueue"); return (flags & kMultipleChanges) ? YES : NO; } - (void)setMultipleReachabilityChanges:(BOOL)flag { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked private method outside moduleQueue"); if (flag) flags |= kMultipleChanges; else flags &= ~kMultipleChanges; } - (BOOL)manuallyStarted { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked private method outside moduleQueue"); return (flags & kManuallyStarted) ? YES : NO; } - (void)setManuallyStarted:(BOOL)flag { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked private method outside moduleQueue"); if (flag) flags |= kManuallyStarted; else flags &= ~kManuallyStarted; } - (BOOL)queryingDelegates { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked private method outside moduleQueue"); return (flags & kQueryingDelegates) ? YES : NO; } - (void)setQueryingDelegates:(BOOL)flag { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked private method outside moduleQueue"); if (flag) flags |= kQueryingDelegates; else flags &= ~kQueryingDelegates; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Manual Manipulation //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)manualStart { dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if ([xmppStream isDisconnected] && [self manuallyStarted] == NO) { [self setManuallyStarted:YES]; [self setupReconnectTimer]; [self setupNetworkMonitoring]; } [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (void)stop { dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Clear all flags to disable any further reconnect attemts regardless of the state we're in. flags = 0; // Stop any planned reconnect attempts and stop monitoring the network. reconnectTicket++; [self teardownReconnectTimer]; [self teardownNetworkMonitoring]; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPStream Delegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)xmppStreamDidConnect:(XMPPStream *)sender { // This method is executed on our moduleQueue. // The stream is up so we can stop our reconnect attempts now. // // We essentially want to do the same thing as the stop method with one exception: // We do not want to clear the shouldReconnect flag. // // Remember the shouldReconnect flag gets set upon authentication. // A combination of this flag and the autoReconnect flag controls the auto reconnect mechanism. // // It is possible for us to get accidentally disconnected after // the stream opens but prior to authentication completing. // If this happens we still want to abide by the previous shouldReconnect setting. [self setMultipleReachabilityChanges:NO]; [self setManuallyStarted:NO]; reconnectTicket++; [self teardownReconnectTimer]; [self teardownNetworkMonitoring]; } - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender { // This method is executed on our moduleQueue. // We're now connected and properly authenticated. // Should we get accidentally disconnected we should automatically reconnect (if autoReconnect is set). [self setShouldReconnect:YES]; } - (void)xmppStream:(XMPPStream *)sender didReceiveError:(NSXMLElement *)element { // This method is executed on our moduleQueue. // <stream:error> // <conflict xmlns="urn:ietf:params:xml:ns:xmpp-streams"/> // <text xmlns="urn:ietf:params:xml:ns:xmpp-streams" xml:lang="">Replaced by new connection</text> // </stream:error> // // If our connection ever gets replaced, we shouldn't attempt a reconnect, // because the user has logged in on another device. // If we still applied the reconnect logic, // the two devices may get into an infinite loop of kicking each other off the system. NSString *elementName = [element name]; if ([elementName isEqualToString:@"stream:error"] || [elementName isEqualToString:@"error"]) { NSXMLElement *conflict = [element elementForName:@"conflict" xmlns:@"urn:ietf:params:xml:ns:xmpp-streams"]; if (conflict) { [self setShouldReconnect:NO]; } } } - (void)xmppStreamWasToldToDisconnect:(XMPPStream *)sender { // This method is executed on our moduleQueue. // We should not automatically attempt to reconnect when the connection closes. [self stop]; } - (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error { // This method is executed on our moduleQueue. if ([self autoReconnect] && [self shouldReconnect]) { [self setupReconnectTimer]; [self setupNetworkMonitoring]; SCNetworkReachabilityFlags reachabilityFlags = 0; SCNetworkReachabilityGetFlags(reachability, &reachabilityFlags); [multicastDelegate xmppReconnect:self didDetectAccidentalDisconnect:reachabilityFlags]; } if ([self multipleReachabilityChanges]) { // While the previous connection attempt was in progress, the reachability of the xmpp host changed. // This means that while the previous attempt failed, an attempt now might succeed. int ticket = ++reconnectTicket; dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (0.1 * NSEC_PER_SEC)); dispatch_after(tt, moduleQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self maybeAttemptReconnectWithTicket:ticket]; [pool drain]; }); // Note: We delay the method call. // This allows the other delegates to be notified of the closed stream prior to our reconnect attempt. } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Reachability //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static void ReachabilityChanged(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPReconnect *instance = (XMPPReconnect *)info; [instance maybeAttemptReconnectWithReachabilityFlags:flags]; [pool release]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Logic //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)setupReconnectTimer { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); if (reconnectTimer == NULL) { if ((reconnectDelay <= 0.0) && (reconnectTimerInterval <= 0.0)) { // All timed reconnect attempts are disabled return; } reconnectTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, moduleQueue); dispatch_source_set_event_handler(reconnectTimer, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self maybeAttemptReconnect]; [pool drain]; }); dispatch_source_t theReconnectTimer = reconnectTimer; dispatch_source_set_cancel_handler(reconnectTimer, ^{ XMPPLogVerbose(@"dispatch_release(reconnectTimer)"); dispatch_release(theReconnectTimer); }); dispatch_time_t startTime; if (reconnectDelay > 0.0) startTime = dispatch_time(DISPATCH_TIME_NOW, (reconnectDelay * NSEC_PER_SEC)); else startTime = dispatch_time(DISPATCH_TIME_NOW, (reconnectTimerInterval * NSEC_PER_SEC)); uint64_t intervalTime; if (reconnectTimerInterval > 0.0) intervalTime = reconnectTimerInterval * NSEC_PER_SEC; else intervalTime = 0.0; dispatch_source_set_timer(reconnectTimer, startTime, intervalTime, 0.25); dispatch_resume(reconnectTimer); } } - (void)teardownReconnectTimer { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); if (reconnectTimer) { dispatch_source_cancel(reconnectTimer); reconnectTimer = NULL; } } - (void)setupNetworkMonitoring { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); if (reachability == NULL) { NSString *domain = xmppStream.hostName; if (domain == nil) { domain = @"apple.com"; } reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); if (reachability) { SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL}; SCNetworkReachabilitySetCallback(reachability, ReachabilityChanged, &context); CFRunLoopRef xmppRunLoop = [[xmppStream xmppUtilityRunLoop] getCFRunLoop]; if (xmppRunLoop) { SCNetworkReachabilityScheduleWithRunLoop(reachability, xmppRunLoop, kCFRunLoopDefaultMode); } else { XMPPLogWarn(@"%@: %@ - No xmpp run loop available!", THIS_FILE, THIS_METHOD); } } } } - (void)teardownNetworkMonitoring { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); if (reachability) { CFRunLoopRef xmppRunLoop = [[xmppStream xmppUtilityRunLoop] getCFRunLoop]; if (xmppRunLoop) { SCNetworkReachabilityUnscheduleFromRunLoop(reachability, xmppRunLoop, kCFRunLoopDefaultMode); } else { XMPPLogWarn(@"%@: %@ - No xmpp run loop available!", THIS_FILE, THIS_METHOD); } SCNetworkReachabilitySetCallback(reachability, NULL, NULL); CFRelease(reachability); reachability = NULL; } } /** * This method may be invoked by the reconnectTimer. * * During auto reconnection it is invoked reconnectDelay seconds after an accidental disconnection. * After that, it is then invoked every reconnectTimerInterval seconds. * * This handles disconnections that were not the result of an internet connectivity issue. **/ - (void)maybeAttemptReconnect { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); if (reachability) { SCNetworkReachabilityFlags reachabilityFlags; if (SCNetworkReachabilityGetFlags(reachability, &reachabilityFlags)) { [self maybeAttemptReconnectWithReachabilityFlags:reachabilityFlags]; } } } /** * This method is invoked (after a short delay) if the reachability changed while * a reconnection attempt was in progress. **/ - (void)maybeAttemptReconnectWithTicket:(int)ticket { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); if (ticket != reconnectTicket) { // The dispatched task was cancelled. return; } if (reachability) { SCNetworkReachabilityFlags reachabilityFlags; if (SCNetworkReachabilityGetFlags(reachability, &reachabilityFlags)) { [self maybeAttemptReconnectWithReachabilityFlags:reachabilityFlags]; } } } - (void)maybeAttemptReconnectWithReachabilityFlags:(SCNetworkReachabilityFlags)reachabilityFlags { if (dispatch_get_current_queue() != moduleQueue) { dispatch_async(moduleQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self maybeAttemptReconnectWithReachabilityFlags:reachabilityFlags]; [pool drain]; }); return; } if (([self manuallyStarted]) || ([self autoReconnect] && [self shouldReconnect])) { if ([xmppStream isDisconnected] && ([self queryingDelegates] == NO)) { // The xmpp stream is disconnected, and is not attempting reconnection // Delegate rules: // // If ALL of the delegates return YES, then the result is YES. // If ANY of the delegates return NO, then the result is NO. // If there are no delegates, the default answer is YES. GCDMulticastDelegateEnumerator *delegateEnumerator = [multicastDelegate delegateEnumerator]; id del; dispatch_queue_t dq; SEL selector = @selector(xmppReconnect:shouldAttemptAutoReconnect:); NSUInteger delegateCount = [delegateEnumerator countForSelector:selector]; dispatch_semaphore_t delSemaphore = dispatch_semaphore_create(0); dispatch_group_t delGroup = dispatch_group_create(); while ([delegateEnumerator getNextDelegate:&del delegateQueue:&dq forSelector:selector]) { dispatch_group_async(delGroup, dq, ^{ NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init]; if (![del xmppReconnect:self shouldAttemptAutoReconnect:reachabilityFlags]) { dispatch_semaphore_signal(delSemaphore); } [innerPool release]; }); } [self setQueryingDelegates:YES]; dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(concurrentQueue, ^{ NSAutoreleasePool *outerPool = [[NSAutoreleasePool alloc] init]; dispatch_group_wait(delGroup, DISPATCH_TIME_FOREVER); // What was the delegate response? BOOL shouldAttemptReconnect; if (delegateCount == 0) { shouldAttemptReconnect = YES; } else { shouldAttemptReconnect = (dispatch_semaphore_wait(delSemaphore, DISPATCH_TIME_NOW) != 0); } dispatch_async(moduleQueue, ^{ NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init]; [self setQueryingDelegates:NO]; if (shouldAttemptReconnect) { [self setMultipleReachabilityChanges:NO]; previousReachabilityFlags = reachabilityFlags; [xmppStream connect:nil]; } else if ([self multipleReachabilityChanges]) { [self setMultipleReachabilityChanges:NO]; previousReachabilityFlags = IMPOSSIBLE_REACHABILITY_FLAGS; [self maybeAttemptReconnect]; } else { previousReachabilityFlags = IMPOSSIBLE_REACHABILITY_FLAGS; } [innerPool drain]; }); dispatch_release(delSemaphore); dispatch_release(delGroup); [outerPool drain]; }); } else { // The xmpp stream is already attempting a connection. if (reachabilityFlags != previousReachabilityFlags) { // It seems that the reachability of our xmpp host has changed in the middle of either // a reconnection attempt or while querying our delegates for permission to attempt reconnect. // // This may mean that the current attempt will fail, // but an another attempt after the failure will succeed. // // We make a note of the multiple changes, // and if the current attempt fails, we'll try again after a short delay. [self setMultipleReachabilityChanges:YES]; } } } } @end
04081337-xmpp
Extensions/Reconnect/XMPPReconnect.m
Objective-C
bsd
18,652
#import "XMPPElement+Delay.h" #import "XMPPDateTimeProfiles.h" #import "NSXMLElement+XMPP.h" @implementation XMPPElement (XEP0203) - (BOOL)wasDelayed { NSXMLElement *delay; delay = [self elementForName:@"delay" xmlns:@"urn:xmpp:delay"]; if (delay) { return YES; } delay = [self elementForName:@"delay" xmlns:@"jabber:x:delay"]; if (delay) { return YES; } return NO; } - (NSDate *)delayedDeliveryDate { NSXMLElement *delay; // From XEP-0203 (Delayed Delivery) // // <delay xmlns='urn:xmpp:delay' // from='juliet@capulet.com/balcony' // stamp='2002-09-10T23:41:07Z'/> // // The format [of the stamp attribute] MUST adhere to the dateTime format // specified in XEP-0082 and MUST be expressed in UTC. delay = [self elementForName:@"delay" xmlns:@"urn:xmpp:delay"]; if (delay) { NSString *stampValue = [delay attributeStringValueForName:@"stamp"]; // There are other considerations concerning XEP-0082. // For example, it may optionally contain milliseconds. // And it may possibly express UTC as "+00:00" instead of "Z". // // Thankfully there is already an implementation that takes into account all these possibilities. return [XMPPDateTimeProfiles parseDateTime:stampValue]; } // From XEP-0091 (Legacy Delayed Delivery) // // <x xmlns='jabber:x:delay' // from='capulet.com' // stamp='20020910T23:08:25'> delay = [self elementForName:@"delay" xmlns:@"jabber:x:delay"]; if (delay) { NSDate *stamp; NSString *stampValue = [delay attributeStringValueForName:@"stamp"]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4]; [dateFormatter setDateFormat:@"yyyyMMdd'T'HH:mm:ss"]; [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]]; stamp = [dateFormatter dateFromString:stampValue]; [dateFormatter release]; return stamp; } return nil; } @end
04081337-xmpp
Extensions/XEP-0203/XMPPElement+Delay.m
Objective-C
bsd
1,969
#import <Foundation/Foundation.h> #import "XMPPElement.h" @interface XMPPElement (XEP0203) - (BOOL)wasDelayed; - (NSDate *)delayedDeliveryDate; @end
04081337-xmpp
Extensions/XEP-0203/XMPPElement+Delay.h
Objective-C
bsd
153
#import "XMPPPing.h" #import "XMPP.h" #import "XMPPIDTracker.h" #define DEFAULT_TIMEOUT 30.0 // seconds #define INTEGRATE_WITH_CAPABILITIES 1 #if INTEGRATE_WITH_CAPABILITIES #import "XMPPCapabilities.h" #endif //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @interface XMPPPingInfo : XMPPBasicTrackingInfo { NSDate *timeSent; } @property (nonatomic, readonly) NSDate *timeSent; - (NSTimeInterval)rtt; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPPing - (id)init { return [self initWithDispatchQueue:NULL]; } - (id)initWithDispatchQueue:(dispatch_queue_t)queue { if ((self = [super initWithDispatchQueue:queue])) { respondsToQueries = YES; } return self; } - (BOOL)activate:(XMPPStream *)aXmppStream { if ([super activate:aXmppStream]) { #if INTEGRATE_WITH_CAPABILITIES [xmppStream autoAddDelegate:self delegateQueue:moduleQueue toModulesOfClass:[XMPPCapabilities class]]; #endif pingTracker = [[XMPPIDTracker alloc] initWithDispatchQueue:moduleQueue]; return YES; } return NO; } - (void)deactivate { #if INTEGRATE_WITH_CAPABILITIES [xmppStream removeAutoDelegate:self delegateQueue:moduleQueue fromModulesOfClass:[XMPPCapabilities class]]; #endif dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [pingTracker removeAllIDs]; [pingTracker release]; pingTracker = nil; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_sync(moduleQueue, block); [super deactivate]; } - (void)dealloc { // pingTracker is handled in the deactivate method, // which is automatically called by [super dealloc] if needed. [super dealloc]; } - (BOOL)respondsToQueries { if (dispatch_get_current_queue() == moduleQueue) { return respondsToQueries; } else { __block BOOL result; dispatch_sync(moduleQueue, ^{ result = respondsToQueries; }); return result; } } - (void)setRespondsToQueries:(BOOL)flag { dispatch_block_t block = ^{ if (respondsToQueries != flag) { respondsToQueries = flag; #if INTEGRATE_WITH_CAPABILITIES // Capabilities may have changed, need to notify others. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPPresence *presence = xmppStream.myPresence; if (presence) { [xmppStream sendElement:presence]; } [pool drain]; #endif } }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (NSString *)generatePingIDWithTimeout:(NSTimeInterval)timeout { // This method may be invoked on any thread/queue. // Generate unique ID for Ping packet // It's important the ID be unique as the ID is the only thing that distinguishes a pong packet NSString *pingID = [xmppStream generateUUID]; dispatch_async(moduleQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPPingInfo *pingInfo = [[XMPPPingInfo alloc] initWithTarget:self selector:@selector(handlePong:withInfo:) timeout:timeout]; [pingTracker addID:pingID trackingInfo:pingInfo]; [pingInfo release]; [pool release]; }); return pingID; } - (NSString *)sendPingToServer { // This is a public method. // It may be invoked on any thread/queue. return [self sendPingToServerWithTimeout:DEFAULT_TIMEOUT]; } - (NSString *)sendPingToServerWithTimeout:(NSTimeInterval)timeout { // This is a public method. // It may be invoked on any thread/queue. NSString *pingID = [self generatePingIDWithTimeout:timeout]; // Send ping packet // // <iq type="get" id="pingID"> // <ping xmlns="urn:xmpp:ping"/> // </iq> NSXMLElement *ping = [NSXMLElement elementWithName:@"ping" xmlns:@"urn:xmpp:ping"]; XMPPIQ *iq = [XMPPIQ iqWithType:@"get" to:nil elementID:pingID child:ping]; [xmppStream sendElement:iq]; return pingID; } - (NSString *)sendPingToJID:(XMPPJID *)jid { // This is a public method. // It may be invoked on any thread/queue. return [self sendPingToJID:jid withTimeout:DEFAULT_TIMEOUT]; } - (NSString *)sendPingToJID:(XMPPJID *)jid withTimeout:(NSTimeInterval)timeout { // This is a public method. // It may be invoked on any thread/queue. NSString *pingID = [self generatePingIDWithTimeout:timeout]; // Send ping element // // <iq to="fullJID" type="get" id="pingID"> // <ping xmlns="urn:xmpp:ping"/> // </iq> NSXMLElement *ping = [NSXMLElement elementWithName:@"ping" xmlns:@"urn:xmpp:ping"]; XMPPIQ *iq = [XMPPIQ iqWithType:@"get" to:jid elementID:pingID child:ping]; [xmppStream sendElement:iq]; return pingID; } - (void)handlePong:(XMPPIQ *)pongIQ withInfo:(XMPPPingInfo *)pingInfo { if (pongIQ) { [multicastDelegate xmppPing:self didReceivePong:pongIQ withRTT:[pingInfo rtt]]; } else { // Timeout [multicastDelegate xmppPing:self didNotReceivePong:[pingInfo elementID] dueToTimeout:[pingInfo timeout]]; } } - (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq { // This method is invoked on the moduleQueue. NSString *type = [iq type]; if ([type isEqualToString:@"result"] || [type isEqualToString:@"error"]) { // Example: // // <iq from="deusty.com" to="robbiehanson@deusty.com/work" id="abc123" type="result"/> // If this is a response to a ping that we've sent, // then the pingTracker will invoke our handlePong:withInfo: method and return YES. return [pingTracker invokeForID:[iq elementID] withObject:iq]; } else if (respondsToQueries && [type isEqualToString:@"get"]) { // Example: // // <iq from="deusty.com" to="robbiehanson@deusty.com/work" id="zhq325" type="get"> // <ping xmlns="urn:xmpp:ping"/> // </iq> NSXMLElement *ping = [iq elementForName:@"ping" xmlns:@"urn:xmpp:ping"]; if (ping) { XMPPIQ *pong = [XMPPIQ iqWithType:@"result" to:[iq from] elementID:[iq elementID]]; [sender sendElement:pong]; return YES; } } return NO; } - (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error { [pingTracker removeAllIDs]; } #if INTEGRATE_WITH_CAPABILITIES /** * If an XMPPCapabilites instance is used we want to advertise our support for ping. **/ - (void)xmppCapabilities:(XMPPCapabilities *)sender collectingMyCapabilities:(NSXMLElement *)query { // This method is invoked on the moduleQueue. if (respondsToQueries) { // <query xmlns="http://jabber.org/protocol/disco#info"> // ... // <feature var="urn:xmpp:ping"/> // ... // </query> NSXMLElement *feature = [NSXMLElement elementWithName:@"feature"]; [feature addAttributeWithName:@"var" stringValue:@"urn:xmpp:ping"]; [query addChild:feature]; } } #endif @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPPingInfo @synthesize timeSent; - (id)initWithTarget:(id)aTarget selector:(SEL)aSelector timeout:(NSTimeInterval)aTimeout { if ((self = [super initWithTarget:aTarget selector:aSelector timeout:aTimeout])) { timeSent = [[NSDate alloc] init]; } return self; } - (NSTimeInterval)rtt { return [timeSent timeIntervalSinceNow] * -1.0; } - (void)dealloc { [timeSent release]; [super dealloc]; } @end
04081337-xmpp
Extensions/XEP-0199/XMPPPing.m
Objective-C
bsd
7,903
#import <Foundation/Foundation.h> #import "XMPPModule.h" @class XMPPJID; @class XMPPStream; @class XMPPIQ; @class XMPPIDTracker; @protocol XMPPPingDelegate; @interface XMPPPing : XMPPModule { BOOL respondsToQueries; XMPPIDTracker *pingTracker; } /** * Whether or not the module should respond to incoming ping queries. * It you create multiple instances of this module, only one instance should respond to queries. * * It is recommended you set this (if needed) before you activate the module. * The default value is YES. **/ @property (readwrite) BOOL respondsToQueries; /** * Send pings to the server or a specific JID. * The disco module may be used to detect if the target supports ping. * * The returned string is the pingID (the elementID of the query that was sent). * In other words: * * SEND: <iq id="<returned_string>" type="get" .../> * RECV: <iq id="<returned_string>" type="result" .../> * * This may be helpful if you are sending multiple simultaneous pings to the same target. **/ - (NSString *)sendPingToServer; - (NSString *)sendPingToServerWithTimeout:(NSTimeInterval)timeout; - (NSString *)sendPingToJID:(XMPPJID *)jid; - (NSString *)sendPingToJID:(XMPPJID *)jid withTimeout:(NSTimeInterval)timeout; @end @protocol XMPPPingDelegate @optional - (void)xmppPing:(XMPPPing *)sender didReceivePong:(XMPPIQ *)pong withRTT:(NSTimeInterval)rtt; - (void)xmppPing:(XMPPPing *)sender didNotReceivePong:(NSString *)pingID dueToTimeout:(NSTimeInterval)timeout; // Note: If the xmpp stream is disconnected, no delegate methods will be called, and outstanding pings are forgotten. @end
04081337-xmpp
Extensions/XEP-0199/XMPPPing.h
Objective-C
bsd
1,621
#import <Foundation/Foundation.h> #import "XMPPModule.h" #import "XMPPPing.h" @class XMPPJID; /** * The XMPPAutoPing module sends pings on a designated interval to the target. * The target may simply be the server, or a specific resource. * * The module only sends pings as needed. * If the xmpp stream is receiving data from the target, there's no need to send a ping. * Only when no data has been received from the target is a ping sent. **/ @interface XMPPAutoPing : XMPPModule { @private NSTimeInterval pingInterval; NSTimeInterval pingTimeout; XMPPJID *targetJID; NSString *targetJIDStr; dispatch_time_t lastReceiveTime; dispatch_source_t pingIntervalTimer; BOOL awaitingPingResponse; XMPPPing *xmppPing; } /** * How often to send a ping. * * The internal timer fires every (pingInterval / 4) seconds. * Upon firing it checks when data was last received from the target, * and sends a ping if the elapsed time has exceeded the pingInterval. * Thus the effective resolution of the timer is based on the configured interval. * * To temporarily disable auto-ping, set the interval to zero. * * The default pingInterval is 60 seconds. **/ @property (readwrite) NSTimeInterval pingInterval; /** * How long to wait after sending a ping before timing out. * * The timeout is decoupled from the pingInterval to allow for longer pingIntervals, * which avoids flooding the network, and to allow more precise control overall. * * After a ping is sent, if a reply is not received by this timeout, * the delegate method is invoked. * * The default pingTimeout is 10 seconds. **/ @property (readwrite) NSTimeInterval pingTimeout; /** * The target to send pings to. * * If the targetJID is nil, this implies the target is the xmpp server we're connected to. * In this case, receiving any data means we've received data from the target. * * If the targetJID is non-nil, it must be a full JID (user@domain.tld/rsrc). * In this case, the module will monitor the stream for data from the given JID. * * The default targetJID is nil. **/ @property (readwrite, retain) XMPPJID *targetJID; /** * The last time data was received from the target. **/ @property (readonly) dispatch_time_t lastReceiveTime; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol XMPPAutoPingDelegate @optional - (void)xmppAutoPingDidSendPing:(XMPPAutoPing *)sender; - (void)xmppAutoPingDidReceivePong:(XMPPAutoPing *)sender; - (void)xmppAutoPingDidTimeout:(XMPPAutoPing *)sender; @end
04081337-xmpp
Extensions/XEP-0199/XMPPAutoPing.h
Objective-C
bsd
2,598
#import "XMPPAutoPing.h" #import "XMPPPing.h" #import "XMPP.h" #import "XMPPLogging.h" // Log levels: off, error, warn, info, verbose // Log flags: trace #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN | XMPP_LOG_FLAG_TRACE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif @interface XMPPAutoPing () - (void)updatePingIntervalTimer; - (void)startPingIntervalTimer; - (void)stopPingIntervalTimer; @end #pragma mark - @implementation XMPPAutoPing - (id)init { return [self initWithDispatchQueue:NULL]; } - (id)initWithDispatchQueue:(dispatch_queue_t)queue { if ((self = [super initWithDispatchQueue:queue])) { pingInterval = 60; pingTimeout = 10; lastReceiveTime = DISPATCH_TIME_FOREVER; xmppPing = [[XMPPPing alloc] initWithDispatchQueue:queue]; xmppPing.respondsToQueries = NO; [xmppPing addDelegate:self delegateQueue:moduleQueue]; } return self; } - (BOOL)activate:(XMPPStream *)aXmppStream { if ([super activate:aXmppStream]) { [xmppPing activate:aXmppStream]; return YES; } return NO; } - (void)deactivate { dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self stopPingIntervalTimer]; lastReceiveTime = DISPATCH_TIME_FOREVER; awaitingPingResponse = NO; [xmppPing deactivate]; [super deactivate]; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_sync(moduleQueue, block); } - (void)dealloc { [targetJID release]; [targetJIDStr release]; [self stopPingIntervalTimer]; [xmppPing removeDelegate:self]; [xmppPing release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Properties //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSTimeInterval)pingInterval { if (dispatch_get_current_queue() == moduleQueue) { return pingInterval; } else { __block NSTimeInterval result; dispatch_sync(moduleQueue, ^{ result = pingInterval; }); return result; } } - (void)setPingInterval:(NSTimeInterval)interval { dispatch_block_t block = ^{ if (pingInterval != interval) { pingInterval = interval; // Update the pingTimer. // // Depending on new value and current state of the pingTimer, // this may mean starting, stoping, or simply updating the timer. if (pingInterval > 0) { // Remember: Only start the pinger after the xmpp stream is up and authenticated if ([xmppStream isAuthenticated]) [self startPingIntervalTimer]; } else { [self stopPingIntervalTimer]; } } }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (NSTimeInterval)pingTimeout { if (dispatch_get_current_queue() == moduleQueue) { return pingTimeout; } else { __block NSTimeInterval result; dispatch_sync(moduleQueue, ^{ result = pingTimeout; }); return result; } } - (void)setPingTimeout:(NSTimeInterval)timeout { dispatch_block_t block = ^{ if (pingTimeout != timeout) { pingTimeout = timeout; } }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (XMPPJID *)targetJID { if (dispatch_get_current_queue() == moduleQueue) { return targetJID; } else { __block XMPPJID *result; dispatch_sync(moduleQueue, ^{ result = [targetJID retain]; }); return [result autorelease]; } } - (void)setTargetJID:(XMPPJID *)jid { dispatch_block_t block = ^{ if (![targetJID isEqualToJID:jid]) { [targetJID release]; targetJID = [jid retain]; [targetJIDStr release]; targetJIDStr = [[targetJID full] retain]; } }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (dispatch_time_t)lastReceiveTime { if (dispatch_get_current_queue() == moduleQueue) { return lastReceiveTime; } else { __block dispatch_time_t result; dispatch_sync(moduleQueue, ^{ result = lastReceiveTime; }); return result; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Ping Interval //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)handlePingIntervalTimerFire { if (awaitingPingResponse) return; BOOL sendPing = NO; if (lastReceiveTime == DISPATCH_TIME_FOREVER) { sendPing = YES; } else { dispatch_time_t now = dispatch_time(DISPATCH_TIME_NOW, 0); NSTimeInterval elapsed = ((double)(now - lastReceiveTime) / (double)NSEC_PER_SEC); XMPPLogTrace2(@"%@: %@ - elapsed(%f)", [self class], THIS_METHOD, elapsed); sendPing = (elapsed >= pingInterval); } if (sendPing) { awaitingPingResponse = YES; if (targetJID) [xmppPing sendPingToJID:targetJID withTimeout:pingTimeout]; else [xmppPing sendPingToServerWithTimeout:pingTimeout]; [multicastDelegate xmppAutoPingDidSendPing:self]; } } - (void)updatePingIntervalTimer { XMPPLogTrace(); NSAssert(pingIntervalTimer != NULL, @"Broken logic (1)"); NSAssert(pingInterval > 0, @"Broken logic (2)"); uint64_t interval = ((pingInterval / 4.0) * NSEC_PER_SEC); dispatch_time_t tt; if (lastReceiveTime != DISPATCH_TIME_FOREVER) tt = dispatch_time(lastReceiveTime, interval); else tt = dispatch_time(DISPATCH_TIME_NOW, interval); dispatch_source_set_timer(pingIntervalTimer, tt, interval, 0); } - (void)startPingIntervalTimer { XMPPLogTrace(); if (pingInterval <= 0) { // Pinger is disabled return; } BOOL newTimer = NO; if (pingIntervalTimer == NULL) { newTimer = YES; pingIntervalTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, moduleQueue); dispatch_source_set_event_handler(pingIntervalTimer, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self handlePingIntervalTimerFire]; [pool drain]; }); } [self updatePingIntervalTimer]; if (newTimer) { dispatch_resume(pingIntervalTimer); } } - (void)stopPingIntervalTimer { XMPPLogTrace(); if (pingIntervalTimer) { dispatch_release(pingIntervalTimer); pingIntervalTimer = NULL; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPPing Delegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)xmppPing:(XMPPPing *)sender didReceivePong:(XMPPIQ *)pong withRTT:(NSTimeInterval)rtt { XMPPLogTrace(); awaitingPingResponse = NO; [multicastDelegate xmppAutoPingDidReceivePong:self]; } - (void)xmppPing:(XMPPPing *)sender didNotReceivePong:(NSString *)pingID dueToTimeout:(NSTimeInterval)timeout { XMPPLogTrace(); awaitingPingResponse = NO; [multicastDelegate xmppAutoPingDidTimeout:self]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPStream Delegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender { lastReceiveTime = dispatch_time(DISPATCH_TIME_NOW, 0); awaitingPingResponse = NO; [self startPingIntervalTimer]; } - (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq { if (targetJID == nil || [targetJIDStr isEqualToString:[iq fromStr]]) { lastReceiveTime = dispatch_time(DISPATCH_TIME_NOW, 0); } return NO; } - (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message { if (targetJID == nil || [targetJIDStr isEqualToString:[message fromStr]]) { lastReceiveTime = dispatch_time(DISPATCH_TIME_NOW, 0); } } - (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence { if (targetJID == nil || [targetJIDStr isEqualToString:[presence fromStr]]) { lastReceiveTime = dispatch_time(DISPATCH_TIME_NOW, 0); } } - (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error { [self stopPingIntervalTimer]; lastReceiveTime = DISPATCH_TIME_FOREVER; awaitingPingResponse = NO; } @end
04081337-xmpp
Extensions/XEP-0199/XMPPAutoPing.m
Objective-C
bsd
8,399
// // XMPPStreamFacebook.m // // Created by Eric Chamberlain on 10/13/10. // Copyright 2010 RF.com. All rights reserved. // #import "XMPPStreamFacebook.h" #import "XMPPInternal.h" #import "XMPPLogging.h" #import "GCDAsyncSocket.h" #import "NSData+XMPP.h" #import "NSXMLElement+XMPP.h" /** * Seeing a return statements within an inner block * can sometimes be mistaken for a return point of the enclosing method. * This makes inline blocks a bit easier to read. **/ #define return_from_block return // Log levels: off, error, warn, info, verbose #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_INFO | XMPP_LOG_FLAG_SEND_RECV; // | XMPP_LOG_FLAG_TRACE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN | XMPP_LOG_FLAG_SEND_RECV; #endif @interface XMPPXFacebookPlatformAuthentication : NSObject { NSString *nonce; NSString *method; NSString *accessToken; NSString *sessionSecret; } @property (nonatomic,copy) NSString *accessToken; @property (nonatomic,copy) NSString *sessionSecret; @property (nonatomic,copy) NSString *nonce; @property (nonatomic,copy) NSString *method; @property (nonatomic,retain,readonly) NSString *appId; @property (nonatomic,retain,readonly) NSString *sessionKey; - (id)initWithChallenge:(NSXMLElement *)challenge; - (NSString *)base64EncodedFullResponse; @end #pragma mark - @implementation XMPPStreamFacebook @dynamic facebook; - (Facebook *)facebook { if (dispatch_get_current_queue() == xmppQueue) { return facebook; } else { __block Facebook *result; dispatch_sync(xmppQueue, ^{ result = [facebook retain]; }); return [result autorelease]; } } - (void)setFacebook:(Facebook *)newFacebook { dispatch_block_t block = ^{ if (facebook != newFacebook) { [facebook release]; facebook = [newFacebook retain]; } }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_async(xmppQueue, block); } - (void)dealloc { [facebook release]; [super dealloc]; } #pragma mark Public class methods + (NSArray *)permissions { return [NSArray arrayWithObjects:@"offline_access", @"xmpp_login", nil]; } #pragma mark Public instance methods /** * This method checks the stream features of the connected server to * determine if X-FACEBOOK-PLATFORM authentication is supported. * If we are not connected to a server, this method simply returns NO. * * This is the preferred authentication technique, and will be used if * the server supports it. **/ - (BOOL)supportsXFacebookPlatform { __block BOOL result = NO; dispatch_block_t block = ^{ // The root element can be properly queried for authentication mechanisms anytime after the // stream:features are received, and TLS has been setup (if required) if (state >= STATE_XMPP_POST_NEGOTIATION) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSXMLElement *features = [rootElement elementForName:@"stream:features"]; NSXMLElement *mech = [features elementForName:@"mechanisms" xmlns:@"urn:ietf:params:xml:ns:xmpp-sasl"]; NSArray *mechanisms = [mech elementsForName:@"mechanism"]; for (NSXMLElement *mechanism in mechanisms) { if ([[mechanism stringValue] isEqualToString:@"X-FACEBOOK-PLATFORM"]) { result = YES; break; } } [pool drain]; } }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); return result; } /** * This method attemts to sign-in to Facebook using the access token. **/ - (BOOL)authenticateWithAppId:(NSString *)appId accessToken:(NSString *)accessToken error:(NSError **)errPtr { // Hard coding expiration date, because we use offline_access in the permissions return [self authenticateWithAppId:appId accessToken:accessToken expirationDate:[NSDate distantFuture] error:errPtr]; } - (BOOL)authenticateWithAppId:(NSString *)appId accessToken:(NSString *)accessToken expirationDate:(NSDate *)expirationDate error:(NSError **)errPtr { XMPPLogTrace(); __block BOOL result = YES; __block NSError *err = nil; dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (state != STATE_XMPP_CONNECTED) { NSString *errMsg = @"Please wait until the stream is connected."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } if (![self supportsXFacebookPlatform]) { NSString *errMsg = @"The server does not support X-FACEBOOK-PLATFORM authentication."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamUnsupportedAction userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } if (accessToken == nil || expirationDate == nil) { NSString *errMsg = @"Facebook accessToken and expirationDate required."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidProperty userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } [facebook release]; facebook = [[Facebook alloc] initWithAppId:appId]; facebook.accessToken = accessToken; facebook.expirationDate = expirationDate; // Facebook uses NSURLConnection which is dependent on a RunLoop. // So we need to use the xmppUtilityThread. [self performSelector:@selector(sendFacebookRequest:) onThread:xmppUtilityThread withObject:facebook waitUntilDone:NO]; // Update state state = STATE_XMPP_AUTH_1; [pool drain]; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); if (errPtr) *errPtr = [err autorelease]; else [err release]; return result; } - (BOOL)authenticateWithPassword:(NSString *)password error:(NSError **)errPtr { XMPPLogTrace(); __block BOOL result = YES; __block NSError *err = nil; dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (state != STATE_XMPP_CONNECTED) { NSString *errMsg = @"Please wait until the stream is connected."; NSDictionary *info = [NSDictionary dictionaryWithObject:errMsg forKey:NSLocalizedDescriptionKey]; err = [NSError errorWithDomain:XMPPStreamErrorDomain code:XMPPStreamInvalidState userInfo:info]; [err retain]; [pool drain]; result = NO; return_from_block; } if (facebook != nil && [self supportsXFacebookPlatform]) { NSString *auth = @"<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='X-FACEBOOK-PLATFORM'/>"; NSData *outgoingData = [auth dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", auth); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; // Save authentication information [tempPassword release]; tempPassword = [password copy]; // Update state state = STATE_XMPP_AUTH_1; } else { result = [super authenticateWithPassword:password error:&err]; } [err retain]; [pool drain]; }; if (dispatch_get_current_queue() == xmppQueue) block(); else dispatch_sync(xmppQueue, block); if (errPtr) *errPtr = [err autorelease]; else [err release]; return result; } #pragma mark Private instance methods - (void)handleAuth1:(NSXMLElement *)response { NSAssert(dispatch_get_current_queue() == xmppQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); if (facebook != nil && [self supportsXFacebookPlatform]) { if (![[response name] isEqualToString:@"challenge"]) { // Revert back to connected state (from authenticating state) state = STATE_XMPP_CONNECTED; [multicastDelegate xmppStream:self didNotAuthenticate:response]; } else { XMPPXFacebookPlatformAuthentication *auth; auth = [[XMPPXFacebookPlatformAuthentication alloc] initWithChallenge:response]; [auth setAccessToken:facebook.accessToken]; [auth setSessionSecret:tempPassword]; // Create and send challenge response element NSXMLElement *cr = [NSXMLElement elementWithName:@"response" xmlns:@"urn:ietf:params:xml:ns:xmpp-sasl"]; [cr setStringValue:[auth base64EncodedFullResponse]]; NSString *outgoingStr = [cr compactXMLString]; NSData *outgoingData = [outgoingStr dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogSend(@"SEND: %@", outgoingStr); numberOfBytesSent += [outgoingData length]; [asyncSocket writeData:outgoingData withTimeout:TIMEOUT_XMPP_WRITE tag:TAG_XMPP_WRITE_STREAM]; // Release unneeded resources [auth release]; [tempPassword release]; tempPassword = nil; // Update state state = STATE_XMPP_AUTH_3; } } else { [super handleAuth1:response]; } } - (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err { [super socketDidDisconnect:sock withError:err]; [facebookRequest release]; facebookRequest = nil; [facebook release]; facebook = nil; } #pragma mark FBRequest - (void)sendFacebookRequest:(Facebook *)fb { // // This method is run on the xmppUtilityThread. // FBRequest *fbRequest = [fb requestWithMethodName:@"auth.promoteSession" andParams:[NSMutableDictionary dictionaryWithCapacity:3] andHttpMethod:@"GET" andDelegate:self]; dispatch_async(xmppQueue, ^{ [facebookRequest release]; facebookRequest = [fbRequest retain]; }); } /** * Called when an error prevents the request from completing successfully. **/ - (void)request:(FBRequest *)sender didFailWithError:(NSError *)error { XMPPLogTrace(); // // This method is invoked on the xmppUtilityThread. // dispatch_async(xmppQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (sender == facebookRequest) { XMPPLogWarn(@"%@: Facebook request failed - error: %@", THIS_FILE, error); // Revert back to connected state (from authenticating state) state = STATE_XMPP_CONNECTED; [multicastDelegate xmppStream:self didNotAuthenticate:nil]; } [pool drain]; }); } /** * Called when a request returns and its response has been parsed into an object. * The resulting object may be a dictionary, an array, a string, or a number, * depending on thee format of the API response. **/ - (void)request:(FBRequest *)sender didLoad:(id)result { XMPPLogTrace(); // // This method is invoked on the xmppUtilityThread. // if ([result isKindOfClass:[NSData class]]) { NSString *resultStr = [[[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding] autorelease]; NSString *pwd = [resultStr stringByReplacingOccurrencesOfString:@"\"" withString:@""]; dispatch_async(xmppQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (sender == facebookRequest) { // Revert back to connected state (from authenticating state) state = STATE_XMPP_CONNECTED; // Finish authenticating NSError *error = nil; if (![self authenticateWithPassword:pwd error:&error]) { XMPPLogWarn(@"%@: Facebook auth failed - resultStr(%@) error: %@", THIS_FILE, resultStr, error); [multicastDelegate xmppStream:self didNotAuthenticate:nil]; } } [pool drain]; }); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @end @implementation XMPPXFacebookPlatformAuthentication - (id)initWithChallenge:(NSXMLElement *)challenge { if ((self = [super init])) { // Convert the base 64 encoded data into a string NSData *base64Data = [[challenge stringValue] dataUsingEncoding:NSASCIIStringEncoding]; NSData *decodedData = [base64Data base64Decoded]; NSString *authStr = [[[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding] autorelease]; XMPPLogVerbose(@"XMPPXFacebookPlatformAuthentication: decoded challenge: %@", authStr); // Extract all the key=value pairs, and put them in a dictionary for easy lookup NSMutableDictionary *auth = [NSMutableDictionary dictionaryWithCapacity:3]; NSArray *components = [authStr componentsSeparatedByString:@"&"]; int i; for(i = 0; i < [components count]; i++) { NSString *component = [components objectAtIndex:i]; NSRange separator = [component rangeOfString:@"="]; if(separator.location != NSNotFound) { NSString *key = [[component substringToIndex:separator.location] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSString *value = [[component substringFromIndex:separator.location+1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; if([value hasPrefix:@"\""] && [value hasSuffix:@"\""] && [value length] > 2) { // Strip quotes from value value = [value substringWithRange:NSMakeRange(1,([value length]-2))]; } [auth setObject:value forKey:key]; } } // Extract and retain the elements we need self.nonce = [auth objectForKey:@"nonce"]; self.method = [auth objectForKey:@"method"]; } return self; } - (void)dealloc { [accessToken release]; [nonce release]; [method release]; [sessionSecret release]; [super dealloc]; } - (NSString *)base64EncodedFullResponse { if (self.accessToken == nil || self.sessionSecret == nil || self.method == nil || self.nonce == nil) { return nil; } srand([[NSDate date] timeIntervalSince1970]); NSMutableString *buffer = [NSMutableString stringWithCapacity:250]; [buffer appendFormat:@"api_key=%@&", self.appId]; [buffer appendFormat:@"call_id=%d&", rand()]; [buffer appendFormat:@"method=%@&", self.method]; [buffer appendFormat:@"nonce=%@&", self.nonce]; [buffer appendFormat:@"session_key=%@&", self.sessionKey]; [buffer appendFormat:@"v=%@&",@"1.0"]; // Make the "sig" hash NSString* sig = [buffer stringByReplacingOccurrencesOfString:@"&" withString:@""]; sig = [sig stringByAppendingString:self.sessionSecret]; NSString* sigMD5 = [[[sig dataUsingEncoding:NSUTF8StringEncoding] md5Digest] hexStringValue]; [buffer appendFormat:@"sig=%@", sigMD5]; XMPPLogVerbose(@"XMPPXFacebookPlatformAuthentication: sig for facebook: %@", sig); XMPPLogVerbose(@"XMPPXFacebookPlatformAuthentication: response for facebook: %@", buffer); NSData *utf8data = [buffer dataUsingEncoding:NSUTF8StringEncoding]; return [utf8data base64Encoded]; } @synthesize nonce; @synthesize method; @synthesize accessToken; @synthesize sessionSecret; - (NSString *)appId { NSArray *parts = [self.accessToken componentsSeparatedByString:@"|"]; if ([parts count] < 3) { return nil; } return [parts objectAtIndex:0]; } - (NSString *)sessionKey { NSArray *parts = [self.accessToken componentsSeparatedByString:@"|"]; if ([parts count] < 3) { return nil; } return [parts objectAtIndex:1]; } @end
04081337-xmpp
Extensions/X-FACEBOOK-PLATFORM/XMPPStreamFacebook.m
Objective-C
bsd
16,354
// // XMPPStreamFacebook.h // // Created by Eric Chamberlain on 10/13/10. // Copyright 2010 RF.com. All rights reserved. // #import <Foundation/Foundation.h> #import "FBConnect.h" #import "XMPPStream.h" @interface XMPPStreamFacebook : XMPPStream <FBRequestDelegate> { Facebook *facebook; FBRequest *facebookRequest; } @property (readwrite, retain) Facebook *facebook; /** * returns the correct permissions for xmpp **/ + (NSArray *)permissions; - (BOOL)supportsXFacebookPlatform; - (BOOL)authenticateWithAppId:(NSString *)appId accessToken:(NSString *)accessToken error:(NSError **)errPtr; - (BOOL)authenticateWithAppId:(NSString *)appId accessToken:(NSString *)accessToken expirationDate:(NSDate *)expirationDate error:(NSError **)errPtr; @end
04081337-xmpp
Extensions/X-FACEBOOK-PLATFORM/XMPPStreamFacebook.h
Objective-C
bsd
867
// // XMPPPubSub.m // // Created by Duncan Robertson [duncan@whomwah.com] // #import "XMPPPubSub.h" #import "XMPP.h" #define NS_PUBSUB @"http://jabber.org/protocol/pubsub" #define NS_PUBSUB_EVENT @"http://jabber.org/protocol/pubsub#event" #define NS_PUBSUB_CONFIG @"http://jabber.org/protocol/pubsub#node_config" #define NS_PUBSUB_OWNER @"http://jabber.org/protocol/pubsub#owner" #define NS_DISCO_ITEMS @"http://jabber.org/protocol/disco#items" #define INTEGRATE_WITH_CAPABILITIES 1 #if INTEGRATE_WITH_CAPABILITIES #import "XMPPCapabilities.h" #endif @implementation XMPPPubSub; @synthesize serviceJID; - (id)init { return [self initWithServiceJID:nil dispatchQueue:NULL]; } - (id)initWithDispatchQueue:(dispatch_queue_t)queue { return [self initWithServiceJID:nil dispatchQueue:NULL]; } - (id)initWithServiceJID:(XMPPJID *)aServiceJID { return [self initWithServiceJID:aServiceJID dispatchQueue:NULL]; } - (id)initWithServiceJID:(XMPPJID *)aServiceJID dispatchQueue:(dispatch_queue_t)queue { NSParameterAssert(aServiceJID != nil); if ((self = [super initWithDispatchQueue:queue])) { serviceJID = [aServiceJID copy]; } return self; } - (BOOL)activate:(XMPPStream *)aXmppStream { if ([self activate:aXmppStream]) { #if INTEGRATE_WITH_CAPABILITIES [xmppStream autoAddDelegate:self delegateQueue:moduleQueue toModulesOfClass:[XMPPCapabilities class]]; #endif return YES; } return NO; } - (void)deactivate { #if INTEGRATE_WITH_CAPABILITIES [xmppStream removeAutoDelegate:self delegateQueue:moduleQueue fromModulesOfClass:[XMPPCapabilities class]]; #endif [super deactivate]; } - (void)dealloc { [serviceJID release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPStream Delegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Delegate method to receive incoming IQ stanzas. **/ - (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq { if ([iq isResultIQ]) { NSXMLElement *pubsub = [iq elementForName:@"pubsub" xmlns:NS_PUBSUB]; if (pubsub) { // <iq from="pubsub.host.com" to="user@host.com/rsrc" id="ABC123:subscribenode" type="result"> // <pubsub xmlns="http://jabber.org/protocol/pubsub"> // <subscription jid="tv@xmpp.local" subscription="subscribed" subid="DEF456"/> // </pubsub> // </iq> NSXMLElement *subscription = [pubsub elementForName:@"subscription"]; if (subscription) { NSString *value = [subscription attributeStringValueForName:@"subscription"]; if (value && ([value caseInsensitiveCompare:@"subscribed"] == NSOrderedSame)) { [multicastDelegate xmppPubSub:self didSubscribe:iq]; return YES; } } } [multicastDelegate xmppPubSub:self didReceiveResult:iq]; return YES; } else if ([iq isErrorIQ]) { [multicastDelegate xmppPubSub:self didReceiveError:iq]; return YES; } return NO; } /** * Delegate method to receive incoming message stanzas. **/ - (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message { // <message from='pubsub.foo.co.uk' to='admin@foo.co.uk'> // <event xmlns='http://jabber.org/protocol/pubsub#event'> // <items node='/pubsub.foo'> // <item id='5036AA52A152B'> // <text id='724427814855'> // Huw Stephens sits in for Greg James and David Garrido takes a look at the sporting week // </text> // </item> // </items> // </event> // </message> NSXMLElement *event = [message elementForName:@"event" xmlns:NS_PUBSUB_EVENT]; if (event) { [multicastDelegate xmppPubSub:self didReceiveMessage:message]; } } #if INTEGRATE_WITH_CAPABILITIES /** * If an XMPPCapabilites instance is used we want to advertise our support for pubsub support. **/ - (void)xmppCapabilities:(XMPPCapabilities *)sender collectingMyCapabilities:(NSXMLElement *)query { // <query xmlns="http://jabber.org/protocol/disco#info"> // ... // <identity category='pubsub' type='service'/> // <feature var='http://jabber.org/protocol/pubsub' /> // ... // </query> NSXMLElement *identity = [NSXMLElement elementWithName:@"identity"]; [identity addAttributeWithName:@"category" stringValue:@"pubsub"]; [identity addAttributeWithName:@"type" stringValue:@"service"]; [query addChild:identity]; NSXMLElement *feature = [NSXMLElement elementWithName:@"feature"]; [feature addAttributeWithName:@"var" stringValue:NS_PUBSUB]; [query addChild:feature]; } #endif //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Subscription Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSString *)subscribeToNode:(NSString *)node withOptions:(NSDictionary *)options { // <iq type='set' from='francisco@denmark.lit/barracks' to='pubsub.shakespeare.lit' id='sub1'> // <pubsub xmlns='http://jabber.org/protocol/pubsub'> // <subscribe node='princely_musings' jid='francisco@denmark.lit'/> // </pubsub> // </iq> NSString *sid = [NSString stringWithFormat:@"%@:subscribe_node", xmppStream.generateUUID]; XMPPIQ *iq = [XMPPIQ iqWithType:@"set" to:serviceJID elementID:sid]; NSXMLElement *ps = [NSXMLElement elementWithName:@"pubsub" xmlns:NS_PUBSUB]; NSXMLElement *subscribe = [NSXMLElement elementWithName:@"subscribe"]; [subscribe addAttributeWithName:@"node" stringValue:node]; [subscribe addAttributeWithName:@"jid" stringValue:[xmppStream.myJID full]]; [ps addChild:subscribe]; [iq addChild:ps]; [xmppStream sendElement:iq]; return sid; } - (NSString *)unsubscribeFromNode:(NSString*)node { // <iq type='set' from='francisco@denmark.lit/barracks' to='pubsub.shakespeare.lit' id='unsub1'> // <pubsub xmlns='http://jabber.org/protocol/pubsub'> // <unsubscribe node='princely_musings' jid='francisco@denmark.lit'/> // </pubsub> // </iq> NSString *sid = [NSString stringWithFormat:@"%@:unsubscribe_node", xmppStream.generateUUID]; XMPPIQ *iq = [XMPPIQ iqWithType:@"set" to:serviceJID elementID:sid]; NSXMLElement *ps = [NSXMLElement elementWithName:@"pubsub" xmlns:NS_PUBSUB]; NSXMLElement *subscribe = [NSXMLElement elementWithName:@"unsubscribe"]; [subscribe addAttributeWithName:@"node" stringValue:node]; [subscribe addAttributeWithName:@"jid" stringValue:[xmppStream.myJID full]]; // join them all together [ps addChild:subscribe]; [iq addChild:ps]; [xmppStream sendElement:iq]; return sid; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Node Admin //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSString *)createNode:(NSString *)node withOptions:(NSDictionary *)options { // <iq type='set' from='hamlet@denmark.lit/elsinore' to='pubsub.shakespeare.lit' id='create1'> // <pubsub xmlns='http://jabber.org/protocol/pubsub'> // <create node='princely_musings'/> // <configure> // <x xmlns='jabber:x:data' type='submit'> // <field var='FORM_TYPE' type='hidden'> // <value>http://jabber.org/protocol/pubsub#node_config</value> // </field> // <field var='pubsub#title'><value>Princely Musings (Atom)</value></field> // <field var='pubsub#deliver_notifications'><value>1</value></field> // <field var='pubsub#deliver_payloads'><value>1</value></field> // <field var='pubsub#persist_items'><value>1</value></field> // <field var='pubsub#max_items'><value>10</value></field> // ... // </x> // </configure> // </pubsub> // </iq> NSString *sid = [NSString stringWithFormat:@"%@:create_node", xmppStream.generateUUID]; XMPPIQ *iq = [XMPPIQ iqWithType:@"set" to:serviceJID elementID:sid]; NSXMLElement *ps = [NSXMLElement elementWithName:@"pubsub" xmlns:NS_PUBSUB]; NSXMLElement *create = [NSXMLElement elementWithName:@"create"]; [create addAttributeWithName:@"node" stringValue:node]; if (options != nil && [options count] > 0) { NSXMLElement *config = [NSXMLElement elementWithName:@"configure"]; NSXMLElement *x = [NSXMLElement elementWithName:@"x" xmlns:@"jabber:x:data"]; [x addAttributeWithName:@"type" stringValue:@"submit"]; NSXMLElement *field = [NSXMLElement elementWithName:@"field"]; [field addAttributeWithName:@"var" stringValue:@"FORM_TYPE"]; [field addAttributeWithName:@"type" stringValue:@"hidden"]; NSXMLElement *value = [NSXMLElement elementWithName:@"value"]; [value setStringValue:NS_PUBSUB_CONFIG]; [field addChild:value]; [x addChild:field]; NSXMLElement *f; NSXMLElement *v; for (NSString *item in options) { f = [NSXMLElement elementWithName:@"field"]; [f addAttributeWithName:@"var" stringValue:[NSString stringWithFormat:@"pubsub#%@", [options valueForKey:item]]]; v = [NSXMLElement elementWithName:@"value"]; [v setStringValue:item]; [f addChild:v]; [x addChild:f]; } [config addChild:x]; [ps addChild:config]; } [ps addChild:create]; [iq addChild:ps]; [xmppStream sendElement:iq]; return sid; } /** * This method currently does not support redirection **/ - (NSString*)deleteNode:(NSString*)node { // <iq type='set' from='hamlet@denmark.lit/elsinore' to='pubsub.shakespeare.lit' id='delete1'> // <pubsub xmlns='http://jabber.org/protocol/pubsub#owner'> // <delete node='princely_musings'> // <redirect uri='xmpp:hamlet@denmark.lit?;node=blog'/> // </delete> // </pubsub> // </iq> NSString *sid = [NSString stringWithFormat:@"%@:delete_node", xmppStream.generateUUID]; XMPPIQ *iq = [XMPPIQ iqWithType:@"set" to:serviceJID elementID:sid]; NSXMLElement *ps = [NSXMLElement elementWithName:@"pubsub" xmlns:NS_PUBSUB_OWNER]; NSXMLElement *delete = [NSXMLElement elementWithName:@"delete"]; [delete addAttributeWithName:@"node" stringValue:node]; [ps addChild:delete]; [iq addChild:ps]; [xmppStream sendElement:iq]; return sid; } - (NSString*)allItemsForNode:(NSString*)node { // <iq type='get' from='francisco@denmark.lit/barracks' to='pubsub.shakespeare.lit' id='nodes2'> // <query xmlns='http://jabber.org/protocol/disco#items' node='blogs'/> // </iq> NSString *sid = [NSString stringWithFormat:@"%@:items_for_node", xmppStream.generateUUID]; XMPPIQ *iq = [XMPPIQ iqWithType:@"get" to:serviceJID elementID:sid]; NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:NS_DISCO_ITEMS]; if (node != nil) { [query addAttributeWithName:@"node" stringValue:node]; } [iq addChild:query]; [xmppStream sendElement:iq]; return sid; } - (NSString*)configureNode:(NSString*)node { // <iq type='get' from='hamlet@denmark.lit/elsinore' to='pubsub.shakespeare.lit' id='config1'> // <pubsub xmlns='http://jabber.org/protocol/pubsub#owner'> // <configure node='princely_musings'/> // </pubsub> // </iq> NSString *sid = [NSString stringWithFormat:@"%@:configure_node", xmppStream.generateUUID]; XMPPIQ *iq = [XMPPIQ iqWithType:@"get" to:serviceJID elementID:sid]; NSXMLElement *ps = [NSXMLElement elementWithName:@"pubsub" xmlns:NS_PUBSUB_OWNER]; NSXMLElement *conf = [NSXMLElement elementWithName:@"configure"]; [conf addAttributeWithName:@"node" stringValue:node]; [ps addChild:conf]; [iq addChild:ps]; [xmppStream sendElement:iq]; return sid; } @end
04081337-xmpp
Extensions/XEP-0060/XMPPPubSub.m
Objective-C
bsd
11,615
// // XMPPPubSub.h // // Created by Duncan Robertson [duncan@whomwah.com] // #import <Foundation/Foundation.h> #import "XMPPModule.h" @class XMPPStream; @class XMPPJID; @class XMPPIQ; @class XMPPMessage; @interface XMPPPubSub : XMPPModule { XMPPJID *serviceJID; } - (id)initWithServiceJID:(XMPPJID *)aServiceJID; - (id)initWithServiceJID:(XMPPJID *)aServiceJID dispatchQueue:(dispatch_queue_t)queue; @property (nonatomic, readonly) XMPPJID *serviceJID; - (NSString *)subscribeToNode:(NSString *)node withOptions:(NSDictionary *)options; - (NSString *)unsubscribeFromNode:(NSString *)node; - (NSString *)createNode:(NSString *)node withOptions:(NSDictionary *)options; - (NSString *)deleteNode:(NSString *)node; - (NSString *)configureNode:(NSString *)node; - (NSString *)allItemsForNode:(NSString *)node; @end @protocol XMPPPubSubDelegate @optional - (void)xmppPubSub:(XMPPPubSub *)sender didSubscribe:(XMPPIQ *)iq; - (void)xmppPubSub:(XMPPPubSub *)sender didCreateNode:(NSString *)node withIQ:(XMPPIQ *)iq; - (void)xmppPubSub:(XMPPPubSub *)sender didReceiveMessage:(XMPPMessage *)message; - (void)xmppPubSub:(XMPPPubSub *)sender didReceiveError:(XMPPIQ *)iq; - (void)xmppPubSub:(XMPPPubSub *)sender didReceiveResult:(XMPPIQ *)iq; @end
04081337-xmpp
Extensions/XEP-0060/XMPPPubSub.h
Objective-C
bsd
1,249
#import "XMPPRoster.h" #import "XMPP.h" #import "XMPPLogging.h" // Log levels: off, error, warn, info, verbose // Log flags: trace #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; // | XMPP_LOG_FLAG_TRACE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif enum XMPPRosterFlags { kAutoRoster = 1 << 0, // If set, we automatically request roster after authentication kRequestedRoster = 1 << 1, // If set, we have requested the roster kHasRoster = 1 << 2, // If set, we have received the roster }; @interface XMPPRoster (PrivateAPI) - (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPRoster @dynamic xmppRosterStorage; @dynamic autoRoster; - (id)init { return [self initWithRosterStorage:nil dispatchQueue:NULL]; } - (id)initWithDispatchQueue:(dispatch_queue_t)queue { return [self initWithRosterStorage:nil dispatchQueue:queue]; } - (id)initWithRosterStorage:(id <XMPPRosterStorage>)storage { return [self initWithRosterStorage:storage dispatchQueue:NULL]; } - (id)initWithRosterStorage:(id <XMPPRosterStorage>)storage dispatchQueue:(dispatch_queue_t)queue { NSParameterAssert(storage != nil); if ((self = [super initWithDispatchQueue:queue])) { if ([storage configureWithParent:self queue:moduleQueue]) { xmppRosterStorage = [storage retain]; } else { XMPPLogError(@"%@: %@ - Unable to configure storage!", THIS_FILE, THIS_METHOD); } flags = 0; earlyPresenceElements = [[NSMutableArray alloc] initWithCapacity:2]; } return self; } - (BOOL)activate:(XMPPStream *)aXmppStream { XMPPLogTrace(); if ([super activate:aXmppStream]) { XMPPLogVerbose(@"%@: Activated", THIS_FILE); // Custom code goes here (if needed) return YES; } return NO; } - (void)deactivate { XMPPLogTrace(); // Custom code goes here (if needed) [super deactivate]; } - (void)dealloc { [xmppRosterStorage release]; [earlyPresenceElements release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Internal //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * This method is used by XMPPRosterStorage classes. **/ - (GCDMulticastDelegate *)multicastDelegate { return multicastDelegate; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Configuration //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSString *)moduleName { return @"XMPPRoster"; } - (id <XMPPRosterStorage>)xmppRosterStorage { // Note: The xmppRosterStorage variable is read-only (set in the init method) return [[xmppRosterStorage retain] autorelease]; } - (BOOL)autoRoster { __block BOOL result; dispatch_block_t block = ^{ result = (flags & kAutoRoster) ? YES : NO; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_sync(moduleQueue, block); return result; } - (void)setAutoRoster:(BOOL)flag { dispatch_block_t block = ^{ if (flag) flags |= kAutoRoster; else flags &= ~kAutoRoster; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Buddy Management //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)addBuddy:(XMPPJID *)jid withNickname:(NSString *)optionalName { // This is a public method. // It may be invoked on any thread/queue. if (jid == nil) return; XMPPJID *myJID = xmppStream.myJID; if ([[myJID bare] isEqualToString:[jid bare]]) { // No, you don't need to add yourself return; } // Add the buddy to our roster // // <iq type="set"> // <query xmlns="jabber:iq:roster"> // <item jid="bareJID" name="optionalName"/> // </query> // </iq> NSXMLElement *item = [NSXMLElement elementWithName:@"item"]; [item addAttributeWithName:@"jid" stringValue:[jid bare]]; if (optionalName) { [item addAttributeWithName:@"name" stringValue:optionalName]; } NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:roster"]; [query addChild:item]; NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"]; [iq addAttributeWithName:@"type" stringValue:@"set"]; [iq addChild:query]; [xmppStream sendElement:iq]; // Subscribe to the buddy's presence // // <presence to="bareJID" type="subscribe"/> NSXMLElement *presence = [NSXMLElement elementWithName:@"presence"]; [presence addAttributeWithName:@"to" stringValue:[jid bare]]; [presence addAttributeWithName:@"type" stringValue:@"subscribe"]; [xmppStream sendElement:presence]; } - (void)removeBuddy:(XMPPJID *)jid { // This is a public method. // It may be invoked on any thread/queue. if (jid == nil) return; XMPPJID *myJID = xmppStream.myJID; if ([[myJID bare] isEqualToString:[jid bare]]) { // No, you shouldn't remove yourself return; } // Remove the buddy from our roster // Unsubscribe from presence // And revoke contact's subscription to our presence // ...all in one step // <iq type="set"> // <query xmlns="jabber:iq:roster"> // <item jid="bareJID" subscription="remove"/> // </query> // </iq> NSXMLElement *item = [NSXMLElement elementWithName:@"item"]; [item addAttributeWithName:@"jid" stringValue:[jid bare]]; [item addAttributeWithName:@"subscription" stringValue:@"remove"]; NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:roster"]; [query addChild:item]; NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"]; [iq addAttributeWithName:@"type" stringValue:@"set"]; [iq addChild:query]; [xmppStream sendElement:iq]; } - (void)setNickname:(NSString *)nickname forBuddy:(XMPPJID *)jid { // This is a public method. // It may be invoked on any thread/queue. if (jid == nil) return; // <iq type="set"> // <query xmlns="jabber:iq:roster"> // <item jid="bareJID" name="nickname"/> // </query> // </iq> NSXMLElement *item = [NSXMLElement elementWithName:@"item"]; [item addAttributeWithName:@"jid" stringValue:[jid bare]]; [item addAttributeWithName:@"name" stringValue:nickname]; NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:roster"]; [query addChild:item]; NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"]; [iq addAttributeWithName:@"type" stringValue:@"set"]; [iq addChild:query]; [xmppStream sendElement:iq]; } - (void)acceptBuddyRequest:(XMPPJID *)jid { // This is a public method. // It may be invoked on any thread/queue. // Send presence response // // <presence to="bareJID" type="subscribed"/> NSXMLElement *response = [NSXMLElement elementWithName:@"presence"]; [response addAttributeWithName:@"to" stringValue:[jid bare]]; [response addAttributeWithName:@"type" stringValue:@"subscribed"]; [xmppStream sendElement:response]; // Add user to our roster [self addBuddy:jid withNickname:nil]; } - (void)rejectBuddyRequest:(XMPPJID *)jid { // This is a public method. // It may be invoked on any thread/queue. // Send presence response // // <presence to="bareJID" type="unsubscribed"/> NSXMLElement *response = [NSXMLElement elementWithName:@"presence"]; [response addAttributeWithName:@"to" stringValue:[jid bare]]; [response addAttributeWithName:@"type" stringValue:@"unsubscribed"]; [xmppStream sendElement:response]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)requestedRoster { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); return (flags & kRequestedRoster) ? YES : NO; } - (void)setRequestedRoster:(BOOL)flag { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); if (flag) flags |= kRequestedRoster; else flags &= ~kRequestedRoster; } - (BOOL)hasRoster { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); return (flags & kHasRoster) ? YES : NO; } - (void)setHasRoster:(BOOL)flag { NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); if (flag) flags |= kHasRoster; else flags &= ~kHasRoster; } - (void)fetchRoster { // This is a public method. // It may be invoked on any thread/queue. dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if ([self requestedRoster]) { // We've already requested the roster from the server. [pool drain]; return; } // <iq type="get"> // <query xmlns="jabber:iq:roster"/> // </iq> NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:roster"]; NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"]; [iq addAttributeWithName:@"type" stringValue:@"get"]; [iq addChild:query]; [xmppStream sendElement:iq]; [self setRequestedRoster:YES]; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Roster methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (id <XMPPUser>)myUser { return [xmppRosterStorage myUserForXMPPStream:xmppStream]; } - (id <XMPPResource>)myResource { return [xmppRosterStorage myResourceForXMPPStream:xmppStream]; } - (id <XMPPUser>)userForJID:(XMPPJID *)jid { return [xmppRosterStorage userForJID:jid xmppStream:xmppStream]; } - (id <XMPPResource>)resourceForJID:(XMPPJID *)jid { return [xmppRosterStorage resourceForJID:jid xmppStream:xmppStream]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPStream Delegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender { // This method is invoked on the moduleQueue. XMPPLogTrace(); if ([self autoRoster]) { [self fetchRoster]; } } - (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq { // This method is invoked on the moduleQueue. XMPPLogTrace(); // Note: Some jabber servers send an iq element with an xmlns. // Because of the bug in Apple's NSXML (documented in our elementForName method), // it is important we specify the xmlns for the query. NSXMLElement *query = [iq elementForName:@"query" xmlns:@"jabber:iq:roster"]; if (query) { if (![self hasRoster]) { [xmppRosterStorage beginRosterPopulationForXMPPStream:xmppStream]; } NSArray *items = [query elementsForName:@"item"]; for (NSXMLElement *item in items) { // Filter out items for users who aren't actually in our roster. // That is, those users who have requested to be our buddy, but we haven't approved yet. [xmppRosterStorage handleRosterItem:item xmppStream:xmppStream]; } if (![self hasRoster]) { // We should have our roster now [self setHasRoster:YES]; // Which means we can process any premature presence elements we received. // // Note: We do this before invoking endRosterPopulation to enable optimizations // concerning the possible presence storm. for (XMPPPresence *presence in earlyPresenceElements) { [self xmppStream:xmppStream didReceivePresence:presence]; } [earlyPresenceElements removeAllObjects]; // And finally, notify roster storage that the roster population is complete [xmppRosterStorage endRosterPopulationForXMPPStream:xmppStream]; } return YES; } return NO; } - (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence { // This method is invoked on the moduleQueue. XMPPLogTrace(); if (![self hasRoster]) { // We received a presence notification, // but we don't have a roster to apply it to yet. // // This is possible if we send our presence before we've received our roster. // It's even possible if we send our presence after we've requested our roster. // There is no guarantee the server will process our requests serially, // and the server may start sending presence elements before it sends our roster. // // However, if we've requested the roster, // then it shouldn't be too long before we receive it. // So we should be able to simply queue the presence elements for later processing. if ([self requestedRoster]) { // We store the presence element until we get our roster. [earlyPresenceElements addObject:presence]; } else { // The user has not requested the roster. // This is a rogue presence element, or the user is simply not using our roster management. } return; } if ([[presence type] isEqualToString:@"subscribe"]) { id <XMPPUser> user = [xmppRosterStorage userForJID:[presence from] xmppStream:xmppStream]; if (user && [self autoRoster]) { // Presence subscription request from someone who's already in our roster. // Automatically approve. // // <presence to="bareJID" type="subscribed"/> NSXMLElement *response = [NSXMLElement elementWithName:@"presence"]; [response addAttributeWithName:@"to" stringValue:[[presence from] bare]]; [response addAttributeWithName:@"type" stringValue:@"subscribed"]; [xmppStream sendElement:response]; } else { // Presence subscription request from someone who's NOT in our roster [multicastDelegate xmppRoster:self didReceiveBuddyRequest:presence]; } } else { [xmppRosterStorage handlePresence:presence xmppStream:xmppStream]; } } - (void)xmppStream:(XMPPStream *)sender didSendPresence:(XMPPPresence *)presence { // This method is invoked on the moduleQueue. XMPPLogTrace(); // We check the toStr, so we don't dump the resources when a user leaves a MUC room. if ([[presence type] isEqualToString:@"unavailable"] && [presence toStr] == nil) { // We don't receive presence notifications when we're offline. // So we need to remove all resources from our roster when we're offline. // When we become available again, we'll automatically receive the // presence from every available user in our roster. // // We will receive general roster updates as long as we're still connected though. // So there's no need to refetch the roster. [xmppRosterStorage clearAllResourcesForXMPPStream:xmppStream]; [earlyPresenceElements removeAllObjects]; } } - (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error { // This method is invoked on the moduleQueue. XMPPLogTrace(); [xmppRosterStorage clearAllUsersAndResourcesForXMPPStream:xmppStream]; [self setRequestedRoster:NO]; [self setHasRoster:NO]; [earlyPresenceElements removeAllObjects]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPvCardAvatarDelegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if TARGET_OS_IPHONE - (void)xmppvCardAvatarModule:(XMPPvCardAvatarModule *)vCardTempModule didReceivePhoto:(UIImage *)photo forJID:(XMPPJID *)jid #else - (void)xmppvCardAvatarModule:(XMPPvCardAvatarModule *)vCardTempModule didReceivePhoto:(NSImage *)photo forJID:(XMPPJID *)jid #endif { id <XMPPUser> user = [self userForJID:jid]; if (user != nil) { user.photo = photo; } } @end
04081337-xmpp
Extensions/Roster/XMPPRoster.m
Objective-C
bsd
16,471
#import <Foundation/Foundation.h> #import "XMPPRoster.h" @interface XMPPRoster (PrivateInternalAPI) /** * The XMPPRosterStorage classes use the same delegate(s) as their parent XMPPRoster. * This method allows these classes to access the delegate(s). * * Note: If the storage class operates on a different queue than its parent, * it MUST dispatch all calls to the multicastDelegate onto its parent's queue. * The parent's dispatch queue is passed in the configureWithParent:queue: method. **/ - (GCDMulticastDelegate *)multicastDelegate; @end
04081337-xmpp
Extensions/Roster/XMPPRosterPrivate.h
Objective-C
bsd
566
#import <Foundation/Foundation.h> #import "XMPPModule.h" #import "XMPPUser.h" #import "XMPPResource.h" #import "XMPPvCardAvatarModule.h" #if TARGET_OS_IPHONE #import "DDXML.h" #endif @class XMPPJID; @class XMPPStream; @class XMPPPresence; @protocol XMPPRosterStorage; @protocol XMPPRosterDelegate; /** * Add XMPPRoster as a delegate of XMPPvCardAvatarModule to cache roster photos in the roster. * This frees the view controller from having to save photos on the main thread. **/ @interface XMPPRoster : XMPPModule <XMPPvCardAvatarDelegate> { /* Inherited from XMPPModule: XMPPStream *xmppStream; dispatch_queue_t moduleQueue; id multicastDelegate; */ id <XMPPRosterStorage> xmppRosterStorage; Byte flags; NSMutableArray *earlyPresenceElements; } - (id)initWithRosterStorage:(id <XMPPRosterStorage>)storage; - (id)initWithRosterStorage:(id <XMPPRosterStorage>)storage dispatchQueue:(dispatch_queue_t)queue; /* Inherited from XMPPModule: - (BOOL)activate:(XMPPStream *)xmppStream; - (void)deactivate; @property (readonly) XMPPStream *xmppStream; - (void)addDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue; - (void)removeDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue; - (void)removeDelegate:(id)delegate; - (NSString *)moduleName; */ @property (nonatomic, readonly) id <XMPPRosterStorage> xmppRosterStorage; @property (nonatomic, assign) BOOL autoRoster; - (void)fetchRoster; - (void)addBuddy:(XMPPJID *)jid withNickname:(NSString *)optionalName; - (void)removeBuddy:(XMPPJID *)jid; - (void)setNickname:(NSString *)nickname forBuddy:(XMPPJID *)jid; - (void)acceptBuddyRequest:(XMPPJID *)jid; - (void)rejectBuddyRequest:(XMPPJID *)jid; - (id <XMPPUser>)myUser; - (id <XMPPResource>)myResource; - (id <XMPPUser>)userForJID:(XMPPJID *)jid; - (id <XMPPResource>)resourceForJID:(XMPPJID *)jid; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol XMPPRosterStorage <NSObject> @required // // // -- PUBLIC METHODS -- // // - (id <XMPPUser>)myUserForXMPPStream:(XMPPStream *)stream; - (id <XMPPResource>)myResourceForXMPPStream:(XMPPStream *)stream; - (id <XMPPUser>)userForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream; - (id <XMPPResource>)resourceForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream; // // // -- PRIVATE METHODS -- // // These methods are designed to be used ONLY by the XMPPRoster class. // // /** * Configures the storage class, passing its parent and parent's dispatch queue. * * This method is called by the init method of the XMPPRoster class. * This method is designed to inform the storage class of its parent * and of the dispatch queue the parent will be operating on. * * The storage class may choose to operate on the same queue as its parent, * or it may operate on its own internal dispatch queue. * * This method should return YES if it was configured properly. * If a storage class is designed to be used with a single parent at a time, this method may return NO. * The XMPPRoster class is configured to ignore the passed * storage class in its init method if this method returns NO. **/ - (BOOL)configureWithParent:(XMPPRoster *)aParent queue:(dispatch_queue_t)queue; - (void)beginRosterPopulationForXMPPStream:(XMPPStream *)stream; - (void)endRosterPopulationForXMPPStream:(XMPPStream *)stream; - (void)handleRosterItem:(NSXMLElement *)item xmppStream:(XMPPStream *)stream; - (void)handlePresence:(XMPPPresence *)presence xmppStream:(XMPPStream *)stream; - (void)clearAllResourcesForXMPPStream:(XMPPStream *)stream; - (void)clearAllUsersAndResourcesForXMPPStream:(XMPPStream *)stream; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol XMPPRosterDelegate @optional /** * Sent when a buddy request is received. * * The entire presence packet is provided for proper extensibility. * You can use [presence from] to get the JID of the buddy who sent the request. **/ - (void)xmppRoster:(XMPPRoster *)sender didReceiveBuddyRequest:(XMPPPresence *)presence; @end
04081337-xmpp
Extensions/Roster/XMPPRoster.h
Objective-C
bsd
4,458
#import "XMPP.h" #import "XMPPElement+Delay.h" #import "XMPPRosterMemoryStoragePrivate.h" @implementation XMPPResourceMemoryStorage - (id)initWithPresence:(XMPPPresence *)aPresence { if((self = [super init])) { jid = [[aPresence from] retain]; presence = [aPresence retain]; presenceDate = [[presence delayedDeliveryDate] retain]; if (presenceDate == nil) { presenceDate = [[NSDate alloc] init]; } } return self; } - (void)dealloc { [jid release]; [presence release]; [presenceDate release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Copying //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (id)copyWithZone:(NSZone *)zone { XMPPResourceMemoryStorage *deepCopy = [[XMPPResourceMemoryStorage alloc] init]; deepCopy->jid = [jid copy]; deepCopy->presence = [presence retain]; // No need to bother with a copy we don't alter presence deepCopy->presenceDate = [presenceDate copy]; return deepCopy; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Encoding, Decoding //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if ! TARGET_OS_IPHONE - (id)replacementObjectForPortCoder:(NSPortCoder *)encoder { if([encoder isBycopy]) return self; else return [super replacementObjectForPortCoder:encoder]; // return [NSDistantObject proxyWithLocal:self connection:[encoder connection]]; } #endif - (id)initWithCoder:(NSCoder *)coder { if((self = [super init])) { if([coder allowsKeyedCoding]) { jid = [[coder decodeObjectForKey:@"jid"] retain]; presence = [[coder decodeObjectForKey:@"presence"] retain]; presenceDate = [[coder decodeObjectForKey:@"presenceDate"] retain]; } else { jid = [[coder decodeObject] retain]; presence = [[coder decodeObject] retain]; presenceDate = [[coder decodeObject] retain]; } } return self; } - (void)encodeWithCoder:(NSCoder *)coder { if([coder allowsKeyedCoding]) { [coder encodeObject:jid forKey:@"jid"]; [coder encodeObject:presence forKey:@"presence"]; [coder encodeObject:presenceDate forKey:@"presenceDate"]; } else { [coder encodeObject:jid]; [coder encodeObject:presence]; [coder encodeObject:presenceDate]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Standard Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (XMPPJID *)jid { return jid; } - (XMPPPresence *)presence { return presence; } - (NSDate *)presenceDate { return presenceDate; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Update Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)updateWithPresence:(XMPPPresence *)aPresence { [presence release]; presence = [aPresence retain]; [presenceDate release]; presenceDate = [[presence delayedDeliveryDate] retain]; if (presenceDate == nil) { presenceDate = [[NSDate alloc] init]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Comparison Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSComparisonResult)compare:(id <XMPPResource>)another { XMPPPresence *mp = [self presence]; XMPPPresence *ap = [another presence]; int mpp = [mp priority]; int app = [ap priority]; if(mpp < app) return NSOrderedDescending; if(mpp > app) return NSOrderedAscending; // Priority is the same. // Determine who is more available based on their show. int mps = [mp intShow]; int aps = [ap intShow]; if(mps < aps) return NSOrderedDescending; if(mps > aps) return NSOrderedAscending; // Priority and Show are the same. // Determine based on who was the last to receive a presence element. NSDate *mpd = [self presenceDate]; NSDate *apd = [another presenceDate]; return [mpd compare:apd]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark NSObject Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSUInteger)hash { return [jid hash]; } - (BOOL)isEqual:(id)anObject { if([anObject isMemberOfClass:[self class]]) { XMPPResourceMemoryStorage *another = (XMPPResourceMemoryStorage *)anObject; return [jid isEqual:[another jid]]; } return NO; } - (NSString *)description { return [NSString stringWithFormat:@"XMPPResource: %@", [jid full]]; } @end
04081337-xmpp
Extensions/Roster/MemoryStorage/XMPPResourceMemoryStorage.m
Objective-C
bsd
5,110
#import "XMPP.h" #import "XMPPRosterPrivate.h" #import "XMPPRosterMemoryStorage.h" #import "XMPPRosterMemoryStoragePrivate.h" #import "XMPPLogging.h" // Log levels: off, error, warn, info, verbose #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; // | XMPP_LOG_FLAG_TRACE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif @interface XMPPRosterMemoryStorage (PrivateAPI) - (BOOL)isRosterItem:(NSXMLElement *)item; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPRosterMemoryStorage @synthesize parent; - (GCDMulticastDelegate <XMPPRosterMemoryStorageDelegate> *)multicastDelegate { return (GCDMulticastDelegate <XMPPRosterMemoryStorageDelegate> *)[parent multicastDelegate]; } - (id)init { if ((self = [super init])) { roster = [[NSMutableDictionary alloc] init]; } return self; } - (BOOL)configureWithParent:(XMPPRoster *)aParent queue:(dispatch_queue_t)queue { NSParameterAssert(aParent != nil); NSParameterAssert(queue != NULL); if ((parent == nil) && (parentQueue == NULL)) { parent = aParent; // Parents retain their children, children do NOT retain their parent parentQueue = queue; dispatch_retain(parentQueue); return YES; } return NO; } - (void)dealloc { if (parentQueue) dispatch_release(parentQueue); [roster release]; [myUser release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Internal API //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (id <XMPPUser>)_userForJID:(XMPPJID *)jid { // Private method: Only invoked on the parentQueue. XMPPUserMemoryStorage *result = [roster objectForKey:[jid bareJID]]; if (result) { return result; } XMPPJID *myJID = parent.xmppStream.myJID; XMPPJID *myBareJID = [myJID bareJID]; XMPPJID *bareJID = [jid bareJID]; if ([bareJID isEqual:myBareJID]) { return myUser; } return nil; } - (id <XMPPResource>)_resourceForJID:(XMPPJID *)jid { // Private method: Only invoked on the parentQueue. XMPPUserMemoryStorage *user = (XMPPUserMemoryStorage *)[self _userForJID:jid]; return [user resourceForJID:jid]; } - (NSArray *)_unsortedUsers { // Private method: Only invoked on the parentQueue. return [roster allValues]; } - (NSArray *)_unsortedAvailableUsers { // Private method: Only invoked on the parentQueue. NSArray *allUsers = [roster allValues]; NSMutableArray *result = [NSMutableArray arrayWithCapacity:[allUsers count]]; for (id <XMPPUser> user in allUsers) { if ([user isOnline]) { [result addObject:user]; } } return result; } - (NSArray *)_unsortedUnavailableUsers { // Private method: Only invoked on the parentQueue. NSArray *allUsers = [roster allValues]; NSMutableArray *result = [NSMutableArray arrayWithCapacity:[allUsers count]]; for (id <XMPPUser> user in allUsers) { if (![user isOnline]) { [result addObject:user]; } } return result; } - (NSArray *)_sortedUsersByName { // Private method: Only invoked on the parentQueue. return [[roster allValues] sortedArrayUsingSelector:@selector(compareByName:)]; } - (NSArray *)_sortedUsersByAvailabilityName { // Private method: Only invoked on the parentQueue. return [[roster allValues] sortedArrayUsingSelector:@selector(compareByAvailabilityName:)]; } - (NSArray *)_sortedAvailableUsersByName { // Private method: Only invoked on the parentQueue. return [[self _unsortedAvailableUsers] sortedArrayUsingSelector:@selector(compareByName:)]; } - (NSArray *)_sortedUnavailableUsersByName { // Private method: Only invoked on the parentQueue. return [[self _unsortedUnavailableUsers] sortedArrayUsingSelector:@selector(compareByName:)]; } - (NSArray *)_sortedResources:(BOOL)includeResourcesForMyUserExcludingMyself { // Private method: Only invoked on the parentQueue. // Add all the resouces from all the available users in the roster // // Remember: There may be multiple resources per user NSArray *availableUsers = [self unsortedAvailableUsers]; NSMutableArray *result = [NSMutableArray arrayWithCapacity:[availableUsers count]]; for (id<XMPPUser> user in availableUsers) { [result addObjectsFromArray:[user unsortedResources]]; } if (includeResourcesForMyUserExcludingMyself) { // Now add all the available resources from our own user account (excluding ourselves) XMPPJID *myJID = parent.xmppStream.myJID; NSArray *myResources = [myUser unsortedResources]; for (id<XMPPResource> resource in myResources) { if (![myJID isEqual:[resource jid]]) { [result addObject:resource]; } } } return [result sortedArrayUsingSelector:@selector(compare:)]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Roster Management //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (id <XMPPUser>)myUser { // This is a public method. // It may be invoked on any thread/queue. if (parentQueue == NULL) return nil; if (dispatch_get_current_queue() == parentQueue) { return myUser; } else { __block XMPPUserMemoryStorage *result; dispatch_sync(parentQueue, ^{ result = [myUser copy]; }); return [result autorelease]; } } - (id <XMPPResource>)myResource { // This is a public method. // It may be invoked on any thread/queue. if (parentQueue == NULL) return nil; XMPPJID *myJID = parent.xmppStream.myJID; if (dispatch_get_current_queue() == parentQueue) { return [myUser resourceForJID:myJID]; } else { __block XMPPResourceMemoryStorage *result; dispatch_sync(parentQueue, ^{ XMPPResourceMemoryStorage *resource = (XMPPResourceMemoryStorage *)[myUser resourceForJID:myJID]; result = [resource copy]; }); return [result autorelease]; } } - (id <XMPPUser>)userForJID:(XMPPJID *)jid { // This is a public method. // It may be invoked on any thread/queue. if (parentQueue == NULL) return nil; if (dispatch_get_current_queue() == parentQueue) { return [self _userForJID:jid]; } else { __block XMPPUserMemoryStorage *result; dispatch_sync(parentQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPUserMemoryStorage *user = (XMPPUserMemoryStorage *)[self _userForJID:jid]; result = [user copy]; [pool release]; }); return [result autorelease]; } } - (id <XMPPResource>)resourceForJID:(XMPPJID *)jid { // This is a public method. // It may be invoked on any thread/queue. if (parentQueue == NULL) return nil; if (dispatch_get_current_queue() == parentQueue) { return [self _resourceForJID:jid]; } else { __block XMPPResourceMemoryStorage *result; dispatch_sync(parentQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPResourceMemoryStorage *resource = (XMPPResourceMemoryStorage *)[self _resourceForJID:jid]; result = [resource copy]; [pool release]; }); return [result autorelease]; } } - (NSArray *)sortedUsersByName { // This is a public method. // It may be invoked on any thread/queue. if (parentQueue == NULL) return nil; if (dispatch_get_current_queue() == parentQueue) { return [self _sortedUsersByName]; } else { __block NSArray *result; dispatch_sync(parentQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSArray *temp = [self _sortedUsersByName]; result = [[NSArray alloc] initWithArray:temp copyItems:YES]; [pool release]; }); return [result autorelease]; } } - (NSArray *)sortedUsersByAvailabilityName { // This is a public method. // It may be invoked on any thread/queue. if (parentQueue == NULL) return nil; if (dispatch_get_current_queue() == parentQueue) { return [self _sortedUsersByAvailabilityName]; } else { __block NSArray *result; dispatch_sync(parentQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSArray *temp = [self _sortedUsersByAvailabilityName]; result = [[NSArray alloc] initWithArray:temp copyItems:YES]; [pool release]; }); return [result autorelease]; } } - (NSArray *)sortedAvailableUsersByName { // This is a public method. // It may be invoked on any thread/queue. if (parentQueue == NULL) return nil; if (dispatch_get_current_queue() == parentQueue) { return [self _sortedAvailableUsersByName]; } else { __block NSArray *result; dispatch_sync(parentQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSArray *temp = [self _sortedAvailableUsersByName]; result = [[NSArray alloc] initWithArray:temp copyItems:YES]; [pool release]; }); return [result autorelease]; } } - (NSArray *)sortedUnavailableUsersByName { // This is a public method. // It may be invoked on any thread/queue. if (parentQueue == NULL) return nil; if (dispatch_get_current_queue() == parentQueue) { return [self _sortedUnavailableUsersByName]; } else { __block NSArray *result; dispatch_sync(parentQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSArray *temp = [self _sortedUnavailableUsersByName]; result = [[NSArray alloc] initWithArray:temp copyItems:YES]; [pool release]; }); return [result autorelease]; } } - (NSArray *)unsortedUsers { // This is a public method. // It may be invoked on any thread/queue. if (parentQueue == NULL) return nil; if (dispatch_get_current_queue() == parentQueue) { return [self _unsortedUsers]; } else { __block NSArray *result; dispatch_sync(parentQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSArray *temp = [self _unsortedUsers]; result = [[NSArray alloc] initWithArray:temp copyItems:YES]; [pool release]; }); return [result autorelease]; } } - (NSArray *)unsortedAvailableUsers { // This is a public method. // It may be invoked on any thread/queue. if (parentQueue == NULL) return nil; if (dispatch_get_current_queue() == parentQueue) { return [self _unsortedAvailableUsers]; } else { __block NSArray *result; dispatch_sync(parentQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSArray *temp = [self _unsortedAvailableUsers]; result = [[NSArray alloc] initWithArray:temp copyItems:YES]; [pool release]; }); return [result autorelease]; } } - (NSArray *)unsortedUnavailableUsers { // This is a public method. // It may be invoked on any thread/queue. if (parentQueue == NULL) return nil; if (dispatch_get_current_queue() == parentQueue) { return [self _unsortedUnavailableUsers]; } else { __block NSArray *result; dispatch_sync(parentQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSArray *temp = [self _unsortedUnavailableUsers]; result = [[NSArray alloc] initWithArray:temp copyItems:YES]; [pool release]; }); return [result autorelease]; } } - (NSArray *)sortedResources:(BOOL)includeResourcesForMyUserExcludingMyself { // This is a public method. // It may be invoked on any thread/queue. if (parentQueue == NULL) return nil; if (dispatch_get_current_queue() == parentQueue) { return [self _sortedResources:includeResourcesForMyUserExcludingMyself]; } else { __block NSArray *result; dispatch_sync(parentQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSArray *temp = [self _sortedResources:includeResourcesForMyUserExcludingMyself]; result = [[NSArray alloc] initWithArray:temp copyItems:YES]; [pool release]; }); return [result autorelease]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPRosterStorage Protocol //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (id <XMPPUser>)myUserForXMPPStream:(XMPPStream *)stream { return [self myUser]; } - (id <XMPPResource>)myResourceForXMPPStream:(XMPPStream *)stream { return [self myResource]; } - (id <XMPPUser>)userForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { return [self userForJID:jid]; } - (id <XMPPResource>)resourceForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { return [self resourceForJID:jid]; } - (void)beginRosterPopulationForXMPPStream:(XMPPStream *)stream { XMPPLogTrace(); isRosterPopulation = YES; XMPPJID *myJID = parent.xmppStream.myJID; [myUser release]; myUser = [[XMPPUserMemoryStorage alloc] initWithJID:myJID]; } - (void)endRosterPopulationForXMPPStream:(XMPPStream *)stream { XMPPLogTrace(); isRosterPopulation = NO; [[self multicastDelegate] xmppRosterDidChange:self]; } - (void)handleRosterItem:(NSXMLElement *)item xmppStream:(XMPPStream *)stream { XMPPLogTrace(); if ([self isRosterItem:item]) { NSString *jidStr = [item attributeStringValueForName:@"jid"]; XMPPJID *jid = [[XMPPJID jidWithString:jidStr] bareJID]; NSString *subscription = [item attributeStringValueForName:@"subscription"]; if ([subscription isEqualToString:@"remove"]) { [roster removeObjectForKey:jid]; } else { XMPPUserMemoryStorage *user = [roster objectForKey:jid]; if (user) { [user updateWithItem:item]; } else { XMPPUserMemoryStorage *newUser = [[XMPPUserMemoryStorage alloc] initWithItem:item]; [roster setObject:newUser forKey:jid]; [newUser release]; } } if (!isRosterPopulation) { [[self multicastDelegate] xmppRosterDidChange:self]; } } } - (void)handlePresence:(XMPPPresence *)presence xmppStream:(XMPPStream *)stream { XMPPLogTrace(); XMPPJID *jidKey = [[presence from] bareJID]; XMPPUserMemoryStorage *rosterUser = [roster objectForKey:jidKey]; if (rosterUser) { [rosterUser updateWithPresence:presence]; if (!isRosterPopulation) { [[self multicastDelegate] xmppRosterDidChange:self]; } } else { // Not a presence element for anyone in our roster. // Is it a presence element for our user (either our resource or another resource)? XMPPJID *myJID = parent.xmppStream.myJID; XMPPJID *myBareJID = [myJID bareJID]; if([myBareJID isEqual:jidKey]) { [myUser updateWithPresence:presence]; if (!isRosterPopulation) { [[self multicastDelegate] xmppRosterDidChange:self]; } } } } - (void)clearAllResourcesForXMPPStream:(XMPPStream *)stream { XMPPLogTrace(); NSEnumerator *enumerator = [roster objectEnumerator]; XMPPUserMemoryStorage *user; while ((user = [enumerator nextObject])) { [user clearAllResources]; } [[self multicastDelegate] xmppRosterDidChange:self]; } - (void)clearAllUsersAndResourcesForXMPPStream:(XMPPStream *)stream { XMPPLogTrace(); [roster removeAllObjects]; [myUser release]; myUser = nil; [[self multicastDelegate] xmppRosterDidChange:self]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * For some bizarre reason (in my opinion), when you request your roster, * the server will return JID's NOT in your roster. * These are the JID's of users who have requested to be alerted to our presence. * After we sign in, we'll again be notified, via the normal presence request objects. * It's redundant, and annoying, and just plain incorrect to include these JID's when we request our personal roster. * So now, we have to go to the extra effort to filter out these JID's, which is exactly what this method does. **/ - (BOOL)isRosterItem:(NSXMLElement *)item { NSString *subscription = [item attributeStringValueForName:@"subscription"]; if ([subscription isEqualToString:@"none"]) { NSString *ask = [item attributeStringValueForName:@"ask"]; if ([ask isEqualToString:@"subscribe"]) { return YES; } else { return NO; } } return YES; } @end
04081337-xmpp
Extensions/Roster/MemoryStorage/XMPPRosterMemoryStorage.m
Objective-C
bsd
16,410
#import <Foundation/Foundation.h> #import "XMPPResource.h" @class XMPPJID; @class XMPPIQ; @class XMPPPresence; @interface XMPPResourceMemoryStorage : NSObject <XMPPResource, NSCopying, NSCoding> { XMPPJID *jid; XMPPPresence *presence; NSDate *presenceDate; } // See the XMPPResource protocol for available methods. @end
04081337-xmpp
Extensions/Roster/MemoryStorage/XMPPResourceMemoryStorage.h
Objective-C
bsd
330
#import "XMPPUserMemoryStorage.h" #import "XMPPResourceMemoryStorage.h" /** * The following methods are designed to be invoked ONLY from * within the XMPPRosterMemoryStorage implementation. * * Warning: XMPPUserMemoryStorage and XMPPResourceMemoryStorage are not explicitly thread-safe. * Only copies that are no longer being actively * altered by the XMPPRosterMemoryStorage class should be considered read-only and therefore thread-safe. **/ @interface XMPPUserMemoryStorage (Internal) - (id)initWithJID:(XMPPJID *)aJid; - (id)initWithItem:(NSXMLElement *)item; - (void)clearAllResources; - (void)updateWithItem:(NSXMLElement *)item; - (void)updateWithPresence:(XMPPPresence *)presence; - (NSInteger)tag; - (void)setTag:(NSInteger)anInt; @end @interface XMPPResourceMemoryStorage (Internal) - (id)initWithPresence:(XMPPPresence *)aPresence; - (void)updateWithPresence:(XMPPPresence *)presence; - (XMPPPresence *)presence; @end
04081337-xmpp
Extensions/Roster/MemoryStorage/XMPPRosterMemoryStoragePrivate.h
Objective-C
bsd
948
#import <Foundation/Foundation.h> #import "XMPPUser.h" #if TARGET_OS_IPHONE #import "DDXML.h" #endif @class XMPPJID; @class XMPPPresence; @class XMPPResourceMemoryStorage; @interface XMPPUserMemoryStorage : NSObject <XMPPUser, NSCopying, NSCoding> { XMPPJID *jid; NSMutableDictionary *itemAttributes; #if TARGET_OS_IPHONE UIImage *photo; #else NSImage *photo; #endif NSMutableDictionary *resources; XMPPResourceMemoryStorage *primaryResource; NSInteger tag; } // See the XMPPUser protocol for available methods. @end
04081337-xmpp
Extensions/Roster/MemoryStorage/XMPPUserMemoryStorage.h
Objective-C
bsd
538
#import <Foundation/Foundation.h> #import "XMPPRoster.h" @class XMPPUserMemoryStorage; /** * This class is an example implementation of XMPPRosterStorage using core data. * You are free to substitute your own storage class. **/ @interface XMPPRosterMemoryStorage : NSObject <XMPPRosterStorage> { XMPPRoster *parent; dispatch_queue_t parentQueue; NSMutableDictionary *roster; BOOL isRosterPopulation; XMPPUserMemoryStorage *myUser; } - (id)init; @property (nonatomic, readonly) XMPPRoster *parent; // The methods below provide access to the roster data. // If invoked from a dispatch queue other than the roster's queue, // the methods return snapshots (copies) of the roster data. // These snapshots provide a thread-safe version of the roster data. // The thread-safety comes from the fact that the copied data will not be altered, // so it can therefore be used from multiple threads/queues if needed. - (id <XMPPUser>)myUser; - (id <XMPPResource>)myResource; - (id <XMPPUser>)userForJID:(XMPPJID *)jid; - (id <XMPPResource>)resourceForJID:(XMPPJID *)jid; - (NSArray *)sortedUsersByName; - (NSArray *)sortedUsersByAvailabilityName; - (NSArray *)sortedAvailableUsersByName; - (NSArray *)sortedUnavailableUsersByName; - (NSArray *)unsortedUsers; - (NSArray *)unsortedAvailableUsers; - (NSArray *)unsortedUnavailableUsers; - (NSArray *)sortedResources:(BOOL)includeResourcesForMyUserExcludingMyself; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol XMPPRosterMemoryStorageDelegate @optional /** * The XMPPRosterStorage classes use the same delegate as their parent XMPPRoster. **/ - (void)xmppRosterDidChange:(XMPPRosterMemoryStorage *)sender; @end
04081337-xmpp
Extensions/Roster/MemoryStorage/XMPPRosterMemoryStorage.h
Objective-C
bsd
1,904
#import "XMPP.h" #import "XMPPRosterMemoryStoragePrivate.h" @interface XMPPUserMemoryStorage (PrivateAPI) - (void)recalculatePrimaryResource; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPUserMemoryStorage - (id)initWithJID:(XMPPJID *)aJid item:(NSXMLElement *)item { if ((self = [super init])) { jid = [[aJid bareJID] retain]; resources = [[NSMutableDictionary alloc] initWithCapacity:1]; photo = nil; tag = 0; if (item == nil) { itemAttributes = [[NSMutableDictionary alloc] initWithCapacity:0]; } else { itemAttributes = [[item attributesAsDictionary] retain]; } } return self; } - (id)initWithJID:(XMPPJID *)aJid { return [self initWithJID:aJid item:nil]; } - (id)initWithItem:(NSXMLElement *)item { NSString *jidStr = [[item attributeForName:@"jid"] stringValue]; jid = [[XMPPJID jidWithString:jidStr] bareJID]; return [self initWithJID:jid item:item]; } - (void)dealloc { [photo release]; [jid release]; [itemAttributes release]; [resources release]; [primaryResource release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Copying //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (id)copyWithZone:(NSZone *)zone { XMPPUserMemoryStorage *deepCopy = [[XMPPUserMemoryStorage alloc] init]; deepCopy->jid = [jid copy]; deepCopy->itemAttributes = [itemAttributes mutableCopy]; deepCopy->resources = [[NSMutableDictionary alloc] initWithCapacity:[resources count]]; for (XMPPJID *key in resources) { XMPPResourceMemoryStorage *resourceCopy = [[resources objectForKey:key] copy]; [deepCopy->resources setObject:resourceCopy forKey:key]; [resourceCopy release]; } [deepCopy recalculatePrimaryResource]; deepCopy->tag = tag; return deepCopy; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Encoding, Decoding //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if ! TARGET_OS_IPHONE - (id)replacementObjectForPortCoder:(NSPortCoder *)encoder { if([encoder isBycopy]) return self; else return [super replacementObjectForPortCoder:encoder]; // return [NSDistantObject proxyWithLocal:self connection:[encoder connection]]; } #endif - (id)initWithCoder:(NSCoder *)coder { if((self = [super init])) { if([coder allowsKeyedCoding]) { jid = [[coder decodeObjectForKey:@"jid"] retain]; itemAttributes = [[coder decodeObjectForKey:@"itemAttributes"] mutableCopy]; #if TARGET_OS_IPHONE photo = [[UIImage alloc] initWithData:[coder decodeObjectForKey:@"photo"]]; #else photo = [[NSImage alloc] initWithData:[coder decodeObjectForKey:@"photo"]]; #endif resources = [[coder decodeObjectForKey:@"resources"] mutableCopy]; primaryResource = [[coder decodeObjectForKey:@"primaryResource"] retain]; tag = [coder decodeIntegerForKey:@"tag"]; } else { jid = [[coder decodeObject] retain]; itemAttributes = [[coder decodeObject] mutableCopy]; #if TARGET_OS_IPHONE photo = [[UIImage alloc] initWithData:[coder decodeObject]]; #else photo = [[NSImage alloc] initWithData:[coder decodeObject]]; #endif resources = [[coder decodeObject] mutableCopy]; primaryResource = [[coder decodeObject] retain]; tag = [[coder decodeObject] integerValue]; } } return self; } - (void)encodeWithCoder:(NSCoder *)coder { if([coder allowsKeyedCoding]) { [coder encodeObject:jid forKey:@"jid"]; [coder encodeObject:itemAttributes forKey:@"itemAttributes"]; #if TARGET_OS_IPHONE [coder encodeObject:UIImagePNGRepresentation(photo) forKey:@"photo"]; #else [coder encodeObject:[photo TIFFRepresentation] forKey:@"photo"]; #endif [coder encodeObject:resources forKey:@"resources"]; [coder encodeObject:primaryResource forKey:@"primaryResource"]; [coder encodeInteger:tag forKey:@"tag"]; } else { [coder encodeObject:jid]; [coder encodeObject:itemAttributes]; #if TARGET_OS_IPHONE [coder encodeObject:UIImagePNGRepresentation(photo)]; #else [coder encodeObject:[photo TIFFRepresentation]]; #endif [coder encodeObject:resources]; [coder encodeObject:primaryResource]; [coder encodeObject:[NSNumber numberWithInteger:tag]]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Standard Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @synthesize photo; - (XMPPJID *)jid { return jid; } - (NSString *)nickname { return (NSString *)[itemAttributes objectForKey:@"name"]; } - (NSString *)displayName { NSString *nickname = [self nickname]; if(nickname) return nickname; else return [jid bare]; } - (BOOL)isOnline { return (primaryResource != nil); } - (BOOL)isPendingApproval { // Either of the following mean we're waiting to have our presence subscription approved: // <item ask='subscribe' subscription='none' jid='robbiehanson@deusty.com'/> // <item ask='subscribe' subscription='from' jid='robbiehanson@deusty.com'/> NSString *subscription = [itemAttributes objectForKey:@"subscription"]; NSString *ask = [itemAttributes objectForKey:@"ask"]; if ([subscription isEqualToString:@"none"] || [subscription isEqualToString:@"from"]) { if([ask isEqualToString:@"subscribe"]) { return YES; } } return NO; } - (id <XMPPResource>)primaryResource { return primaryResource; } - (id <XMPPResource>)resourceForJID:(XMPPJID *)aJid { return [resources objectForKey:aJid]; } - (NSArray *)sortedResources { return [[resources allValues] sortedArrayUsingSelector:@selector(compare:)]; } - (NSArray *)unsortedResources { return [resources allValues]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Helper Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)recalculatePrimaryResource { [primaryResource release]; primaryResource = nil; NSArray *sortedResources = [self sortedResources]; if([sortedResources count] > 0) { XMPPResourceMemoryStorage *possiblePrimary = [sortedResources objectAtIndex:0]; // Primary resource must have a non-negative priority if([[possiblePrimary presence] priority] >= 0) { primaryResource = [possiblePrimary retain]; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Update Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)clearAllResources { [resources removeAllObjects]; [primaryResource release]; primaryResource = nil; } - (void)updateWithItem:(NSXMLElement *)item { NSArray *attributes = [item attributes]; int i; for(i = 0; i < [attributes count]; i++) { NSXMLNode *node = [attributes objectAtIndex:i]; NSString *key = [node name]; NSString *value = [node stringValue]; if(![value isEqualToString:[itemAttributes objectForKey:key]]) { [itemAttributes setObject:value forKey:key]; } } } - (void)updateWithPresence:(XMPPPresence *)presence { if([[presence type] isEqualToString:@"unavailable"] || [presence isErrorPresence]) { [resources removeObjectForKey:[presence from]]; } else { XMPPJID *key = [presence from]; XMPPResourceMemoryStorage *resource = [resources objectForKey:key]; if(resource) { [resource updateWithPresence:presence]; } else { XMPPResourceMemoryStorage *newResource = [[XMPPResourceMemoryStorage alloc] initWithPresence:presence]; [resources setObject:newResource forKey:key]; [newResource release]; } } [self recalculatePrimaryResource]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Comparison Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Returns the result of invoking compareByName:options: with no options. **/ - (NSComparisonResult)compareByName:(id <XMPPUser>)another { return [self compareByName:another options:0]; } /** * This method compares the two users according to their display name. * * Options for the search — you can combine any of the following using a C bitwise OR operator: * NSCaseInsensitiveSearch, NSLiteralSearch, NSNumericSearch. * See "String Programming Guide for Cocoa" for details on these options. **/ - (NSComparisonResult)compareByName:(id <XMPPUser>)another options:(NSStringCompareOptions)mask { NSString *myName = [self displayName]; NSString *theirName = [another displayName]; return [myName compare:theirName options:mask]; } /** * Returns the result of invoking compareByAvailabilityName:options: with no options. **/ - (NSComparisonResult)compareByAvailabilityName:(id <XMPPUser>)another { return [self compareByAvailabilityName:another options:0]; } /** * This method compares the two users according to availability first, and then display name. * Thus available users come before unavailable users. * If both users are available, or both users are not available, * this method follows the same functionality as the compareByName:options: as documented above. **/ - (NSComparisonResult)compareByAvailabilityName:(id <XMPPUser>)another options:(NSStringCompareOptions)mask { if([self isOnline]) { if([another isOnline]) return [self compareByName:another options:mask]; else return NSOrderedAscending; } else { if([another isOnline]) return NSOrderedDescending; else return [self compareByName:another options:mask]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark NSObject Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSUInteger)hash { return [jid hash]; } - (BOOL)isEqual:(id)anObject { if([anObject isMemberOfClass:[self class]]) { XMPPUserMemoryStorage *another = (XMPPUserMemoryStorage *)anObject; return [jid isEqual:[another jid]]; } return NO; } - (NSString *)description { return [NSString stringWithFormat:@"XMPPUser: %@", [jid bare]]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark User Defined Content //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSInteger)tag { return tag; } - (void)setTag:(NSInteger)anInt { tag = anInt; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark KVO Compliance methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + (NSSet *)keyPathsForValuesAffectingIsOnline { return [NSSet setWithObject:@"primaryResource"]; } + (NSSet *)keyPathsForValuesAffectingUnsortedResources { return [NSSet setWithObject:@"resources"]; } + (NSSet *)keyPathsForValuesAffectingSortedResources { return [NSSet setWithObject:@"unsortedResources"]; } @end
04081337-xmpp
Extensions/Roster/MemoryStorage/XMPPUserMemoryStorage.m
Objective-C
bsd
11,966
#import "XMPP.h" #import "XMPPRosterCoreDataStorage.h" #import "XMPPUserCoreDataStorageObject.h" #import "XMPPResourceCoreDataStorageObject.h" #import "XMPPGroupCoreDataStorageObject.h" #import "NSNumber+XMPP.h" @interface XMPPUserCoreDataStorageObject () @property(nonatomic,retain) XMPPJID *primitiveJid; @property(nonatomic,retain) NSString *primitiveJidStr; @property(nonatomic,retain) NSString *primitiveDisplayName; @property(nonatomic,assign) NSInteger primitiveSection; @property(nonatomic,retain) NSString *primitiveSectionName; @property(nonatomic,retain) NSNumber *primitiveSectionNum; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPUserCoreDataStorageObject //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Accessors //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @dynamic jid, primitiveJid; @dynamic jidStr, primitiveJidStr; @dynamic streamBareJidStr; @dynamic nickname; @dynamic displayName, primitiveDisplayName; @dynamic subscription; @dynamic ask; @dynamic unreadMessages; @dynamic photo; @dynamic section, primitiveSection; @dynamic sectionName, primitiveSectionName; @dynamic sectionNum, primitiveSectionNum; @dynamic groups; @dynamic primaryResource; @dynamic resources; - (XMPPJID *)jid { // Create and cache the jid on demand [self willAccessValueForKey:@"jid"]; XMPPJID *tmp = [self primitiveJid]; [self didAccessValueForKey:@"jid"]; if (tmp == nil) { tmp = [XMPPJID jidWithString:[self jidStr]]; [self setPrimitiveJid:tmp]; } return tmp; } - (void)setJid:(XMPPJID *)jid { self.jidStr = [jid bare]; } - (void)setJidStr:(NSString *)jidStr { [self willChangeValueForKey:@"jidStr"]; [self setPrimitiveJidStr:jidStr]; [self didChangeValueForKey:@"jidStr"]; // If the jidStr changes, the jid becomes invalid. [self setPrimitiveJid:nil]; } - (NSInteger)section { // Create and cache the section on demand [self willAccessValueForKey:@"section"]; NSInteger tmp = [self primitiveSection]; [self didAccessValueForKey:@"section"]; // section uses zero, so to distinguish unset values, use NSNotFound if (tmp == NSNotFound) { tmp = [[self sectionNum] integerValue]; [self setPrimitiveSection:tmp]; } return tmp; } - (void)setSection:(NSInteger)value { self.sectionNum = [NSNumber numberWithInteger:value]; } - (NSInteger)primitiveSection { return section; } - (void)setPrimitiveSection:(NSInteger)primitiveSection { section = primitiveSection; } - (void)setSectionNum:(NSNumber *)sectionNum { [self willChangeValueForKey:@"sectionNum"]; [self setPrimitiveSectionNum:sectionNum]; [self didChangeValueForKey:@"sectionNum"]; // If the sectionNum changes, the section becomes invalid. // section uses zero, so to distinguish unset values, use NSNotFound [self setPrimitiveSection:NSNotFound]; } - (NSString *)sectionName { // Create and cache the sectionName on demand [self willAccessValueForKey:@"sectionName"]; NSString *tmp = [self primitiveSectionName]; [self didAccessValueForKey:@"sectionName"]; if (tmp == nil) { // Section names are organized by capitalizing the first letter of the displayName NSString *upperCase = [self.displayName uppercaseString]; // return the first character with support UTF-16: tmp = [upperCase substringWithRange:[upperCase rangeOfComposedCharacterSequenceAtIndex:0]]; [self setPrimitiveSectionName:tmp]; } return tmp; } - (void)setDisplayName:(NSString *)displayName { [self willChangeValueForKey:@"displayName"]; [self setPrimitiveDisplayName:displayName]; [self didChangeValueForKey:@"displayName"]; // If the displayName changes, the sectionName becomes invalid. [self setPrimitiveSectionName:nil]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark NSManagedObject //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)awakeFromInsert { // Section uses zero, so to distinguish unset values, use NSNotFound. self.primitiveSection = NSNotFound; } - (void)awakeFromFetch { // Section uses zero, so to distinguish unset values, use NSNotFound. // // Note: Do NOT use "self.section = NSNotFound" as this will in turn set the sectionNum. self.primitiveSection = NSNotFound; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Creation & Updates //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + (id)insertInManagedObjectContext:(NSManagedObjectContext *)moc withItem:(NSXMLElement *)item streamBareJidStr:(NSString *)streamBareJidStr { NSString *jidStr = [item attributeStringValueForName:@"jid"]; XMPPJID *jid = [XMPPJID jidWithString:jidStr]; if (jid == nil) { NSLog(@"XMPPUserCoreDataStorageObject: invalid item (missing or invalid jid): %@", item); return nil; } XMPPUserCoreDataStorageObject *newUser; newUser = [NSEntityDescription insertNewObjectForEntityForName:@"XMPPUserCoreDataStorageObject" inManagedObjectContext:moc]; newUser.streamBareJidStr = streamBareJidStr; [newUser updateWithItem:item]; return newUser; } - (void)updateGroupsWithItem:(NSXMLElement *)item { XMPPGroupCoreDataStorageObject *group = nil; // clear existing group memberships first if ([self.groups count] > 0) { [self removeGroups:self.groups]; } NSArray *groupItems = [item elementsForName:@"group"]; NSString *groupName = nil; for (NSXMLElement *groupElement in groupItems) { groupName = [groupElement stringValue]; group = [XMPPGroupCoreDataStorageObject fetchOrInsertGroupName:groupName inManagedObjectContext:[self managedObjectContext]]; if (group != nil) { [self addGroupsObject:group]; } } } - (void)updateWithItem:(NSXMLElement *)item { NSString *jidStr = [item attributeStringValueForName:@"jid"]; XMPPJID *jid = [XMPPJID jidWithString:jidStr]; if (jid == nil) { NSLog(@"XMPPUserCoreDataStorageObject: invalid item (missing or invalid jid): %@", item); return; } self.jid = jid; self.nickname = [item attributeStringValueForName:@"name"]; self.displayName = (self.nickname != nil) ? self.nickname : jidStr; self.subscription = [item attributeStringValueForName:@"subscription"]; self.ask = [item attributeStringValueForName:@"ask"]; [self updateGroupsWithItem:item]; } - (void)recalculatePrimaryResource { self.primaryResource = nil; NSArray *sortedResources = [self sortedResources]; if ([sortedResources count] > 0) { XMPPResourceCoreDataStorageObject *resource = [sortedResources objectAtIndex:0]; // Primary resource must have a non-negative priority if([resource priority] >= 0) { self.primaryResource = resource; if (resource.intShow >= 3) self.section = 0; else self.section = 1; } } if (self.primaryResource == nil) { self.section = 2; } } - (void)updateWithPresence:(XMPPPresence *)presence streamBareJidStr:(NSString *)streamBareJidStr { XMPPResourceCoreDataStorageObject *resource; resource = (XMPPResourceCoreDataStorageObject *)[self resourceForJID:[presence from]]; if ([[presence type] isEqualToString:@"unavailable"] || [presence isErrorPresence]) { if (resource) { [self removeResourcesObject:resource]; [[self managedObjectContext] deleteObject:resource]; } } else { if(resource) { [resource updateWithPresence:presence]; } else { XMPPResourceCoreDataStorageObject *newResource; newResource = [XMPPResourceCoreDataStorageObject insertInManagedObjectContext:[self managedObjectContext] withPresence:presence streamBareJidStr:streamBareJidStr]; [self addResourcesObject:newResource]; } } [self recalculatePrimaryResource]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPUser Protocol //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)isOnline { return (self.primaryResource != nil); } - (BOOL)isPendingApproval { // Either of the following mean we're waiting to have our presence subscription approved: // <item ask='subscribe' subscription='none' jid='robbiehanson@deusty.com'/> // <item ask='subscribe' subscription='from' jid='robbiehanson@deusty.com'/> NSString *subscription = self.subscription; NSString *ask = self.ask; if ([subscription isEqualToString:@"none"] || [subscription isEqualToString:@"from"]) { if ([ask isEqualToString:@"subscribe"]) { return YES; } } return NO; } - (id <XMPPResource>)resourceForJID:(XMPPJID *)jid { NSString *jidStr = [jid full]; for (XMPPResourceCoreDataStorageObject *resource in [self resources]) { if ([jidStr isEqualToString:[resource jidStr]]) { return resource; } } return nil; } - (NSArray *)sortedResources { return [[self unsortedResources] sortedArrayUsingSelector:@selector(compare:)]; } - (NSArray *)unsortedResources { return [[self resources] allObjects]; } /** * Returns the result of invoking compareByName:options: with no options. **/ - (NSComparisonResult)compareByName:(id <XMPPUser>)another { return [self compareByName:another options:0]; } /** * This method compares the two users according to their display name. * * Options for the search — you can combine any of the following using a C bitwise OR operator: * NSCaseInsensitiveSearch, NSLiteralSearch, NSNumericSearch. * See "String Programming Guide for Cocoa" for details on these options. **/ - (NSComparisonResult)compareByName:(id <XMPPUser>)another options:(NSStringCompareOptions)mask { NSString *myName = [self displayName]; NSString *theirName = [another displayName]; return [myName compare:theirName options:mask]; } /** * Returns the result of invoking compareByAvailabilityName:options: with no options. **/ - (NSComparisonResult)compareByAvailabilityName:(id <XMPPUser>)another { return [self compareByAvailabilityName:another options:0]; } /** * This method compares the two users according to availability first, and then display name. * Thus available users come before unavailable users. * If both users are available, or both users are not available, * this method follows the same functionality as the compareByName:options: as documented above. **/ - (NSComparisonResult)compareByAvailabilityName:(id <XMPPUser>)another options:(NSStringCompareOptions)mask { if ([self isOnline]) { if ([another isOnline]) return [self compareByName:another options:mask]; else return NSOrderedAscending; } else { if ([another isOnline]) return NSOrderedDescending; else return [self compareByName:another options:mask]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark KVO compliance methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + (NSSet *)keyPathsForValuesAffectingJid { // If the jidStr changes, the jid may change as well. return [NSSet setWithObject:@"jidStr"]; } + (NSSet *)keyPathsForValuesAffectingIsOnline { return [NSSet setWithObject:@"primaryResource"]; } + (NSSet *)keyPathsForValuesAffectingSection { // If the value of sectionNum changes, the section may change as well. return [NSSet setWithObject:@"sectionNum"]; } + (NSSet *)keyPathsForValuesAffectingSectionName { // If the value of displayName changes, the sectionName may change as well. return [NSSet setWithObject:@"displayName"]; } + (NSSet *)keyPathsForValuesAffectingSortedResources { return [NSSet setWithObject:@"unsortedResources"]; } + (NSSet *)keyPathsForValuesAffectingUnsortedResources { return [NSSet setWithObject:@"resources"]; } @end
04081337-xmpp
Extensions/Roster/CoreDataStorage/XMPPUserCoreDataStorageObject.m
Objective-C
bsd
12,658
#import <Foundation/Foundation.h> #import <CoreData/CoreData.h> #import "XMPPUser.h" #if TARGET_OS_IPHONE #import "DDXML.h" #endif @class XMPPStream; @class XMPPGroupCoreDataStorageObject; @class XMPPResourceCoreDataStorageObject; @interface XMPPUserCoreDataStorageObject : NSManagedObject <XMPPUser> { NSInteger section; } @property (nonatomic, retain) XMPPJID *jid; @property (nonatomic, retain) NSString * jidStr; @property (nonatomic, retain) NSString * streamBareJidStr; @property (nonatomic, retain) NSString * nickname; @property (nonatomic, retain) NSString * displayName; @property (nonatomic, retain) NSString * subscription; @property (nonatomic, retain) NSString * ask; @property (nonatomic, retain) NSNumber * unreadMessages; #if TARGET_OS_IPHONE @property (nonatomic, retain) UIImage *photo; #else @property (nonatomic, retain) NSImage *photo; #endif @property (nonatomic, assign) NSInteger section; @property (nonatomic, retain) NSString * sectionName; @property (nonatomic, retain) NSNumber * sectionNum; @property (nonatomic, retain) NSSet * groups; @property (nonatomic, retain) XMPPResourceCoreDataStorageObject * primaryResource; @property (nonatomic, retain) NSSet * resources; + (id)insertInManagedObjectContext:(NSManagedObjectContext *)moc withItem:(NSXMLElement *)item streamBareJidStr:(NSString *)streamBareJidStr; - (void)updateWithItem:(NSXMLElement *)item; - (void)updateWithPresence:(XMPPPresence *)presence streamBareJidStr:(NSString *)streamBareJidStr; @end @interface XMPPUserCoreDataStorageObject (CoreDataGeneratedAccessors) - (void)addResourcesObject:(XMPPResourceCoreDataStorageObject *)value; - (void)removeResourcesObject:(XMPPResourceCoreDataStorageObject *)value; - (void)addResources:(NSSet *)value; - (void)removeResources:(NSSet *)value; - (void)addGroupsObject:(XMPPGroupCoreDataStorageObject *)value; - (void)removeGroupsObject:(XMPPGroupCoreDataStorageObject *)value; - (void)addGroups:(NSSet *)value; - (void)removeGroups:(NSSet *)value; @end
04081337-xmpp
Extensions/Roster/CoreDataStorage/XMPPUserCoreDataStorageObject.h
Objective-C
bsd
2,055
// // XMPPGroupCoreDataStorageObject.m // // Created by Eric Chamberlain on 3/20/11. // Copyright (c) 2011 RF.com. All rights reserved. // #import "XMPPGroupCoreDataStorageObject.h" #import "XMPPUserCoreDataStorageObject.h" @implementation XMPPGroupCoreDataStorageObject //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Public //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + (void)clearEmptyGroupsInManagedObjectContext:(NSManagedObjectContext *)moc { NSEntityDescription *entity = [NSEntityDescription entityForName:NSStringFromClass([self class]) inManagedObjectContext:moc]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"users.@count == 0"]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; [fetchRequest setEntity:entity]; [fetchRequest setPredicate:predicate]; [fetchRequest setIncludesPendingChanges:YES]; NSArray *results = [moc executeFetchRequest:fetchRequest error:nil]; [fetchRequest release]; for (NSManagedObject *group in results) { [moc deleteObject:group]; } } + (id)insertGroupName:(NSString *)groupName inManagedObjectContext:(NSManagedObjectContext *)moc { if (groupName == nil) { return nil; } XMPPGroupCoreDataStorageObject *newGroup = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([self class]) inManagedObjectContext:moc]; newGroup.name = groupName; return newGroup; } + (id)fetchOrInsertGroupName:(NSString *)groupName inManagedObjectContext:(NSManagedObjectContext *)moc { if (groupName == nil) { return nil; } NSEntityDescription *entity = [NSEntityDescription entityForName:NSStringFromClass([self class]) inManagedObjectContext:moc]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", groupName]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; [fetchRequest setEntity:entity]; [fetchRequest setPredicate:predicate]; [fetchRequest setIncludesPendingChanges:YES]; [fetchRequest setFetchLimit:1]; NSArray *results = [moc executeFetchRequest:fetchRequest error:nil]; [fetchRequest release]; if ([results count] > 0) { return [results objectAtIndex:0]; } return [self insertGroupName:groupName inManagedObjectContext:moc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Accessors //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @dynamic name; @dynamic users; - (void)addUsersObject:(XMPPUserCoreDataStorageObject *)value { NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1]; [self willChangeValueForKey:@"users" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects]; [[self primitiveValueForKey:@"users"] addObject:value]; [self didChangeValueForKey:@"users" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects]; [changedObjects release]; } - (void)removeUsersObject:(XMPPUserCoreDataStorageObject *)value { NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1]; [self willChangeValueForKey:@"users" withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects]; [[self primitiveValueForKey:@"users"] removeObject:value]; [self didChangeValueForKey:@"users" withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects]; [changedObjects release]; } - (void)addUsers:(NSSet *)value { [self willChangeValueForKey:@"users" withSetMutation:NSKeyValueUnionSetMutation usingObjects:value]; [[self primitiveValueForKey:@"users"] unionSet:value]; [self didChangeValueForKey:@"users" withSetMutation:NSKeyValueUnionSetMutation usingObjects:value]; } - (void)removeUsers:(NSSet *)value { [self willChangeValueForKey:@"users" withSetMutation:NSKeyValueMinusSetMutation usingObjects:value]; [[self primitiveValueForKey:@"users"] minusSet:value]; [self didChangeValueForKey:@"users" withSetMutation:NSKeyValueMinusSetMutation usingObjects:value]; } @end
04081337-xmpp
Extensions/Roster/CoreDataStorage/XMPPGroupCoreDataStorageObject.m
Objective-C
bsd
4,374
// // XMPPGroupCoreDataStorageObject.h // // Created by Eric Chamberlain on 3/20/11. // Copyright (c) 2011 RF.com. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> @class XMPPUserCoreDataStorageObject; @interface XMPPGroupCoreDataStorageObject : NSManagedObject { @private } @property (nonatomic, retain) NSString * name; @property (nonatomic, retain) NSSet* users; + (void)clearEmptyGroupsInManagedObjectContext:(NSManagedObjectContext *)moc; + (id)fetchOrInsertGroupName:(NSString *)groupName inManagedObjectContext:(NSManagedObjectContext *)moc; + (id)insertGroupName:(NSString *)groupName inManagedObjectContext:(NSManagedObjectContext *)moc; @end
04081337-xmpp
Extensions/Roster/CoreDataStorage/XMPPGroupCoreDataStorageObject.h
Objective-C
bsd
704
#import "XMPP.h" #import "XMPPLogging.h" #import "XMPPRosterCoreDataStorage.h" #import "XMPPUserCoreDataStorageObject.h" #import "XMPPResourceCoreDataStorageObject.h" // Log levels: off, error, warn, info, verbose #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif @interface XMPPResourceCoreDataStorageObject (CoreDataGeneratedPrimitiveAccessors) - (NSDate *)primitivePresenceDate; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPResourceCoreDataStorageObject @dynamic jid; // Implementation below @dynamic presence; // Implementation below @dynamic priority; // Implementation below @dynamic intShow; // Implementation below @dynamic jidStr; @dynamic presenceStr; @dynamic streamBareJidStr; @dynamic type; @dynamic show; @dynamic status; @dynamic presenceDate; @dynamic priorityNum; @dynamic showNum; @dynamic user; - (XMPPJID *)jid { return [XMPPJID jidWithString:[self jidStr]]; } - (void)setJid:(XMPPJID *)jid { self.jidStr = [jid full]; } - (XMPPPresence *)presence { [self willAccessValueForKey:@"presence"]; XMPPPresence *presence = [self primitiveValueForKey:@"presence"]; [self didAccessValueForKey:@"presence"]; if (presence == nil) { NSString *presenceStr = self.presenceStr; if (presenceStr != nil) { NSXMLElement *element = [[NSXMLElement alloc] initWithXMLString:presenceStr error:nil]; presence = [XMPPPresence presenceFromElement:element]; [self setPrimitiveValue:presence forKey:@"presence"]; [element release]; } } return presence; } - (void)setPresence:(XMPPPresence *)newPresence { [self willChangeValueForKey:@"presence"]; [self setPrimitiveValue:newPresence forKey:@"presence"]; [self didChangeValueForKey:@"presence"]; self.presenceStr = [newPresence compactXMLString]; } - (int)priority { return [[self priorityNum] intValue]; } - (void)setPriority:(int)priority { self.priorityNum = [NSNumber numberWithInt:priority]; } - (int)intShow { return [[self showNum] intValue]; } - (void)setIntShow:(int)intShow { self.showNum = [NSNumber numberWithInt:intShow]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Compiler Workarounds //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if TARGET_OS_IPHONE && !TARGET_IPHONE_SIMULATOR /** * This method is here to quiet the compiler. * Without it the compiler complains that this method is not implemented as required by the protocol. * This only seems to be a problem when compiling for the device. **/ - (NSDate *)presenceDate { NSDate * tmpValue; [self willAccessValueForKey:@"presenceDate"]; tmpValue = [self primitivePresenceDate]; [self didAccessValueForKey:@"presenceDate"]; return tmpValue; } #endif //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Creation & Updates //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + (id)insertInManagedObjectContext:(NSManagedObjectContext *)moc withPresence:(XMPPPresence *)presence streamBareJidStr:(NSString *)streamBareJidStr { XMPPJID *jid = [presence from]; if (jid == nil) { XMPPLogWarn(@"%@: %@ - Invalid presence (missing or invalid jid): %@", [self class], THIS_METHOD, presence); return nil; } XMPPResourceCoreDataStorageObject *newResource; newResource = [NSEntityDescription insertNewObjectForEntityForName:@"XMPPResourceCoreDataStorageObject" inManagedObjectContext:moc]; newResource.streamBareJidStr = streamBareJidStr; [newResource updateWithPresence:presence]; return newResource; } - (void)updateWithPresence:(XMPPPresence *)presence { XMPPJID *jid = [presence from]; if (jid == nil) { XMPPLogWarn(@"%@: %@ - Invalid presence (missing or invalid jid): %@", [self class], THIS_METHOD, presence); return; } self.jid = jid; self.presence = presence; self.priority = [presence priority]; self.intShow = [presence intShow]; self.type = [presence type]; self.show = [presence show]; self.status = [presence status]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPResource Protocol //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSComparisonResult)compare:(id <XMPPResource>)another { XMPPPresence *mp = [self presence]; XMPPPresence *ap = [another presence]; int mpp = [mp priority]; int app = [ap priority]; if(mpp < app) return NSOrderedDescending; if(mpp > app) return NSOrderedAscending; // Priority is the same. // Determine who is more available based on their show. int mps = [mp intShow]; int aps = [ap intShow]; if(mps < aps) return NSOrderedDescending; if(mps > aps) return NSOrderedAscending; // Priority and Show are the same. // Determine based on who was the last to receive a presence element. NSDate *mpd = [self presenceDate]; NSDate *apd = [another presenceDate]; return [mpd compare:apd]; } @end
04081337-xmpp
Extensions/Roster/CoreDataStorage/XMPPResourceCoreDataStorageObject.m
Objective-C
bsd
5,647
#import <Foundation/Foundation.h> #import <CoreData/CoreData.h> #import "XMPPRoster.h" #import "XMPPCoreDataStorage.h" /** * This class is an example implementation of XMPPRosterStorage using core data. * You are free to substitute your own roster storage class. **/ @interface XMPPRosterCoreDataStorage : XMPPCoreDataStorage <XMPPRosterStorage> { // Inherits protected variables from XMPPCoreDataStorage NSMutableSet *rosterPopulationSet; } /** * Convenience method to get an instance with the default database name. * * IMPORTANT: * You are NOT required to use the sharedInstance. * * If your application uses multiple xmppStreams, and you use a sharedInstance of this class, * then all of your streams share the same database store. You might get better performance if you create * multiple instances of this class instead (using different database filenames), as this way you can have * concurrent writes to multiple databases. **/ + (XMPPRosterCoreDataStorage *)sharedInstance; // // This class inherits from XMPPCoreDataStorage. // // Please see the XMPPCoreDataStorage header file for more information. // @end
04081337-xmpp
Extensions/Roster/CoreDataStorage/XMPPRosterCoreDataStorage.h
Objective-C
bsd
1,144
#import "XMPPRosterCoreDataStorage.h" #import "XMPPGroupCoreDataStorageObject.h" #import "XMPPUserCoreDataStorageObject.h" #import "XMPPResourceCoreDataStorageObject.h" #import "XMPPRosterPrivate.h" #import "XMPPCoreDataStorageProtected.h" #import "XMPP.h" #import "XMPPLogging.h" #import "NSNumber+XMPP.h" // Log levels: off, error, warn, info, verbose #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_INFO | XMPP_LOG_FLAG_TRACE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif @implementation XMPPRosterCoreDataStorage static XMPPRosterCoreDataStorage *sharedInstance; + (XMPPRosterCoreDataStorage *)sharedInstance { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[XMPPRosterCoreDataStorage alloc] initWithDatabaseFilename:nil]; }); return sharedInstance; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Setup //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (id)init { return [self initWithDatabaseFilename:nil]; } - (id)initWithDatabaseFilename:(NSString *)aDatabaseFileName { if ((self = [super initWithDatabaseFilename:aDatabaseFileName])) { rosterPopulationSet = [[NSMutableSet alloc] init]; } return self; } - (BOOL)configureWithParent:(XMPPRoster *)aParent queue:(dispatch_queue_t)queue { return [super configureWithParent:aParent queue:queue]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Utilities //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * For some bizarre reason (in my opinion), when you request your roster, * the server will return JID's NOT in your roster. * These are the JID's of users who have requested to be alerted to our presence. * After we sign in, we'll again be notified, via the normal presence request objects. * It's redundant, and annoying, and just plain incorrect to include these JID's when we request our personal roster. * So now, we have to go to the extra effort to filter out these JID's, which is exactly what this method does. **/ - (BOOL)isRosterItem:(NSXMLElement *)item { NSString *subscription = [item attributeStringValueForName:@"subscription"]; if ([subscription isEqualToString:@"none"]) { NSString *ask = [item attributeStringValueForName:@"ask"]; if ([ask isEqualToString:@"subscribe"]) { return YES; } else { return NO; } } return YES; } - (id <XMPPUser>)_userForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { NSAssert(dispatch_get_current_queue() == storageQueue, @"Invoked on incorrect queue"); if (jid == nil) return nil; NSString *bareJIDStr = [jid bare]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPUserCoreDataStorageObject" inManagedObjectContext:[self managedObjectContext]]; NSPredicate *predicate; if (stream == nil) predicate = [NSPredicate predicateWithFormat:@"jidStr == %@", bareJIDStr]; else predicate = [NSPredicate predicateWithFormat:@"jidStr == %@ AND streamBareJidStr == %@", bareJIDStr, [[self myJIDForXMPPStream:stream] bare]]; NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; [fetchRequest setEntity:entity]; [fetchRequest setPredicate:predicate]; [fetchRequest setIncludesPendingChanges:YES]; [fetchRequest setFetchLimit:1]; NSArray *results = [[self managedObjectContext] executeFetchRequest:fetchRequest error:nil]; return (XMPPUserCoreDataStorageObject *)[results lastObject]; } - (id <XMPPResource>)_resourceForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { NSAssert(dispatch_get_current_queue() == storageQueue, @"Invoked on incorrect queue"); if (jid == nil) return nil; NSString *fullJIDStr = [jid full]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPResourceCoreDataStorageObject" inManagedObjectContext:[self managedObjectContext]]; NSPredicate *predicate; if (stream == nil) predicate = [NSPredicate predicateWithFormat:@"jidStr == %@", fullJIDStr]; else predicate = [NSPredicate predicateWithFormat:@"jidStr == %@ AND streamBareJidStr == %@", fullJIDStr, [[self myJIDForXMPPStream:stream] bare]]; NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; [fetchRequest setEntity:entity]; [fetchRequest setPredicate:predicate]; [fetchRequest setIncludesPendingChanges:YES]; [fetchRequest setFetchLimit:1]; NSArray *results = [[self managedObjectContext] executeFetchRequest:fetchRequest error:nil]; return (XMPPResourceCoreDataStorageObject *)[results lastObject]; } - (void)_clearAllResourcesForXMPPStream:(XMPPStream *)stream { NSAssert(dispatch_get_current_queue() == storageQueue, @"Invoked on incorrect queue"); NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPResourceCoreDataStorageObject" inManagedObjectContext:[self managedObjectContext]]; NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; [fetchRequest setEntity:entity]; [fetchRequest setFetchBatchSize:saveThreshold]; if (stream) { NSPredicate *predicate; predicate = [NSPredicate predicateWithFormat:@"streamBareJidStr == %@", [[self myJIDForXMPPStream:stream] bare]]; [fetchRequest setPredicate:predicate]; } NSArray *allResources = [[self managedObjectContext] executeFetchRequest:fetchRequest error:nil]; NSUInteger unsavedCount = [self numberOfUnsavedChanges]; for (XMPPResourceCoreDataStorageObject *resource in allResources) { [[self managedObjectContext] deleteObject:resource]; if (++unsavedCount >= saveThreshold) { [self save]; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Overrides //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)willCreatePersistentStore:(NSString *)filePath { // This method is overriden from the XMPPCoreDataStore superclass. // From the documentation: // // Override me, if needed, to provide customized behavior. // // For example, if you are using the database for non-persistent data you may want to delete the database // file if it already exists on disk. // // The default implementation does nothing. if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil]; } } - (void)didCreateManagedObjectContext { // This method is overriden from the XMPPCoreDataStore superclass. // From the documentation: // // Override me, if needed, to provide customized behavior. // // For example, if you are using the database for non-persistent data you may want to delete the database // file if it already exists on disk. // // The default implementation does nothing. // Reserved for future use (directory versioning). // Perhaps invoke [self _clearAllResourcesForXMPPStream:nil] ? } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Protocol Public API //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (id <XMPPUser>)myUserForXMPPStream:(XMPPStream *)stream { // This is a public method. // It may be invoked on any thread/queue. XMPPLogTrace(); XMPPJID *myJID = stream.myJID; if (myJID == nil) { return nil; } __block XMPPUserCoreDataStorageObject *result; [self executeBlock:^{ result = [[self _userForJID:myJID xmppStream:stream] retain]; }]; return [result autorelease]; } - (id <XMPPResource>)myResourceForXMPPStream:(XMPPStream *)stream { // This is a public method. // It may be invoked on any thread/queue. XMPPLogTrace(); XMPPJID *myJID = stream.myJID; if (myJID == nil) { return nil; } __block XMPPResourceCoreDataStorageObject *result; [self executeBlock:^{ result = [[self resourceForJID:myJID xmppStream:stream] retain]; }]; return [result autorelease]; } - (id <XMPPUser>)userForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { // This is a public method. // It may be invoked on any thread/queue. XMPPLogTrace(); __block XMPPUserCoreDataStorageObject *result; [self executeBlock:^{ result = [[self _userForJID:jid xmppStream:stream] retain]; }]; return [result autorelease]; } - (id <XMPPResource>)resourceForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { // This is a public method. // It may be invoked on any thread/queue. XMPPLogTrace(); __block XMPPResourceCoreDataStorageObject *result; [self executeBlock:^{ result = [[self _resourceForJID:jid xmppStream:stream] retain]; }]; return [result autorelease]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Protocol Private API //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)beginRosterPopulationForXMPPStream:(XMPPStream *)stream { XMPPLogTrace(); [self scheduleBlock:^{ [rosterPopulationSet addObject:[NSNumber numberWithPtr:stream]]; // clear anything already in the roster core data store // Note: Deleting a user will delete all associated resources // because of the cascade rule in our core data model. NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPUserCoreDataStorageObject" inManagedObjectContext:[self managedObjectContext]]; NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; [fetchRequest setEntity:entity]; [fetchRequest setFetchBatchSize:saveThreshold]; if (stream) { NSPredicate *predicate; predicate = [NSPredicate predicateWithFormat:@"streamBareJidStr == %@", [[self myJIDForXMPPStream:stream] bare]]; [fetchRequest setPredicate:predicate]; } NSArray *allUsers = [[self managedObjectContext] executeFetchRequest:fetchRequest error:nil]; for (XMPPUserCoreDataStorageObject *user in allUsers) { [[self managedObjectContext] deleteObject:user]; } [XMPPGroupCoreDataStorageObject clearEmptyGroupsInManagedObjectContext:[self managedObjectContext]]; }]; } - (void)endRosterPopulationForXMPPStream:(XMPPStream *)stream { XMPPLogTrace(); [self scheduleBlock:^{ [rosterPopulationSet removeObject:[NSNumber numberWithPtr:stream]]; }]; } - (void)handleRosterItem:(NSXMLElement *)itemSubElement xmppStream:(XMPPStream *)stream { XMPPLogTrace(); // Remember XML heirarchy memory management rules. // The passed parameter is a subnode of the IQ, and we need to pass it to an asynchronous operation. NSXMLElement *item = [[itemSubElement copy] autorelease]; [self scheduleBlock:^{ if ([self isRosterItem:item]) { if ([rosterPopulationSet containsObject:[NSNumber numberWithPtr:stream]]) { NSString *streamBareJidStr = [[self myJIDForXMPPStream:stream] bare]; [XMPPUserCoreDataStorageObject insertInManagedObjectContext:[self managedObjectContext] withItem:item streamBareJidStr:streamBareJidStr]; } else { NSString *jidStr = [item attributeStringValueForName:@"jid"]; XMPPJID *jid = [[XMPPJID jidWithString:jidStr] bareJID]; XMPPUserCoreDataStorageObject *user = (XMPPUserCoreDataStorageObject *)[self _userForJID:jid xmppStream:stream]; NSString *subscription = [item attributeStringValueForName:@"subscription"]; if ([subscription isEqualToString:@"remove"]) { if (user) { [[self managedObjectContext] deleteObject:user]; } } else { if (user) { [user updateWithItem:item]; } else { NSString *streamBareJidStr = [[self myJIDForXMPPStream:stream] bare]; [XMPPUserCoreDataStorageObject insertInManagedObjectContext:[self managedObjectContext] withItem:item streamBareJidStr:streamBareJidStr]; } } } } }]; } - (void)handlePresence:(XMPPPresence *)presence xmppStream:(XMPPStream *)stream { XMPPLogTrace(); [self scheduleBlock:^{ XMPPJID *jid = [presence from]; XMPPUserCoreDataStorageObject *user = (XMPPUserCoreDataStorageObject *)[self _userForJID:jid xmppStream:stream]; if (user) { NSString *streamBareJidStr = [[self myJIDForXMPPStream:stream] bare]; [user updateWithPresence:presence streamBareJidStr:streamBareJidStr]; } }]; } - (void)clearAllResourcesForXMPPStream:(XMPPStream *)stream { XMPPLogTrace(); [self scheduleBlock:^{ [self _clearAllResourcesForXMPPStream:stream]; }]; } - (void)clearAllUsersAndResourcesForXMPPStream:(XMPPStream *)stream { XMPPLogTrace(); [self scheduleBlock:^{ // Note: Deleting a user will delete all associated resources // because of the cascade rule in our core data model. NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPUserCoreDataStorageObject" inManagedObjectContext:[self managedObjectContext]]; NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; [fetchRequest setEntity:entity]; [fetchRequest setFetchBatchSize:saveThreshold]; if (stream) { NSPredicate *predicate; predicate = [NSPredicate predicateWithFormat:@"streamBareJidStr == %@", [[self myJIDForXMPPStream:stream] bare]]; [fetchRequest setPredicate:predicate]; } NSArray *allUsers = [[self managedObjectContext] executeFetchRequest:fetchRequest error:nil]; NSUInteger unsavedCount = [self numberOfUnsavedChanges]; for (XMPPUserCoreDataStorageObject *user in allUsers) { [[self managedObjectContext] deleteObject:user]; if (++unsavedCount >= saveThreshold) { [self save]; } } [XMPPGroupCoreDataStorageObject clearEmptyGroupsInManagedObjectContext:[self managedObjectContext]]; }]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Memory Management //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)dealloc { [rosterPopulationSet release]; [super dealloc]; } @end
04081337-xmpp
Extensions/Roster/CoreDataStorage/XMPPRosterCoreDataStorage.m
Objective-C
bsd
14,948
#import <Foundation/Foundation.h> #import <CoreData/CoreData.h> #import "XMPPResource.h" @class XMPPStream; @class XMPPPresence; @class XMPPUserCoreDataStorageObject; @interface XMPPResourceCoreDataStorageObject : NSManagedObject <XMPPResource> @property (nonatomic, retain) XMPPJID *jid; @property (nonatomic, retain) XMPPPresence *presence; @property (nonatomic, assign) int priority; @property (nonatomic, assign) int intShow; @property (nonatomic, retain) NSString * jidStr; @property (nonatomic, retain) NSString * presenceStr; @property (nonatomic, retain) NSString * streamBareJidStr; @property (nonatomic, retain) NSString * type; @property (nonatomic, retain) NSString * show; @property (nonatomic, retain) NSString * status; @property (nonatomic, retain) NSDate * presenceDate; @property (nonatomic, retain) NSNumber * priorityNum; @property (nonatomic, retain) NSNumber * showNum; @property (nonatomic, retain) XMPPUserCoreDataStorageObject * user; + (id)insertInManagedObjectContext:(NSManagedObjectContext *)moc withPresence:(XMPPPresence *)presence streamBareJidStr:(NSString *)streamBareJidStr; - (void)updateWithPresence:(XMPPPresence *)presence; @end
04081337-xmpp
Extensions/Roster/CoreDataStorage/XMPPResourceCoreDataStorageObject.h
Objective-C
bsd
1,222
#import <Foundation/Foundation.h> #if !TARGET_OS_IPHONE #import <Cocoa/Cocoa.h> #endif #if TARGET_OS_IPHONE #import "DDXML.h" #endif @class XMPPJID; @class XMPPIQ; @class XMPPPresence; @protocol XMPPResource; @protocol XMPPUser <NSObject> #if TARGET_OS_IPHONE @property (nonatomic, retain) UIImage * photo; #else @property (nonatomic, retain) NSImage * photo; #endif - (XMPPJID *)jid; - (NSString *)nickname; - (NSString *)displayName; - (BOOL)isOnline; - (BOOL)isPendingApproval; - (id <XMPPResource>)primaryResource; - (id <XMPPResource>)resourceForJID:(XMPPJID *)jid; - (NSArray *)sortedResources; - (NSArray *)unsortedResources; - (NSComparisonResult)compareByName:(id <XMPPUser>)another; - (NSComparisonResult)compareByName:(id <XMPPUser>)another options:(NSStringCompareOptions)mask; - (NSComparisonResult)compareByAvailabilityName:(id <XMPPUser>)another; - (NSComparisonResult)compareByAvailabilityName:(id <XMPPUser>)another options:(NSStringCompareOptions)mask; @end
04081337-xmpp
Extensions/Roster/XMPPUser.h
Objective-C
bsd
994
#import <Foundation/Foundation.h> @class XMPPJID; @class XMPPIQ; @class XMPPPresence; @protocol XMPPResource <NSObject> - (XMPPJID *)jid; - (XMPPPresence *)presence; - (NSDate *)presenceDate; - (NSComparisonResult)compare:(id <XMPPResource>)another; @end
04081337-xmpp
Extensions/Roster/XMPPResource.h
Objective-C
bsd
262
// // XMPPJabberRPCModule.h // XEP-0009 // // Originally created by Eric Chamberlain on 5/16/10. // #import <Foundation/Foundation.h> #import "XMPPModule.h" extern NSString *const XMPPJabberRPCErrorDomain; @class XMPPJID; @class XMPPStream; @class XMPPIQ; @protocol XMPPJabberRPCModuleDelegate; @interface XMPPJabberRPCModule : XMPPModule { NSMutableDictionary *rpcIDs; NSTimeInterval defaultTimeout; } @property (nonatomic, assign) NSTimeInterval defaultTimeout; - (NSString *)sendRpcIQ:(XMPPIQ *)iq; - (NSString *)sendRpcIQ:(XMPPIQ *)iq withTimeout:(NSTimeInterval)timeout; // caller knows best when a request has timed out // it should remove the rpcID, on timeout. - (void)timeoutRemoveRpcID:(NSString *)rpcID; @end @protocol XMPPJabberRPCModuleDelegate @optional // sent when transport error is received -(void)jabberRPC:(XMPPJabberRPCModule *)sender elementID:(NSString *)elementID didReceiveError:(NSError *)error; // sent when a methodResponse comes back -(void)jabberRPC:(XMPPJabberRPCModule *)sender elementID:(NSString *)elementID didReceiveMethodResponse:(id)response; // sent when a Jabber-RPC server request is received -(void)jabberRPC:(XMPPJabberRPCModule *)sender didReceiveSetIQ:(XMPPIQ *)iq; @end
04081337-xmpp
Extensions/XEP-0009/XMPPJabberRPCModule.h
Objective-C
bsd
1,235
// // XMPPIQ+JabberRPCResonse.h // XEP-0009 // // Created by Eric Chamberlain on 5/25/10. // #import "XMPPIQ.h" typedef enum { JabberRPCElementTypeArray, JabberRPCElementTypeDictionary, JabberRPCElementTypeMember, JabberRPCElementTypeName, JabberRPCElementTypeInteger, JabberRPCElementTypeDouble, JabberRPCElementTypeBoolean, JabberRPCElementTypeString, JabberRPCElementTypeDate, JabberRPCElementTypeData } JabberRPCElementType; @interface XMPPIQ(JabberRPCResonse) -(NSXMLElement *)methodResponseElement; // is this a Jabber RPC method response -(BOOL)isMethodResponse; -(BOOL)isFault; -(BOOL)isJabberRPC; -(id)methodResponse:(NSError **)error; -(id)objectFromElement:(NSXMLElement *)param; #pragma mark - -(NSArray *)parseArray:(NSXMLElement *)arrayElement; -(NSDictionary *)parseStruct:(NSXMLElement *)structElement; -(NSDictionary *)parseMember:(NSXMLElement *)memberElement; #pragma mark - - (NSDate *)parseDateString: (NSString *)dateString withFormat: (NSString *)format; #pragma mark - - (NSNumber *)parseInteger: (NSString *)value; - (NSNumber *)parseDouble: (NSString *)value; - (NSNumber *)parseBoolean: (NSString *)value; - (NSString *)parseString: (NSString *)value; - (NSDate *)parseDate: (NSString *)value; - (NSData *)parseData: (NSString *)value; @end
04081337-xmpp
Extensions/XEP-0009/XMPPIQ+JabberRPCResonse.h
Objective-C
bsd
1,336
// // XMPPIQ+JabberRPC.h // XEP-0009 // // Created by Eric Chamberlain on 5/16/10. // #import <Foundation/Foundation.h> #import "XMPPIQ.h" @interface XMPPIQ(JabberRPC) /** * Creates and returns a new autoreleased XMPPIQ. * This is the only method you normally need to call. **/ + (XMPPIQ *)rpcTo:(XMPPJID *)jid methodName:(NSString *)method parameters:(NSArray *)parameters; #pragma mark - #pragma mark Element helper methods // returns a Jabber-RPC query elelement // <query xmlns='jabber:iq:rpc'> +(NSXMLElement *)elementRpcQuery; // returns a Jabber-RPC methodCall element // <methodCall> +(NSXMLElement *)elementMethodCall; // returns a Jabber-RPC methodName element // <methodName>method</methodName> +(NSXMLElement *)elementMethodName:(NSString *)method; // returns a Jabber-RPC params element // <params> +(NSXMLElement *)elementParams; #pragma mark - #pragma mark Disco elements // returns the Disco query identity element // <identity category='automation' type='rpc'/> +(NSXMLElement *)elementRpcIdentity; // returns the Disco query feature element // <feature var='jabber:iq:rpc'/> +(NSXMLElement *)elementRpcFeature; #pragma mark - #pragma mark Conversion methods // encode any object into JabberRPC formatted element // this method calls the others +(NSXMLElement *)paramElementFromObject:(id)object; +(NSXMLElement *)valueElementFromObject:(id)object; +(NSXMLElement *)valueElementFromArray:(NSArray *)array; +(NSXMLElement *)valueElementFromDictionary:(NSDictionary *)dictionary; +(NSXMLElement *)valueElementFromBoolean:(CFBooleanRef)boolean; +(NSXMLElement *)valueElementFromNumber:(NSNumber *)number; +(NSXMLElement *)valueElementFromString:(NSString *)string; +(NSXMLElement *)valueElementFromDate:(NSDate *)date; +(NSXMLElement *)valueElementFromData:(NSData *)data; +(NSXMLElement *)valueElementFromElementWithName:(NSString *)elementName value:(NSString *)value; #pragma mark Wrapper methods +(NSXMLElement *)wrapElement:(NSString *)elementName aroundElement:(NSXMLElement *)element; +(NSXMLElement *)wrapValueElementAroundElement:(NSXMLElement *)element; @end
04081337-xmpp
Extensions/XEP-0009/XMPPIQ+JabberRPC.h
Objective-C
bsd
2,124
// // XMPPIQ+JabberRPCResonse.m // XEP-0009 // // Created by Eric Chamberlain on 5/25/10. // #import "XMPPIQ+JabberRPCResonse.h" #import "NSData+XMPP.h" #import "NSXMLElement+XMPP.h" #import "XMPPJabberRPCModule.h" #import "XMPPLogging.h" // Log levels: off, error, warn, info, verbose #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif @implementation XMPPIQ(JabberRPCResonse) -(NSXMLElement *)methodResponseElement { NSXMLElement *query = [self elementForName:@"query"]; return [query elementForName:@"methodResponse"]; } // is this a Jabber RPC method response -(BOOL)isMethodResponse { /* <methodResponse> <params> <param> <value><string>South Dakota</string></value> </param> </params> </methodResponse> */ NSXMLElement *methodResponse = [self methodResponseElement]; return methodResponse != nil; } -(BOOL)isFault { /* <methodResponse> <fault> <value> <struct> <member> <name>faultCode</name> <value><int>4</int></value> </member> <member> <name>faultString</name> <value><string>Too many parameters.</string></value> </member> </struct> </value> </fault> </methodResponse> */ NSXMLElement *methodResponse = [self methodResponseElement]; return [methodResponse elementForName:@"fault"] != nil; } -(BOOL)isJabberRPC { /* <query xmlns="jabber:iq:rpc"> ... </query> */ NSXMLElement *rpcQuery = [self elementForName:@"query" xmlns:@"jabber:iq:rpc"]; return rpcQuery != nil; } -(id)methodResponse:(NSError **)error { id response = nil; /* <methodResponse> <params> <param> <value><string>South Dakota</string></value> </param> </params> </methodResponse> */ // or /* <methodResponse> <fault> <value> <struct> <member> <name>faultCode</name> <value><int>4</int></value> </member> <member> <name>faultString</name> <value><string>Too many parameters.</string></value> </member> </struct> </value> </fault> </methodResponse> */ NSXMLElement *methodResponse = [self methodResponseElement]; // parse the methodResponse response = [self objectFromElement:(NSXMLElement *)[methodResponse childAtIndex:0]]; if ([self isFault]) { // we should produce an error // response should be a dict if (error) { *error = [NSError errorWithDomain:XMPPJabberRPCErrorDomain code:[[response objectForKey:@"faultCode"] intValue] userInfo:(NSDictionary *)response]; } response = nil; } else { if (error) { *error = nil; } } return response; } -(id)objectFromElement:(NSXMLElement *)param { NSString *element = [param name]; if ([element isEqualToString:@"params"] || [element isEqualToString:@"param"] || [element isEqualToString:@"fault"] || [element isEqualToString:@"value"]) { NSXMLElement *firstChild = (NSXMLElement *)[param childAtIndex:0]; if (firstChild) { return [self objectFromElement:firstChild]; } else { // no child element, treat it like a string return [self parseString:[param stringValue]]; } } else if ([element isEqualToString:@"string"] || [element isEqualToString:@"name"]) { return [self parseString:[param stringValue]]; } else if ([element isEqualToString:@"member"]) { return [self parseMember:param]; } else if ([element isEqualToString:@"array"]) { return [self parseArray:param]; } else if ([element isEqualToString:@"struct"]) { return [self parseStruct:param]; } else if ([element isEqualToString:@"int"]) { return [self parseInteger:[param stringValue]]; } else if ([element isEqualToString:@"double"]) { return [self parseDouble:[param stringValue]]; } else if ([element isEqualToString:@"boolean"]) { return [self parseBoolean:[param stringValue]]; } else if ([element isEqualToString:@"dateTime.iso8601"]) { return [self parseDate:[param stringValue]]; } else if ([element isEqualToString:@"base64"]) { return [self parseData:[param stringValue]]; } else { // bad element XMPPLogWarn(@"%@: %@ - bad element: %@", THIS_FILE, THIS_METHOD, [param stringValue]); } return nil; } #pragma mark - -(NSArray *)parseArray:(NSXMLElement *)arrayElement { /* <array> <data> <value><i4>12</i4></value> <value><string>Egypt</string></value> <value><boolean>0</boolean></value> <value><i4>-31</i4></value> </data> </array> */ NSXMLElement *data = (NSXMLElement *)[arrayElement childAtIndex:0]; NSArray *children = [data children]; NSMutableArray *array = [NSMutableArray arrayWithCapacity:[children count]]; for (NSXMLElement *child in children) { [array addObject:[self objectFromElement:child]]; } return array; } -(NSDictionary *)parseStruct:(NSXMLElement *)structElement { /* <struct> <member> <name>lowerBound</name> <value><i4>18</i4></value> </member> <member> <name>upperBound</name> <value><i4>139</i4></value> </member> </struct> */ NSArray *children = [structElement children]; NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:[children count]]; for (NSXMLElement *child in children) { [dict addEntriesFromDictionary:[self parseMember:child]]; } return dict; } -(NSDictionary *)parseMember:(NSXMLElement *)memberElement { NSString *key = [self objectFromElement:[memberElement elementForName:@"name"]]; id value = [self objectFromElement:[memberElement elementForName:@"value"]]; return [NSDictionary dictionaryWithObject:value forKey:key]; } #pragma mark - - (NSDate *)parseDateString: (NSString *)dateString withFormat: (NSString *)format { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; NSDate *result = nil; [dateFormatter setDateFormat: format]; result = [dateFormatter dateFromString: dateString]; [dateFormatter release]; return result; } #pragma mark - - (NSNumber *)parseInteger: (NSString *)value { return [NSNumber numberWithInteger: [value integerValue]]; } - (NSNumber *)parseDouble: (NSString *)value { return [NSNumber numberWithDouble: [value doubleValue]]; } - (NSNumber *)parseBoolean: (NSString *)value { if ([value isEqualToString: @"1"]) { return [NSNumber numberWithBool: YES]; } return [NSNumber numberWithBool: NO]; } - (NSString *)parseString: (NSString *)value { return [value stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; } - (NSDate *)parseDate: (NSString *)value { NSDate *result = nil; result = [self parseDateString: value withFormat: @"yyyyMMdd'T'HH:mm:ss"]; if (!result) { result = [self parseDateString: value withFormat: @"yyyy'-'MM'-'dd'T'HH:mm:ss"]; } return result; } - (NSData *)parseData: (NSString *)value { // Convert the base 64 encoded data into a string NSData *base64Data = [value dataUsingEncoding:NSASCIIStringEncoding]; NSData *decodedData = [base64Data base64Decoded]; return decodedData; } @end
04081337-xmpp
Extensions/XEP-0009/XMPPIQ+JabberRPCResonse.m
Objective-C
bsd
7,074
// // XMPPJabberRPCModule.m // XEP-0009 // // Originally created by Eric Chamberlain on 5/16/10. // #import "XMPPJabberRPCModule.h" #import "XMPP.h" #import "XMPPIQ+JabberRPC.h" #import "XMPPIQ+JabberRPCResonse.h" #import "XMPPLogging.h" // Log levels: off, error, warn, info, verbose // Log flags: trace #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; // | XMPP_LOG_FLAG_TRACE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif // can turn off if not acting as a Jabber-RPC server #define INTEGRATE_WITH_CAPABILITIES 1 #if INTEGRATE_WITH_CAPABILITIES #import "XMPPCapabilities.h" #endif NSString *const XMPPJabberRPCErrorDomain = @"XMPPJabberRPCErrorDomain"; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @interface RPCID : NSObject { NSString *rpcID; dispatch_source_t timer; } @property (nonatomic, readonly) NSString *rpcID; @property (nonatomic, readonly) dispatch_source_t timer; - (id)initWithRpcID:(NSString *)rpcID timer:(dispatch_source_t)timer; - (void)cancelTimer; @end @implementation RPCID @synthesize rpcID; @synthesize timer; - (id)initWithRpcID:(NSString *)aRpcID timer:(dispatch_source_t)aTimer { if ((self = [super init])) { rpcID = [aRpcID copy]; timer = aTimer; dispatch_retain(timer); } return self; } - (BOOL)isEqual:(id)anObject { return [rpcID isEqual:anObject]; } - (NSUInteger)hash { return [rpcID hash]; } - (void)cancelTimer { if (timer) { dispatch_source_cancel(timer); dispatch_release(timer); timer = NULL; } } - (void)dealloc { [self cancelTimer]; [rpcID release]; [super dealloc]; } @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPJabberRPCModule @dynamic defaultTimeout; - (NSTimeInterval)defaultTimeout { __block NSTimeInterval result; dispatch_block_t block = ^{ result = defaultTimeout; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_sync(moduleQueue, block); return result; } - (void)setDefaultTimeout:(NSTimeInterval)newDefaultTimeout { dispatch_block_t block = ^{ XMPPLogTrace(); defaultTimeout = newDefaultTimeout; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Module Management //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (id)init { return [self initWithDispatchQueue:NULL]; } - (id)initWithDispatchQueue:(dispatch_queue_t)queue { if ((self = [super initWithDispatchQueue:queue])) { XMPPLogTrace(); rpcIDs = [[NSMutableDictionary alloc] initWithCapacity:5]; defaultTimeout = 5.0; } return self; } - (BOOL)activate:(XMPPStream *)aXmppStream { XMPPLogTrace(); if ([super activate:aXmppStream]) { #if INTEGRATE_WITH_CAPABILITIES [xmppStream autoAddDelegate:self delegateQueue:moduleQueue toModulesOfClass:[XMPPCapabilities class]]; #endif return YES; } return NO; } - (void)deactivate { XMPPLogTrace(); #if INTEGRATE_WITH_CAPABILITIES [xmppStream removeAutoDelegate:self delegateQueue:moduleQueue fromModulesOfClass:[XMPPCapabilities class]]; #endif [super deactivate]; } - (void)dealloc { XMPPLogTrace(); [rpcIDs release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Send RPC //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSString *)sendRpcIQ:(XMPPIQ *)iq { return [self sendRpcIQ:iq withTimeout:[self defaultTimeout]]; } - (NSString *)sendRpcIQ:(XMPPIQ *)iq withTimeout:(NSTimeInterval)timeout { XMPPLogTrace(); NSString *elementID = [iq elementID]; dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, moduleQueue); dispatch_source_set_event_handler(timer, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self timeoutRemoveRpcID:elementID]; [pool drain]; }); dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (timeout * NSEC_PER_SEC)); dispatch_source_set_timer(timer, tt, DISPATCH_TIME_FOREVER, 0); dispatch_resume(timer); RPCID *rpcID = [[RPCID alloc] initWithRpcID:elementID timer:timer]; [rpcIDs setObject:rpcID forKey:elementID]; [rpcID release]; [xmppStream sendElement:iq]; return elementID; } - (void)timeoutRemoveRpcID:(NSString *)elementID { XMPPLogTrace(); RPCID *rpcID = [rpcIDs objectForKey:elementID]; if (rpcID) { [rpcID cancelTimer]; [rpcIDs removeObjectForKey:elementID]; NSError *error = [NSError errorWithDomain:XMPPJabberRPCErrorDomain code:1400 userInfo:[NSDictionary dictionaryWithObjectsAndKeys: @"Request timed out", @"error",nil]]; [multicastDelegate jabberRPC:self elementID:elementID didReceiveError:error]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPStream delegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq { XMPPLogTrace(); if ([iq isJabberRPC]) { if ([iq isResultIQ] || [iq isErrorIQ]) { // Example: // // <iq from="deusty.com" to="robbiehanson@deusty.com/work" id="abc123" type="result"/> NSString *elementID = [iq elementID]; // check if this is a JabberRPC query // we could check the query element, but we should be able to do a lookup based on the unique elementID // because we send an ID, we should get one back RPCID *rpcID = [rpcIDs objectForKey:elementID]; if (rpcID == nil) { return NO; } XMPPLogVerbose(@"%@: Received RPC response!", THIS_FILE); if ([iq isResultIQ]) { id response; NSError *error = nil; //TODO: parse iq and generate response. response = [iq methodResponse:&error]; if (error == nil) { [multicastDelegate jabberRPC:self elementID:elementID didReceiveMethodResponse:response]; } else { [multicastDelegate jabberRPC:self elementID:elementID didReceiveError:error]; } } else { // TODO: implement error parsing // not much specified in XEP, only 403 forbidden error NSXMLElement *errorElement = [iq childErrorElement]; NSError *error = [NSError errorWithDomain:XMPPJabberRPCErrorDomain code:[errorElement attributeIntValueForName:@"code"] userInfo:[NSDictionary dictionaryWithObjectsAndKeys: [errorElement attributesAsDictionary],@"error", [[errorElement childAtIndex:0] name], @"condition", iq,@"iq", nil]]; [multicastDelegate jabberRPC:self elementID:elementID didReceiveError:error]; } [rpcID cancelTimer]; [rpcIDs removeObjectForKey:elementID]; #if INTEGRATE_WITH_CAPABILITIES } else if ([iq isSetIQ]) { // we would receive set when implementing Jabber-RPC server [multicastDelegate jabberRPC:self didReceiveSetIQ:iq]; #endif } // Jabber-RPC doesn't use get iq type } return NO; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPCapabilities delegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if INTEGRATE_WITH_CAPABILITIES /** * If an XMPPCapabilites instance is used we want to advertise our support for JabberRPC. **/ - (void)xmppCapabilities:(XMPPCapabilities *)sender collectingMyCapabilities:(NSXMLElement *)query { XMPPLogTrace(); // <query xmlns="http://jabber.org/protocol/disco#info"> // ... // <identity category='automation' type='rpc'/> // <feature var='jabber:iq:rpc'/> // ... // </query> [query addChild:[XMPPIQ elementRpcIdentity]]; [query addChild:[XMPPIQ elementRpcFeature]]; } #endif @end
04081337-xmpp
Extensions/XEP-0009/XMPPJabberRPCModule.m
Objective-C
bsd
8,698
// // XMPPIQ+JabberRPC.m // XEP-0009 // // Created by Eric Chamberlain on 5/16/10. // #import "XMPPIQ+JabberRPC.h" #import "NSData+XMPP.h" #import "XMPP.h" @implementation XMPPIQ(JabberRPC) +(XMPPIQ *)rpcTo:(XMPPJID *)jid methodName:(NSString *)method parameters:(NSArray *)parameters { // Send JabberRPC element // // <iq to="fullJID" type="set" id="elementID"> // <query xmlns='jabber:iq:rpc'> // <methodCall> // <methodName>method</methodName> // <params> // <param> // <value><string>example</string></value> // </param> // ... // </params> // </methodCall> // </query> // </iq> XMPPIQ *iq = [XMPPIQ iqWithType:@"set" to:jid elementID:[XMPPStream generateUUID]]; NSXMLElement *jabberRPC = [self elementRpcQuery]; NSXMLElement *methodCall = [self elementMethodCall]; NSXMLElement *methodName = [self elementMethodName:method]; NSXMLElement *params = [self elementParams]; for (id parameter in parameters) { [params addChild:[self paramElementFromObject:parameter]]; } [methodCall addChild:methodName]; [methodCall addChild:params]; [jabberRPC addChild:methodCall]; [iq addChild:jabberRPC]; return iq; } #pragma mark Element helper methods +(NSXMLElement *)elementRpcQuery { return [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:rpc"]; } +(NSXMLElement *)elementMethodCall { return [NSXMLElement elementWithName:@"methodCall"]; } +(NSXMLElement *)elementMethodName:(NSString *)method { return [NSXMLElement elementWithName:@"methodName" stringValue:method]; } +(NSXMLElement *)elementParams { return [NSXMLElement elementWithName:@"params"]; } #pragma mark - #pragma mark Disco elements +(NSXMLElement *)elementRpcIdentity { NSXMLElement *identity = [NSXMLElement elementWithName:@"identity"]; [identity addAttributeWithName:@"category" stringValue:@"automation"]; [identity addAttributeWithName:@"type" stringValue:@"rpc"]; return identity; } // returns the Disco query feature element // <feature var='jabber:iq:rpc'/> +(NSXMLElement *)elementRpcFeature { NSXMLElement *feature = [NSXMLElement elementWithName:@"feature"]; [feature addAttributeWithName:@"var" stringValue:@"jabber:iq:rpc"]; return feature; } #pragma mark Conversion methods +(NSXMLElement *)paramElementFromObject:(id)object { if (!object) { return nil; } return [self wrapElement:@"param" aroundElement:[self valueElementFromObject:object]]; } +(NSXMLElement *)valueElementFromObject:(id)object { if (!object) { return nil; } if ([object isKindOfClass: [NSArray class]]) { return [self valueElementFromArray: object]; } else if ([object isKindOfClass: [NSDictionary class]]) { return [self valueElementFromDictionary: object]; } else if (((CFBooleanRef)object == kCFBooleanTrue) || ((CFBooleanRef)object == kCFBooleanFalse)) { return [self valueElementFromBoolean: (CFBooleanRef)object]; } else if ([object isKindOfClass: [NSNumber class]]) { return [self valueElementFromNumber: object]; } else if ([object isKindOfClass: [NSString class]]) { return [self valueElementFromString: object]; } else if ([object isKindOfClass: [NSDate class]]) { return [self valueElementFromDate: object]; } else if ([object isKindOfClass: [NSData class]]) { return [self valueElementFromData: object]; } else { return [self valueElementFromString: object]; } } +(NSXMLElement *)valueElementFromArray:(NSArray *)array { NSXMLElement *data = [NSXMLElement elementWithName:@"data"]; for (id object in array) { [data addChild:[self valueElementFromObject:object]]; } return [self wrapValueElementAroundElement:data]; } +(NSXMLElement *)valueElementFromDictionary:(NSDictionary *)dictionary { NSXMLElement *structElement = [NSXMLElement elementWithName:@"struct"]; NSXMLElement *member; NSXMLElement *name; for (NSString *key in dictionary) { member = [NSXMLElement elementWithName:@"member"]; name = [NSXMLElement elementWithName:@"name" stringValue:key]; [member addChild:name]; [member addChild:[self valueElementFromObject:[dictionary objectForKey:key]]]; } return [self wrapValueElementAroundElement:structElement]; } +(NSXMLElement *)valueElementFromBoolean:(CFBooleanRef)boolean { if (boolean == kCFBooleanTrue) { return [self valueElementFromElementWithName:@"boolean" value:@"1"]; } else { return [self valueElementFromElementWithName:@"boolean" value:@"0"]; } } +(NSXMLElement *)valueElementFromNumber:(NSNumber *)number { // what type of NSNumber is this? if ([[NSString stringWithCString: [number objCType] encoding: NSUTF8StringEncoding] isEqualToString: @"d"]) { return [self valueElementFromElementWithName:@"double" value:[number stringValue]]; } else { return [self valueElementFromElementWithName:@"i4" value:[number stringValue]]; } } +(NSXMLElement *)valueElementFromString:(NSString *)string { return [self valueElementFromElementWithName:@"string" value:string]; } +(NSXMLElement *)valueElementFromDate:(NSDate *)date { unsigned calendarComponents = kCFCalendarUnitYear | kCFCalendarUnitMonth | kCFCalendarUnitDay | kCFCalendarUnitHour | kCFCalendarUnitMinute | kCFCalendarUnitSecond; NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:calendarComponents fromDate:date]; NSString *dateString = [NSString stringWithFormat: @"%.4d%.2d%.2dT%.2d:%.2d:%.2d", [dateComponents year], [dateComponents month], [dateComponents day], [dateComponents hour], [dateComponents minute], [dateComponents second], nil]; return [self valueElementFromElementWithName:@"dateTime.iso8601" value: dateString]; } +(NSXMLElement *)valueElementFromData:(NSData *)data { return [self valueElementFromElementWithName:@"base64" value:[data base64Encoded]]; } +(NSXMLElement *)valueElementFromElementWithName:(NSString *)elementName value:(NSString *)value { return [self wrapValueElementAroundElement:[NSXMLElement elementWithName:elementName stringValue:value]]; } #pragma mark Wrapper methods +(NSXMLElement *)wrapElement:(NSString *)elementName aroundElement:(NSXMLElement *)element { NSXMLElement *wrapper = [NSXMLElement elementWithName:elementName]; [wrapper addChild:element]; return wrapper; } +(NSXMLElement *)wrapValueElementAroundElement:(NSXMLElement *)element { return [self wrapElement:@"value" aroundElement:element]; } @end
04081337-xmpp
Extensions/XEP-0009/XMPPIQ+JabberRPC.m
Objective-C
bsd
6,515
// // XMPPvCardAvatarModule.h // XEP-0153 vCard-Based Avatars // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // TODO: publish after upload vCard /* * XEP-0153 Section 4.2 rule 1 * * However, a client MUST advertise an image if it has just uploaded the vCard with a new avatar * image. In this case, the client MAY choose not to redownload the vCard to verify its contents. */ #import "XMPPvCardAvatarModule.h" #import "NSData+XMPP.h" #import "NSXMLElement+XMPP.h" #import "XMPPLogging.h" #import "XMPPPresence.h" #import "XMPPStream.h" #import "XMPPvCardTempModule.h" // Log levels: off, error, warn, info, verbose // Log flags: trace #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; // | XMPP_LOG_FLAG_TRACE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif NSString *const kXMPPvCardAvatarElement = @"x"; NSString *const kXMPPvCardAvatarNS = @"vcard-temp:x:update"; NSString *const kXMPPvCardAvatarPhotoElement = @"photo"; @implementation XMPPvCardAvatarModule //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Init/dealloc //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (id)init { // This will cause a crash - it's designed to. // Only the init methods listed in XMPPvCardAvatarModule.h are supported. return [self initWithvCardTempModule:nil dispatchQueue:NULL]; } - (id)initWithDispatchQueue:(dispatch_queue_t)queue { // This will cause a crash - it's designed to. // Only the init methods listed in XMPPvCardAvatarModule.h are supported. return [self initWithvCardTempModule:nil dispatchQueue:NULL]; } - (id)initWithvCardTempModule:(XMPPvCardTempModule *)xmppvCardTempModule { return [self initWithvCardTempModule:xmppvCardTempModule dispatchQueue:NULL]; } - (id)initWithvCardTempModule:(XMPPvCardTempModule *)xmppvCardTempModule dispatchQueue:(dispatch_queue_t)queue { NSParameterAssert(xmppvCardTempModule != nil); if ((self = [super initWithDispatchQueue:queue])) { _xmppvCardTempModule = [xmppvCardTempModule retain]; // we don't need to call the storage configureWithParent:queue: method, // because the vCardTempModule already did that. _moduleStorage = [(id <XMPPvCardAvatarStorage>)xmppvCardTempModule.moduleStorage retain]; [_xmppvCardTempModule addDelegate:self delegateQueue:moduleQueue]; } return self; } - (void)dealloc { [_xmppvCardTempModule removeDelegate:self]; [_moduleStorage release]; _moduleStorage = nil; [_xmppvCardTempModule release]; _xmppvCardTempModule = nil; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Public //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSData *)photoDataForJID:(XMPPJID *)jid { // This is a public method, so it may be invoked on any thread/queue. // // The vCardTempModule is thread safe. // The moduleStorage should be thread safe. (User may be using custom module storage class). // The multicastDelegate is NOT thread safe. __block NSData *photoData; dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; photoData = [[_moduleStorage photoDataForJID:jid xmppStream:xmppStream] retain]; if (photoData == nil) { [_xmppvCardTempModule fetchvCardTempForJID:jid useCache:YES]; } else { #if TARGET_OS_IPHONE UIImage *photo = [UIImage imageWithData:photoData]; #else NSImage *photo = [[[NSImage alloc] initWithData:photoData] autorelease]; #endif [multicastDelegate xmppvCardAvatarModule:self didReceivePhoto:photo forJID:jid]; } [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_sync(moduleQueue, block); return [photoData autorelease]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPStreamDelegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)xmppStreamWillConnect:(XMPPStream *)sender { XMPPLogTrace(); /* * XEP-0153 Section 4.2 rule 1 * * A client MUST NOT advertise an avatar image without first downloading the current vCard. * Once it has done this, it MAY advertise an image. */ [_moduleStorage clearvCardTempForJID:[sender myJID] xmppStream:xmppStream]; } - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender { XMPPLogTrace(); [_xmppvCardTempModule fetchvCardTempForJID:[sender myJID] useCache:NO]; } - (void)xmppStream:(XMPPStream *)sender willSendPresence:(XMPPPresence *)presence { XMPPLogTrace(); // add our photo info to the presence stanza NSXMLElement *photoElement = nil; NSXMLElement *xElement = [NSXMLElement elementWithName:kXMPPvCardAvatarElement xmlns:kXMPPvCardAvatarNS]; NSString *photoHash = [_moduleStorage photoHashForJID:[sender myJID] xmppStream:xmppStream]; if (photoHash != nil) { photoElement = [NSXMLElement elementWithName:kXMPPvCardAvatarPhotoElement stringValue:photoHash]; } else { photoElement = [NSXMLElement elementWithName:kXMPPvCardAvatarPhotoElement]; } [xElement addChild:photoElement]; [presence addChild:xElement]; // Question: If photoElement is nil, should we be adding xElement? } - (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence { XMPPLogTrace(); NSXMLElement *xElement = [presence elementForName:kXMPPvCardAvatarElement xmlns:kXMPPvCardAvatarNS]; if (xElement == nil) { return; } NSString *photoHash = [[xElement elementForName:kXMPPvCardAvatarPhotoElement] stringValue]; if (photoHash == nil || [photoHash isEqualToString:@""]) { return; } XMPPJID *jid = [presence from]; // check the hash if (![photoHash isEqualToString:[_moduleStorage photoHashForJID:jid xmppStream:xmppStream]]) { [_xmppvCardTempModule fetchvCardTempForJID:jid useCache:NO]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPvCardTempModuleDelegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)xmppvCardTempModule:(XMPPvCardTempModule *)vCardTempModule didReceivevCardTemp:(XMPPvCardTemp *)vCardTemp forJID:(XMPPJID *)jid { XMPPLogTrace(); if (vCardTemp.photo != nil) { #if TARGET_OS_IPHONE UIImage *photo = [UIImage imageWithData:vCardTemp.photo]; #else NSImage *photo = [[[NSImage alloc] initWithData:vCardTemp.photo] autorelease]; #endif if (photo != nil) { [multicastDelegate xmppvCardAvatarModule:self didReceivePhoto:photo forJID:jid]; } } /* * XEP-0153 4.1.3 * If the client subsequently obtains an avatar image (e.g., by updating or retrieving the vCard), * it SHOULD then publish a new <presence/> stanza with character data in the <photo/> element. */ if ([jid isEqual:[[xmppStream myJID] bareJID]]) { XMPPPresence *presence = xmppStream.myPresence; if(presence) { [xmppStream sendElement:presence]; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Getter/setter //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @synthesize xmppvCardTempModule = _xmppvCardTempModule; @end
04081337-xmpp
Extensions/XEP-0153/XMPPvCardAvatarModule.m
Objective-C
bsd
7,911
// // XMPPvCardAvatarModule.h // XEP-0153 vCard-Based Avatars // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. /* * NOTE: Currently this implementation only supports downloading and caching avatars. */ #import <Foundation/Foundation.h> #if !TARGET_OS_IPHONE #import <Cocoa/Cocoa.h> #endif #import "XMPPModule.h" #import "XMPPvCardTempModule.h" @class XMPPJID; @class XMPPStream; @protocol XMPPvCardAvatarDelegate; @protocol XMPPvCardAvatarStorage; @interface XMPPvCardAvatarModule : XMPPModule <XMPPvCardTempModuleDelegate> { XMPPvCardTempModule *_xmppvCardTempModule; id <XMPPvCardAvatarStorage> _moduleStorage; } @property(nonatomic,retain,readonly) XMPPvCardTempModule *xmppvCardTempModule; - (id)initWithvCardTempModule:(XMPPvCardTempModule *)xmppvCardTempModule; - (id)initWithvCardTempModule:(XMPPvCardTempModule *)xmppvCardTempModule dispatchQueue:(dispatch_queue_t)queue; - (NSData *)photoDataForJID:(XMPPJID *)jid; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol XMPPvCardAvatarDelegate <NSObject> #if TARGET_OS_IPHONE - (void)xmppvCardAvatarModule:(XMPPvCardAvatarModule *)vCardTempModule didReceivePhoto:(UIImage *)photo forJID:(XMPPJID *)jid; #else - (void)xmppvCardAvatarModule:(XMPPvCardAvatarModule *)vCardTempModule didReceivePhoto:(NSImage *)photo forJID:(XMPPJID *)jid; #endif @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol XMPPvCardAvatarStorage <NSObject> - (NSData *)photoDataForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream; - (NSString *)photoHashForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream; /** * Clears the vCardTemp from the store. * This is used so we can clear any cached vCardTemp's for the JID. **/ - (void)clearvCardTempForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream; @end
04081337-xmpp
Extensions/XEP-0153/XMPPvCardAvatarModule.h
Objective-C
bsd
2,333
#import <Foundation/Foundation.h> #import "NSDate+XMPPDateTimeProfiles.h" @interface XMPPDateTimeProfiles : NSObject /** * The following methods attempt to parse the given string following XEP-0082. * They return nil if the given string doesn't follow the spec. **/ + (NSDate *)parseDate:(NSString *)dateStr; + (NSDate *)parseTime:(NSString *)timeStr; + (NSDate *)parseDateTime:(NSString *)dateTimeStr; + (NSTimeZone *)parseTimeZoneOffset:(NSString *)tzo; @end
04081337-xmpp
Extensions/XEP-0082/XMPPDateTimeProfiles.h
Objective-C
bsd
468
#import "XMPPDateTimeProfiles.h" #import "NSNumber+XMPP.h" @interface XMPPDateTimeProfiles (PrivateAPI) + (NSDate *)parseDateTime:(NSString *)dateTimeStr withMandatoryTimeZone:(BOOL)mandatoryTZ; @end @implementation XMPPDateTimeProfiles /** * The following acronyms and characters are used from XEP-0082 to represent time-related concepts: * * CCYY four-digit year portion of Date * MM two-digit month portion of Date * DD two-digit day portion of Date * - ISO 8601 separator among Date portions * T ISO 8601 separator between Date and Time * hh two-digit hour portion of Time (00 through 23) * mm two-digit minutes portion of Time (00 through 59) * ss two-digit seconds portion of Time (00 through 59) * : ISO 8601 separator among Time portions * . ISO 8601 separator between seconds and milliseconds * sss fractional second addendum to Time (MAY contain any number of digits) * TZD Time Zone Definition (either "Z" for UTC or "(+|-)hh:mm" for a specific time zone) * **/ + (NSDate *)parseDate:(NSString *)dateStr { if ([dateStr length] < 10) return nil; // The Date profile defines a date without including the time of day. // The lexical representation is as follows: // // CCYY-MM-DD // // Example: // // 1776-07-04 NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setFormatterBehavior:NSDateFormatterBehavior10_4]; // Use unicode patterns (as opposed to 10_3) [df setDateFormat:@"yyyy-MM-dd"]; NSDate *result = [df dateFromString:dateStr]; [df release]; return result; } + (NSDate *)parseTime:(NSString *)timeStr { // The Time profile is used to specify an instant of time that recurs (e.g., every day). // The lexical representation is as follows: // // hh:mm:ss[.sss][TZD] // // The Time Zone Definition is optional; if included, it MUST be either UTC (denoted by addition // of the character 'Z' to the end of the string) or some offset from UTC (denoted by addition // of '[+|-]' and 'hh:mm' to the end of the string). // // Examples: // // 16:00:00 // 16:00:00Z // 16:00:00+07:00 // 16:00:00.123 // 16:00:00.123Z // 16:00:00.123+07:00 // Extract the current day so the result can be on the current day. // Why do we bother doing this? // // First, it is rather intuitive. // Second, if we don't we risk being on a date with a conflicting DST (daylight saving time). // // For example, -0800 instead of the current -0700. // This can be rather confusing when printing the result. NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setFormatterBehavior:NSDateFormatterBehavior10_4]; // Use unicode patterns (as opposed to 10_3) [df setDateFormat:@"yyyy-MM-dd"]; NSString *today = [df stringFromDate:[NSDate date]]; [df release]; NSString *dateTimeStr = [NSString stringWithFormat:@"%@T%@", today, timeStr]; return [self parseDateTime:dateTimeStr withMandatoryTimeZone:NO]; } + (NSDate *)parseDateTime:(NSString *)dateTimeStr { // The DateTime profile is used to specify a non-recurring moment in time to an accuracy of seconds (or, // optionally, fractions of a second). The format is as follows: // // CCYY-MM-DDThh:mm:ss[.sss]TZD // // The Time Zone Definition is mandatory and MUST be either UTC (denoted by addition of the character 'Z' // to the end of the string) or some offset from UTC (denoted by addition of '[+|-]' and 'hh:mm' to the // end of the string). // // Examples: // // 1969-07-21T02:56:15Z // 1969-07-20T21:56:15-05:00 // 1969-07-21T02:56:15.123Z // 1969-07-20T21:56:15.123-05:00 return [self parseDateTime:dateTimeStr withMandatoryTimeZone:YES]; } + (NSDate *)parseDateTime:(NSString *)dateTimeStr withMandatoryTimeZone:(BOOL)mandatoryTZ { if ([dateTimeStr length] < 19) return nil; // The DateTime profile is used to specify a non-recurring moment in time to an accuracy of seconds (or, // optionally, fractions of a second). The format is as follows: // // CCYY-MM-DDThh:mm:ss[.sss]{TZD} // // Examples: // // 1969-07-21T02:56:15 // 1969-07-21T02:56:15Z // 1969-07-20T21:56:15-05:00 // 1969-07-21T02:56:15.123 // 1969-07-21T02:56:15.123Z // 1969-07-20T21:56:15.123-05:00 BOOL hasMilliseconds = NO; BOOL hasTimeZoneInfo = NO; BOOL hasTimeZoneOffset = NO; if ([dateTimeStr length] > 19) { unichar c = [dateTimeStr characterAtIndex:19]; // Check for optional milliseconds if (c == '.') { hasMilliseconds = YES; if ([dateTimeStr length] < 23) return nil; if ([dateTimeStr length] > 23) { c = [dateTimeStr characterAtIndex:23]; } } // Check for optional time zone info if (c == 'Z') { hasTimeZoneInfo = YES; hasTimeZoneOffset = NO; } else if (c == '+' || c == '-') { hasTimeZoneInfo = YES; hasTimeZoneOffset = YES; if (hasMilliseconds) { if ([dateTimeStr length] < 29) return nil; } else { if ([dateTimeStr length] < 25) return nil; } } } if (mandatoryTZ && !hasTimeZoneInfo) return nil; NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setFormatterBehavior:NSDateFormatterBehavior10_4]; // Use unicode patterns (as opposed to 10_3) if (hasMilliseconds) { if (hasTimeZoneInfo) { if (hasTimeZoneOffset) [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"]; // Offset calculated separately else [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"]; } else { [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"]; } } else if (hasTimeZoneInfo) { if (hasTimeZoneOffset) [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"]; // Offset calculated separately else [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"]; } else { [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"]; } NSDate *result; if (hasTimeZoneInfo && !hasTimeZoneOffset) { [df setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; result = [df dateFromString:dateTimeStr]; } else if (hasTimeZoneInfo && hasTimeZoneOffset) { NSString *dto; NSString *tzo; if (hasMilliseconds) { dto = [dateTimeStr substringToIndex:23]; tzo = [dateTimeStr substringFromIndex:23]; } else { dto = [dateTimeStr substringToIndex:19]; tzo = [dateTimeStr substringFromIndex:19]; } NSTimeZone *timeZone = [self parseTimeZoneOffset:tzo]; if (timeZone == nil) { result = nil; } else { [df setTimeZone:timeZone]; result = [df dateFromString:dto]; } } else { result = [df dateFromString:dateTimeStr]; } [df release]; return result; } + (NSTimeZone *)parseTimeZoneOffset:(NSString *)tzo { // The tzo value is supposed to start with '+' or '-'. // Spec says: (+-)hh:mm // // hh : two-digit hour portion (00 through 23) // mm : two-digit minutes portion (00 through 59) if ([tzo length] != 6) { return nil; } NSString *hoursStr = [tzo substringWithRange:NSMakeRange(1, 2)]; NSString *minutesStr = [tzo substringWithRange:NSMakeRange(4, 2)]; NSUInteger hours; if (![NSNumber parseString:hoursStr intoNSUInteger:&hours]) return nil; NSUInteger minutes; if (![NSNumber parseString:minutesStr intoNSUInteger:&minutes]) return nil; if (hours > 23) return nil; if (minutes > 59) return nil; NSInteger secondsOffset = (NSInteger)((hours * 60 * 60) + (minutes * 60)); if ([tzo hasPrefix:@"-"]) { secondsOffset = -1 * secondsOffset; } else if (![tzo hasPrefix:@"+"]) { return nil; } return [NSTimeZone timeZoneForSecondsFromGMT:secondsOffset]; } @end
04081337-xmpp
Extensions/XEP-0082/XMPPDateTimeProfiles.m
Objective-C
bsd
7,441
// // NSDate+XMPPDateTimeProfiles.h // // NSDate category to implement XEP-0082. // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // Copyright 2010 Martin Morrison. All rights reserved. // #import <Foundation/Foundation.h> @interface NSDate(XMPPDateTimeProfiles) + (NSDate *)dateWithXmppDateString:(NSString *)str; + (NSDate *)dateWithXmppTimeString:(NSString *)str; + (NSDate *)dateWithXmppDateTimeString:(NSString *)str; - (NSString *)xmppDateString; - (NSString *)xmppTimeString; - (NSString *)xmppDateTimeString; @end
04081337-xmpp
Extensions/XEP-0082/NSDate+XMPPDateTimeProfiles.h
Objective-C
bsd
578
// // NSDate+XMPPDateTimeProfiles.m // // NSDate category to implement XEP-0082. // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // Copyright 2010 Martin Morrison. All rights reserved. // #import "NSDate+XMPPDateTimeProfiles.h" #import "XMPPDateTimeProfiles.h" @interface NSDate(XMPPDateTimeProfilesPrivate) - (NSString *)xmppStringWithDateFormat:(NSString *)dateFormat; @end @implementation NSDate(XMPPDateTimeProfiles) #pragma mark - #pragma mark Convert from XMPP string to NSDate + (NSDate *)dateWithXmppDateString:(NSString *)str { return [XMPPDateTimeProfiles parseDate:str]; } + (NSDate *)dateWithXmppTimeString:(NSString *)str { return [XMPPDateTimeProfiles parseTime:str]; } + (NSDate *)dateWithXmppDateTimeString:(NSString *)str { return [XMPPDateTimeProfiles parseDateTime:str]; } #pragma mark - #pragma mark Convert from NSDate to XMPP string - (NSString *)xmppDateString { return [self xmppStringWithDateFormat:@"yyyy-MM-dd"]; } - (NSString *)xmppTimeString { return [self xmppStringWithDateFormat:@"HH:mm:ss'Z'"]; } - (NSString *)xmppDateTimeString { return [self xmppStringWithDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"]; } #pragma mark - #pragma mark XMPPDateTimeProfilesPrivate methods - (NSString *)xmppStringWithDateFormat:(NSString *)dateFormat { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4]; [dateFormatter setDateFormat:dateFormat]; [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; NSString *str = [dateFormatter stringFromDate:self]; [dateFormatter release]; return str; } @end
04081337-xmpp
Extensions/XEP-0082/NSDate+XMPPDateTimeProfiles.m
Objective-C
bsd
1,700
#import "TURNSocket.h" #import "XMPP.h" #import "XMPPLogging.h" #import "GCDAsyncSocket.h" #import "NSData+XMPP.h" #import "NSNumber+XMPP.h" // Log levels: off, error, warn, info, verbose #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; // | XMPP_LOG_FLAG_TRACE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif // Define various states #define STATE_INIT 0 #define STATE_PROXY_DISCO_ITEMS 10 #define STATE_PROXY_DISCO_INFO 11 #define STATE_PROXY_DISCO_ADDR 12 #define STATE_REQUEST_SENT 13 #define STATE_INITIATOR_CONNECT 14 #define STATE_ACTIVATE_SENT 15 #define STATE_TARGET_CONNECT 20 #define STATE_DONE 30 #define STATE_FAILURE 31 // Define various socket tags #define SOCKS_OPEN 101 #define SOCKS_CONNECT 102 #define SOCKS_CONNECT_REPLY_1 103 #define SOCKS_CONNECT_REPLY_2 104 // Define various timeouts (in seconds) #define TIMEOUT_DISCO_ITEMS 8.00 #define TIMEOUT_DISCO_INFO 8.00 #define TIMEOUT_DISCO_ADDR 5.00 #define TIMEOUT_CONNECT 8.00 #define TIMEOUT_READ 5.00 #define TIMEOUT_TOTAL 80.00 // Declare private methods @interface TURNSocket (PrivateAPI) - (void)processDiscoItemsResponse:(XMPPIQ *)iq; - (void)processDiscoInfoResponse:(XMPPIQ *)iq; - (void)processDiscoAddressResponse:(XMPPIQ *)iq; - (void)processRequestResponse:(XMPPIQ *)iq; - (void)processActivateResponse:(XMPPIQ *)iq; - (void)performPostInitSetup; - (void)queryProxyCandidates; - (void)queryNextProxyCandidate; - (void)queryCandidateJIDs; - (void)queryNextCandidateJID; - (void)queryProxyAddress; - (void)targetConnect; - (void)targetNextConnect; - (void)initiatorConnect; - (void)setupDiscoTimerForDiscoItems; - (void)setupDiscoTimerForDiscoInfo; - (void)setupDiscoTimerForDiscoAddress; - (void)doDiscoItemsTimeout:(NSString *)uuid; - (void)doDiscoInfoTimeout:(NSString *)uuid; - (void)doDiscoAddressTimeout:(NSString *)uuid; - (void)doTotalTimeout; - (void)succeed; - (void)fail; - (void)cleanup; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation TURNSocket static NSMutableDictionary *existingTurnSockets; static NSMutableArray *proxyCandidates; /** * Called automatically (courtesy of Cocoa) before the first method of this class is called. * It may also be called directly, hence the safety mechanism. **/ + (void)initialize { static BOOL initialized = NO; if (!initialized) { initialized = YES; existingTurnSockets = [[NSMutableDictionary alloc] init]; proxyCandidates = [[NSMutableArray alloc] initWithObjects:@"jabber.org", nil]; } } /** * Returns whether or not the given IQ is a new start TURN request. * That is, the IQ must have a query with the proper namespace, * and it must not correspond to an existing TURNSocket. **/ + (BOOL)isNewStartTURNRequest:(XMPPIQ *)iq { XMPPLogTrace(); // An incoming turn request looks like this: // // <iq type="set" from="[jid full]" id="uuid"> // <query xmlns="http://jabber.org/protocol/bytestreams" sid="uuid" mode="tcp"> // <streamhosts> // <streamhost jid="proxy1.domain.tld" host="100.200.30.41" port"6969"/> // <streamhost jid="proxy2.domain.tld" host="100.200.30.42" port"6969"/> // </streamhosts> // </query> // </iq> NSXMLElement *query = [iq elementForName:@"query" xmlns:@"http://jabber.org/protocol/bytestreams"]; NSString *queryMode = [[query attributeForName:@"mode"] stringValue]; BOOL isTcpBytestreamQuery = NO; if (queryMode) { isTcpBytestreamQuery = [queryMode caseInsensitiveCompare:@"tcp"] == NSOrderedSame; } if (isTcpBytestreamQuery) { NSString *uuid = [iq elementID]; @synchronized(existingTurnSockets) { if ([existingTurnSockets objectForKey:uuid]) return NO; else return YES; } } return NO; } /** * Returns a list of proxy candidates. * * You may want to configure this to include NSUserDefaults stuff, or implement your own static/dynamic list. **/ + (NSArray *)proxyCandidates { NSArray *result = nil; @synchronized(proxyCandidates) { XMPPLogTrace(); result = [[proxyCandidates copy] autorelease]; } return result; } + (void)setProxyCandidates:(NSArray *)candidates { @synchronized(proxyCandidates) { XMPPLogTrace(); [proxyCandidates removeAllObjects]; [proxyCandidates addObjectsFromArray:candidates]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Init, Dealloc //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Initializes a new TURN socket to create a TCP connection by routing through a proxy. * This constructor configures the object to be the client connecting to a server. **/ - (id)initWithStream:(XMPPStream *)stream toJID:(XMPPJID *)aJid { if ((self = [super init])) { XMPPLogTrace(); // Store references xmppStream = [stream retain]; jid = [aJid retain]; // Create a uuid to be used as the id for all messages in the stun communication. // This helps differentiate various turn messages between various turn sockets. // Relying only on JID's is troublesome, because client A could be initiating a connection to server B, // while at the same time client B could be initiating a connection to server A. // So an incoming connection from JID clientB@deusty.com/home would be for which turn socket? uuid = [[xmppStream generateUUID] retain]; // Setup initial state for a client connection state = STATE_INIT; isClient = YES; // Get list of proxy candidates // Each host in this list will be queried to see if it can be used as a proxy proxyCandidates = [[[self class] proxyCandidates] retain]; // Configure everything else [self performPostInitSetup]; } return self; } /** * Initializes a new TURN socket to create a TCP connection by routing through a proxy. * This constructor configures the object to be the server accepting a connection from a client. **/ - (id)initWithStream:(XMPPStream *)stream incomingTURNRequest:(XMPPIQ *)iq { if ((self = [super init])) { XMPPLogTrace(); // Store references xmppStream = [stream retain]; jid = [[iq from] retain]; // Store a copy of the ID (which will be our uuid) uuid = [[iq elementID] copy]; // Setup initial state for a server connection state = STATE_INIT; isClient = NO; // Extract streamhost information from turn request NSXMLElement *query = [iq elementForName:@"query" xmlns:@"http://jabber.org/protocol/bytestreams"]; streamhosts = [[query elementsForName:@"streamhost"] retain]; // Configure everything else [self performPostInitSetup]; } return self; } /** * Common initialization tasks shared by all init methods. **/ - (void)performPostInitSetup { // Create dispatch queue. turnQueue = dispatch_queue_create("TURNSocket", NULL); // We want to add this new turn socket to the list of existing sockets. // This gives us a central repository of turn socket objects that we can easily query. @synchronized(existingTurnSockets) { [existingTurnSockets setObject:self forKey:uuid]; } } /** * Standard deconstructor. * Release any objects we may have retained. * These objects should all be defined in the header. **/ - (void)dealloc { XMPPLogTrace(); if ((state > STATE_INIT) && (state < STATE_DONE)) { XMPPLogWarn(@"%@: Deallocating prior to completion or cancellation. " @"You should explicitly cancel before releasing.", THIS_FILE); } if (turnQueue) dispatch_release(turnQueue); [xmppStream release]; [jid release]; [uuid release]; if (delegateQueue) dispatch_release(delegateQueue); if (turnTimer) { dispatch_source_cancel(turnTimer); dispatch_release(turnTimer); } [discoUUID release]; if (discoTimer) { dispatch_source_cancel(discoTimer); dispatch_release(discoTimer); } [proxyCandidates release]; [candidateJIDs release]; [streamhosts release]; [proxyJID release]; [proxyHost release]; if ([asyncSocket delegate] == self) { [asyncSocket setDelegate:nil delegateQueue:NULL]; [asyncSocket disconnect]; } [asyncSocket release]; [startTime release]; [finishTime release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Correspondence Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Starts the TURNSocket with the given delegate. * If the TURNSocket has already been started, this method does nothing, and the existing delegate is not changed. **/ - (void)startWithDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)aDelegateQueue { NSParameterAssert(aDelegate != nil); NSParameterAssert(aDelegateQueue != NULL); dispatch_async(turnQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if (state != STATE_INIT) { XMPPLogWarn(@"%@: Ignoring start request. Turn procedure already started.", THIS_FILE); return; } // Set reference to delegate and delegate's queue. // Note that we do NOT retain the delegate. delegate = aDelegate; delegateQueue = aDelegateQueue; dispatch_retain(delegateQueue); // Add self as xmpp delegate so we'll get message responses [xmppStream addDelegate:self delegateQueue:turnQueue]; // Start the timer to calculate how long the procedure takes startTime = [[NSDate alloc] init]; // Schedule timer to cancel the turn procedure. // This ensures that, in the event of network error or crash, // the TURNSocket object won't remain in memory forever, and will eventually fail. turnTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, turnQueue); dispatch_source_set_event_handler(turnTimer, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self doTotalTimeout]; [pool drain]; }); dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (TIMEOUT_TOTAL * NSEC_PER_SEC)); dispatch_source_set_timer(turnTimer, tt, DISPATCH_TIME_FOREVER, 0.1); dispatch_resume(turnTimer); // Start the TURN procedure if (isClient) [self queryProxyCandidates]; else [self targetConnect]; [pool drain]; }); } /** * Returns the type of connection * YES for a client connection to a server, NO for a server connection from a client. **/ - (BOOL)isClient { // Note: The isClient variable is readonly (set in the init method). return isClient; } /** * Aborts the TURN connection attempt. * The status will be changed to failure, and no delegate messages will be posted. **/ - (void)abort { dispatch_block_t block = ^{ if ((state > STATE_INIT) && (state < STATE_DONE)) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // The only thing we really have to do here is move the state to failure. // This simple act should prevent any further action from being taken in this TUNRSocket object, // since every action is dictated based on the current state. state = STATE_FAILURE; // And don't forget to cleanup after ourselves [self cleanup]; [pool drain]; } }; if (dispatch_get_current_queue() == turnQueue) block(); else dispatch_async(turnQueue, block); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Communication //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Sends the request, from initiator to target, to start a connection to one of the streamhosts. * This method automatically updates the state. **/ - (void)sendRequest { NSAssert(isClient, @"Only the Initiator sends the request"); XMPPLogTrace(); // <iq type="set" to="target" id="123"> // <query xmlns="http://jabber.org/protocol/bytestreams" sid="123" mode="tcp"> // <streamhost jid="proxy.domain1.org" host="100.200.300.401" port="7777"/> // <streamhost jid="proxy.domain2.org" host="100.200.300.402" port="7777"/> // </query> // </iq> NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"http://jabber.org/protocol/bytestreams"]; [query addAttributeWithName:@"sid" stringValue:uuid]; [query addAttributeWithName:@"mode" stringValue:@"tcp"]; NSUInteger i; for(i = 0; i < [streamhosts count]; i++) { [query addChild:[streamhosts objectAtIndex:i]]; } XMPPIQ *iq = [XMPPIQ iqWithType:@"set" to:jid elementID:uuid child:query]; [xmppStream sendElement:iq]; // Update state state = STATE_REQUEST_SENT; } /** * Sends the reply, from target to initiator, notifying the initiator of the streamhost we connected to. **/ - (void)sendReply { NSAssert(!isClient, @"Only the Target sends the reply"); XMPPLogTrace(); // <iq type="result" to="initiator" id="123"> // <query xmlns="http://jabber.org/protocol/bytestreams" sid="123"> // <streamhost-used jid="proxy.domain"/> // </query> // </iq> NSXMLElement *streamhostUsed = [NSXMLElement elementWithName:@"streamhost-used"]; [streamhostUsed addAttributeWithName:@"jid" stringValue:[proxyJID full]]; NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"http://jabber.org/protocol/bytestreams"]; [query addAttributeWithName:@"sid" stringValue:uuid]; [query addChild:streamhostUsed]; XMPPIQ *iq = [XMPPIQ iqWithType:@"result" to:jid elementID:uuid child:query]; [xmppStream sendElement:iq]; } /** * Sends the activate message to the proxy after the target and initiator are both connected to the proxy. * This method automatically updates the state. **/ - (void)sendActivate { NSAssert(isClient, @"Only the Initiator activates the proxy"); XMPPLogTrace(); NSXMLElement *activate = [NSXMLElement elementWithName:@"activate" stringValue:[jid full]]; NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"http://jabber.org/protocol/bytestreams"]; [query addAttributeWithName:@"sid" stringValue:uuid]; [query addChild:activate]; XMPPIQ *iq = [XMPPIQ iqWithType:@"set" to:proxyJID elementID:uuid child:query]; [xmppStream sendElement:iq]; // Update state state = STATE_ACTIVATE_SENT; } /** * Sends the error, from target to initiator, notifying the initiator we were unable to connect to any streamhost. **/ - (void)sendError { NSAssert(!isClient, @"Only the Target sends the error"); XMPPLogTrace(); // <iq type="error" to="initiator" id="123"> // <error code="404" type="cancel"> // <item-not-found xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"> // </error> // </iq> NSXMLElement *inf = [NSXMLElement elementWithName:@"item-not-found" xmlns:@"urn:ietf:params:xml:ns:xmpp-stanzas"]; NSXMLElement *error = [NSXMLElement elementWithName:@"error"]; [error addAttributeWithName:@"code" stringValue:@"404"]; [error addAttributeWithName:@"type" stringValue:@"cancel"]; [error addChild:inf]; XMPPIQ *iq = [XMPPIQ iqWithType:@"error" to:jid elementID:uuid child:error]; [xmppStream sendElement:iq]; } /** * Invoked by XMPPClient when an IQ is received. * We can determine if the IQ applies to us by checking its element ID. **/ - (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq { // Disco queries (sent to jabber server) use id=discoUUID // P2P queries (sent to other Mojo app) use id=uuid if (state <= STATE_PROXY_DISCO_ADDR) { if (![discoUUID isEqualToString:[iq elementID]]) { // Doesn't apply to us, or is a delayed response that we've decided to ignore return NO; } } else { if (![uuid isEqualToString:[iq elementID]]) { // Doesn't apply to us return NO; } } XMPPLogTrace2(@"%@: %@ - state(%i)", THIS_FILE, THIS_METHOD, state); if (state == STATE_PROXY_DISCO_ITEMS) { [self processDiscoItemsResponse:iq]; } else if (state == STATE_PROXY_DISCO_INFO) { [self processDiscoInfoResponse:iq]; } else if (state == STATE_PROXY_DISCO_ADDR) { [self processDiscoAddressResponse:iq]; } else if (state == STATE_REQUEST_SENT) { [self processRequestResponse:iq]; } else if (state == STATE_ACTIVATE_SENT) { [self processActivateResponse:iq]; } return YES; } - (void)processDiscoItemsResponse:(XMPPIQ *)iq { XMPPLogTrace(); // We queried the current proxy candidate for all known JIDs in it's disco list. // // <iq from="domain.org" to="initiator" id="123" type="result"> // <query xmlns="http://jabber.org/protocol/disco#items"> // <item jid="conference.domain.org"/> // <item jid="proxy.domain.org"/> // </query> // </iq> NSXMLElement *query = [iq elementForName:@"query" xmlns:@"http://jabber.org/protocol/disco#items"]; NSArray *items = [query elementsForName:@"item"]; [candidateJIDs release]; candidateJIDs = [[NSMutableArray alloc] initWithCapacity:[items count]]; NSUInteger i; for(i = 0; i < [items count]; i++) { NSString *itemJidStr = [[[items objectAtIndex:i] attributeForName:@"jid"] stringValue]; XMPPJID *itemJid = [XMPPJID jidWithString:itemJidStr]; if(itemJid) { [candidateJIDs addObject:itemJid]; } } [self queryCandidateJIDs]; } - (void)processDiscoInfoResponse:(XMPPIQ *)iq { XMPPLogTrace(); // We queried a potential proxy server to see if it was indeed a proxy. // // <iq from="domain.org" to="initiator" id="123" type="result"> // <query xmlns="http://jabber.org/protocol/disco#info"> // <identity category="proxy" type="bytestreams" name="SOCKS5 Bytestreams Service"/> // <feature var="http://jabber.org/protocol/bytestreams"/> // </query> // </iq> NSXMLElement *query = [iq elementForName:@"query" xmlns:@"http://jabber.org/protocol/disco#info"]; NSArray *identities = [query elementsForName:@"identity"]; BOOL found = NO; NSUInteger i; for(i = 0; i < [identities count] && !found; i++) { NSXMLElement *identity = [identities objectAtIndex:i]; NSString *category = [[identity attributeForName:@"category"] stringValue]; NSString *type = [[identity attributeForName:@"type"] stringValue]; if([category isEqualToString:@"proxy"] && [type isEqualToString:@"bytestreams"]) { found = YES; } } if(found) { // We found a proxy service! // Now we query the proxy for its public IP and port. [self queryProxyAddress]; } else { // There are many jabber servers out there that advertise a proxy service via JID proxy.domain.tld. // However, not all of these servers have an entry for proxy.domain.tld in the DNS servers. // Thus, when we try to query the proxy JID, we end up getting a 404 error because our // jabber server was unable to connect to the given JID. // // We could ignore the 404 error, and try to connect anyways, // but this would be useless because we'd be unable to activate the stream later. XMPPJID *candidateJID = [candidateJIDs objectAtIndex:candidateJIDIndex]; // So the service was not a useable proxy service, or will not allow us to use its proxy. // // Now most servers have serveral services such as proxy, conference, pubsub, etc. // If we queried a JID that started with "proxy", and it said no, // chances are that none of the other services are proxies either, // so we might as well not waste our time querying them. if([[candidateJID domain] hasPrefix:@"proxy"]) { // Move on to the next server [self queryNextProxyCandidate]; } else { // Try the next JID in the list from the server [self queryNextCandidateJID]; } } } - (void)processDiscoAddressResponse:(XMPPIQ *)iq { XMPPLogTrace(); // We queried a proxy for its public IP and port. // // <iq from="domain.org" to="initiator" id="123" type="result"> // <query xmlns="http://jabber.org/protocol/bytestreams"> // <streamhost jid="proxy.domain.org" host="100.200.300.400" port="7777"/> // </query> // </iq> NSXMLElement *query = [iq elementForName:@"query" xmlns:@"http://jabber.org/protocol/bytestreams"]; NSXMLElement *streamhost = [query elementForName:@"streamhost"]; NSString *jidStr = [[streamhost attributeForName:@"jid"] stringValue]; XMPPJID *streamhostJID = [XMPPJID jidWithString:jidStr]; NSString *host = [[streamhost attributeForName:@"host"] stringValue]; UInt16 port = [[[streamhost attributeForName:@"port"] stringValue] intValue]; if(streamhostJID != nil || host != nil || port > 0) { [streamhost detach]; [streamhosts addObject:streamhost]; } // Finished with the current proxy candidate - move on to the next [self queryNextProxyCandidate]; } - (void)processRequestResponse:(XMPPIQ *)iq { XMPPLogTrace(); // Target has replied - hopefully they've been able to connect to one of the streamhosts NSXMLElement *query = [iq elementForName:@"query" xmlns:@"http://jabber.org/protocol/bytestreams"]; NSXMLElement *streamhostUsed = [query elementForName:@"streamhost-used"]; NSString *streamhostUsedJID = [[streamhostUsed attributeForName:@"jid"] stringValue]; BOOL found = NO; NSUInteger i; for(i = 0; i < [streamhosts count] && !found; i++) { NSXMLElement *streamhost = [streamhosts objectAtIndex:i]; NSString *streamhostJID = [[streamhost attributeForName:@"jid"] stringValue]; if([streamhostJID isEqualToString:streamhostUsedJID]) { NSAssert(proxyJID == nil && proxyHost == nil, @"proxy and proxyHost are expected to be nil"); proxyJID = [[XMPPJID jidWithString:streamhostJID] retain]; proxyHost = [[streamhost attributeForName:@"host"] stringValue]; if([proxyHost isEqualToString:@"0.0.0.0"]) { proxyHost = [proxyJID full]; } [proxyHost retain]; proxyPort = [[[streamhost attributeForName:@"port"] stringValue] intValue]; found = YES; } } if(found) { // The target is connected to the proxy // Now it's our turn to connect [self initiatorConnect]; } else { // Target was unable to connect to any of the streamhosts we sent it [self fail]; } } - (void)processActivateResponse:(XMPPIQ *)iq { XMPPLogTrace(); NSString *type = [[iq attributeForName:@"type"] stringValue]; BOOL activated = NO; if (type) { activated = [type caseInsensitiveCompare:@"result"] == NSOrderedSame; } if (activated) { [self succeed]; } else { [self fail]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Proxy Discovery //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Each query we send during the proxy discovery process has a different element id. * This allows us to easily use timeouts, so we can recover from offline servers, and overly slow servers. * In other words, changing the discoUUID allows us to easily ignore delayed responses from a server. **/ - (void)updateDiscoUUID { [discoUUID release]; discoUUID = [[xmppStream generateUUID] retain]; } /** * Initiates the process of querying each item in the proxyCandidates array to determine if it supports XEP-65. * In order to do this we have to: * - ask the server for a list of services, which returns a list of JIDs * - query each service JID to determine if it's a proxy * - if it is a proxy, we ask the proxy for it's public IP and port **/ - (void)queryProxyCandidates { XMPPLogTrace(); // Prepare the streamhosts array, which will hold all of our results streamhosts = [[NSMutableArray alloc] initWithCapacity:[proxyCandidates count]]; // Start querying each candidate in order proxyCandidateIndex = -1; [self queryNextProxyCandidate]; } /** * Queries the next proxy candidate in the list. * If we've queried every candidate, then sends the request to the target, or fails if no proxies were found. **/ - (void)queryNextProxyCandidate { XMPPLogTrace(); // Update state state = STATE_PROXY_DISCO_ITEMS; // We start off with multiple proxy candidates (servers that have been known to be proxy servers in the past). // We can stop when we've found at least 2 proxies. XMPPJID *proxyCandidateJID = nil; if ([streamhosts count] < 2) { while ((proxyCandidateJID == nil) && (++proxyCandidateIndex < [proxyCandidates count])) { NSString *proxyCandidate = [proxyCandidates objectAtIndex:proxyCandidateIndex]; proxyCandidateJID = [XMPPJID jidWithString:proxyCandidate]; if (proxyCandidateJID == nil) { XMPPLogWarn(@"%@: Invalid proxy candidate '%@', not a valid JID", THIS_FILE, proxyCandidate); } } } if (proxyCandidateJID) { [self updateDiscoUUID]; NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"http://jabber.org/protocol/disco#items"]; XMPPIQ *iq = [XMPPIQ iqWithType:@"get" to:proxyCandidateJID elementID:discoUUID child:query]; [xmppStream sendElement:iq]; [self setupDiscoTimerForDiscoItems]; } else { if ([streamhosts count] > 0) { // We've got a list of potential proxy servers to send to the initiator XMPPLogVerbose(@"%@: Streamhosts: \n%@", THIS_FILE, streamhosts); [self sendRequest]; } else { // We were unable to find a single proxy server from our list XMPPLogVerbose(@"%@: No proxies found", THIS_FILE); [self fail]; } } } /** * Initiates the process of querying each candidate JID to determine if it represents a proxy service. * This process will be stopped when a proxy service is found, or after each candidate JID has been queried. **/ - (void)queryCandidateJIDs { XMPPLogTrace(); // Most of the time, the proxy will have a domain name that includes the word "proxy". // We can speed up the process of discovering the proxy by searching for these domains, and querying them first. NSUInteger i; for (i = 0; i < [candidateJIDs count]; i++) { XMPPJID *candidateJID = [candidateJIDs objectAtIndex:i]; NSRange proxyRange = [[candidateJID domain] rangeOfString:@"proxy" options:NSCaseInsensitiveSearch]; if (proxyRange.length > 0) { [candidateJID retain]; [candidateJIDs removeObjectAtIndex:i]; [candidateJIDs insertObject:candidateJID atIndex:0]; [candidateJID release]; } } XMPPLogVerbose(@"%@: CandidateJIDs: \n%@", THIS_FILE, candidateJIDs); // Start querying each candidate in order (we can stop when we find one) candidateJIDIndex = -1; [self queryNextCandidateJID]; } /** * Queries the next candidate JID in the list. * If we've queried every item, we move on to the next proxy candidate. **/ - (void)queryNextCandidateJID { XMPPLogTrace(); // Update state state = STATE_PROXY_DISCO_INFO; candidateJIDIndex++; if (candidateJIDIndex < [candidateJIDs count]) { [self updateDiscoUUID]; XMPPJID *candidateJID = [candidateJIDs objectAtIndex:candidateJIDIndex]; NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"http://jabber.org/protocol/disco#info"]; XMPPIQ *iq = [XMPPIQ iqWithType:@"get" to:candidateJID elementID:discoUUID child:query]; [xmppStream sendElement:iq]; [self setupDiscoTimerForDiscoInfo]; } else { // Ran out of candidate JIDs for the current proxy candidate. // Time to move on to the next proxy candidate. [self queryNextProxyCandidate]; } } /** * Once we've discovered a proxy service, we need to query it to obtain its public IP and port. **/ - (void)queryProxyAddress { XMPPLogTrace(); // Update state state = STATE_PROXY_DISCO_ADDR; [self updateDiscoUUID]; XMPPJID *candidateJID = [candidateJIDs objectAtIndex:candidateJIDIndex]; NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"http://jabber.org/protocol/bytestreams"]; XMPPIQ *iq = [XMPPIQ iqWithType:@"get" to:candidateJID elementID:discoUUID child:query]; [xmppStream sendElement:iq]; [self setupDiscoTimerForDiscoAddress]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Proxy Connection //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)targetConnect { XMPPLogTrace(); // Update state state = STATE_TARGET_CONNECT; // Start trying to connect to each streamhost in order streamhostIndex = -1; [self targetNextConnect]; } - (void)targetNextConnect { XMPPLogTrace(); streamhostIndex++; if(streamhostIndex < [streamhosts count]) { NSXMLElement *streamhost = [streamhosts objectAtIndex:streamhostIndex]; [proxyJID release]; [proxyHost release]; proxyJID = [[XMPPJID jidWithString:[[streamhost attributeForName:@"jid"] stringValue]] retain]; proxyHost = [[streamhost attributeForName:@"host"] stringValue]; if([proxyHost isEqualToString:@"0.0.0.0"]) { proxyHost = [proxyJID full]; } [proxyHost retain]; proxyPort = [[[streamhost attributeForName:@"port"] stringValue] intValue]; NSAssert([asyncSocket isDisconnected], @"Expecting the socket to be disconnected at this point..."); if (asyncSocket == nil) { asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:turnQueue]; } XMPPLogVerbose(@"TURNSocket: targetNextConnect: %@(%@:%hu)", [proxyJID full], proxyHost, proxyPort); NSError *err = nil; if (![asyncSocket connectToHost:proxyHost onPort:proxyPort withTimeout:TIMEOUT_CONNECT error:&err]) { XMPPLogError(@"TURNSocket: targetNextConnect: err: %@", err); [self targetNextConnect]; } } else { [self sendError]; [self fail]; } } - (void)initiatorConnect { NSAssert(asyncSocket == nil, @"Expecting asyncSocket to be nil"); asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:turnQueue]; XMPPLogVerbose(@"TURNSocket: initiatorConnect: %@(%@:%hu)", [proxyJID full], proxyHost, proxyPort); NSError *err = nil; if (![asyncSocket connectToHost:proxyHost onPort:proxyPort withTimeout:TIMEOUT_CONNECT error:&err]) { XMPPLogError(@"TURNSocket: initiatorConnect: err: %@", err); [self fail]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark SOCKS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Sends the SOCKS5 open/handshake/authentication data, and starts reading the response. * We attempt to gain anonymous access (no authentication). **/ - (void)socksOpen { XMPPLogTrace(); // +-----+-----------+---------+ // NAME | VER | NMETHODS | METHODS | // +-----+-----------+---------+ // SIZE | 1 | 1 | 1 - 255 | // +-----+-----------+---------+ // // Note: Size is in bytes // // Version = 5 (for SOCKS5) // NumMethods = 1 // Method = 0 (No authentication, anonymous access) void *byteBuffer = malloc(3); UInt8 ver = 5; memcpy(byteBuffer+0, &ver, sizeof(ver)); UInt8 nMethods = 1; memcpy(byteBuffer+1, &nMethods, sizeof(nMethods)); UInt8 method = 0; memcpy(byteBuffer+2, &method, sizeof(method)); NSData *data = [NSData dataWithBytesNoCopy:byteBuffer length:3 freeWhenDone:YES]; XMPPLogVerbose(@"TURNSocket: SOCKS_OPEN: %@", data); [asyncSocket writeData:data withTimeout:-1 tag:SOCKS_OPEN]; // +-----+--------+ // NAME | VER | METHOD | // +-----+--------+ // SIZE | 1 | 1 | // +-----+--------+ // // Note: Size is in bytes // // Version = 5 (for SOCKS5) // Method = 0 (No authentication, anonymous access) [asyncSocket readDataToLength:2 withTimeout:TIMEOUT_READ tag:SOCKS_OPEN]; } /** * Sends the SOCKS5 connect data (according to XEP-65), and starts reading the response. **/ - (void)socksConnect { XMPPLogTrace(); XMPPJID *myJID = [xmppStream myJID]; // From XEP-0065: // // The [address] MUST be SHA1(SID + Initiator JID + Target JID) and // the output is hexadecimal encoded (not binary). XMPPJID *initiatorJID = isClient ? myJID : jid; XMPPJID *targetJID = isClient ? jid : myJID; NSString *hashMe = [NSString stringWithFormat:@"%@%@%@", uuid, [initiatorJID full], [targetJID full]]; NSData *hashRaw = [[hashMe dataUsingEncoding:NSUTF8StringEncoding] sha1Digest]; NSData *hash = [[hashRaw hexStringValue] dataUsingEncoding:NSUTF8StringEncoding]; XMPPLogVerbose(@"TURNSocket: hashMe : %@", hashMe); XMPPLogVerbose(@"TURNSocket: hashRaw: %@", hashRaw); XMPPLogVerbose(@"TURNSocket: hash : %@", hash); // +-----+-----+-----+------+------+------+ // NAME | VER | CMD | RSV | ATYP | ADDR | PORT | // +-----+-----+-----+------+------+------+ // SIZE | 1 | 1 | 1 | 1 | var | 2 | // +-----+-----+-----+------+------+------+ // // Note: Size is in bytes // // Version = 5 (for SOCKS5) // Command = 1 (for Connect) // Reserved = 0 // Address Type = 3 (1=IPv4, 3=DomainName 4=IPv6) // Address = P:D (P=LengthOfDomain D=DomainWithoutNullTermination) // Port = 0 uint byteBufferLength = (uint)(4 + 1 + [hash length] + 2); void *byteBuffer = malloc(byteBufferLength); UInt8 ver = 5; memcpy(byteBuffer+0, &ver, sizeof(ver)); UInt8 cmd = 1; memcpy(byteBuffer+1, &cmd, sizeof(cmd)); UInt8 rsv = 0; memcpy(byteBuffer+2, &rsv, sizeof(rsv)); UInt8 atyp = 3; memcpy(byteBuffer+3, &atyp, sizeof(atyp)); UInt8 hashLength = [hash length]; memcpy(byteBuffer+4, &hashLength, sizeof(hashLength)); memcpy(byteBuffer+5, [hash bytes], [hash length]); UInt16 port = 0; memcpy(byteBuffer+5+[hash length], &port, sizeof(port)); NSData *data = [NSData dataWithBytesNoCopy:byteBuffer length:byteBufferLength freeWhenDone:YES]; XMPPLogVerbose(@"TURNSocket: SOCKS_CONNECT: %@", data); [asyncSocket writeData:data withTimeout:-1 tag:SOCKS_CONNECT]; // +-----+-----+-----+------+------+------+ // NAME | VER | REP | RSV | ATYP | ADDR | PORT | // +-----+-----+-----+------+------+------+ // SIZE | 1 | 1 | 1 | 1 | var | 2 | // +-----+-----+-----+------+------+------+ // // Note: Size is in bytes // // Version = 5 (for SOCKS5) // Reply = 0 (0=Succeeded, X=ErrorCode) // Reserved = 0 // Address Type = 3 (1=IPv4, 3=DomainName 4=IPv6) // Address = P:D (P=LengthOfDomain D=DomainWithoutNullTermination) // Port = 0 // // It is expected that the SOCKS server will return the same address given in the connect request. // But according to XEP-65 this is only marked as a SHOULD and not a MUST. // So just in case, we'll read up to the address length now, and then read in the address+port next. [asyncSocket readDataToLength:5 withTimeout:TIMEOUT_READ tag:SOCKS_CONNECT_REPLY_1]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark AsyncSocket Delegate Methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port { XMPPLogTrace(); // Start the SOCKS protocol stuff [self socksOpen]; } - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag { XMPPLogTrace(); if (tag == SOCKS_OPEN) { // See socksOpen method for socks reply format UInt8 ver = [NSNumber extractUInt8FromData:data atOffset:0]; UInt8 mtd = [NSNumber extractUInt8FromData:data atOffset:1]; XMPPLogVerbose(@"TURNSocket: SOCKS_OPEN: ver(%o) mtd(%o)", ver, mtd); if(ver == 5 && mtd == 0) { [self socksConnect]; } else { // Some kind of error occurred. // The proxy probably requires some kind of authentication. [asyncSocket disconnect]; } } else if (tag == SOCKS_CONNECT_REPLY_1) { // See socksConnect method for socks reply format XMPPLogVerbose(@"TURNSocket: SOCKS_CONNECT_REPLY_1: %@", data); UInt8 ver = [NSNumber extractUInt8FromData:data atOffset:0]; UInt8 rep = [NSNumber extractUInt8FromData:data atOffset:1]; XMPPLogVerbose(@"TURNSocket: SOCKS_CONNECT_REPLY_1: ver(%o) rep(%o)", ver, rep); if(ver == 5 && rep == 0) { // We read in 5 bytes which we expect to be: // 0: ver = 5 // 1: rep = 0 // 2: rsv = 0 // 3: atyp = 3 // 4: size = size of addr field // // However, some servers don't follow the protocol, and send a atyp value of 0. UInt8 atyp = [NSNumber extractUInt8FromData:data atOffset:3]; if (atyp == 3) { UInt8 addrLength = [NSNumber extractUInt8FromData:data atOffset:4]; UInt8 portLength = 2; XMPPLogVerbose(@"TURNSocket: addrLength: %o", addrLength); XMPPLogVerbose(@"TURNSocket: portLength: %o", portLength); [asyncSocket readDataToLength:(addrLength+portLength) withTimeout:TIMEOUT_READ tag:SOCKS_CONNECT_REPLY_2]; } else if (atyp == 0) { // The size field was actually the first byte of the port field // We just have to read in that last byte [asyncSocket readDataToLength:1 withTimeout:TIMEOUT_READ tag:SOCKS_CONNECT_REPLY_2]; } else { XMPPLogError(@"TURNSocket: Unknown atyp field in connect reply"); [asyncSocket disconnect]; } } else { // Some kind of error occurred. [asyncSocket disconnect]; } } else if (tag == SOCKS_CONNECT_REPLY_2) { // See socksConnect method for socks reply format XMPPLogVerbose(@"TURNSocket: SOCKS_CONNECT_REPLY_2: %@", data); if (isClient) { [self sendActivate]; } else { [self sendReply]; [self succeed]; } } } - (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err { XMPPLogTrace2(@"%@: %@ %@", THIS_FILE, THIS_METHOD, err); if (state == STATE_TARGET_CONNECT) { [self targetNextConnect]; } else if (state == STATE_INITIATOR_CONNECT) { [self fail]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Timeouts //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)setupDiscoTimer:(NSTimeInterval)timeout { NSAssert(dispatch_get_current_queue() == turnQueue, @"Invoked on incorrect queue"); if (discoTimer == NULL) { discoTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, turnQueue); dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (timeout * NSEC_PER_SEC)); dispatch_source_set_timer(discoTimer, tt, DISPATCH_TIME_FOREVER, 0.1); dispatch_resume(discoTimer); } else { dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (timeout * NSEC_PER_SEC)); dispatch_source_set_timer(discoTimer, tt, DISPATCH_TIME_FOREVER, 0.1); } } - (void)setupDiscoTimerForDiscoItems { XMPPLogTrace(); [self setupDiscoTimer:TIMEOUT_DISCO_ITEMS]; NSString *theUUID = discoUUID; dispatch_source_set_event_handler(discoTimer, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self doDiscoItemsTimeout:theUUID]; [pool drain]; }); } - (void)setupDiscoTimerForDiscoInfo { XMPPLogTrace(); [self setupDiscoTimer:TIMEOUT_DISCO_INFO]; NSString *theUUID = discoUUID; dispatch_source_set_event_handler(discoTimer, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self doDiscoInfoTimeout:theUUID]; [pool drain]; }); } - (void)setupDiscoTimerForDiscoAddress { XMPPLogTrace(); [self setupDiscoTimer:TIMEOUT_DISCO_ADDR]; NSString *theUUID = discoUUID; dispatch_source_set_event_handler(discoTimer, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self doDiscoAddressTimeout:theUUID]; [pool drain]; }); } - (void)doDiscoItemsTimeout:(NSString *)theUUID { NSAssert(dispatch_get_current_queue() == turnQueue, @"Invoked on incorrect queue"); if (state == STATE_PROXY_DISCO_ITEMS) { if ([theUUID isEqualToString:discoUUID]) { XMPPLogTrace(); // Server isn't responding - server may be offline [self queryNextProxyCandidate]; } } } - (void)doDiscoInfoTimeout:(NSString *)theUUID { NSAssert(dispatch_get_current_queue() == turnQueue, @"Invoked on incorrect queue"); if (state == STATE_PROXY_DISCO_INFO) { if ([theUUID isEqualToString:discoUUID]) { XMPPLogTrace(); // Move on to the next proxy candidate [self queryNextProxyCandidate]; } } } - (void)doDiscoAddressTimeout:(NSString *)theUUID { NSAssert(dispatch_get_current_queue() == turnQueue, @"Invoked on incorrect queue"); if (state == STATE_PROXY_DISCO_ADDR) { if ([theUUID isEqualToString:discoUUID]) { XMPPLogTrace(); // Server is taking a long time to respond to a simple query. // We could jump to the next candidate JID, but we'll take this as a sign of an overloaded server. [self queryNextProxyCandidate]; } } } - (void)doTotalTimeout { NSAssert(dispatch_get_current_queue() == turnQueue, @"Invoked on incorrect queue"); if ((state != STATE_DONE) && (state != STATE_FAILURE)) { XMPPLogTrace(); // A timeout occured to cancel the entire TURN procedure. // This probably means the other endpoint crashed, or a network error occurred. // In either case, we can consider this a failure, and recycle the memory associated with this object. [self fail]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Finish and Cleanup //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)succeed { NSAssert(dispatch_get_current_queue() == turnQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); // Record finish time finishTime = [[NSDate alloc] init]; // Update state state = STATE_DONE; dispatch_async(delegateQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if ([delegate respondsToSelector:@selector(turnSocket:didSucceed:)]) { [delegate turnSocket:self didSucceed:asyncSocket]; } [pool drain]; }); [self cleanup]; } - (void)fail { NSAssert(dispatch_get_current_queue() == turnQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); // Record finish time finishTime = [[NSDate alloc] init]; // Update state state = STATE_FAILURE; dispatch_async(delegateQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if ([delegate respondsToSelector:@selector(turnSocketDidFail:)]) { [delegate turnSocketDidFail:self]; } [pool drain]; }); [self cleanup]; } - (void)cleanup { // This method must be run on the turnQueue NSAssert(dispatch_get_current_queue() == turnQueue, @"Invoked on incorrect queue."); XMPPLogTrace(); if (turnTimer) { dispatch_source_cancel(turnTimer); dispatch_release(turnTimer); turnTimer = NULL; } if (discoTimer) { dispatch_source_cancel(discoTimer); dispatch_release(discoTimer); discoTimer = NULL; } // Remove self as xmpp delegate [xmppStream removeDelegate:self delegateQueue:turnQueue]; // Remove self from existingStuntSockets dictionary so we can be deallocated @synchronized(existingTurnSockets) { [existingTurnSockets removeObjectForKey:uuid]; } } @end
04081337-xmpp
Extensions/XEP-0065/TURNSocket.m
Objective-C
bsd
43,467
#import <Foundation/Foundation.h> @class XMPPIQ; @class XMPPJID; @class XMPPStream; @class GCDAsyncSocket; /** * TURNSocket is an implementation of XEP-0065: SOCKS5 Bytestreams. * * It is used for establishing an out-of-band bytestream between any two XMPP users, * mainly for the purpose of file transfer. **/ @interface TURNSocket : NSObject { int state; BOOL isClient; dispatch_queue_t turnQueue; XMPPStream *xmppStream; XMPPJID *jid; NSString *uuid; id delegate; dispatch_queue_t delegateQueue; dispatch_source_t turnTimer; NSString *discoUUID; dispatch_source_t discoTimer; NSArray *proxyCandidates; NSUInteger proxyCandidateIndex; NSMutableArray *candidateJIDs; NSUInteger candidateJIDIndex; NSMutableArray *streamhosts; NSUInteger streamhostIndex; XMPPJID *proxyJID; NSString *proxyHost; UInt16 proxyPort; GCDAsyncSocket *asyncSocket; NSDate *startTime, *finishTime; } + (BOOL)isNewStartTURNRequest:(XMPPIQ *)iq; + (NSArray *)proxyCandidates; + (void)setProxyCandidates:(NSArray *)candidates; - (id)initWithStream:(XMPPStream *)xmppStream toJID:(XMPPJID *)jid; - (id)initWithStream:(XMPPStream *)xmppStream incomingTURNRequest:(XMPPIQ *)iq; - (void)startWithDelegate:(id)aDelegate delegateQueue:(dispatch_queue_t)aDelegateQueue; - (BOOL)isClient; - (void)abort; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol TURNSocketDelegate @optional - (void)turnSocket:(TURNSocket *)sender didSucceed:(GCDAsyncSocket *)socket; - (void)turnSocketDidFail:(TURNSocket *)sender; @end
04081337-xmpp
Extensions/XEP-0065/TURNSocket.h
Objective-C
bsd
1,761
// // XMPPvCardTempAdr.m // XEP-0054 vCard-temp // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // Copyright 2010 Martin Morrison. All rights reserved. // #import "XMPPvCardTempAdr.h" #import "XMPPLogging.h" #import <objc/runtime.h> #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_ERROR; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_ERROR; #endif @implementation XMPPvCardTempAdr + (void)initialize { // We use the object_setClass method below to dynamically change the class from a standard NSXMLElement. // The size of the two classes is expected to be the same. // // If a developer adds instance methods to this class, bad things happen at runtime that are very hard to debug. // This check is here to aid future developers who may make this mistake. // // For Fearless And Experienced Objective-C Developers: // It may be possible to support adding instance variables to this class if you seriously need it. // To do so, try realloc'ing self after altering the class, and then initialize your variables. size_t superSize = class_getInstanceSize([NSXMLElement class]); size_t ourSize = class_getInstanceSize([XMPPvCardTempAdr class]); if (superSize != ourSize) { XMPPLogError(@"Adding instance variables to XMPPvCardTempAdr is not currently supported!"); [DDLog flushLog]; exit(15); } } + (XMPPvCardTempAdr *)vCardAdrFromElement:(NSXMLElement *)elem { object_setClass(elem, [XMPPvCardTempAdr class]); return (XMPPvCardTempAdr *)elem; } #pragma mark - #pragma mark Getter/setter methods - (NSString *)pobox { return [[self elementForName:@"POBOX"] stringValue]; } - (void)setPobox:(NSString *)pobox { XMPP_VCARD_SET_STRING_CHILD(pobox, @"POBOX"); } - (NSString *)extendedAddress { return [[self elementForName:@"EXTADD"] stringValue]; } - (void)setExtendedAddress:(NSString *)extadd { XMPP_VCARD_SET_STRING_CHILD(extadd, @"EXTADD"); } - (NSString *)street { return [[self elementForName:@"STREET"] stringValue]; } - (void)setStreet:(NSString *)street { XMPP_VCARD_SET_STRING_CHILD(street, @"STREET"); } - (NSString *)locality { return [[self elementForName:@"LOCALITY"] stringValue]; } - (void)setLocality:(NSString *)locality { XMPP_VCARD_SET_STRING_CHILD(locality, @"LOCALITY"); } - (NSString *)region { return [[self elementForName:@"REGION"] stringValue]; } - (void)setRegion:(NSString *)region { XMPP_VCARD_SET_STRING_CHILD(region, @"REGION"); } - (NSString *)postalCode { return [[self elementForName:@"PCODE"] stringValue]; } - (void)setPostalCode:(NSString *)pcode { XMPP_VCARD_SET_STRING_CHILD(pcode, @"PCODE"); } - (NSString *)country { return [[self elementForName:@"CTRY"] stringValue]; } - (void)setCountry:(NSString *)ctry { XMPP_VCARD_SET_STRING_CHILD(ctry, @"CTRY"); } @end
04081337-xmpp
Extensions/XEP-0054/XMPPvCardTempAdr.m
Objective-C
bsd
2,856
// // XMPPvCardTempEmail.h // XEP-0054 vCard-temp // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // Copyright 2010 Martin Morrison. All rights reserved. // #import <Foundation/Foundation.h> #import "XMPPvCardTempBase.h" @interface XMPPvCardTempEmail : XMPPvCardTempBase @property (nonatomic, assign, setter=setHome:) BOOL isHome; @property (nonatomic, assign, setter=setWork:) BOOL isWork; @property (nonatomic, assign, setter=setInternet:) BOOL isInternet; @property (nonatomic, assign, setter=setX400:) BOOL isX400; @property (nonatomic, assign, setter=setPreferred:) BOOL isPreferred; @property (nonatomic, assign) NSString *userid; + (XMPPvCardTempEmail *)vCardEmailFromElement:(NSXMLElement *)elem; @end
04081337-xmpp
Extensions/XEP-0054/XMPPvCardTempEmail.h
Objective-C
bsd
770
// // XMPPvCardTemp.h // XEP-0054 vCard-temp // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // Copyright 2010 Martin Morrison. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreLocation/CoreLocation.h> #import "XMPPIQ.h" #import "XMPPJID.h" #import "XMPPUser.h" #import "XMPPvCardTempAdr.h" #import "XMPPvCardTempBase.h" #import "XMPPvCardTempEmail.h" #import "XMPPvCardTempLabel.h" #import "XMPPvCardTempTel.h" typedef enum _XMPPvCardTempClass { XMPPvCardTempClassNone, XMPPvCardTempClassPublic, XMPPvCardTempClassPrivate, XMPPvCardTempClassConfidential, } XMPPvCardTempClass; extern NSString *const kXMPPNSvCardTemp; extern NSString *const kXMPPvCardTempElement; /* * Note: according to the DTD, every fields bar N and FN can appear multiple times. * The provided accessors only support this for the field types where multiple * entries make sense - for the others, if required, the NSXMLElement accessors * must be used. */ @interface XMPPvCardTemp : XMPPvCardTempBase @property (nonatomic, assign) NSDate *bday; @property (nonatomic, assign) NSData *photo; @property (nonatomic, assign) NSString *nickname; @property (nonatomic, assign) NSString *formattedName; @property (nonatomic, assign) NSString *familyName; @property (nonatomic, assign) NSString *givenName; @property (nonatomic, assign) NSString *middleName; @property (nonatomic, assign) NSString *prefix; @property (nonatomic, assign) NSString *suffix; @property (nonatomic, assign) NSArray *addresses; @property (nonatomic, assign) NSArray *labels; @property (nonatomic, assign) NSArray *telecomsAddresses; @property (nonatomic, assign) NSArray *emailAddresses; @property (nonatomic, assign) XMPPJID *jid; @property (nonatomic, assign) NSString *mailer; @property (nonatomic, assign) NSTimeZone *timeZone; @property (nonatomic, assign) CLLocation *location; @property (nonatomic, assign) NSString *title; @property (nonatomic, assign) NSString *role; @property (nonatomic, assign) NSData *logo; @property (nonatomic, assign) XMPPvCardTemp *agent; @property (nonatomic, assign) NSString *orgName; /* * ORGUNITs can only be set if there is already an ORGNAME. Otherwise, changes are ignored. */ @property (nonatomic, assign) NSArray *orgUnits; @property (nonatomic, assign) NSArray *categories; @property (nonatomic, assign) NSString *note; @property (nonatomic, assign) NSString *prodid; @property (nonatomic, assign) NSDate *revision; @property (nonatomic, assign) NSString *sortString; @property (nonatomic, assign) NSString *phoneticSound; @property (nonatomic, assign) NSData *sound; @property (nonatomic, assign) NSString *uid; @property (nonatomic, assign) NSString *url; @property (nonatomic, assign) NSString *version; @property (nonatomic, assign) NSString *description; @property (nonatomic, assign) XMPPvCardTempClass privacyClass; @property (nonatomic, assign) NSData *key; @property (nonatomic, assign) NSString *keyType; + (XMPPvCardTemp *)vCardTempFromElement:(NSXMLElement *)element; + (XMPPvCardTemp *)vCardTempSubElementFromIQ:(XMPPIQ *)iq; + (XMPPvCardTemp *)vCardTempCopyFromIQ:(XMPPIQ *)iq; + (XMPPIQ *)iqvCardRequestForJID:(XMPPJID *)jid; - (void)addAddress:(XMPPvCardTempAdr *)adr; - (void)removeAddress:(XMPPvCardTempAdr *)adr; - (void)clearAddresses; - (void)addLabel:(XMPPvCardTempLabel *)label; - (void)removeLabel:(XMPPvCardTempLabel *)label; - (void)clearLabels; - (void)addTelecomsAddress:(XMPPvCardTempTel *)tel; - (void)removeTelecomsAddress:(XMPPvCardTempTel *)tel; - (void)clearTelecomsAddresses; - (void)addEmailAddress:(XMPPvCardTempEmail *)email; - (void)removeEmailAddress:(XMPPvCardTempEmail *)email; - (void)clearEmailAddresses; @end
04081337-xmpp
Extensions/XEP-0054/XMPPvCardTemp.h
Objective-C
bsd
3,750
// // XMPPvCardTempEmail.m // XEP-0054 vCard-temp // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // Copyright 2010 Martin Morrison. All rights reserved. // #import "XMPPvCardTempEmail.h" #import "XMPPLogging.h" #import <objc/runtime.h> #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_ERROR; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_ERROR; #endif @implementation XMPPvCardTempEmail + (void)initialize { // We use the object_setClass method below to dynamically change the class from a standard NSXMLElement. // The size of the two classes is expected to be the same. // // If a developer adds instance methods to this class, bad things happen at runtime that are very hard to debug. // This check is here to aid future developers who may make this mistake. // // For Fearless And Experienced Objective-C Developers: // It may be possible to support adding instance variables to this class if you seriously need it. // To do so, try realloc'ing self after altering the class, and then initialize your variables. size_t superSize = class_getInstanceSize([NSXMLElement class]); size_t ourSize = class_getInstanceSize([XMPPvCardTempEmail class]); if (superSize != ourSize) { XMPPLogError(@"Adding instance variables to XMPPvCardTempEmail is not currently supported!"); [DDLog flushLog]; exit(15); } } + (XMPPvCardTempEmail *)vCardEmailFromElement:(NSXMLElement *)elem { object_setClass(elem, [XMPPvCardTempEmail class]); return (XMPPvCardTempEmail *)elem; } #pragma mark - #pragma mark Getter/setter methods - (BOOL)isHome { return [self elementForName:@"HOME"] != nil; } - (void)setHome:(BOOL)home { XMPP_VCARD_SET_EMPTY_CHILD(home && ![self isHome], @"HOME"); } - (BOOL)isWork { return [self elementForName:@"WORK"] != nil; } - (void)setWork:(BOOL)work { XMPP_VCARD_SET_EMPTY_CHILD(work && ![self isWork], @"WORK"); } - (BOOL)isInternet { return [self elementForName:@"INTERNET"] != nil; } - (void)setInternet:(BOOL)internet { XMPP_VCARD_SET_EMPTY_CHILD(internet && ![self isInternet], @"INTERNET"); } - (BOOL)isX400 { return [self elementForName:@"X400"] != nil; } - (void)setX400:(BOOL)x400 { XMPP_VCARD_SET_EMPTY_CHILD(x400 && ![self isX400], @"X400"); } - (BOOL)isPreferred { return [self elementForName:@"PREF"] != nil; } - (void)setPreferred:(BOOL)pref { XMPP_VCARD_SET_EMPTY_CHILD(pref && ![self isPreferred], @"PREF"); } - (NSString *)userid { return [[self elementForName:@"USERID"] stringValue]; } - (void)setUserid:(NSString *)userid { XMPP_VCARD_SET_STRING_CHILD(userid, @"USERID"); } @end
04081337-xmpp
Extensions/XEP-0054/XMPPvCardTempEmail.m
Objective-C
bsd
2,659
// // XMPPvCardTemp.m // XEP-0054 vCard-temp // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // Copyright 2010 Martin Morrison. All rights reserved. // #import "XMPPvCardTemp.h" #import <objc/runtime.h> #import "XMPPLogging.h" #import "NSData+XMPP.h" #import "XMPPDateTimeProfiles.h" #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_ERROR; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_ERROR; #endif NSString *const kXMPPNSvCardTemp = @"vcard-temp"; NSString *const kXMPPvCardTempElement = @"vCard"; @implementation XMPPvCardTemp + (void)initialize { // We use the object_setClass method below to dynamically change the class from a standard NSXMLElement. // The size of the two classes is expected to be the same. // // If a developer adds instance methods to this class, bad things happen at runtime that are very hard to debug. // This check is here to aid future developers who may make this mistake. // // For Fearless And Experienced Objective-C Developers: // It may be possible to support adding instance variables to this class if you seriously need it. // To do so, try realloc'ing self after altering the class, and then initialize your variables. size_t superSize = class_getInstanceSize([NSXMLElement class]); size_t ourSize = class_getInstanceSize([XMPPvCardTemp class]); if (superSize != ourSize) { XMPPLogError(@"Adding instance variables to XMPPvCardTemp is not currently supported!"); [DDLog flushLog]; exit(15); } } + (XMPPvCardTemp *)vCardTempFromElement:(NSXMLElement *)elem { object_setClass(elem, [XMPPvCardTemp class]); return (XMPPvCardTemp *)elem; } + (XMPPvCardTemp *)vCardTempSubElementFromIQ:(XMPPIQ *)iq { if ([iq isResultIQ]) { NSXMLElement *query = [iq elementForName:kXMPPvCardTempElement xmlns:kXMPPNSvCardTemp]; if (query) { return [self vCardTempFromElement:query]; } } return nil; } + (XMPPvCardTemp *)vCardTempCopyFromIQ:(XMPPIQ *)iq { // This doesn't work. // It looks like the copy that comes back is of class DDXMLElement. // So maybe the vCardTemp class has to implement its own copy method... // //return [[[self vCardTempSubElementFromIQ:iq] copy] autorelease]; if ([iq isResultIQ]) { NSXMLElement *query = [iq elementForName:kXMPPvCardTempElement xmlns:kXMPPNSvCardTemp]; if (query) { NSXMLElement *queryCopy = [[query copy] autorelease]; return [self vCardTempFromElement:queryCopy]; } } return nil; } + (XMPPIQ *)iqvCardRequestForJID:(XMPPJID *)jid { XMPPIQ *iq = [XMPPIQ iqWithType:@"get" to:[jid bareJID]]; NSXMLElement *vCardElem = [NSXMLElement elementWithName:kXMPPvCardTempElement xmlns:kXMPPNSvCardTemp]; [iq addChild:vCardElem]; return iq; } #pragma mark - #pragma mark Identification Types - (NSDate *)bday { NSDate *bday = nil; NSXMLElement *elem = [self elementForName:@"BDAY"]; if (elem != nil) { bday = [NSDate dateWithXmppDateString:[elem stringValue]]; } return bday; } - (void)setBday:(NSDate *)bday { NSXMLElement *elem = [self elementForName:@"BDAY"]; if (elem == nil) { elem = [NSXMLElement elementWithName:@"BDAY"]; [self addChild:elem]; } [elem setStringValue:[bday xmppDateString]]; } - (NSData *)photo { NSData *decodedData = nil; NSXMLElement *photo = [self elementForName:@"PHOTO"]; if (photo != nil) { // There is a PHOTO element. It should have a TYPE and a BINVAL //NSXMLElement *fileType = [photo elementForName:@"TYPE"]; NSXMLElement *binval = [photo elementForName:@"BINVAL"]; if (binval) { NSData *base64Data = [[binval stringValue] dataUsingEncoding:NSASCIIStringEncoding]; decodedData = [base64Data base64Decoded]; } } return decodedData; } - (void)setPhoto:(NSData *)data { NSXMLElement *photo = [self elementForName:@"PHOTO"]; if (photo == nil) { photo = [NSXMLElement elementWithName:@"PHOTO"]; [self addChild:photo]; } NSXMLElement *binval = [photo elementForName:@"BINVAL"]; if (binval == nil) { binval = [NSXMLElement elementWithName:@"BINVAL"]; [photo addChild:binval]; } [binval setStringValue:[data base64Encoded]]; } - (NSString *)nickname { return [[self elementForName:@"NICKNAME"] stringValue]; } - (void)setNickname:(NSString *)nick { XMPP_VCARD_SET_STRING_CHILD(nick, @"NICKNAME"); } - (NSString *)formattedName { return [[self elementForName:@"FN"] stringValue]; } - (void)setFormattedName:(NSString *)fn { XMPP_VCARD_SET_STRING_CHILD(fn, @"FN"); } - (NSString *)familyName { NSString *result = nil; NSXMLElement *name = [self elementForName:@"N"]; if (name != nil) { NSXMLElement *part = [name elementForName:@"FAMILY"]; if (part != nil) { result = [part stringValue]; } } return result; } - (void)setFamilyName:(NSString *)family { XMPP_VCARD_SET_N_CHILD(family, @"FAMILY"); } - (NSString *)givenName { NSString *result = nil; NSXMLElement *name = [self elementForName:@"N"]; if (name != nil) { NSXMLElement *part = [name elementForName:@"GIVEN"]; if (part != nil) { result = [part stringValue]; } } return result; } - (void)setGivenName:(NSString *)given { XMPP_VCARD_SET_N_CHILD(given, @"GIVEN"); } - (NSString *)middleName { NSString *result = nil; NSXMLElement *name = [self elementForName:@"N"]; if (name != nil) { NSXMLElement *part = [name elementForName:@"MIDDLE"]; if (part != nil) { result = [part stringValue]; } } return result; } - (void)setMiddleName:(NSString *)middle { XMPP_VCARD_SET_N_CHILD(middle, @"MIDDLE"); } - (NSString *)prefix { NSString *result = nil; NSXMLElement *name = [self elementForName:@"N"]; if (name != nil) { NSXMLElement *part = [name elementForName:@"PREFIX"]; if (part != nil) { result = [part stringValue]; } } return result; } - (void)setPrefix:(NSString *)prefix { XMPP_VCARD_SET_N_CHILD(prefix, @"PREFIX"); } - (NSString *)suffix { NSString *result = nil; NSXMLElement *name = [self elementForName:@"N"]; if (name != nil) { NSXMLElement *part = [name elementForName:@"SUFFIC"]; if (part != nil) { result = [part stringValue]; } } return result; } - (void)setSuffix:(NSString *)suffix { XMPP_VCARD_SET_N_CHILD(suffix, @"SUFFIX"); } #pragma mark Delivery Addressing Types - (NSArray *)addresses { return nil; } - (void)addAddress:(XMPPvCardTempAdr *)adr { } - (void)removeAddress:(XMPPvCardTempAdr *)adr { } - (void)setAddresses:(NSArray *)adrs { } - (void)clearAddresses { } - (NSArray *)labels { return nil; } - (void)addLabel:(XMPPvCardTempLabel *)label { } - (void)removeLabel:(XMPPvCardTempLabel *)label { } - (void)setLabels:(NSArray *)labels { } - (void)clearLabels { } - (NSArray *)telecomsAddresses { return nil; } - (void)addTelecomsAddress:(XMPPvCardTempTel *)tel { } - (void)removeTelecomsAddress:(XMPPvCardTempTel *)tel { } - (void)setTelecomsAddresses:(NSArray *)tels { } - (void)clearTelecomsAddresses { } - (NSArray *)emailAddresses { return nil; } - (void)addEmailAddress:(XMPPvCardTempEmail *)email { } - (void)removeEmailAddress:(XMPPvCardTempEmail *)email { } - (void)setEmailAddresses:(NSArray *)emails { } - (void)clearEmailAddresses { } - (XMPPJID *)jid { XMPPJID *jid = nil; NSXMLElement *elem = [self elementForName:@"JABBERID"]; if (elem != nil) { jid = [XMPPJID jidWithString:[elem stringValue]]; } return jid; } - (void)setJid:(XMPPJID *)jid { NSXMLElement *elem = [self elementForName:@"JABBERID"]; if (elem == nil && jid != nil) { elem = [NSXMLElement elementWithName:@"JABBERID"]; [self addChild:elem]; } if (jid != nil) { [elem setStringValue:[jid full]]; } else if (elem != nil) { [self removeChildAtIndex:[[self children] indexOfObject:elem]]; } } - (NSString *)mailer { return [[self elementForName:@"MAILER"] stringValue]; } - (void)setMailer:(NSString *)mailer { XMPP_VCARD_SET_STRING_CHILD(mailer, @"MAILER"); } #pragma mark Geographical Types - (NSTimeZone *)timeZone { // Turns out this is hard. Being lazy for now (not like anyone actually uses this, right?) NSXMLElement *tz = [self elementForName:@"TZ"]; if (tz != nil) { // This is unlikely to work. :-( return [NSTimeZone timeZoneWithName:[tz stringValue]]; } else { return nil; } } - (void)setTimeZone:(NSTimeZone *)tz { NSXMLElement *elem = [self elementForName:@"TZ"]; if (elem == nil && tz != nil) { elem = [NSXMLElement elementWithName:@"TZ"]; [self addChild:elem]; } if (tz != nil) { NSInteger offset = [tz secondsFromGMT]; [elem setStringValue:[NSString stringWithFormat:@"%02d:%02d", offset / 3600, (offset % 3600) / 60]]; } else if (elem != nil) { [self removeChildAtIndex:[[self children] indexOfObject:elem]]; } } - (CLLocation *)location { CLLocation *loc = nil; NSXMLElement *geo = [self elementForName:@"GEO"]; if (geo != nil) { NSXMLElement *lat = [geo elementForName:@"LAT"]; NSXMLElement *lon = [geo elementForName:@"LON"]; loc = [[[CLLocation alloc] initWithLatitude:[[lat stringValue] doubleValue] longitude:[[lon stringValue] doubleValue]] autorelease]; } return loc; } - (void)setLocation:(CLLocation *)geo { NSXMLElement *elem = [self elementForName:@"GEO"]; NSXMLElement *lat; NSXMLElement *lon; if (geo != nil) { CLLocationCoordinate2D coord = [geo coordinate]; if (elem == nil) { elem = [NSXMLElement elementWithName:@"GEO"]; [self addChild:elem]; lat = [NSXMLElement elementWithName:@"LAT"]; [elem addChild:lat]; lon = [NSXMLElement elementWithName:@"LON"]; [elem addChild:lon]; } else { lat = [elem elementForName:@"LAT"]; lon = [elem elementForName:@"LON"]; } [lat setStringValue:[NSString stringWithFormat:@"%.6f", coord.latitude]]; [lon setStringValue:[NSString stringWithFormat:@"%.6f", coord.longitude]]; } else if (elem != nil) { [self removeChildAtIndex:[[self children] indexOfObject:elem]]; } } #pragma mark Organizational Types - (NSString *)title { return [[self elementForName:@"TITLE"] stringValue]; } - (void)setTitle:(NSString *)title { XMPP_VCARD_SET_STRING_CHILD(title, @"TITLE"); } - (NSString *)role { return [[self elementForName:@"ROLE"] stringValue]; } - (void)setRole:(NSString *)role { XMPP_VCARD_SET_STRING_CHILD(role, @"ROLE"); } - (NSData *)logo { NSData *decodedData = nil; NSXMLElement *logo = [self elementForName:@"LOGO"]; if (logo != nil) { // There is a LOGO element. It should have a TYPE and a BINVAL //NSXMLElement *fileType = [photo elementForName:@"TYPE"]; NSXMLElement *binval = [logo elementForName:@"BINVAL"]; if (binval) { NSData *base64Data = [[binval stringValue] dataUsingEncoding:NSASCIIStringEncoding]; decodedData = [base64Data base64Decoded]; } } return decodedData; } - (void)setLogo:(NSData *)data { NSXMLElement *logo = [self elementForName:@"LOGO"]; if (logo == nil) { logo = [NSXMLElement elementWithName:@"LOGO"]; [self addChild:logo]; } NSXMLElement *binval = [logo elementForName:@"BINVAL"]; if (binval == nil) { binval = [NSXMLElement elementWithName:@"BINVAL"]; [logo addChild:binval]; } [binval setStringValue:[data base64Encoded]]; } - (XMPPvCardTemp *)agent { XMPPvCardTemp *agent = nil; NSXMLElement *elem = [self elementForName:@"AGENT"]; if (elem != nil) { agent = [XMPPvCardTemp vCardTempFromElement:elem]; } return agent; } - (void)setAgent:(XMPPvCardTemp *)agent { NSXMLElement *elem = [self elementForName:@"AGENT"]; if (elem != nil) { [self removeChildAtIndex:[[self children] indexOfObject:elem]]; } if (agent != nil) { [self addChild:agent]; } } - (NSString *)orgName { NSString *result = nil; NSXMLElement *org = [self elementForName:@"ORG"]; if (org != nil) { NSXMLElement *orgname = [org elementForName:@"ORGNAME"]; if (orgname != nil) { result = [orgname stringValue]; } } return result; } - (void)setOrgName:(NSString *)orgname { NSXMLElement *org = [self elementForName:@"ORG"]; NSXMLElement *elem = nil; if (orgname != nil) { if (org == nil) { org = [NSXMLElement elementWithName:@"ORG"]; [self addChild:org]; } else { elem = [org elementForName:@"ORGNAME"]; } if (elem == nil) { elem = [NSXMLElement elementWithName:@"ORGNAME"]; [org addChild:elem]; } [elem setStringValue:orgname]; } else if (org != nil) { // This implicitly removes all orgunits too, as per the spec [self removeChildAtIndex:[[self children] indexOfObject:org]]; } } - (NSArray *)orgUnits { NSArray *result = nil; NSXMLElement *org = [self elementForName:@"ORG"]; if (org != nil) { NSArray *elems = [org elementsForName:@"ORGUNIT"]; NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:[elems count]]; for (NSXMLElement *elem in elems) { [arr addObject:[elem stringValue]]; } result = [NSArray arrayWithArray:arr]; [arr release]; } return result; } - (void)setOrgUnits:(NSArray *)orgunits { NSXMLElement *org = [self elementForName:@"ORG"]; // If there is no org, then there is nothing to do (need ORGNAME first) if (org != nil) { NSArray *elems = [org elementsForName:@"ORGUNIT"]; for (NSXMLElement *elem in elems) { [org removeChildAtIndex:[[org children] indexOfObject:elem]]; } for (NSString *unit in orgunits) { NSXMLElement *elem = [NSXMLElement elementWithName:@"ORGUNIT"]; [elem setStringValue:unit]; [org addChild:elem]; } } } #pragma mark Explanatory Types - (NSArray *)categories { NSArray *result = nil; NSXMLElement *categories = [self elementForName:@"CATEGORIES"]; if (categories != nil) { NSArray *elems = [categories elementsForName:@"KEYWORD"]; NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:[elems count]]; for (NSXMLElement *elem in elems) { [arr addObject:[elem stringValue]]; } result = [NSArray arrayWithArray:arr]; [arr release]; } return result; } - (void)setCategories:(NSArray *)categories { NSXMLElement *cat = [self elementForName:@"CATEGORIES"]; if (categories != nil) { if (cat == nil) { cat = [NSXMLElement elementWithName:@"CATEGORIES"]; [self addChild:cat]; } NSArray *elems = [cat elementsForName:@"KEYWORD"]; for (NSXMLElement *elem in elems) { [cat removeChildAtIndex:[[cat children] indexOfObject:elem]]; } for (NSString *kw in categories) { NSXMLElement *elem = [NSXMLElement elementWithName:@"KEYWORD"]; [elem setStringValue:kw]; [cat addChild:elem]; } } else if (cat != nil) { [self removeChildAtIndex:[[self children] indexOfObject:cat]]; } } - (NSString *)note { return [[self elementForName:@"NOTE"] stringValue]; } - (void)setNote:(NSString *)note { XMPP_VCARD_SET_STRING_CHILD(note, @"NOTE"); } - (NSString *)prodid { return [[self elementForName:@"PRODID"] stringValue]; } - (void)setProdid:(NSString *)prodid { XMPP_VCARD_SET_STRING_CHILD(prodid, @"PRODID"); } - (NSDate *)revision { NSDate *rev = nil; NSXMLElement *elem = [self elementForName:@"REV"]; if (elem != nil) { rev = [NSDate dateWithXmppDateTimeString:[elem stringValue]]; } return rev; } - (void)setRevision:(NSDate *)rev { NSXMLElement *elem = [self elementForName:@"REV"]; if (elem == nil) { elem = [NSXMLElement elementWithName:@"REV"]; [self addChild:elem]; } [elem setStringValue:[rev xmppDateTimeString]]; } - (NSString *)sortString { return [[self elementForName:@"SORT-STRING"] stringValue]; } - (void)setSortString:(NSString *)sortString { XMPP_VCARD_SET_STRING_CHILD(sortString, @"SORT-STRING"); } - (NSString *)phoneticSound { NSString *phon = nil; NSXMLElement *sound = [self elementForName:@"SOUND"]; if (sound != nil) { NSXMLElement *elem = [sound elementForName:@"PHONETIC"]; if (elem != nil) { phon = [elem stringValue]; } } return phon; } - (void)setPhoneticSound:(NSString *)phonetic { NSXMLElement *sound = [self elementForName:@"SOUND"]; NSXMLElement *elem; if (sound == nil && phonetic != nil) { sound = [NSXMLElement elementWithName:@"SOUND"]; [self addChild:sound]; } if (sound != nil) { elem = [sound elementForName:@"PHONETIC"]; if (elem != nil && phonetic != nil) { elem = [NSXMLElement elementWithName:@"PHONETIC"]; [sound addChild:elem]; } } if (phonetic != nil) { [elem setStringValue:phonetic]; } else if (sound != nil) { [self removeChildAtIndex:[[self children] indexOfObject:phonetic]]; } } - (NSData *)sound { NSData *decodedData = nil; NSXMLElement *sound = [self elementForName:@"SOUND"]; if (sound != nil) { NSXMLElement *binval = [sound elementForName:@"BINVAL"]; if (binval) { NSData *base64Data = [[binval stringValue] dataUsingEncoding:NSASCIIStringEncoding]; decodedData = [base64Data base64Decoded]; } } return decodedData; } - (void)setSound:(NSData *)data { NSXMLElement *sound = [self elementForName:@"SOUND"]; if (sound == nil) { sound = [NSXMLElement elementWithName:@"SOUND"]; [self addChild:sound]; } NSXMLElement *binval = [sound elementForName:@"BINVAL"]; if (binval == nil) { binval = [NSXMLElement elementWithName:@"BINVAL"]; [sound addChild:binval]; } [binval setStringValue:[data base64Encoded]]; } - (NSString *)uid { return [[self elementForName:@"UID"] stringValue]; } - (void)setUid:(NSString *)uid { XMPP_VCARD_SET_STRING_CHILD(uid, @"UID"); } - (NSString *)url { return [[self elementForName:@"URL"] stringValue]; } - (void)setUrl:(NSString *)url { XMPP_VCARD_SET_STRING_CHILD(url, @"URL"); } - (NSString *)version { return [self attributeStringValueForName:@"version"]; } - (void)setVersion:(NSString *)version { [self addAttributeWithName:@"version" stringValue:version]; } - (NSString *)description { return [[self elementForName:@"DESC"] stringValue]; } - (void)setDescription:(NSString *)desc { XMPP_VCARD_SET_STRING_CHILD(desc, @"DESC"); } #pragma mark Security Types - (XMPPvCardTempClass)privacyClass { XMPPvCardTempClass priv = XMPPvCardTempClassNone; NSXMLElement *elem = [self elementForName:@"CLASS"]; if (elem != nil) { if ([elem elementForName:@"PUBLIC"] != nil) { priv = XMPPvCardTempClassPublic; } else if ([elem elementForName:@"PRIVATE"] != nil) { priv = XMPPvCardTempClassPrivate; } else if ([elem elementForName:@"CONFIDENTIAL"] != nil) { priv = XMPPvCardTempClassConfidential; } } return priv; } - (void)setPrivacyClass:(XMPPvCardTempClass)privacyClass { NSXMLElement *elem = [self elementForName:@"CLASS"]; if (elem == nil && privacyClass != XMPPvCardTempClassNone) { elem = [NSXMLElement elementWithName:@"CLASS"]; } if (elem != nil) { for (NSString *cls in [NSArray arrayWithObjects:@"PUBLIC", @"PRIVATE", @"CONFIDENTIAL", nil]) { NSXMLElement *priv = [elem elementForName:cls]; if (priv != nil) { [elem removeChildAtIndex:[[elem children] indexOfObject:priv]]; } } switch (privacyClass) { case XMPPvCardTempClassPublic: [elem addChild:[NSXMLElement elementWithName:@"PUBLIC"]]; break; case XMPPvCardTempClassPrivate: [elem addChild:[NSXMLElement elementWithName:@"PRIVATE"]]; break; case XMPPvCardTempClassConfidential: [elem addChild:[NSXMLElement elementWithName:@"CONFIDENTIAL"]]; break; default: case XMPPvCardTempClassNone: // Remove the whole element [self removeChildAtIndex:[[self children] indexOfObject:elem]]; break; } } } - (NSData *)key { return nil; } - (void)setKey:(NSData *)key { } - (NSString *)keyType { NSString *typ = nil; NSXMLElement *key = [self elementForName:@"KEY"]; if (key != nil) { NSXMLElement *elem = [key elementForName:@"TYPE"]; if (elem != nil) { typ = [elem stringValue]; } } return typ; } - (void)setKeyType:(NSString *)type { NSXMLElement *key = [self elementForName:@"KEY"]; NSXMLElement *elem; if (key == nil && type != nil) { key = [NSXMLElement elementWithName:@"KEY"]; [self addChild:key]; } if (key != nil) { elem = [key elementForName:@"TYPE"]; if (elem != nil && type != nil) { elem = [NSXMLElement elementWithName:@"TYPE"]; [key addChild:elem]; } } if (type != nil) { [elem setStringValue:type]; } else if (key != nil) { [self removeChildAtIndex:[[self children] indexOfObject:key]]; } } @end
04081337-xmpp
Extensions/XEP-0054/XMPPvCardTemp.m
Objective-C
bsd
20,339
// // XMPPvCardTempBase.m // XEP-0054 vCard-temp // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // Copyright 2010 Martin Morrison. All rights reserved. // #import "XMPPvCardTempBase.h" #import <objc/runtime.h> @implementation XMPPvCardTempBase //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - #pragma mark NSCoding protocol //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #if ! TARGET_OS_IPHONE - (id)replacementObjectForPortCoder:(NSPortCoder *)encoder { if([encoder isBycopy]) return self; else return [super replacementObjectForPortCoder:encoder]; // return [NSDistantObject proxyWithLocal:self connection:[encoder connection]]; } #endif - (id)initWithCoder:(NSCoder *)coder { NSString *xmlString; if([coder allowsKeyedCoding]) { xmlString = [coder decodeObjectForKey:@"xmlString"]; } else { xmlString = [coder decodeObject]; } NSXMLElement *elem = [self initWithXMLString:xmlString error:nil]; object_setClass(elem, [self class]); return elem; } - (void)encodeWithCoder:(NSCoder *)coder { NSString *xmlString = [self XMLString]; if([coder allowsKeyedCoding]) { [coder encodeObject:xmlString forKey:@"xmlString"]; } else { [coder encodeObject:xmlString]; } } @end
04081337-xmpp
Extensions/XEP-0054/XMPPvCardTempBase.m
Objective-C
bsd
1,433
// // XMPPvCardTempAdrTypes.m // XEP-0054 vCard-temp // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // Copyright 2010 Martin Morrison. All rights reserved. // #import "XMPPvCardTempAdrTypes.h" @implementation XMPPvCardTempAdrTypes #pragma mark - #pragma mark Getter/setter methods - (BOOL)isHome { return [self elementForName:@"HOME"] != nil; } - (void)setHome:(BOOL)home { XMPP_VCARD_SET_EMPTY_CHILD(home && ![self isHome], @"HOME"); } - (BOOL)isWork { return [self elementForName:@"WORK"] != nil; } - (void)setWork:(BOOL)work { XMPP_VCARD_SET_EMPTY_CHILD(work && ![self isWork], @"WORK"); } - (BOOL)isParcel { return [self elementForName:@"PARCEL"] != nil; } - (void)setParcel:(BOOL)parcel { XMPP_VCARD_SET_EMPTY_CHILD(parcel && ![self isParcel], @"PARCEL"); } - (BOOL)isPostal { return [self elementForName:@"POSTAL"] != nil; } - (void)setPostal:(BOOL)postal { XMPP_VCARD_SET_EMPTY_CHILD(postal && ![self isPostal], @"POSTAL"); } - (BOOL)isDomestic { return [self elementForName:@"DOM"] != nil; } - (void)setDomestic:(BOOL)dom { XMPP_VCARD_SET_EMPTY_CHILD(dom && ![self isDomestic], @"DOM"); // INTL and DOM are mutually exclusive if (dom) { [self setInternational:NO]; } } - (BOOL)isInternational { return [self elementForName:@"INTL"] != nil; } - (void)setInternational:(BOOL)intl { XMPP_VCARD_SET_EMPTY_CHILD(intl && ![self isInternational], @"INTL"); // INTL and DOM are mutually exclusive if (intl) { [self setDomestic:NO]; } } - (BOOL)isPreferred { return [self elementForName:@"PREF"] != nil; } - (void)setPreferred:(BOOL)pref { XMPP_VCARD_SET_EMPTY_CHILD(pref && ![self isPreferred], @"PREF"); } @end
04081337-xmpp
Extensions/XEP-0054/XMPPvCardTempAdrTypes.m
Objective-C
bsd
1,722
// // XMPPvCardTempTel.h // XEP-0054 vCard-temp // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // Copyright 2010 Martin Morrison. All rights reserved. // #import <Foundation/Foundation.h> #import "XMPPvCardTempBase.h" @interface XMPPvCardTempTel : XMPPvCardTempBase @property (nonatomic, assign, setter=setHome:) BOOL isHome; @property (nonatomic, assign, setter=setWork:) BOOL isWork; @property (nonatomic, assign, setter=setVoice:) BOOL isVoice; @property (nonatomic, assign, setter=setFax:) BOOL isFax; @property (nonatomic, assign, setter=setPager:) BOOL isPager; @property (nonatomic, assign, setter=setMessaging:) BOOL hasMessaging; @property (nonatomic, assign, setter=setCell:) BOOL isCell; @property (nonatomic, assign, setter=setVideo:) BOOL isVideo; @property (nonatomic, assign, setter=setBBS:) BOOL isBBS; @property (nonatomic, assign, setter=setModem:) BOOL isModem; @property (nonatomic, assign, setter=setISDN:) BOOL isISDN; @property (nonatomic, assign, setter=setPCS:) BOOL isPCS; @property (nonatomic, assign, setter=setPreferred:) BOOL isPreferred; @property (nonatomic, assign) NSString *number; + (XMPPvCardTempTel *)vCardTelFromElement:(NSXMLElement *)elem; @end
04081337-xmpp
Extensions/XEP-0054/XMPPvCardTempTel.h
Objective-C
bsd
1,247
// // XMPPvCardTempModule.h // XEP-0054 vCard-temp // // Created by Eric Chamberlain on 3/17/11. // Copyright 2011 RF.com. All rights reserved. // #import <Foundation/Foundation.h> #import "XMPPModule.h" #import "XMPPvCardTemp.h" @class XMPPJID; @class XMPPStream; @protocol XMPPvCardTempModuleStorage; @interface XMPPvCardTempModule : XMPPModule { id <XMPPvCardTempModuleStorage> _moduleStorage; } @property(nonatomic, readonly) id <XMPPvCardTempModuleStorage> moduleStorage; @property(nonatomic, readonly) XMPPvCardTemp *myvCardTemp; - (id)initWithvCardStorage:(id <XMPPvCardTempModuleStorage>)storage; - (id)initWithvCardStorage:(id <XMPPvCardTempModuleStorage>)storage dispatchQueue:(dispatch_queue_t)queue; /* * Return the cached vCard for the user or fetch it, if we don't have it. */ - (XMPPvCardTemp *)fetchvCardTempForJID:(XMPPJID *)jid; - (XMPPvCardTemp *)fetchvCardTempForJID:(XMPPJID *)jid useCache:(BOOL)useCache; - (void)updateMyvCardTemp:(XMPPvCardTemp *)vCardTemp; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol XMPPvCardTempModuleDelegate @optional - (void)xmppvCardTempModule:(XMPPvCardTempModule *)vCardTempModule didReceivevCardTemp:(XMPPvCardTemp *)vCardTemp forJID:(XMPPJID *)jid; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol XMPPvCardTempModuleStorage <NSObject> /** * Configures the storage class, passing its parent and parent's dispatch queue. * * This method is called by the init methods of the XMPPvCardTempModule class. * This method is designed to inform the storage class of its parent * and of the dispatch queue the parent will be operating on. * * The storage class may choose to operate on the same queue as its parent, * or it may operate on its own internal dispatch queue. * * This method should return YES if it was configured properly. * The parent class is configured to ignore the passed * storage class in its init method if this method returns NO. **/ - (BOOL)configureWithParent:(XMPPvCardTempModule *)aParent queue:(dispatch_queue_t)queue; /** * Returns a vCardTemp object or nil **/ - (XMPPvCardTemp *)vCardTempForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream; /** * Used to set the vCardTemp object when we get it from the XMPP server. **/ - (void)setvCardTemp:(XMPPvCardTemp *)vCardTemp forJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream; /** * Asks the backend if we should fetch the vCardTemp from the network. * This is used so that we don't request the vCardTemp multiple times. **/ - (BOOL)shouldFetchvCardTempForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream; @end
04081337-xmpp
Extensions/XEP-0054/XMPPvCardTempModule.h
Objective-C
bsd
3,063
// // XMPPvCardTempTel.m // XEP-0054 vCard-temp // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // Copyright 2010 Martin Morrison. All rights reserved. // #import "XMPPvCardTempTel.h" #import "XMPPLogging.h" #import <objc/runtime.h> #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_ERROR; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_ERROR; #endif @implementation XMPPvCardTempTel + (void)initialize { // We use the object_setClass method below to dynamically change the class from a standard NSXMLElement. // The size of the two classes is expected to be the same. // // If a developer adds instance methods to this class, bad things happen at runtime that are very hard to debug. // This check is here to aid future developers who may make this mistake. // // For Fearless And Experienced Objective-C Developers: // It may be possible to support adding instance variables to this class if you seriously need it. // To do so, try realloc'ing self after altering the class, and then initialize your variables. size_t superSize = class_getInstanceSize([NSXMLElement class]); size_t ourSize = class_getInstanceSize([XMPPvCardTempTel class]); if (superSize != ourSize) { XMPPLogError(@"Adding instance variables to XMPPvCardTempTel is not currently supported!"); [DDLog flushLog]; exit(15); } } + (XMPPvCardTempTel *)vCardTelFromElement:(NSXMLElement *)elem { object_setClass(elem, [XMPPvCardTempTel class]); return (XMPPvCardTempTel *)elem; } #pragma mark - #pragma mark Getter/setter methods - (BOOL)isHome { return [self elementForName:@"HOME"] != nil; } - (void)setHome:(BOOL)home { XMPP_VCARD_SET_EMPTY_CHILD(home && ![self isHome], @"HOME"); } - (BOOL)isWork { return [self elementForName:@"WORK"] != nil; } - (void)setWork:(BOOL)work { XMPP_VCARD_SET_EMPTY_CHILD(work && ![self isWork], @"WORK"); } - (BOOL)isVoice { return [self elementForName:@"VOICE"] != nil; } - (void)setVoice:(BOOL)voice { XMPP_VCARD_SET_EMPTY_CHILD(voice && ![self isVoice], @"VOICE"); } - (BOOL)isFax { return [self elementForName:@"FAX"] != nil; } - (void)setFax:(BOOL)fax { XMPP_VCARD_SET_EMPTY_CHILD(fax && ![self isFax], @"FAX"); } - (BOOL)isPager { return [self elementForName:@"PAGER"] != nil; } - (void)setPager:(BOOL)pager { XMPP_VCARD_SET_EMPTY_CHILD(pager && ![self isPager], @"PAGER"); } - (BOOL)hasMessaging { return [self elementForName:@"MSG"] != nil; } - (void)setMessaging:(BOOL)msg { XMPP_VCARD_SET_EMPTY_CHILD(msg && ![self hasMessaging], @"MSG"); } - (BOOL)isCell { return [self elementForName:@"CELL"] != nil; } - (void)setCell:(BOOL)cell { XMPP_VCARD_SET_EMPTY_CHILD(cell && ![self isCell], @"CELL"); } - (BOOL)isVideo { return [self elementForName:@"VIDEO"] != nil; } - (void)setVideo:(BOOL)video { XMPP_VCARD_SET_EMPTY_CHILD(video && ![self isVideo], @"VIDEO"); } - (BOOL)isBBS { return [self elementForName:@"BBS"] != nil; } - (void)setBBS:(BOOL)bbs { XMPP_VCARD_SET_EMPTY_CHILD(bbs && ![self isBBS], @"BBS"); } - (BOOL)isModem { return [self elementForName:@"MODEM"] != nil; } - (void)setModem:(BOOL)modem { XMPP_VCARD_SET_EMPTY_CHILD(modem && ![self isModem], @"MODEM"); } - (BOOL)isISDN { return [self elementForName:@"ISDN"] != nil; } - (void)setISDN:(BOOL)isdn { XMPP_VCARD_SET_EMPTY_CHILD(isdn && ![self isISDN], @"ISDN"); } - (BOOL)isPCS { return [self elementForName:@"PCS"] != nil; } - (void)setPCS:(BOOL)pcs { XMPP_VCARD_SET_EMPTY_CHILD(pcs && ![self isPCS], @"PCS"); } - (BOOL)isPreferred { return [self elementForName:@"PREF"] != nil; } - (void)setPreferred:(BOOL)pref { XMPP_VCARD_SET_EMPTY_CHILD(pref && ![self isPreferred], @"PREF"); } - (NSString *)number { return [[self elementForName:@"NUMBER"] stringValue]; } - (void)setNumber:(NSString *)number { XMPP_VCARD_SET_STRING_CHILD(number, @"NUMBER"); } @end
04081337-xmpp
Extensions/XEP-0054/XMPPvCardTempTel.m
Objective-C
bsd
3,928
// // XMPPvCardTempLabel.h // XEP-0054 vCard-temp // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // Copyright 2010 Martin Morrison. All rights reserved. // #import <Foundation/Foundation.h> #import "XMPPvCardTempAdrTypes.h" @interface XMPPvCardTempLabel : XMPPvCardTempAdrTypes @property (nonatomic, assign) NSArray *lines; + (XMPPvCardTempLabel *)vCardLabelFromElement:(NSXMLElement *)elem; @end
04081337-xmpp
Extensions/XEP-0054/XMPPvCardTempLabel.h
Objective-C
bsd
458
// // XMPPvCardCoreDataStorage.h // XEP-0054 vCard-temp // // Originally created by Eric Chamberlain on 3/18/11. // #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> #import "XMPPCoreDataStorage.h" #import "XMPPvCardTempModule.h" #import "XMPPvCardAvatarModule.h" /** * This class is an example implementation of XMPPCapabilitiesStorage using core data. * You are free to substitute your own storage class. **/ @interface XMPPvCardCoreDataStorage : XMPPCoreDataStorage < XMPPvCardAvatarStorage, XMPPvCardTempModuleStorage > { // Inherits protected variables from XMPPCoreDataStorage } /** * XEP-0054 provides a mechanism for transmitting vCards via XMPP. * Because the JID doesn't change very often and can be large with image data, * it is safe to persistently store the JID and wait for a user to explicity ask for an update, * or use XEP-0153 to monitor for JID changes. * * For this reason, it is recommended you use this sharedInstance across all your xmppStreams. * This way all streams can shared a knowledgebase concerning known JIDs and Avatar photos. * * All other aspects of vCard handling (such as lookup failures, etc) are kept separate between streams. **/ + (XMPPvCardCoreDataStorage *)sharedInstance; // // This class inherits from XMPPCoreDataStorage. // // Please see the XMPPCoreDataStorage header file for more information. // @end
04081337-xmpp
Extensions/XEP-0054/CoreDataStorage/XMPPvCardCoreDataStorage.h
Objective-C
bsd
1,397
// // XMPPvCardCoreDataStorageObject.h // XEP-0054 vCard-temp // // Originally created by Eric Chamberlain on 3/18/11. // #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> @class XMPPJID; @class XMPPvCardTemp; @class XMPPvCardTempCoreDataStorageObject; @class XMPPvCardAvatarCoreDataStorageObject; @interface XMPPvCardCoreDataStorageObject : NSManagedObject /* * User's JID, indexed for lookups */ @property (nonatomic, retain) NSString * jidStr; /* * User's photoHash used by XEP-0153 */ @property (nonatomic, retain, readonly) NSString * photoHash; /* * The last time the record was modified, also used to determine if we need to fetch again */ @property (nonatomic, retain) NSDate * lastUpdated; /* * Flag indicating whether a get request is already pending, used in conjunction with lastUpdated */ @property (nonatomic, retain) NSNumber * waitingForFetch; /* * Relationship to the vCardTemp record. * We use a relationship, so the vCardTemp stays faulted until we really need it. */ @property (nonatomic, retain) XMPPvCardTempCoreDataStorageObject * vCardTempRel; /* * Relationship to the vCardAvatar record. * We use a relationship, so the vCardAvatar stays faulted until we really need it. */ @property (nonatomic, retain) XMPPvCardAvatarCoreDataStorageObject * vCardAvatarRel; /* * Accessor to retrieve photoData, so we can hide the underlying relationship implementation. */ @property (nonatomic, retain) NSData *photoData; /* * Accessor to retrieve vCardTemp, so we can hide the underlying relationship implementation. */ @property (nonatomic, retain) XMPPvCardTemp *vCardTemp; + (XMPPvCardCoreDataStorageObject *)fetchOrInsertvCardForJID:(XMPPJID *)jid inManagedObjectContext:(NSManagedObjectContext *)moc; @end
04081337-xmpp
Extensions/XEP-0054/CoreDataStorage/XMPPvCardCoreDataStorageObject.h
Objective-C
bsd
1,828
// // XMPPvCardTempCoreDataStorageObject.h // XEP-0054 vCard-temp // // Oringally created by Eric Chamberlain on 3/18/11. // // This class is so that we don't load the vCardTemp each time we need to touch the XMPPvCardCoreDataStorageObject. // The vCardTemp abstraction also makes it easier to eventually add support for vCard4 over XMPP (XEP-0292). #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> #import "XMPPvcardTemp.h" @class XMPPvCardCoreDataStorageObject; @interface XMPPvCardTempCoreDataStorageObject : NSManagedObject @property (nonatomic, retain) XMPPvCardTemp * vCardTemp; @property (nonatomic, retain) XMPPvCardCoreDataStorageObject * vCard; @end
04081337-xmpp
Extensions/XEP-0054/CoreDataStorage/XMPPvCardTempCoreDataStorageObject.h
Objective-C
bsd
687
// // XMPPvCardAvatarCoreDataStorageObject.m // XEP-0054 vCard-temp // // Originally created by Eric Chamberlain on 3/18/11. // #import "XMPPvCardAvatarCoreDataStorageObject.h" #import "XMPPvCardCoreDataStorageObject.h" @implementation XMPPvCardAvatarCoreDataStorageObject @dynamic photoData; @dynamic vCard; @end
04081337-xmpp
Extensions/XEP-0054/CoreDataStorage/XMPPvCardAvatarCoreDataStorageObject.m
Objective-C
bsd
322
// // XMPPvCardCoreDataStorage.m // XEP-0054 vCard-temp // // Originally created by Eric Chamberlain on 3/18/11. // #import "XMPPvCardCoreDataStorage.h" #import "XMPPvCardCoreDataStorageObject.h" #import "XMPPvCardTempCoreDataStorageObject.h" #import "XMPPvCardAvatarCoreDataStorageObject.h" #import "XMPP.h" #import "XMPPCoreDataStorageProtected.h" #import "XMPPLogging.h" // Log levels: off, error, warn, info, verbose #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; // | XMPP_LOG_FLAG_TRACE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif enum { kXMPPvCardTempNetworkFetchTimeout = 10, }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPvCardCoreDataStorage static XMPPvCardCoreDataStorage *sharedInstance; + (XMPPvCardCoreDataStorage *)sharedInstance { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[XMPPvCardCoreDataStorage alloc] initWithDatabaseFilename:nil]; }); return sharedInstance; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Setup //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)configureWithParent:(XMPPvCardTempModule *)aParent queue:(dispatch_queue_t)queue { return [super configureWithParent:aParent queue:queue]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Overrides //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)addPersistentStoreWithPath:(NSString *)storePath error:(NSError **)errorPtr { BOOL result = [super addPersistentStoreWithPath:storePath error:errorPtr]; if (!result && [*errorPtr code] == NSMigrationMissingSourceModelError && [[*errorPtr domain] isEqualToString:NSCocoaErrorDomain]) { // If we get this error while trying to add the persistent store, it most likely means the model changed. // Since we are caching capabilities, it is safe to delete the persistent store and create a new one. if ([[NSFileManager defaultManager] fileExistsAtPath:storePath]) { [[NSFileManager defaultManager] removeItemAtPath:storePath error:nil]; // Try creating the store again, without creating a deletion/creation loop. result = [super addPersistentStoreWithPath:storePath error:errorPtr]; } } return result; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPvCardAvatarStorage protocol //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSData *)photoDataForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { // This is a public method. // It may be invoked on any thread/queue. XMPPLogTrace(); __block NSData *result; [self executeBlock:^{ XMPPvCardCoreDataStorageObject *vCard; vCard = [XMPPvCardCoreDataStorageObject fetchOrInsertvCardForJID:jid inManagedObjectContext:[self managedObjectContext]]; result = [vCard.photoData retain]; }]; return [result autorelease]; } - (NSString *)photoHashForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { // This is a public method. // It may be invoked on any thread/queue. XMPPLogTrace(); __block NSString *result; [self executeBlock:^{ XMPPvCardCoreDataStorageObject *vCard; vCard = [XMPPvCardCoreDataStorageObject fetchOrInsertvCardForJID:jid inManagedObjectContext:[self managedObjectContext]]; result = [vCard.photoHash retain]; }]; return [result autorelease]; } - (void)clearvCardTempForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { // This is a public method. // It may be invoked on any thread/queue. XMPPLogTrace(); [self scheduleBlock:^{ XMPPvCardCoreDataStorageObject *vCard; vCard = [XMPPvCardCoreDataStorageObject fetchOrInsertvCardForJID:jid inManagedObjectContext:[self managedObjectContext]]; vCard.vCardTemp = nil; vCard.lastUpdated = [NSDate date]; }]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPvCardTempModuleStorage protocol //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (XMPPvCardTemp *)vCardTempForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { // This is a public method. // It may be invoked on any thread/queue. XMPPLogTrace(); __block XMPPvCardTemp *result; [self executeBlock:^{ XMPPvCardCoreDataStorageObject *vCard; vCard = [XMPPvCardCoreDataStorageObject fetchOrInsertvCardForJID:jid inManagedObjectContext:[self managedObjectContext]]; result = [vCard.vCardTemp retain]; }]; return [result autorelease]; } - (void)setvCardTemp:(XMPPvCardTemp *)vCardTemp forJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { // This is a public method. // It may be invoked on any thread/queue. XMPPLogTrace(); [self scheduleBlock:^{ XMPPvCardCoreDataStorageObject *vCard; vCard = [XMPPvCardCoreDataStorageObject fetchOrInsertvCardForJID:jid inManagedObjectContext:[self managedObjectContext]]; vCard.waitingForFetch = [NSNumber numberWithBool:NO]; vCard.vCardTemp = vCardTemp; // Update photo and photo hash vCard.photoData = vCardTemp.photo; vCard.lastUpdated = [NSDate date]; }]; } - (BOOL)shouldFetchvCardTempForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { // This is a public method. // It may be invoked on any thread/queue. XMPPLogTrace(); __block BOOL result; [self executeBlock:^{ XMPPvCardCoreDataStorageObject *vCard; vCard = [XMPPvCardCoreDataStorageObject fetchOrInsertvCardForJID:jid inManagedObjectContext:[self managedObjectContext]]; BOOL waitingForFetch = [vCard.waitingForFetch boolValue]; if (!waitingForFetch) { vCard.waitingForFetch = [NSNumber numberWithBool:YES]; vCard.lastUpdated = [NSDate date]; result = YES; } else if ([vCard.lastUpdated timeIntervalSinceNow] < -kXMPPvCardTempNetworkFetchTimeout) { // Our last request exceeded the timeout, send a new one vCard.lastUpdated = [NSDate date]; result = YES; } else { // We already have an outstanding request, no need to send another one. result = NO; } }]; return result; } @end
04081337-xmpp
Extensions/XEP-0054/CoreDataStorage/XMPPvCardCoreDataStorage.m
Objective-C
bsd
7,118
// // XMPPvCardAvatarCoreDataStorageObject.h // XEP-0054 vCard-temp // // Originally created by Eric Chamberlain on 3/18/11. // // This class is so that we don't load the photoData each time we need to touch the XMPPvCardCoreDataStorageObject. #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> @class XMPPvCardCoreDataStorageObject; @interface XMPPvCardAvatarCoreDataStorageObject : NSManagedObject @property (nonatomic, retain) NSData * photoData; @property (nonatomic, retain) XMPPvCardCoreDataStorageObject * vCard; @end
04081337-xmpp
Extensions/XEP-0054/CoreDataStorage/XMPPvCardAvatarCoreDataStorageObject.h
Objective-C
bsd
548
// // XMPPvCardCoreDataStorageObject.m // XEP-0054 vCard-temp // // Originally created by Eric Chamberlain on 3/18/11. // #import "XMPPvCardCoreDataStorageObject.h" #import "XMPPvCardTempCoreDataStorageObject.h" #import "XMPPvCardAvatarCoreDataStorageObject.h" #import "XMPPJID.h" #import "XMPPStream.h" #import "NSNumber+XMPP.h" #import "NSData+XMPP.h" @implementation XMPPvCardCoreDataStorageObject + (XMPPvCardCoreDataStorageObject *)fetchvCardForJID:(XMPPJID *)jid inManagedObjectContext:(NSManagedObjectContext *)moc { NSString *entityName = NSStringFromClass([XMPPvCardCoreDataStorageObject class]); NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:moc]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"jidStr == %@", [jid bare]]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; [fetchRequest setEntity:entity]; [fetchRequest setPredicate:predicate]; [fetchRequest setIncludesPendingChanges:YES]; [fetchRequest setFetchLimit:1]; NSArray *results = [moc executeFetchRequest:fetchRequest error:nil]; [fetchRequest release]; return (XMPPvCardCoreDataStorageObject *)[results lastObject]; } + (XMPPvCardCoreDataStorageObject *)insertEmptyvCardForJID:(XMPPJID *)jid inManagedObjectContext:(NSManagedObjectContext *)moc { NSString *entityName = NSStringFromClass([XMPPvCardCoreDataStorageObject class]); XMPPvCardCoreDataStorageObject *vCard = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:moc]; vCard.jidStr = [jid bare]; return vCard; } + (XMPPvCardCoreDataStorageObject *)fetchOrInsertvCardForJID:(XMPPJID *)jid inManagedObjectContext:(NSManagedObjectContext *)moc { XMPPvCardCoreDataStorageObject *vCard = [self fetchvCardForJID:jid inManagedObjectContext:moc]; if (vCard == nil) { vCard = [self insertEmptyvCardForJID:jid inManagedObjectContext:moc]; } return vCard; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark NSManagedObject methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)awakeFromInsert { [super awakeFromInsert]; [self setPrimitiveValue:[NSDate date] forKey:@"lastUpdated"]; } - (void)willSave { /* if (![self isDeleted] && [self isUpdated]) { [self setPrimitiveValue:[NSDate date] forKey:@"lastUpdated"]; } */ [super willSave]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Getter/setter methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @dynamic jidStr; @dynamic photoHash; @dynamic lastUpdated; @dynamic waitingForFetch; @dynamic vCardTempRel; @dynamic vCardAvatarRel; - (NSData *)photoData { return self.vCardAvatarRel.photoData; } - (void)setPhotoData:(NSData *)photoData { if (photoData == nil) { if (self.vCardAvatarRel != nil) { [[self managedObjectContext] deleteObject:self.vCardAvatarRel]; [self setPrimitiveValue:nil forKey:@"photoHash"]; } return; } if (self.vCardAvatarRel == nil) { NSString *entityName = NSStringFromClass([XMPPvCardAvatarCoreDataStorageObject class]); self.vCardAvatarRel = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:[self managedObjectContext]]; } [self willChangeValueForKey:@"photoData"]; self.vCardAvatarRel.photoData = photoData; [self didChangeValueForKey:@"photoData"]; [self setPrimitiveValue:[[photoData sha1Digest] hexStringValue] forKey:@"photoHash"]; } - (XMPPvCardTemp *)vCardTemp { return self.vCardTempRel.vCardTemp; } - (void)setVCardTemp:(XMPPvCardTemp *)vCardTemp { if (vCardTemp == nil && self.vCardTempRel != nil) { [[self managedObjectContext] deleteObject:self.vCardTempRel]; return; } if (self.vCardTempRel == nil) { NSString *entityName = NSStringFromClass([XMPPvCardTempCoreDataStorageObject class]); self.vCardTempRel = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:[self managedObjectContext]]; } [self willChangeValueForKey:@"vCardTemp"]; self.vCardTempRel.vCardTemp = vCardTemp; [self didChangeValueForKey:@"vCardTemp"]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark KVO methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + (NSSet *)keyPathsForValuesAffectingPhotoHash { return [NSSet setWithObjects:@"vCardAvatarRel", @"photoData", nil]; } + (NSSet *)keyPathsForValuesAffectingVCardTemp { return [NSSet setWithObject:@"vCardTempRel"]; } @end
04081337-xmpp
Extensions/XEP-0054/CoreDataStorage/XMPPvCardCoreDataStorageObject.m
Objective-C
bsd
5,210
// // XMPPvCardTempCoreDataStorageObject.m // XEP-0054 vCard-temp // // Originally created by Eric Chamberlain on 3/18/11. // #import "XMPPvCardTempCoreDataStorageObject.h" #import "XMPPvCardCoreDataStorageObject.h" @implementation XMPPvCardTempCoreDataStorageObject @dynamic vCardTemp; @dynamic vCard; @end
04081337-xmpp
Extensions/XEP-0054/CoreDataStorage/XMPPvCardTempCoreDataStorageObject.m
Objective-C
bsd
316
// // XMPPvCardTempLabel.m // XEP-0054 vCard-temp // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // Copyright 2010 Martin Morrison. All rights reserved. // #import "XMPPvCardTempLabel.h" #import "XMPPLogging.h" #import <objc/runtime.h> #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_ERROR; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_ERROR; #endif @implementation XMPPvCardTempLabel + (void)initialize { // We use the object_setClass method below to dynamically change the class from a standard NSXMLElement. // The size of the two classes is expected to be the same. // // If a developer adds instance methods to this class, bad things happen at runtime that are very hard to debug. // This check is here to aid future developers who may make this mistake. // // For Fearless And Experienced Objective-C Developers: // It may be possible to support adding instance variables to this class if you seriously need it. // To do so, try realloc'ing self after altering the class, and then initialize your variables. size_t superSize = class_getInstanceSize([NSXMLElement class]); size_t ourSize = class_getInstanceSize([XMPPvCardTempLabel class]); if (superSize != ourSize) { XMPPLogError(@"Adding instance variables to XMPPvCardTempLabel is not currently supported!"); [DDLog flushLog]; exit(15); } } + (XMPPvCardTempLabel *)vCardLabelFromElement:(NSXMLElement *)elem { object_setClass(elem, [XMPPvCardTempLabel class]); return (XMPPvCardTempLabel *)elem; } #pragma mark - #pragma mark Getter/setter methods - (NSArray *)lines { NSArray *elems = [self elementsForName:@"LINE"]; NSMutableArray *lines = [[NSMutableArray alloc] initWithCapacity:[elems count]]; for (NSXMLElement *elem in elems) { [lines addObject:[elem stringValue]]; } NSArray *result = [NSArray arrayWithArray:lines]; [lines release]; return result; } - (void)setLines:(NSArray *)lines { NSArray *elems = [self elementsForName:@"LINE"]; for (NSXMLElement *elem in elems) { [self removeChildAtIndex:[[self children] indexOfObject:elem]]; } for (NSString *line in lines) { NSXMLElement *elem = [NSXMLElement elementWithName:@"LINE"]; [elem setStringValue:line]; [self addChild:elem]; } } @end
04081337-xmpp
Extensions/XEP-0054/XMPPvCardTempLabel.m
Objective-C
bsd
2,311
// // XMPPvCardTempAdr.h // XEP-0054 vCard-temp // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // Copyright 2010 Martin Morrison. All rights reserved. // #import <Foundation/Foundation.h> #import "XMPPvCardTempAdrTypes.h" @interface XMPPvCardTempAdr : XMPPvCardTempAdrTypes @property (nonatomic, assign) NSString *pobox; @property (nonatomic, assign) NSString *extendedAddress; @property (nonatomic, assign) NSString *street; @property (nonatomic, assign) NSString *locality; @property (nonatomic, assign) NSString *region; @property (nonatomic, assign) NSString *postalCode; @property (nonatomic, assign) NSString *country; + (XMPPvCardTempAdr *)vCardAdrFromElement:(NSXMLElement *)elem; @end
04081337-xmpp
Extensions/XEP-0054/XMPPvCardTempAdr.h
Objective-C
bsd
755
// // XMPPvCardTempBase.h // XEP-0054 vCard-temp // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // Copyright 2010 Martin Morrison. All rights reserved. // #import <Foundation/Foundation.h> #import "NSXMLElement+XMPP.h" #define XMPP_VCARD_SET_EMPTY_CHILD(Set, Name) \ if (Set) { \ [self addChild:[NSXMLElement elementWithName:(Name)]]; \ } \ else if (!(Set)) { \ [self removeChildAtIndex:[[self children] indexOfObject:[self elementForName:(Name)]]]; \ } #define XMPP_VCARD_SET_STRING_CHILD(Value, Name) \ NSXMLElement *elem = [self elementForName:(Name)]; \ if ((Value) != nil) \ { \ if (elem == nil) { \ elem = [NSXMLElement elementWithName:(Name)]; \ } \ [elem setStringValue:(Value)]; \ } \ else if (elem != nil) { \ [self removeChildAtIndex:[[self children] indexOfObject:elem]]; \ } #define XMPP_VCARD_SET_N_CHILD(Value, Name) \ NSXMLElement *name = [self elementForName:@"N"]; \ if ((Value) != nil && name == nil) \ { \ name = [NSXMLElement elementWithName:@"N"]; \ [self addChild:name]; \ } \ \ NSXMLElement *part = [name elementForName:(Name)]; \ if ((Value) != nil && part == nil) \ { \ part = [NSXMLElement elementWithName:(Name)]; \ [name addChild:part]; \ } \ \ if (Value) \ { \ [part setStringValue:(Value)]; \ } \ else if (part != nil) \ { \ /* N is mandatory, so we leave it in. */ \ [name removeChildAtIndex:[[self children] indexOfObject:part]]; \ } @interface XMPPvCardTempBase : NSXMLElement <NSCoding> { } @end
04081337-xmpp
Extensions/XEP-0054/XMPPvCardTempBase.h
Objective-C
bsd
2,866
// // XMPPvCardTempModule.m // XEP-0054 vCard-temp // // Created by Eric Chamberlain on 3/17/11. // Copyright 2011 RF.com. All rights reserved. // #import "XMPP.h" #import "XMPPLogging.h" #import "XMPPvCardTempModule.h" // Log levels: off, error, warn, info, verbose // Log flags: trace #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; // | XMPP_LOG_FLAG_TRACE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif @interface XMPPvCardTempModule() - (void)_updatevCardTemp:(XMPPvCardTemp *)vCardTemp forJID:(XMPPJID *)jid; @end @implementation XMPPvCardTempModule @synthesize moduleStorage = _moduleStorage; - (id)init { // This will cause a crash - it's designed to. // Only the init methods listed in XMPPvCardTempModule.h are supported. return [self initWithvCardStorage:nil dispatchQueue:NULL]; } - (id)initWithDispatchQueue:(dispatch_queue_t)queue { // This will cause a crash - it's designed to. // Only the init methods listed in XMPPvCardTempModule.h are supported. return [self initWithvCardStorage:nil dispatchQueue:NULL]; } - (id)initWithvCardStorage:(id <XMPPvCardTempModuleStorage>)storage { return [self initWithvCardStorage:storage dispatchQueue:NULL]; } - (id)initWithvCardStorage:(id <XMPPvCardTempModuleStorage>)storage dispatchQueue:(dispatch_queue_t)queue { NSParameterAssert(storage != nil); if ((self = [super initWithDispatchQueue:queue])) { if ([storage configureWithParent:self queue:moduleQueue]) { _moduleStorage = [storage retain]; } else { XMPPLogError(@"%@: %@ - Unable to configure storage!", THIS_FILE, THIS_METHOD); } } return self; } - (BOOL)activate:(XMPPStream *)aXmppStream { if ([super activate:aXmppStream]) { // Custom code goes here (if needed) return YES; } return NO; } - (void)deactivate { // Custom code goes here (if needed) [super deactivate]; } - (void)dealloc { [_moduleStorage release]; _moduleStorage = nil; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Fetch vCardTemp methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (XMPPvCardTemp *)fetchvCardTempForJID:(XMPPJID *)jid { return [self fetchvCardTempForJID:jid useCache:YES]; } - (XMPPvCardTemp *)fetchvCardTempForJID:(XMPPJID *)jid useCache:(BOOL)useCache { __block XMPPvCardTemp *result; dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPvCardTemp *vCardTemp = nil; if (useCache) { // Try loading from the cache vCardTemp = [_moduleStorage vCardTempForJID:jid xmppStream:xmppStream]; } if (vCardTemp == nil && [_moduleStorage shouldFetchvCardTempForJID:jid xmppStream:xmppStream]) { [xmppStream sendElement:[XMPPvCardTemp iqvCardRequestForJID:jid]]; } result = [vCardTemp retain]; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_sync(moduleQueue, block); return [result autorelease]; } - (XMPPvCardTemp *)myvCardTemp { return [self fetchvCardTempForJID:[xmppStream myJID]]; } - (void)updateMyvCardTemp:(XMPPvCardTemp *)vCardTemp { XMPPvCardTemp *newvCardTemp = [vCardTemp copy]; NSString *elemId = [xmppStream generateUUID]; XMPPIQ *iq = [XMPPIQ iqWithType:@"set" to:nil elementID:elemId child:newvCardTemp]; [xmppStream sendElement:iq]; [self _updatevCardTemp:newvCardTemp forJID:[xmppStream myJID]]; [newvCardTemp release]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Private //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)_updatevCardTemp:(XMPPvCardTemp *)vCardTemp forJID:(XMPPJID *)jid { // this method could be called from anywhere dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPLogVerbose(@"%@: %s %@", THIS_FILE, __PRETTY_FUNCTION__, [jid bare]); [_moduleStorage setvCardTemp:vCardTemp forJID:jid xmppStream:xmppStream]; [(id <XMPPvCardTempModuleDelegate>)multicastDelegate xmppvCardTempModule:self didReceivevCardTemp:vCardTemp forJID:jid]; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPStreamDelegate methods //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq { // This method is invoked on the moduleQueue. // Remember XML heirarchy memory management rules. // The passed parameter is a subnode of the IQ, and we need to pass it to an asynchronous operation. // // Therefore we use vCardTempCopyFromIQ instead of vCardTempSubElementFromIQ. XMPPvCardTemp *vCardTemp = [XMPPvCardTemp vCardTempCopyFromIQ:iq]; if (vCardTemp != nil) { [self _updatevCardTemp:vCardTemp forJID:[iq from]]; return YES; } return NO; } @end
04081337-xmpp
Extensions/XEP-0054/XMPPvCardTempModule.m
Objective-C
bsd
5,465
// // XMPPvCardTempAdrTypes.h // XEP-0054 vCard-temp // // Created by Eric Chamberlain on 3/9/11. // Copyright 2011 RF.com. All rights reserved. // Copyright 2010 Martin Morrison. All rights reserved. // #import <Foundation/Foundation.h> #import "XMPPvCardTempBase.h" @interface XMPPvCardTempAdrTypes : XMPPvCardTempBase @property (nonatomic, assign, setter=setHome:) BOOL isHome; @property (nonatomic, assign, setter=setWork:) BOOL isWork; @property (nonatomic, assign, setter=setParcel:) BOOL isParcel; @property (nonatomic, assign, setter=setPostal:) BOOL isPostal; @property (nonatomic, assign, setter=setDomestic:) BOOL isDomestic; @property (nonatomic, assign, setter=setInternational:) BOOL isInternational; @property (nonatomic, assign, setter=setPreferred:) BOOL isPreferred; @end
04081337-xmpp
Extensions/XEP-0054/XMPPvCardTempAdrTypes.h
Objective-C
bsd
804
#import <Foundation/Foundation.h> #import "XMPPModule.h" #if TARGET_OS_IPHONE #import "DDXML.h" #endif @class XMPPIQ; @class XMPPJID; @class XMPPStream; @protocol XMPPCapabilitiesStorage; @protocol XMPPCapabilitiesDelegate; /** * This class provides support for capabilities discovery. * * It collects our capabilities and publishes them according to the XEP by: * - Injecting the <c/> element into outgoing presence stanzas * - Responding to incoming disco#info queries * * It also collects the capabilities of available resources, * provides a mechanism to persistently store XEP-0115 hased caps, * and makes available a simple API to query (disco#info) a resource or server. **/ @interface XMPPCapabilities : XMPPModule { id <XMPPCapabilitiesStorage> xmppCapabilitiesStorage; NSXMLElement *myCapabilitiesQuery; // Full list of capabilites <query/> NSXMLElement *myCapabilitiesC; // Hashed element <c/> BOOL collectingMyCapabilities; NSMutableSet *discoRequestJidSet; NSMutableDictionary *discoRequestHashDict; NSMutableDictionary *discoTimerJidDict; BOOL autoFetchHashedCapabilities; BOOL autoFetchNonHashedCapabilities; NSTimeInterval capabilitiesRequestTimeout; NSMutableSet *timers; } - (id)initWithCapabilitiesStorage:(id <XMPPCapabilitiesStorage>)storage; - (id)initWithCapabilitiesStorage:(id <XMPPCapabilitiesStorage>)storage dispatchQueue:(dispatch_queue_t)queue; @property (nonatomic, readonly) id <XMPPCapabilitiesStorage> xmppCapabilitiesStorage; /** * Defines fetching behavior for entities using the XEP-0115 standard. * * XEP-0115 defines a technique for hashing capabilities (disco info responses), * and broadcasting them within a presence element. * Due to the standardized hashing technique, capabilities associated with a hash may be persisted indefinitely. * * The end result is that capabilities need to be fetched less often * since they are already known due to the caching of responses. * * The default value is YES. **/ @property (assign) BOOL autoFetchHashedCapabilities; /** * Defines fetching behavior for entities NOT using the XEP-0115 standard. * * Because the capabilities are not associated with a standardized hash, * it is not possible to cache the capabilities between sessions. * * The default value is NO. * * It is recommended you leave this value set to NO unless you * know that you'll need the capabilities of every resource, * and that fetching of the capabilities cannot be delayed. * * You may always fetch the capabilities (if/when needed) via the fetchCapabilitiesForJID method. **/ @property (assign) BOOL autoFetchNonHashedCapabilities; /** * Manually fetch the capabilities for the given jid. * * The jid must be a full jid (user@domain/resource) or a domain JID (domain without user or resource). * You would pass a full jid if you wanted to know the capabilities of a particular user's resource. * You would pass a domain jid if you wanted to know the capabilities of a particular server. * * If there is an existing disco request associated with the given jid, this method does nothing. * * When the capabilities are received, * the xmppCapabilities:didDiscoverCapabilities:forJID: delegate method is invoked. **/ - (void)fetchCapabilitiesForJID:(XMPPJID *)jid; /** * This module automatically collects my capabilities. * See the xmppCapabilities:collectingMyCapabilities: delegate method. * * The design of XEP-115 is such that capabilites are expected to remain rather static. * However, if the capabilities change, this method may be used to perform a manual update. **/ - (void)recollectMyCapabilities; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol XMPPCapabilitiesStorage <NSObject> @required // // // -- PUBLIC METHODS -- // // /** * Returns whether or not we know the capabilities for a given jid. * * The stream parameter is optional. * If given, the jid must have been registered via the given stream. * Otherwise it will match the given jid from any stream this storage instance is managing. **/ - (BOOL)areCapabilitiesKnownForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream; /** * Returns the capabilities for the given jid. * The returned element is the <query/> element response to a disco#info request. * * The stream parameter is optional. * If given, the jid must have been registered via the given stream. * Otherwise it will match the given jid from any stream this storage instance is managing. **/ - (NSXMLElement *)capabilitiesForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream; /** * Returns the capabilities for the given jid. * The returned element is the <query/> element response to a disco#info request. * * The given jid should be a full jid (user@domain/resource) or a domin JID (domain without user or resource). * * If the jid has broadcast capabilities via the legacy format of XEP-0115, * the extension list may optionally be retrieved via the ext parameter. * * For example, the jid may send a presence element like: * * <presence from="jid"> * <c node="imclient.com/caps" ver="1.2" ext="rdserver rdclient avcap"/> * </presence> * * In the above example, the ext string would be set to "rdserver rdclient avcap". * * You may pass nil for extPtr if you don't care about the legacy attributes, * or you could simply use the capabilitiesForJID: method above. * * The stream parameter is optional. * If given, the jid must have been registered via the given stream. * Otherwise it will match the given jid from any stream this storage instance is managing. **/ - (NSXMLElement *)capabilitiesForJID:(XMPPJID *)jid ext:(NSString **)extPtr xmppStream:(XMPPStream *)stream; // // // -- PRIVATE METHODS -- // // These methods are designed to be used ONLY by the XMPPCapabilities class. // // /** * Configures the capabilities storage class, passing it's parent and parent's dispatch queue. * * This method is called by the init methods of the XMPPCapabilities class. * This method is designed to inform the storage class of it's parent * and of the dispatch queue the parent will be operating on. * * A storage class may choose to operate on the same queue as it's parent, * as the majority of the time it will be getting called by the parent. * If both are operating on the same queue, the combination may run faster. * * Some storage classes support multiple xmppStreams, * and may choose to operate on their own internal queue. * * This method should return YES if it was configured properly. * It should return NO only if configuration failed. * For example, a storage class designed to be used only with a single xmppStream is being added to a second stream. * The XMPPCapabilites class is configured to ignore the passed * storage class in it's init method if this method returns NO. **/ - (BOOL)configureWithParent:(XMPPCapabilities *)aParent queue:(dispatch_queue_t)queue; /** * Sets metadata for the given jid. * * This method should return: * - YES if the capabilities for the given jid are known. * - NO if the capabilities for the given jid are NOT known. * * If the hash and algorithm are given, and an associated set of capabilities matches the hash/algorithm, * this method should link the jid to the capabilities and return YES. * * If the linked set of capabilities was not previously linked to the jid, * the newCapabilities parameter shoud be filled out. * * This method may be called multiple times for a given jid with the same information. * If this method sets the newCapabilitiesPtr parameter, * the XMPPCapabilities module will invoke the xmppCapabilities:didDiscoverCapabilities:forJID: delegate method. * This delegate method is designed to be invoked only when the capabilities for the given JID have changed. * That is, the capabilities for the jid have been discovered for the first time (jid just signed in) * or the capabilities for the given jid have changed (jid broadcast new capabilities). **/ - (BOOL)setCapabilitiesNode:(NSString *)node ver:(NSString *)ver ext:(NSString *)ext hash:(NSString *)hash algorithm:(NSString *)hashAlg forJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream andGetNewCapabilities:(NSXMLElement **)newCapabilitiesPtr; /** * Fetches the associated capabilities hash for a given jid. * * If the jid is not associated with a capabilities hash, this method should return NO. * Otherwise it should return YES, and set the corresponding variables. **/ - (BOOL)getCapabilitiesHash:(NSString **)hashPtr algorithm:(NSString **)hashAlgPtr forJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream; /** * Clears any associated hash from a jid. * If the jid is linked to a set of capabilities, it should be unlinked. * * This method should not clear the actual capabilities information itself. * It should simply unlink the connection between the jid and the capabilities. **/ - (void)clearCapabilitiesHashAndAlgorithmForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream; /** * Gets the metadata for the given jid. * * If the capabilities are known, the areCapabilitiesKnown boolean should be set to YES. **/ - (void)getCapabilitiesKnown:(BOOL *)areCapabilitiesKnownPtr failed:(BOOL *)haveFailedFetchingBeforePtr node:(NSString **)nodePtr ver:(NSString **)verPtr ext:(NSString **)extPtr hash:(NSString **)hashPtr algorithm:(NSString **)hashAlgPtr forJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream; /** * Sets the capabilities associated with a given hash. * * Since the capabilities are linked to a hash, these capabilities (and associated hash) * should be persisted to disk and persisted between multiple sessions/streams. * * It is the responsibility of the storage implementation to link the * associated jids (those with the given hash) to the given set of capabilities. * * Implementation Note: * * If we receive multiple simultaneous presence elements from * multiple jids all broadcasting the same capabilities hash: * * - A single disco request will be sent to one of the jids. * - When the response comes back, the setCapabilities:forHash:algorithm: method will be invoked. * * The setCapabilities:forJID: method will NOT be invoked for each corresponding jid. * This is by design to allow the storage implementation to optimize itself. **/ - (void)setCapabilities:(NSXMLElement *)caps forHash:(NSString *)hash algorithm:(NSString *)hashAlg; /** * Sets the capabilities for a given jid. * * The jid is guaranteed NOT to be associated with a capabilities hash. * * Since the capabilities are NOT linked to a hash, * these capabilities should not be persisted between multiple sessions/streams. * See the various clear methods below. **/ - (void)setCapabilities:(NSXMLElement *)caps forJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream; /** * Marks the disco fetch request as failed so we know not to bother trying again. * * This is temporary metadata associated with the jid. * It should be cleared when we go unavailable or offline, or if the given jid goes unavailable. * See the various clear methods below. **/ - (void)setCapabilitiesFetchFailedForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream; /** * This method is called when we go unavailable or offline. * * This method should clear all metadata (node, ver, ext, hash, algorithm, failed) from all jids in the roster. * All jids should be unlinked from associated capabilities. * * If the associated capabilities are persistent, they should not be cleared. * That is, if the associated capabilities are associated with a hash, they should be persisted. * * Non persistent capabilities (those not associated with a hash) * should be cleared at this point as they will no longer be linked to any users. **/ - (void)clearAllNonPersistentCapabilitiesForXMPPStream:(XMPPStream *)stream; /** * This method is called when the given jid goes unavailable. * * This method should clear all metadata (node, ver, ext, hash ,algorithm, failed) from the given jid. * The jid should be unlinked from associated capabilities. * * If the associated capabilities are persistent, they should not be cleared. * That is, if the associated capabilities are associated with a hash, they should be persisted. * * Non persistent capabilities (those not associated with a hash) should be cleared. **/ - (void)clearNonPersistentCapabilitiesForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol XMPPCapabilitiesDelegate @optional /** * Use this delegate method to add specific capabilities. * This method in invoked automatically when the stream is connected for the first time, * or if the module detects an outgoing presence element and my capabilities haven't been collected yet * * The design of XEP-115 is such that capabilites are expected to remain rather static. * However, if the capabilities change, the recollectMyCapabilities method may be used to perform a manual update. **/ - (void)xmppCapabilities:(XMPPCapabilities *)sender collectingMyCapabilities:(NSXMLElement *)query; /** * Invoked when capabilities have been discovered for an available JID. * * The caps element is the <query/> element response to a disco#info request. **/ - (void)xmppCapabilities:(XMPPCapabilities *)sender didDiscoverCapabilities:(NSXMLElement *)caps forJID:(XMPPJID *)jid; @end
04081337-xmpp
Extensions/XEP-0115/XMPPCapabilities.h
Objective-C
bsd
14,213
#import "XMPP.h" #import "XMPPLogging.h" #import "XMPPCapabilities.h" #import "NSData+XMPP.h" // Log levels: off, error, warn, info, verbose // Log flags: trace #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_VERBOSE; // | XMPP_LOG_FLAG_TRACE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif /** * Defines the timeout for a capabilities request. * * There are two reasons to have a timeout: * - To prevent the discoRequest variables from growing indefinitely if responses are not received. * - If a request is sent to a jid broadcasting a capabilities hash, and it does not respond within the timeout, * we can then send a request to a different jid broadcasting the same capabilities hash. * * Remember, if multiple jids all broadcast the same capabilities hash, * we only (initially) send a disco request to the first jid. * This is an obvious optimization to remove unnecessary traffic and cpu load. * * However, if that jid doesn't respond within a sensible time period, * we should move on to the next jid in the list. **/ #define CAPABILITIES_REQUEST_TIMEOUT 30.0 // seconds /** * Define various xmlns values. **/ #define XMLNS_DISCO_INFO @"http://jabber.org/protocol/disco#info" #define XMLNS_CAPS @"http://jabber.org/protocol/caps" /** * Application identifier. * According to the XEP it is RECOMMENDED for the value of the 'node' attribute to be an HTTP URL. **/ #ifndef DISCO_NODE #define DISCO_NODE @"http://code.google.com/p/xmppframework" #endif @interface GCDTimerWrapper : NSObject { dispatch_source_t timer; } - (id)initWithDispatchTimer:(dispatch_source_t)aTimer; - (void)cancel; @end @interface XMPPCapabilities (PrivateAPI) - (void)continueCollectMyCapabilities:(NSXMLElement *)query; - (void)maybeQueryNextJidWithHashKey:(NSString *)key dueToHashMismatch:(BOOL)hashMismatch; - (void)setupTimeoutForDiscoRequestFromJID:(XMPPJID *)jid; - (void)setupTimeoutForDiscoRequestFromJID:(XMPPJID *)jid withHashKey:(NSString *)key; - (void)cancelTimeoutForDiscoRequestFromJID:(XMPPJID *)jid; - (void)processTimeoutWithHashKey:(NSString *)key; - (void)processTimeoutWithJID:(XMPPJID *)jid; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPCapabilities @dynamic xmppCapabilitiesStorage; @dynamic autoFetchHashedCapabilities; @dynamic autoFetchNonHashedCapabilities; - (id)init { // This will cause a crash - it's designed to. // Only the init methods listed in XMPPCapabilities.h are supported. return [self initWithCapabilitiesStorage:nil dispatchQueue:NULL]; } - (id)initWithDispatchQueue:(dispatch_queue_t)queue { // This will cause a crash - it's designed to. // Only the init methods listed in XMPPCapabilities.h are supported. return [self initWithCapabilitiesStorage:nil dispatchQueue:queue]; } - (id)initWithCapabilitiesStorage:(id <XMPPCapabilitiesStorage>)storage { return [self initWithCapabilitiesStorage:storage dispatchQueue:NULL]; } - (id)initWithCapabilitiesStorage:(id <XMPPCapabilitiesStorage>)storage dispatchQueue:(dispatch_queue_t)queue { NSParameterAssert(storage != nil); if ((self = [super initWithDispatchQueue:queue])) { if ([storage configureWithParent:self queue:moduleQueue]) { xmppCapabilitiesStorage = [storage retain]; } else { XMPPLogError(@"%@: %@ - Unable to configure storage!", THIS_FILE, THIS_METHOD); } // discoRequestJidSet: // // A set which contains every JID for which a current disco request applies. // Note that one disco request may satisfy multiple jids in this set. // This is the case if multiple jids broadcast the same capabilities hash. // When this happens we send a single disco request to one of the jids, // but every single jid with that hash is included in this set. // This allows us to quickly and easily see if there is an outstanding disco request for a jid. // // discoRequestHashDict: // // A dictionary which tells us about disco requests that have been sent concerning hashed capabilities. // It maps from hash (key=hash+hashAlgorithm) to an array of jids that use this hash. // // discoTimerJidDict: // // A dictionary that contains all the timers for timing out disco requests. // It maps from jid to associated timer. discoRequestJidSet = [[NSMutableSet alloc] init]; discoRequestHashDict = [[NSMutableDictionary alloc] init]; discoTimerJidDict = [[NSMutableDictionary alloc] init]; autoFetchHashedCapabilities = YES; autoFetchNonHashedCapabilities = NO; } return self; } - (BOOL)activate:(XMPPStream *)aXmppStream { if ([super activate:aXmppStream]) { // Custom code goes here (if needed) return YES; } return NO; } - (void)deactivate { // Custom code goes here (if needed) [super deactivate]; } - (void)dealloc { [xmppCapabilitiesStorage release]; [myCapabilitiesQuery release]; [myCapabilitiesC release]; [discoRequestJidSet release]; [discoRequestHashDict release]; for (GCDTimerWrapper *timerWrapper in discoTimerJidDict) { [timerWrapper cancel]; } [discoTimerJidDict release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Configuration //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (id <XMPPCapabilitiesStorage>)xmppCapabilitiesStorage { return xmppCapabilitiesStorage; } - (BOOL)autoFetchHashedCapabilities { __block BOOL result; dispatch_block_t block = ^{ result = autoFetchHashedCapabilities; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_sync(moduleQueue, block); return result; } - (void)setAutoFetchHashedCapabilities:(BOOL)flag { dispatch_block_t block = ^{ autoFetchHashedCapabilities = flag; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (BOOL)autoFetchNonHashedCapabilities { __block BOOL result; dispatch_block_t block = ^{ result = autoFetchNonHashedCapabilities; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_sync(moduleQueue, block); return result; } - (void)setAutoFetchNonHashedCapabilities:(BOOL)flag { dispatch_block_t block = ^{ autoFetchNonHashedCapabilities = flag; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Hashing //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static NSString* encodeLt(NSString *str) { // From the RFC: // // If the string "&lt;" appears in any of the hash values, // then that value MUST NOT convert it to "<" because // completing such a conversion would open the protocol to trivial attacks. // // All of the XML libraries perform this conversion for us automatically (which makes sense). // Furthermore, it is illegal for an attribute or namespace value to have a raw "<" character (as per XML). // So the solution is very simple: // Just convert any '<' characters to the escaped "&lt;" string. return [str stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"]; } static NSInteger sortIdentities(NSXMLElement *identity1, NSXMLElement *identity2, void *context) { // Sort the service discovery identities by category and then by type and then by xml:lang (if it exists). // // All sort operations MUST be performed using "i;octet" collation as specified in Section 9.3 of RFC 4790. NSComparisonResult result; NSString *category1 = [identity1 attributeStringValueForName:@"category" withDefaultValue:@""]; NSString *category2 = [identity2 attributeStringValueForName:@"category" withDefaultValue:@""]; category1 = encodeLt(category1); category2 = encodeLt(category2); result = [category1 compare:category2 options:NSLiteralSearch]; if (result != NSOrderedSame) { return result; } NSString *type1 = [identity1 attributeStringValueForName:@"type" withDefaultValue:@""]; NSString *type2 = [identity2 attributeStringValueForName:@"type" withDefaultValue:@""]; type1 = encodeLt(type1); type2 = encodeLt(type2); result = [type1 compare:type2 options:NSLiteralSearch]; if (result != NSOrderedSame) { return result; } NSString *lang1 = [identity1 attributeStringValueForName:@"xml:lang" withDefaultValue:@""]; NSString *lang2 = [identity2 attributeStringValueForName:@"xml:lang" withDefaultValue:@""]; lang1 = encodeLt(lang1); lang2 = encodeLt(lang2); result = [lang1 compare:lang2 options:NSLiteralSearch]; if (result != NSOrderedSame) { return result; } NSString *name1 = [identity1 attributeStringValueForName:@"name" withDefaultValue:@""]; NSString *name2 = [identity2 attributeStringValueForName:@"name" withDefaultValue:@""]; name1 = encodeLt(name1); name2 = encodeLt(name2); return [name1 compare:name2 options:NSLiteralSearch]; } static NSInteger sortFeatures(NSXMLElement *feature1, NSXMLElement *feature2, void *context) { // All sort operations MUST be performed using "i;octet" collation as specified in Section 9.3 of RFC 4790. NSString *var1 = [feature1 attributeStringValueForName:@"var" withDefaultValue:@""]; NSString *var2 = [feature2 attributeStringValueForName:@"var" withDefaultValue:@""]; var1 = encodeLt(var1); var2 = encodeLt(var2); return [var1 compare:var2 options:NSLiteralSearch]; } static NSString* extractFormTypeValue(NSXMLElement *form) { // From the RFC: // // If the FORM_TYPE field is not of type "hidden" or the form does not // include a FORM_TYPE field, ignore the form but continue processing. // // If the FORM_TYPE field contains more than one <value/> element with different XML character data, // consider the entire response to be ill-formed. // This method will return: // // - The form type's value if it exists // - An empty string if it does not contain a form type field (or the form type is not of type hidden) // - Nil if the form type is invalid (contains more than one <value/> element which are different) // // In other words // // - Non-empty string -> proper form // - Empty string -> ignore form // - Nil -> Entire response is to be considered ill-formed // // The returned value is properly encoded via encodeLt() and contains the trailing '<' character. NSArray *fields = [form elementsForName:@"field"]; for (NSXMLElement *field in fields) { NSString *var = [field attributeStringValueForName:@"var"]; NSString *type = [field attributeStringValueForName:@"type"]; if ([var isEqualToString:@"FORM_TYPE"] && [type isEqualToString:@"hidden"]) { NSArray *values = [field elementsForName:@"value"]; if ([values count] > 0) { if ([values count] > 1) { NSString *baseValue = [[values objectAtIndex:0] stringValue]; NSUInteger i; for (i = 1; i < [values count]; i++) { NSString *value = [[values objectAtIndex:i] stringValue]; if (![value isEqualToString:baseValue]) { // Multiple <value/> elements with differing XML character data return nil; } } } NSString *result = [[values lastObject] stringValue]; if (result == nil) { // This is why the result contains the trailing '<' character. result = @""; } return [NSString stringWithFormat:@"%@<", encodeLt(result)]; } } } return @""; } static NSInteger sortForms(NSXMLElement *form1, NSXMLElement *form2, void *context) { // Sort the forms by the FORM_TYPE (i.e., by the XML character data of the <value/> element. // // All sort operations MUST be performed using "i;octet" collation as specified in Section 9.3 of RFC 4790. NSString *formTypeValue1 = extractFormTypeValue(form1); NSString *formTypeValue2 = extractFormTypeValue(form2); // The formTypeValue variable is guaranteed to be properly encoded. return [formTypeValue1 compare:formTypeValue2 options:NSLiteralSearch]; } static NSInteger sortFormFields(NSXMLElement *field1, NSXMLElement *field2, void *context) { // Sort the fields by the "var" attribute. // // All sort operations MUST be performed using "i;octet" collation as specified in Section 9.3 of RFC 4790. NSString *var1 = [field1 attributeStringValueForName:@"var" withDefaultValue:@""]; NSString *var2 = [field2 attributeStringValueForName:@"var" withDefaultValue:@""]; var1 = encodeLt(var1); var2 = encodeLt(var2); return [var1 compare:var2 options:NSLiteralSearch]; } static NSInteger sortFieldValues(NSXMLElement *value1, NSXMLElement *value2, void *context) { NSString *str1 = [value1 stringValue]; NSString *str2 = [value2 stringValue]; if (str1 == nil) str1 = @""; if (str2 == nil) str2 = @""; str1 = encodeLt(str1); str2 = encodeLt(str2); return [str1 compare:str2 options:NSLiteralSearch]; } - (NSString *)hashCapabilitiesFromQuery:(NSXMLElement *)query { if (query == nil) return nil; NSMutableSet *set = [NSMutableSet set]; NSMutableString *s = [NSMutableString string]; NSArray *identities = [[query elementsForName:@"identity"] sortedArrayUsingFunction:sortIdentities context:NULL]; for (NSXMLElement *identity in identities) { // Format as: category / type / lang / name NSString *category = [identity attributeStringValueForName:@"category" withDefaultValue:@""]; NSString *type = [identity attributeStringValueForName:@"type" withDefaultValue:@""]; NSString *lang = [identity attributeStringValueForName:@"xml:lang" withDefaultValue:@""]; NSString *name = [identity attributeStringValueForName:@"name" withDefaultValue:@""]; category = encodeLt(category); type = encodeLt(type); lang = encodeLt(lang); name = encodeLt(name); NSString *mash = [NSString stringWithFormat:@"%@/%@/%@/%@<", category, type, lang, name]; // Section 5.4, rule 3.3: // // If the response includes more than one service discovery identity with // the same category/type/lang/name, consider the entire response to be ill-formed. if ([set containsObject:mash]) { return nil; } else { [set addObject:mash]; } [s appendString:mash]; } [set removeAllObjects]; NSArray *features = [[query elementsForName:@"feature"] sortedArrayUsingFunction:sortFeatures context:NULL]; for (NSXMLElement *feature in features) { NSString *var = [feature attributeStringValueForName:@"var" withDefaultValue:@""]; var = encodeLt(var); NSString *mash = [NSString stringWithFormat:@"%@<", var]; // Section 5.4, rule 3.4: // // If the response includes more than one service discovery feature with the // same XML character data, consider the entire response to be ill-formed. if ([set containsObject:mash]) { return nil; } else { [set addObject:mash]; } [s appendString:mash]; } [set removeAllObjects]; NSArray *unsortedForms = [query elementsForLocalName:@"x" URI:@"jabber:x:data"]; NSArray *forms = [unsortedForms sortedArrayUsingFunction:sortForms context:NULL]; for (NSXMLElement *form in forms) { NSString *formTypeValue = extractFormTypeValue(form); if (formTypeValue == nil) { // Invalid according to section 5.4, rule 3.5 return nil; } if ([formTypeValue length] == 0) { // Ignore according to section 5.4, rule 3.6 continue; } // Note: The formTypeValue is properly encoded and contains the trailing '<' character. [s appendString:formTypeValue]; NSArray *fields = [[form elementsForName:@"field"] sortedArrayUsingFunction:sortFormFields context:NULL]; for (NSXMLElement *field in fields) { // For each field other than FORM_TYPE: // // 1. Append the value of the var attribute, followed by the '<' character. // 2. Sort values by the XML character data of the <value/> element. // 3. For each <value/> element, append the XML character data, followed by the '<' character. NSString *var = [field attributeStringValueForName:@"var" withDefaultValue:@""]; var = encodeLt(var); if ([var isEqualToString:@"FORM_TYPE"]) { continue; } [s appendFormat:@"%@<", var]; NSArray *values = [[field elementsForName:@"value"] sortedArrayUsingFunction:sortFieldValues context:NULL]; for (NSXMLElement *value in values) { NSString *str = [value stringValue]; if (str == nil) { str = @""; } str = encodeLt(str); [s appendFormat:@"%@<", str]; } } } NSData *data = [s dataUsingEncoding:NSUTF8StringEncoding]; NSData *hash = [data sha1Digest]; return [hash base64Encoded]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Key Conversions //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSString *)keyFromHash:(NSString *)hash algorithm:(NSString *)hashAlg { return [NSString stringWithFormat:@"%@-%@", hash, hashAlg]; } - (BOOL)getHash:(NSString **)hashPtr algorithm:(NSString **)hashAlgPtr fromKey:(NSString *)key { if (key == nil) return NO; NSRange range = [key rangeOfString:@"-"]; if (range.location == NSNotFound) { return NO; } if (hashPtr) { *hashPtr = [key substringToIndex:range.location]; } if (hashAlgPtr) { *hashAlgPtr = [key substringFromIndex:(range.location + range.length)]; } return YES; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Logic //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)collectMyCapabilities { // This method must be invoked on the moduleQueue NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); if (collectingMyCapabilities) { XMPPLogInfo(@"%@: %@ - Existing collection already in progress", [self class], THIS_METHOD); return; } [myCapabilitiesQuery release]; myCapabilitiesQuery = nil; [myCapabilitiesC release]; myCapabilitiesC = nil; collectingMyCapabilities = YES; // Create new query and add standard features // // <query xmlns="http://jabber.org/protocol/disco#info"> // <feature var='http://jabber.org/protocol/disco#info'/> // <feature var="http://jabber.org/protocol/caps"/> // </query> NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:XMLNS_DISCO_INFO]; NSXMLElement *feature1 = [NSXMLElement elementWithName:@"feature"]; [feature1 addAttributeWithName:@"var" stringValue:XMLNS_DISCO_INFO]; NSXMLElement *feature2 = [NSXMLElement elementWithName:@"feature"]; [feature2 addAttributeWithName:@"var" stringValue:XMLNS_CAPS]; [query addChild:feature1]; [query addChild:feature2]; // Now prompt the delegates to add any additional features. SEL selector = @selector(xmppCapabilities:collectingMyCapabilities:); if ([multicastDelegate countForSelector:selector] == 0) { // None of the delegates implement the method. // Use a shortcut. [self continueCollectMyCapabilities:query]; } else { // Query all interested delegates. // This must be done serially to allow them to alter the element in a thread-safe manner. GCDMulticastDelegateEnumerator *delegateEnumerator = [multicastDelegate delegateEnumerator]; dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(concurrentQueue, ^{ NSAutoreleasePool *outerPool = [[NSAutoreleasePool alloc] init]; // Allow delegates to modify outgoing element id del; dispatch_queue_t dq; while ([delegateEnumerator getNextDelegate:&del delegateQueue:&dq forSelector:selector]) { dispatch_sync(dq, ^{ NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init]; [del xmppCapabilities:self collectingMyCapabilities:query]; [innerPool release]; }); } dispatch_async(moduleQueue, ^{ NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init]; [self continueCollectMyCapabilities:query]; [innerPool release]; }); [outerPool drain]; }); } } - (void)continueCollectMyCapabilities:(NSXMLElement *)query { // This method must be invoked on the moduleQueue NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); collectingMyCapabilities = NO; myCapabilitiesQuery = [query retain]; XMPPLogVerbose(@"%@: My capabilities:\n%@", THIS_FILE, [query XMLStringWithOptions:(NSXMLNodeCompactEmptyElement | NSXMLNodePrettyPrint)]); NSString *hash = [self hashCapabilitiesFromQuery:query]; if (hash == nil) { XMPPLogWarn(@"%@: Unable to hash capabilites (in order to send in presense element)\n", "Perhaps there are duplicate advertised features...\n%@", THIS_FILE, [query XMLStringWithOptions:(NSXMLNodeCompactEmptyElement | NSXMLNodePrettyPrint)]); return; } NSString *hashAlg = @"sha-1"; // Cache the hash [xmppCapabilitiesStorage setCapabilities:query forHash:hash algorithm:hashAlg]; // Create the c element, which will be added to normal outgoing presence elements. // // <c xmlns="http://jabber.org/protocol/caps" // hash="sha-1" // node="http://code.google.com/p/xmppframework" // ver="QgayPKawpkPSDYmwT/WM94uA1u0="/> myCapabilitiesC = [[NSXMLElement alloc] initWithName:@"c" xmlns:XMLNS_CAPS]; [myCapabilitiesC addAttributeWithName:@"hash" stringValue:hashAlg]; [myCapabilitiesC addAttributeWithName:@"node" stringValue:DISCO_NODE]; [myCapabilitiesC addAttributeWithName:@"ver" stringValue:hash]; // If the collection process started when the stream was connected, // and ended up taking so long as to not be available when the presence was sent, // we should re-broadcast our presence now that we know what our capabilities are. XMPPPresence *myPresence = [xmppStream myPresence]; if (myPresence) { [xmppStream sendElement:myPresence]; } } - (void)recollectMyCapabilities { // This is a public method. // It may be invoked on any thread/queue. dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self collectMyCapabilities]; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (void)sendDiscoInfoQueryTo:(XMPPJID *)jid withNode:(NSString *)node ver:(NSString *)ver { // <iq to="romeo@montague.lit/orchard" id="uuid" type="get"> // <query xmlns="http://jabber.org/protocol/disco#info" node="[node]#[ver]"/> // </iq> // // Note: // Some xmpp clients will return an error if we don't specify the proper query node. // Some xmpp clients will return an error if we don't include an id attribute in the iq. NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:XMLNS_DISCO_INFO]; if (node && ver) { NSString *nodeValue = [NSString stringWithFormat:@"%@#%@", node, ver]; [query addAttributeWithName:@"node" stringValue:nodeValue]; } XMPPIQ *iq = [XMPPIQ iqWithType:@"get" to:jid elementID:[xmppStream generateUUID] child:query]; [xmppStream sendElement:iq]; } - (void)fetchCapabilitiesForJID:(XMPPJID *)jid { // This is a public method. // It may be invoked on any thread/queue. dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; if ([discoRequestJidSet containsObject:jid]) { // We're already requesting capabilities concerning this JID [pool drain]; return; } BOOL areCapabilitiesKnown; BOOL haveFailedFetchingBefore; NSString *node = nil; NSString *ver = nil; NSString *hash = nil; NSString *hashAlg = nil; [xmppCapabilitiesStorage getCapabilitiesKnown:&areCapabilitiesKnown failed:&haveFailedFetchingBefore node:&node ver:&ver ext:nil hash:&hash algorithm:&hashAlg forJID:jid xmppStream:xmppStream]; if (areCapabilitiesKnown) { // We already know the capabilities for this JID [pool drain]; return; } if (haveFailedFetchingBefore) { // We've already sent a fetch request to the JID in the past, which failed. [pool drain]; return; } NSString *key = nil; if (hash && hashAlg) { // This jid is associated with a capabilities hash. // // Now, we've verified that the jid is not in the discoRequestJidSet. // But consider the following scenario. // // - autoFetchCapabilities is false. // - We receive 2 presence elements from 2 different jids, both advertising the same capabilities hash. // - This method is called for the first jid. // - This method is then immediately called for the second jid. // // Now since autoFetchCapabilities is false, the second jid will not be in the discoRequestJidSet. // However, there is still a disco request that concerns the jid. key = [self keyFromHash:hash algorithm:hashAlg]; NSMutableArray *jids = [discoRequestHashDict objectForKey:key]; if (jids) { // We're already requesting capabilities concerning this JID. // That is, there is another JID with the same hash, and we've already sent a disco request to it. [jids addObject:jid]; [discoRequestJidSet addObject:jid]; [pool drain]; return; } // The first object in the jids array is the index of the last jid that we've sent a disco request to. // This is used in case the jid does not respond. NSNumber *requestIndexNum = [NSNumber numberWithUnsignedInteger:1]; jids = [NSMutableArray arrayWithObjects:requestIndexNum, jid, nil]; [discoRequestHashDict setObject:jids forKey:key]; [discoRequestJidSet addObject:jid]; } else { [discoRequestJidSet addObject:jid]; } // Send disco#info query [self sendDiscoInfoQueryTo:jid withNode:node ver:ver]; // Setup request timeout if (key) { [self setupTimeoutForDiscoRequestFromJID:jid withHashKey:key]; } else { [self setupTimeoutForDiscoRequestFromJID:jid]; } [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } /** * Invoked when an available presence element is received with * a capabilities child element that conforms to the XEP-0115 standard. **/ - (void)handlePresenceCapabilities:(NSXMLElement *)c fromJID:(XMPPJID *)jid { // This method must be invoked on the moduleQueue NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); XMPPLogTrace2(@"%@: %@ %@", THIS_FILE, THIS_METHOD, jid); // <presence from="romeo@montague.lit/orchard"> // <c xmlns="http://jabber.org/protocol/caps" // hash="sha-1" // node="http://code.google.com/p/exodus" // ver="QgayPKawpkPSDYmwT/WM94uA1u0="/> // </presence> NSString *node = [c attributeStringValueForName:@"node"]; NSString *ver = [c attributeStringValueForName:@"ver"]; NSString *hash = [c attributeStringValueForName:@"hash"]; if ((node == nil) || (ver == nil)) { // Invalid capabilities node! if (autoFetchNonHashedCapabilities) { [self fetchCapabilitiesForJID:jid]; } return; } // Note: We already checked the hash variable in the xmppStream:didReceivePresence: method below. // Remember: hash="sha-1" ver="ABC-Actual-Hash-DEF". // It's a bit confusing as it was designed this way for backwards compatibility with v 1.4 and below. NSXMLElement *newCapabilities = nil; BOOL areCapabilitiesKnown = [xmppCapabilitiesStorage setCapabilitiesNode:node ver:ver ext:nil hash:ver // Yes, this is correct (see above) algorithm:hash // Ditto forJID:jid xmppStream:xmppStream andGetNewCapabilities:&newCapabilities]; if (areCapabilitiesKnown) { XMPPLogVerbose(@"%@: Capabilities already known for jid(%@) with hash(%@)", THIS_FILE, jid, ver); if (newCapabilities) { // This is the first time we've linked the jid with the set of capabilities. // We didn't need to do any lookups due to hashing and caching. // Notify the delegate(s) [multicastDelegate xmppCapabilities:self didDiscoverCapabilities:newCapabilities forJID:jid]; } // The capabilities for this hash are already known return; } // Should we automatically fetch the capabilities? if (!autoFetchHashedCapabilities) { return; } // Are we already fetching the capabilities? NSString *key = [self keyFromHash:ver algorithm:hash]; NSMutableArray *jids = [discoRequestHashDict objectForKey:key]; if (jids) { XMPPLogVerbose(@"%@: We're already fetching capabilities for hash(%@)", THIS_FILE, ver); // Is the jid already included in this list? // // There are actually two ways we can answer this question. // - Invoke containsObject on the array (jids) // - Invoke containsObject on the set (discoRequestJidSet) // // This is much faster to do on a set. if (![discoRequestJidSet containsObject:jid]) { [discoRequestJidSet addObject:jid]; [jids addObject:jid]; } // We've already sent a disco request concerning this hash. return; } // We've never sent a request for this hash. // Add the jid to the discoRequest variables. // Note: The first object in the jids array is the index of the last jid that we've sent a disco request to. // This is used in case the jid does not respond. // // Here's the scenario: // We receive 5 presence elements from 5 different jids, // all advertising the same capabilities via the same hash. // We don't want to waste bandwidth and cpu by sending a disco request to all 5 jids. // So we send a disco request to the first jid. // But then what happens if that jid never responds? // Perhaps it went offline before it could get the message. // After a period of time ellapses, we should send a request to the next jid in the list. // So how do we know what the next jid in the list is? // Via the requestIndexNum of course. NSNumber *requestIndexNum = [NSNumber numberWithUnsignedInteger:1]; jids = [NSMutableArray arrayWithObjects:requestIndexNum, jid, nil]; [discoRequestHashDict setObject:jids forKey:key]; [discoRequestJidSet addObject:jid]; // Send disco#info query [self sendDiscoInfoQueryTo:jid withNode:node ver:ver]; // Setup request timeout [self setupTimeoutForDiscoRequestFromJID:jid withHashKey:key]; } /** * Invoked when an available presence element is received with * a capabilities child element that implements the legacy version of XEP-0115. **/ - (void)handleLegacyPresenceCapabilities:(NSXMLElement *)c fromJID:(XMPPJID *)jid { // This method must be invoked on the moduleQueue NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); XMPPLogTrace2(@"%@: %@ %@", THIS_FILE, THIS_METHOD, jid); NSString *node = [c attributeStringValueForName:@"node"]; NSString *ver = [c attributeStringValueForName:@"ver"]; NSString *ext = [c attributeStringValueForName:@"ext"]; if ((node == nil) || (ver == nil)) { // Invalid capabilities node! if (autoFetchNonHashedCapabilities) { [self fetchCapabilitiesForJID:jid]; } return; } BOOL areCapabilitiesKnown = [xmppCapabilitiesStorage setCapabilitiesNode:node ver:ver ext:ext hash:nil algorithm:nil forJID:jid xmppStream:xmppStream andGetNewCapabilities:nil]; if (areCapabilitiesKnown) { XMPPLogVerbose(@"%@: Capabilities already known for jid(%@)", THIS_FILE, jid); // The capabilities for this jid are already known return; } // Should we automatically fetch the capabilities? if (!autoFetchNonHashedCapabilities) { return; } // Are we already fetching the capabilities? if ([discoRequestJidSet containsObject:jid]) { XMPPLogVerbose(@"%@: We're already fetching capabilities for jid(%@)", THIS_FILE, jid); // We've already sent a disco request to this jid. return; } [discoRequestJidSet addObject:jid]; // Send disco#info query [self sendDiscoInfoQueryTo:jid withNode:node ver:ver]; // Setup request timeout [self setupTimeoutForDiscoRequestFromJID:jid]; } /** * Invoked when we receive a disco request (request for our capabilities). * We should response with the proper disco response. **/ - (void)handleDiscoRequest:(XMPPIQ *)iqRequest { // This method must be invoked on the moduleQueue NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); if (myCapabilitiesQuery == nil) { // It appears we haven't collected our list of capabilites yet. // This will need to be done before we can add the hash to the outgoing presence element. [self collectMyCapabilities]; } else if (myCapabilitiesC) { NSXMLElement *queryRequest = [iqRequest childElement]; NSString *node = [queryRequest attributeStringValueForName:@"node"]; // <iq to="jid" id="id" type="result"> // <query xmlns="http://jabber.org/protocol/disco#info"> // <feature var="feature1"/> // <feature var="feature2"/> // </query> // </iq> NSXMLElement *query = [[myCapabilitiesQuery copy] autorelease]; if (node) { [query addAttributeWithName:@"node" stringValue:node]; } XMPPIQ *iqResponse = [XMPPIQ iqWithType:@"result" to:[iqRequest from] elementID:[iqRequest elementID] child:query]; [xmppStream sendElement:iqResponse]; } } /** * Invoked when we receive a response to one of our previously sent disco requests. **/ - (void)handleDiscoResponse:(NSXMLElement *)querySubElement fromJID:(XMPPJID *)jid { // This method must be invoked on the moduleQueue NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); // Remember XML hiearchy memory management rules. // The passed parameter is a subnode of the IQ, and we need to pass it asynchronously to storge / delegate(s). NSXMLElement *query = [[querySubElement copy] autorelease]; NSString *hash = nil; NSString *hashAlg = nil; BOOL hashResponse = [xmppCapabilitiesStorage getCapabilitiesHash:&hash algorithm:&hashAlg forJID:jid xmppStream:xmppStream]; if (hashResponse) { XMPPLogVerbose(@"%@: %@ - Hash response...", THIS_FILE, THIS_METHOD); // Standard version 1.5+ NSString *key = [self keyFromHash:hash algorithm:hashAlg]; NSString *calculatedHash = [self hashCapabilitiesFromQuery:query]; if ([calculatedHash isEqualToString:hash]) { XMPPLogVerbose(@"%@: %@ - Hash matches!", THIS_FILE, THIS_METHOD); // Store the capabilities (associated with the hash) [xmppCapabilitiesStorage setCapabilities:query forHash:hash algorithm:hashAlg]; // Remove the jid(s) from the discoRequest variables NSArray *jids = [discoRequestHashDict objectForKey:key]; NSUInteger i; for (i = 1; i < [jids count]; i++) { XMPPJID *currentJid = [jids objectAtIndex:i]; [discoRequestJidSet removeObject:currentJid]; // Notify the delegate(s) [multicastDelegate xmppCapabilities:self didDiscoverCapabilities:query forJID:currentJid]; } [discoRequestHashDict removeObjectForKey:key]; // Cancel the request timeout [self cancelTimeoutForDiscoRequestFromJID:jid]; } else { XMPPLogWarn(@"%@: Hash mismatch! hash(%@) != calculatedHash(%@)", THIS_FILE, hash, calculatedHash); // Revoke the associated hash from the jid [xmppCapabilitiesStorage clearCapabilitiesHashAndAlgorithmForJID:jid xmppStream:xmppStream]; // Now set the capabilities for the jid [xmppCapabilitiesStorage setCapabilities:query forJID:jid xmppStream:xmppStream]; // Notify the delegate(s) [multicastDelegate xmppCapabilities:self didDiscoverCapabilities:query forJID:jid]; // We'd still like to know what the capabilities are for this hash. // Move onto the next one in the list (if there are more, otherwise stop). [self maybeQueryNextJidWithHashKey:key dueToHashMismatch:YES]; } } else { XMPPLogVerbose(@"%@: %@ - Non-Hash response", THIS_FILE, THIS_METHOD); // Store the capabilities (associated with the jid) [xmppCapabilitiesStorage setCapabilities:query forJID:jid xmppStream:xmppStream]; // Remove the jid from the discoRequest variable [discoRequestJidSet removeObject:jid]; // Cancel the request timeout [self cancelTimeoutForDiscoRequestFromJID:jid]; // Notify the delegate(s) [multicastDelegate xmppCapabilities:self didDiscoverCapabilities:query forJID:jid]; } } - (void)handleDiscoErrorResponse:(NSXMLElement *)querySubElement fromJID:(XMPPJID *)jid { // This method must be invoked on the moduleQueue NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); NSString *hash = nil; NSString *hashAlg = nil; BOOL hashResponse = [xmppCapabilitiesStorage getCapabilitiesHash:&hash algorithm:&hashAlg forJID:jid xmppStream:xmppStream]; if (hashResponse) { NSString *key = [self keyFromHash:hash algorithm:hashAlg]; // We'd still like to know what the capabilities are for this hash. // Move onto the next one in the list (if there are more, otherwise stop). [self maybeQueryNextJidWithHashKey:key dueToHashMismatch:NO]; } else { // Make a note of the failure [xmppCapabilitiesStorage setCapabilitiesFetchFailedForJID:jid xmppStream:xmppStream]; // Remove the jid from the discoRequest variable [discoRequestJidSet removeObject:jid]; // Cancel the request timeout [self cancelTimeoutForDiscoRequestFromJID:jid]; } } - (void)maybeQueryNextJidWithHashKey:(NSString *)key dueToHashMismatch:(BOOL)hashMismatch { // This method must be invoked on the moduleQueue NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); // Get the list of jids that have the same capabilities hash NSMutableArray *jids = [discoRequestHashDict objectForKey:key]; if (jids == nil) { XMPPLogWarn(@"%@: %@ - Key doesn't exist in discoRequestHashDict", THIS_FILE, THIS_METHOD); return; } // Get the index and jid of the fetch that just failed NSUInteger requestIndex = [[jids objectAtIndex:0] unsignedIntegerValue]; XMPPJID *jid = [jids objectAtIndex:requestIndex]; // Release the associated timer [self cancelTimeoutForDiscoRequestFromJID:jid]; if (hashMismatch) { // We need to remove the naughty jid from the lists. [discoRequestJidSet removeObject:jid]; [jids removeObjectAtIndex:requestIndex]; } else { // We want to move onto the next jid in the list. // Increment request index (and update object in jids array), requestIndex++; [jids replaceObjectAtIndex:0 withObject:[NSNumber numberWithUnsignedInteger:requestIndex]]; } // Do we have another jid that we can query? // That is, another jid that was broadcasting the same capabilities hash. if (requestIndex < [jids count]) { XMPPJID *jid = [jids objectAtIndex:requestIndex]; NSString *node = nil; NSString *ver = nil; [xmppCapabilitiesStorage getCapabilitiesKnown:nil failed:nil node:&node ver:&ver ext:nil hash:nil algorithm:nil forJID:jid xmppStream:xmppStream]; // Send disco#info query [self sendDiscoInfoQueryTo:jid withNode:node ver:ver]; // Setup request timeout [self setupTimeoutForDiscoRequestFromJID:jid withHashKey:key]; } else { // We've queried every single jid that was broadcasting this capabilities hash. // Nothing left to do now but wait. // // If one of the jids happens to eventually respond, // then we'll still be able to link the capabilities to every jid with the same capabilities hash. // // This would be handled by the xmppCapabilitiesStorage class, // via the setCapabilitiesForJID method. NSUInteger i; for (i = 1; i < [jids count]; i++) { XMPPJID *jid = [jids objectAtIndex:i]; [discoRequestJidSet removeObject:jid]; [xmppCapabilitiesStorage setCapabilitiesFetchFailedForJID:jid xmppStream:xmppStream]; } [discoRequestHashDict removeObjectForKey:key]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPStream Delegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)xmppStreamDidConnect:(XMPPStream *)sender { // If this is the first time we've connected, start collecting our list of capabilities. // We do this now so that the process is likely ready by the time we need to send a presence element. if (myCapabilitiesQuery == nil) { [self collectMyCapabilities]; } } - (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence { // This method is invoked on the moduleQueue. // XEP-0115 presence: // // <presence from="romeo@montague.lit/orchard"> // <c xmlns="http://jabber.org/protocol/caps" // hash="sha-1" // node="http://code.google.com/p/exodus" // ver="QgayPKawpkPSDYmwT/WM94uA1u0="/> // </presence> NSString *type = [presence type]; XMPPJID *myJID = xmppStream.myJID; if ([myJID isEqual:[presence from]]) { // Our own presence is being reflected back to us. return; } if ([type isEqualToString:@"unavailable"]) { [xmppCapabilitiesStorage clearNonPersistentCapabilitiesForJID:[presence from] xmppStream:xmppStream]; } else if ([type isEqualToString:@"available"]) { NSXMLElement *c = [presence elementForName:@"c" xmlns:XMLNS_CAPS]; if (c == nil) { if (autoFetchNonHashedCapabilities) { [self fetchCapabilitiesForJID:[presence from]]; } } else { NSString *hash = [c attributeStringValueForName:@"hash"]; if (hash) { [self handlePresenceCapabilities:c fromJID:[presence from]]; } else { [self handleLegacyPresenceCapabilities:c fromJID:[presence from]]; } } } } - (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq { // This method is invoked on the moduleQueue. // Disco Request: // // <iq from="juliet@capulet.lit/chamber" type="get"> // <query xmlns="http://jabber.org/protocol/disco#info"/> // </iq> // // Disco Response: // // <iq from="romeo@montague.lit/orchard" type="result"> // <query xmlns="http://jabber.org/protocol/disco#info"> // <feature var="feature1"/> // <feature var="feature2"/> // </query> // </iq> NSXMLElement *query = [iq elementForName:@"query" xmlns:XMLNS_DISCO_INFO]; if (query == nil) { return NO; } NSString *type = [[iq attributeStringValueForName:@"type"] lowercaseString]; if ([type isEqualToString:@"get"]) { NSString *node = [query attributeStringValueForName:@"node"]; if (node == nil || [node hasPrefix:DISCO_NODE]) { [self handleDiscoRequest:iq]; } else { return NO; } } else if ([type isEqualToString:@"result"]) { [self handleDiscoResponse:query fromJID:[iq from]]; } else if ([type isEqualToString:@"error"]) { [self handleDiscoErrorResponse:query fromJID:[iq from]]; } else { return NO; } return YES; } - (void)xmppStream:(XMPPStream *)sender willSendPresence:(XMPPPresence *)presence { // This method is invoked on the moduleQueue. NSString *type = [presence type]; if ([type isEqualToString:@"unavailable"]) { [xmppCapabilitiesStorage clearAllNonPersistentCapabilitiesForXMPPStream:xmppStream]; } else if ([type isEqualToString:@"available"]) { if (myCapabilitiesQuery == nil) { // It appears we haven't collected our list of capabilites yet. // This will need to be done before we can add the hash to the outgoing presence element. [self collectMyCapabilities]; } else if (myCapabilitiesC) { NSXMLElement *c = [[myCapabilitiesC copy] autorelease]; [presence addChild:c]; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Timers //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)setupTimeoutForDiscoRequestFromJID:(XMPPJID *)jid { // This method must be invoked on the moduleQueue NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); // If the timeout occurs, we will remove the jid from the discoRequestJidSet. // If we eventually get a response (after the timeout) we will still be able to process it. // The timeout simply prevents the set from growing infinitely. dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, moduleQueue); dispatch_source_set_event_handler(timer, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self processTimeoutWithJID:jid]; dispatch_source_cancel(timer); dispatch_release(timer); [pool drain]; }); dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (CAPABILITIES_REQUEST_TIMEOUT * NSEC_PER_SEC)); dispatch_source_set_timer(timer, tt, DISPATCH_TIME_FOREVER, 0); dispatch_resume(timer); // We also keep a reference to the timer in the discoTimerJidDict. // This allows us to cancel the timer when we get a response to the disco request. GCDTimerWrapper *timerWrapper = [[GCDTimerWrapper alloc] initWithDispatchTimer:timer]; [discoTimerJidDict setObject:timerWrapper forKey:jid]; [timerWrapper release]; } - (void)setupTimeoutForDiscoRequestFromJID:(XMPPJID *)jid withHashKey:(NSString *)key { // This method must be invoked on the moduleQueue NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); // If the timeout occurs, we want to send a request to the next jid with the same capabilities hash. // This list of jids is stored in the discoRequestHashDict. // The key will allow us to fetch the jid list. dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, moduleQueue); dispatch_source_set_event_handler(timer, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self processTimeoutWithHashKey:key]; dispatch_source_cancel(timer); dispatch_release(timer); [pool drain]; }); dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (CAPABILITIES_REQUEST_TIMEOUT * NSEC_PER_SEC)); dispatch_source_set_timer(timer, tt, DISPATCH_TIME_FOREVER, 0); dispatch_resume(timer); // We also keep a reference to the timer in the discoTimerJidDict. // This allows us to cancel the timer when we get a response to the disco request. GCDTimerWrapper *timerWrapper = [[GCDTimerWrapper alloc] initWithDispatchTimer:timer]; [discoTimerJidDict setObject:timerWrapper forKey:jid]; [timerWrapper release]; } - (void)cancelTimeoutForDiscoRequestFromJID:(XMPPJID *)jid { // This method must be invoked on the moduleQueue NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); GCDTimerWrapper *timerWrapper = [discoTimerJidDict objectForKey:jid]; if (timerWrapper) { [timerWrapper cancel]; [discoTimerJidDict removeObjectForKey:jid]; } } - (void)processTimeoutWithHashKey:(NSString *)key { // This method must be invoked on the moduleQueue NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); [self maybeQueryNextJidWithHashKey:key dueToHashMismatch:NO]; } - (void)processTimeoutWithJID:(XMPPJID *)jid { // This method must be invoked on the moduleQueue NSAssert(dispatch_get_current_queue() == moduleQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); // We queried the jid for its capabilities, but it didn't answer us. // Nothing left to do now but wait. // // If it happens to eventually respond, // then we'll still be able to process the capabilities properly. // // But at this point we're going to consider the query to be done. // This prevents our discoRequestJidSet from growing infinitely, // and also opens up the possibility of sending it another query in the future. [discoRequestJidSet removeObject:jid]; [xmppCapabilitiesStorage setCapabilitiesFetchFailedForJID:jid xmppStream:xmppStream]; } @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation GCDTimerWrapper - (id)initWithDispatchTimer:(dispatch_source_t)aTimer { if ((self = [super init])) { timer = aTimer; dispatch_retain(timer); } return self; } - (void)cancel { if (timer) { dispatch_source_cancel(timer); dispatch_release(timer); timer = NULL; } } - (void)dealloc { [self cancel]; [super dealloc]; } @end
04081337-xmpp
Extensions/XEP-0115/XMPPCapabilities.m
Objective-C
bsd
51,240
#import <Foundation/Foundation.h> #import <CoreData/CoreData.h> #import "XMPPCapabilities.h" #import "XMPPCoreDataStorage.h" /** * This class is an example implementation of XMPPCapabilitiesStorage using core data. * You are free to substitute your own storage class. **/ @interface XMPPCapabilitiesCoreDataStorage : XMPPCoreDataStorage <XMPPCapabilitiesStorage> { // Inherits protected variables from XMPPCoreDataStorage } /** * XEP-0115 provides a mechanism for hashing a list of capabilities. * Clients then broadcast this hash instead of the entire list to save bandwidth. * Because the hashing is standardized, it is safe to persistently store the linked hash & capabilities. * * For this reason, it is recommended you use this sharedInstance across all your xmppStreams. * This way all streams can shared a knowledgebase concerning known hashes. * * All other aspects of capabilities handling (such as JID's, lookup failures, etc) are kept separate between streams. **/ + (XMPPCapabilitiesCoreDataStorage *)sharedInstance; // // This class inherits from XMPPCoreDataStorage. // // Please see the XMPPCoreDataStorage header file for more information. // @end
04081337-xmpp
Extensions/XEP-0115/CoreDataStorage/XMPPCapabilitiesCoreDataStorage.h
Objective-C
bsd
1,186
#import "XMPPCapsResourceCoreDataStorageObject.h" #import "XMPPCapsCoreDataStorageObject.h" @implementation XMPPCapsResourceCoreDataStorageObject @dynamic jidStr; @dynamic streamBareJidStr; @dynamic haveFailed; @dynamic failed; @dynamic node; @dynamic ver; @dynamic ext; @dynamic hashStr; @dynamic hashAlgorithm; @dynamic caps; - (BOOL)haveFailed { return [[self failed] boolValue]; } - (void)setHaveFailed:(BOOL)flag { self.failed = [NSNumber numberWithBool:flag]; } @end
04081337-xmpp
Extensions/XEP-0115/CoreDataStorage/XMPPCapsResourceCoreDataStorageObject.m
Objective-C
bsd
486
#import "XMPPCapabilitiesCoreDataStorage.h" #import "XMPPCapsCoreDataStorageObject.h" #import "XMPPCapsResourceCoreDataStorageObject.h" #import "XMPP.h" #import "XMPPCoreDataStorageProtected.h" #import "XMPPLogging.h" // Log levels: off, error, warn, info, verbose #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; // | XMPP_LOG_FLAG_TRACE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif @implementation XMPPCapabilitiesCoreDataStorage static XMPPCapabilitiesCoreDataStorage *sharedInstance; + (XMPPCapabilitiesCoreDataStorage *)sharedInstance { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[XMPPCapabilitiesCoreDataStorage alloc] initWithDatabaseFilename:nil]; }); return sharedInstance; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Setup //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)configureWithParent:(XMPPCapabilities *)aParent queue:(dispatch_queue_t)queue { return [super configureWithParent:aParent queue:queue]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Utilities //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (XMPPCapsResourceCoreDataStorageObject *)resourceForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { NSAssert(dispatch_get_current_queue() == storageQueue, @"Invoked on incorrect queue"); XMPPLogTrace2(@"%@: %@ %@", THIS_FILE, THIS_METHOD, jid); if (jid == nil) return nil; NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPCapsResourceCoreDataStorageObject" inManagedObjectContext:[self managedObjectContext]]; NSPredicate *predicate; if (stream == nil) predicate = [NSPredicate predicateWithFormat:@"jidStr == %@", [jid full]]; else predicate = [NSPredicate predicateWithFormat:@"jidStr == %@ AND streamBareJidStr == %@", [jid full], [[self myJIDForXMPPStream:stream] bare]]; NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; [fetchRequest setEntity:entity]; [fetchRequest setPredicate:predicate]; [fetchRequest setFetchLimit:1]; NSArray *results = [[self managedObjectContext] executeFetchRequest:fetchRequest error:nil]; XMPPCapsResourceCoreDataStorageObject *resource = [results lastObject]; XMPPLogVerbose(@"%@: %@ - %@", THIS_FILE, THIS_METHOD, resource); return resource; } - (XMPPCapsCoreDataStorageObject *)capsForHash:(NSString *)hash algorithm:(NSString *)hashAlg { NSAssert(dispatch_get_current_queue() == storageQueue, @"Invoked on incorrect queue"); XMPPLogTrace2(@"%@: capsForHash:%@ algorithm:%@", THIS_FILE, hash, hashAlg); if (hash == nil) return nil; if (hashAlg == nil) return nil; NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPCapsCoreDataStorageObject" inManagedObjectContext:[self managedObjectContext]]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"hashStr == %@ AND hashAlgorithm == %@", hash, hashAlg]; NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; [fetchRequest setEntity:entity]; [fetchRequest setPredicate:predicate]; [fetchRequest setFetchLimit:1]; NSArray *results = [[self managedObjectContext] executeFetchRequest:fetchRequest error:nil]; XMPPCapsCoreDataStorageObject *caps = [results lastObject]; XMPPLogVerbose(@"%@: %@ - %@", THIS_FILE, THIS_METHOD, caps); return caps; } - (void)_clearAllNonPersistentCapabilitiesForXMPPStream:(XMPPStream *)stream { NSAssert(dispatch_get_current_queue() == storageQueue, @"Invoked on incorrect queue"); NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPCapsResourceCoreDataStorageObject" inManagedObjectContext:[self managedObjectContext]]; NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; [fetchRequest setEntity:entity]; [fetchRequest setFetchBatchSize:saveThreshold]; if (stream) { NSPredicate *predicate = [NSPredicate predicateWithFormat:@"streamBareJidStr == %@", [[self myJIDForXMPPStream:stream] bare]]; [fetchRequest setPredicate:predicate]; } NSArray *results = [[self managedObjectContext] executeFetchRequest:fetchRequest error:nil]; NSUInteger unsavedCount = [self numberOfUnsavedChanges]; for (XMPPCapsResourceCoreDataStorageObject *resource in results) { NSString *hash = resource.hashStr; NSString *hashAlg = resource.hashAlgorithm; BOOL nonPersistentCapabilities = ((hash == nil) || (hashAlg == nil)); if (nonPersistentCapabilities) { XMPPCapsCoreDataStorageObject *caps = resource.caps; if (caps) { [[self managedObjectContext] deleteObject:caps]; } } [[self managedObjectContext] deleteObject:resource]; if (++unsavedCount >= saveThreshold) { [self save]; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Overrides //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)addPersistentStoreWithPath:(NSString *)storePath error:(NSError **)errorPtr { BOOL result = [super addPersistentStoreWithPath:storePath error:errorPtr]; if (!result && [*errorPtr code] == NSMigrationMissingSourceModelError && [[*errorPtr domain] isEqualToString:NSCocoaErrorDomain]) { // If we get this error while trying to add the persistent store, it most likely means the model changed. // Since we are caching capabilities, it is safe to delete the persistent store and create a new one. if ([[NSFileManager defaultManager] fileExistsAtPath:storePath]) { [[NSFileManager defaultManager] removeItemAtPath:storePath error:nil]; // Try creating the store again, without creating a deletion/creation loop. result = [super addPersistentStoreWithPath:storePath error:errorPtr]; } } return result; } - (void)didCreateManagedObjectContext { // This method is overriden from the XMPPCoreDataStore superclass. [self _clearAllNonPersistentCapabilitiesForXMPPStream:nil]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Protocol Public API //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)areCapabilitiesKnownForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { XMPPLogTrace(); __block BOOL result; [self executeBlock:^{ XMPPCapsResourceCoreDataStorageObject *resource = [self resourceForJID:jid xmppStream:stream]; result = (resource.caps != nil); }]; return result; } - (NSXMLElement *)capabilitiesForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { XMPPLogTrace(); return [self capabilitiesForJID:jid ext:nil xmppStream:stream]; } - (NSXMLElement *)capabilitiesForJID:(XMPPJID *)jid ext:(NSString **)extPtr xmppStream:(XMPPStream *)stream { // By design this method should not be invoked from the storageQueue. NSAssert(dispatch_get_current_queue() != storageQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); __block NSXMLElement *result = nil; __block NSString *ext = nil; [self executeBlock:^{ XMPPCapsResourceCoreDataStorageObject *resource = [self resourceForJID:jid xmppStream:stream]; if (resource) { result = [[[resource caps] capabilities] retain]; ext = [[resource ext] retain]; } }]; if (extPtr) *extPtr = [ext autorelease]; else [ext release]; return [result autorelease]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Protocol Private API //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (BOOL)setCapabilitiesNode:(NSString *)node ver:(NSString *)ver ext:(NSString *)ext hash:(NSString *)hash algorithm:(NSString *)hashAlg forJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream andGetNewCapabilities:(NSXMLElement **)newCapabilitiesPtr { XMPPLogTrace(); __block BOOL result; __block NSXMLElement *newCapabilities = nil; [self executeBlock:^{ BOOL hashChange = NO; XMPPCapsResourceCoreDataStorageObject *resource = [self resourceForJID:jid xmppStream:stream]; if (resource) { resource.node = node; resource.ver = ver; resource.ext = ext; if (![hash isEqual:[resource hashStr]]) { hashChange = YES; resource.hashStr = hash; } if (![hashAlg isEqual:[resource hashAlgorithm]]) { hashChange = YES; resource.hashAlgorithm = hashAlg; } } else { resource = [NSEntityDescription insertNewObjectForEntityForName:@"XMPPCapsResourceCoreDataStorageObject" inManagedObjectContext:[self managedObjectContext]]; resource.jidStr = [jid full]; resource.streamBareJidStr = [[self myJIDForXMPPStream:stream] bare]; resource.node = node; resource.ver = ver; resource.ext = ext; resource.hashStr = hash; resource.hashAlgorithm = hashAlg; hashChange = ((hash != nil) || (hashAlg != nil)); } if (hashChange) { resource.caps = [self capsForHash:hash algorithm:hashAlg]; newCapabilities = [resource.caps.capabilities retain]; } // Return whether or not the capabilities are known for the given jid result = (resource.caps != nil); }]; if (newCapabilitiesPtr) *newCapabilitiesPtr = [newCapabilities autorelease]; else [newCapabilities release]; return result; } - (BOOL)getCapabilitiesHash:(NSString **)hashPtr algorithm:(NSString **)hashAlgPtr forJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { // By design this method should not be invoked from the storageQueue. NSAssert(dispatch_get_current_queue() != storageQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); __block BOOL result; __block NSString *hash; __block NSString *hashAlg; [self executeBlock:^{ XMPPCapsResourceCoreDataStorageObject *resource = [self resourceForJID:jid xmppStream:stream]; if (resource) { hash = [resource.hashStr retain]; hashAlg = [resource.hashAlgorithm retain]; result = (hash && hashAlg); } else { hash = nil; hashAlg = nil; result = NO; } }]; if (hashPtr) *hashPtr = [hash autorelease]; else [hash release]; if (hashAlgPtr) *hashAlgPtr = [hashAlg autorelease]; else [hashAlg release]; return result; } - (void)clearCapabilitiesHashAndAlgorithmForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { XMPPLogTrace(); [self scheduleBlock:^{ XMPPCapsResourceCoreDataStorageObject *resource = [self resourceForJID:jid xmppStream:stream]; if (resource) { BOOL clearCaps = NO; NSString *hash = resource.hashStr; NSString *hashAlg = resource.hashAlgorithm; if (hash && hashAlg) { clearCaps = YES; } resource.hashStr = nil; resource.hashAlgorithm = nil; if (clearCaps) { resource.caps = nil; } } }]; } - (void)getCapabilitiesKnown:(BOOL *)areCapabilitiesKnownPtr failed:(BOOL *)haveFailedFetchingBeforePtr node:(NSString **)nodePtr ver:(NSString **)verPtr ext:(NSString **)extPtr hash:(NSString **)hashPtr algorithm:(NSString **)hashAlgPtr forJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { // By design this method should not be invoked from the storageQueue. NSAssert(dispatch_get_current_queue() != storageQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); __block BOOL areCapabilitiesKnown; __block BOOL haveFailedFetchingBefore; __block NSString *node; __block NSString *ver; __block NSString *ext; __block NSString *hash; __block NSString *hashAlg; [self executeBlock:^{ XMPPCapsResourceCoreDataStorageObject *resource = [self resourceForJID:jid xmppStream:stream]; if (resource == nil) { // We don't know anything about the given jid areCapabilitiesKnown = NO; haveFailedFetchingBefore = NO; node = nil; ver = nil; ext = nil; hash = nil; hashAlg = nil; } else { areCapabilitiesKnown = (resource.caps != nil); haveFailedFetchingBefore = resource.haveFailed; node = [resource.node retain]; ver = [resource.ver retain]; ext = [resource.ext retain]; hash = [resource.hashStr retain]; hashAlg = [resource.hashAlgorithm retain]; } }]; if (nodePtr) *nodePtr = [node autorelease]; else [node release]; if (verPtr) *verPtr = [ver autorelease]; else [ver release]; if (extPtr) *extPtr = [ext autorelease]; else [ext release]; if (hashPtr) *hashPtr = [hash autorelease]; else [hash release]; if (hashAlgPtr) *hashAlgPtr = [hashAlg autorelease]; else [hashAlg release]; } - (void)setCapabilities:(NSXMLElement *)capabilities forHash:(NSString *)hash algorithm:(NSString *)hashAlg { XMPPLogTrace(); if (hash == nil) return; if (hashAlg == nil) return; [self scheduleBlock:^{ XMPPCapsCoreDataStorageObject *caps = [self capsForHash:hash algorithm:hashAlg]; if (caps) { caps.capabilities = capabilities; } else { caps = [NSEntityDescription insertNewObjectForEntityForName:@"XMPPCapsCoreDataStorageObject" inManagedObjectContext:[self managedObjectContext]]; caps.hashStr = hash; caps.hashAlgorithm = hashAlg; caps.capabilities = capabilities; } NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPCapsResourceCoreDataStorageObject" inManagedObjectContext:[self managedObjectContext]]; NSPredicate *predicate; predicate = [NSPredicate predicateWithFormat:@"hashStr == %@ AND hashAlgorithm == %@", hash, hashAlg]; NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; [fetchRequest setEntity:entity]; [fetchRequest setPredicate:predicate]; [fetchRequest setFetchBatchSize:saveThreshold]; NSArray *results = [[self managedObjectContext] executeFetchRequest:fetchRequest error:nil]; NSUInteger unsavedCount = [self numberOfUnsavedChanges]; for (XMPPCapsResourceCoreDataStorageObject *resource in results) { resource.caps = caps; if (++unsavedCount >= saveThreshold) { [self save]; } } }]; } - (void)setCapabilities:(NSXMLElement *)capabilities forJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { // By design this method should not be invoked from the storageQueue. NSAssert(dispatch_get_current_queue() != storageQueue, @"Invoked on incorrect queue"); XMPPLogTrace(); if (jid == nil) return; [self scheduleBlock:^{ XMPPCapsCoreDataStorageObject *caps; caps = [NSEntityDescription insertNewObjectForEntityForName:@"XMPPCapsCoreDataStorageObject" inManagedObjectContext:[self managedObjectContext]]; caps.capabilities = capabilities; XMPPCapsResourceCoreDataStorageObject *resource = [self resourceForJID:jid xmppStream:stream]; if (resource == nil) { resource = [NSEntityDescription insertNewObjectForEntityForName:@"XMPPCapsResourceCoreDataStorageObject" inManagedObjectContext:[self managedObjectContext]]; resource.jidStr = [jid full]; resource.streamBareJidStr = [[self myJIDForXMPPStream:stream] bare]; } resource.caps = caps; }]; } - (void)setCapabilitiesFetchFailedForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { XMPPLogTrace(); [self scheduleBlock:^{ XMPPCapsResourceCoreDataStorageObject *resource = [self resourceForJID:jid xmppStream:stream]; resource.haveFailed = YES; }]; } - (void)clearAllNonPersistentCapabilitiesForXMPPStream:(XMPPStream *)stream { // This method is called for the protocol, // but is also called when we first load the database file from disk. XMPPLogTrace(); [self scheduleBlock:^{ [self _clearAllNonPersistentCapabilitiesForXMPPStream:stream]; }]; } - (void)clearNonPersistentCapabilitiesForJID:(XMPPJID *)jid xmppStream:(XMPPStream *)stream { XMPPLogTrace(); [self scheduleBlock:^{ XMPPCapsResourceCoreDataStorageObject *resource = [self resourceForJID:jid xmppStream:stream]; if (resource != nil) { NSString *hash = resource.hashStr; NSString *hashAlg = resource.hashAlgorithm; if (hash && hashAlg) { // The associated capabilities are persistent } else { XMPPCapsCoreDataStorageObject *caps = resource.caps; if (caps) { [[self managedObjectContext] deleteObject:caps]; } } [[self managedObjectContext] deleteObject:resource]; } }]; } @end
04081337-xmpp
Extensions/XEP-0115/CoreDataStorage/XMPPCapabilitiesCoreDataStorage.m
Objective-C
bsd
17,587
#import <CoreData/CoreData.h> #if TARGET_OS_IPHONE #import "DDXML.h" #endif @class XMPPCapsResourceCoreDataStorageObject; @interface XMPPCapsCoreDataStorageObject : NSManagedObject @property (nonatomic, retain) NSXMLElement *capabilities; @property (nonatomic, retain) NSString * hashStr; @property (nonatomic, retain) NSString * hashAlgorithm; @property (nonatomic, retain) NSString * capabilitiesStr; @property (nonatomic, retain) NSSet * resources; @end @interface XMPPCapsCoreDataStorageObject (CoreDataGeneratedAccessors) - (void)addResourcesObject:(XMPPCapsResourceCoreDataStorageObject *)value; - (void)removeResourcesObject:(XMPPCapsResourceCoreDataStorageObject *)value; - (void)addResources:(NSSet *)value; - (void)removeResources:(NSSet *)value; @end
04081337-xmpp
Extensions/XEP-0115/CoreDataStorage/XMPPCapsCoreDataStorageObject.h
Objective-C
bsd
776
#import "XMPPCapsCoreDataStorageObject.h" #import "XMPPCapsResourceCoreDataStorageObject.h" #import "XMPP.h" @implementation XMPPCapsCoreDataStorageObject @dynamic capabilities; @dynamic hashStr; @dynamic hashAlgorithm; @dynamic capabilitiesStr; @dynamic resources; - (NSXMLElement *)capabilities { return [[[NSXMLElement alloc] initWithXMLString:[self capabilitiesStr] error:nil] autorelease]; } - (void)setCapabilities:(NSXMLElement *)caps { self.capabilitiesStr = [caps compactXMLString]; } @end
04081337-xmpp
Extensions/XEP-0115/CoreDataStorage/XMPPCapsCoreDataStorageObject.m
Objective-C
bsd
510
#import <CoreData/CoreData.h> @class XMPPCapsCoreDataStorageObject; @interface XMPPCapsResourceCoreDataStorageObject : NSManagedObject @property (nonatomic, retain) NSString * jidStr; @property (nonatomic, retain) NSString * streamBareJidStr; @property (nonatomic, assign) BOOL haveFailed; @property (nonatomic, retain) NSNumber * failed; @property (nonatomic, retain) NSString * node; @property (nonatomic, retain) NSString * ver; @property (nonatomic, retain) NSString * ext; @property (nonatomic, retain) NSString * hashStr; @property (nonatomic, retain) NSString * hashAlgorithm; @property (nonatomic, retain) XMPPCapsCoreDataStorageObject * caps; @end
04081337-xmpp
Extensions/XEP-0115/CoreDataStorage/XMPPCapsResourceCoreDataStorageObject.h
Objective-C
bsd
666
#import "XMPPTime.h" #import "XMPP.h" #import "XMPPIDTracker.h" #import "XMPPDateTimeProfiles.h" #define INTEGRATE_WITH_CAPABILITIES 1 #if INTEGRATE_WITH_CAPABILITIES #import "XMPPCapabilities.h" #endif #define DEFAULT_TIMEOUT 30.0 // seconds //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @interface XMPPTimeQueryInfo : XMPPBasicTrackingInfo { NSDate *timeSent; } @property (nonatomic, readonly) NSDate *timeSent; - (NSTimeInterval)rtt; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPTime - (id)init { return [self initWithDispatchQueue:NULL]; } - (id)initWithDispatchQueue:(dispatch_queue_t)queue { if ((self = [super initWithDispatchQueue:queue])) { respondsToQueries = YES; } return self; } - (BOOL)activate:(XMPPStream *)aXmppStream { if ([super activate:aXmppStream]) { #if INTEGRATE_WITH_CAPABILITIES [xmppStream autoAddDelegate:self delegateQueue:moduleQueue toModulesOfClass:[XMPPCapabilities class]]; #endif queryTracker = [[XMPPIDTracker alloc] initWithDispatchQueue:moduleQueue]; return YES; } return NO; } - (void)deactivate { #if INTEGRATE_WITH_CAPABILITIES [xmppStream removeAutoDelegate:self delegateQueue:moduleQueue fromModulesOfClass:[XMPPCapabilities class]]; #endif dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [queryTracker removeAllIDs]; [queryTracker release]; queryTracker = nil; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_sync(moduleQueue, block); [super deactivate]; } - (void)dealloc { // queryTracker is handled in the deactivate method, // which is automatically called by [super dealloc] if needed. [super dealloc]; } - (BOOL)respondsToQueries { if (dispatch_get_current_queue() == moduleQueue) { return respondsToQueries; } else { __block BOOL result; dispatch_sync(moduleQueue, ^{ result = respondsToQueries; }); return result; } } - (void)setRespondsToQueries:(BOOL)flag { dispatch_block_t block = ^{ if (respondsToQueries != flag) { respondsToQueries = flag; #if INTEGRATE_WITH_CAPABILITIES // Capabilities may have changed, need to notify others. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPPresence *presence = xmppStream.myPresence; if (presence) { [xmppStream sendElement:presence]; } [pool drain]; #endif } }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (NSString *)generateQueryIDWithTimeout:(NSTimeInterval)timeout { // This method may be invoked on any thread/queue. // Generate unique ID for query. // It's important the ID be unique as the ID is the // only thing that distinguishes multiple queries from each other. NSString *queryID = [xmppStream generateUUID]; dispatch_async(moduleQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPTimeQueryInfo *queryInfo = [[XMPPTimeQueryInfo alloc] initWithTarget:self selector:@selector(handleResponse:withInfo:) timeout:timeout]; [queryTracker addID:queryID trackingInfo:queryInfo]; [queryInfo release]; [pool drain]; }); return queryID; } - (NSString *)sendQueryToServer { // This is a public method. // It may be invoked on any thread/queue. return [self sendQueryToServerWithTimeout:DEFAULT_TIMEOUT]; } - (NSString *)sendQueryToServerWithTimeout:(NSTimeInterval)timeout { // This is a public method. // It may be invoked on any thread/queue. NSString *queryID = [self generateQueryIDWithTimeout:timeout]; // Send ping packet // // <iq type="get" to="domain" id="queryID"> // <time xmlns="urn:xmpp:time"/> // </iq> // // Note: Sometimes the to attribute is required. (ejabberd) NSXMLElement *time = [NSXMLElement elementWithName:@"time" xmlns:@"urn:xmpp:time"]; XMPPJID *domainJID = [[xmppStream myJID] domainJID]; XMPPIQ *iq = [XMPPIQ iqWithType:@"get" to:domainJID elementID:queryID child:time]; [xmppStream sendElement:iq]; return queryID; } - (NSString *)sendQueryToJID:(XMPPJID *)jid { // This is a public method. // It may be invoked on any thread/queue. return [self sendQueryToJID:jid withTimeout:DEFAULT_TIMEOUT]; } - (NSString *)sendQueryToJID:(XMPPJID *)jid withTimeout:(NSTimeInterval)timeout { // This is a public method. // It may be invoked on any thread/queue. NSString *queryID = [self generateQueryIDWithTimeout:timeout]; // Send ping element // // <iq type="get" to="fullJID" id="abc123"> // <time xmlns="urn:xmpp:time"/> // </iq> NSXMLElement *time = [NSXMLElement elementWithName:@"time" xmlns:@"urn:xmpp:time"]; XMPPIQ *iq = [XMPPIQ iqWithType:@"get" to:jid elementID:queryID child:time]; [xmppStream sendElement:iq]; return queryID; } - (void)handleResponse:(XMPPIQ *)iq withInfo:(XMPPTimeQueryInfo *)queryInfo { if (iq) { if ([[iq type] isEqualToString:@"result"]) [multicastDelegate xmppTime:self didReceiveResponse:iq withRTT:[queryInfo rtt]]; else [multicastDelegate xmppTime:self didNotReceiveResponse:[queryInfo elementID] dueToTimeout:-1.0]; } else { [multicastDelegate xmppTime:self didNotReceiveResponse:[queryInfo elementID] dueToTimeout:[queryInfo timeout]]; } } - (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq { // This method is invoked on the moduleQueue. NSString *type = [iq type]; if ([type isEqualToString:@"result"] || [type isEqualToString:@"error"]) { // Examples: // // <iq type="result" from="robbie@voalte.com/office" to="robbie@deusty.com/home" id="abc123"> // <time xmlns="urn:xmpp:time"> // <tzo>-06:00</tzo> // <utc>2006-12-19T17:58:35Z</utc> // </time> // </iq> // // <iq type="error" from="robbie@voalte.com/office" to="robbie@deusty.com/home" id="abc123"> // <time xmlns="urn:xmpp:time"/> // <error code="501" type="cancel"> // <feature-not-implemented xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/> // </error> // </iq> return [queryTracker invokeForID:[iq elementID] withObject:iq]; } else if (respondsToQueries && [type isEqualToString:@"get"]) { // Example: // // <iq type="get" from="robbie@deusty.com/home" to="robbie@voalte.com/office" id="abc123"> // <time xmlns="urn:xmpp:time"/> // </iq> NSXMLElement *time = [iq elementForName:@"time" xmlns:@"urn:xmpp:time"]; if (time) { NSXMLElement *time = [[self class] timeElement]; XMPPIQ *response = [XMPPIQ iqWithType:@"result" to:[iq from] elementID:[iq elementID]]; [response addChild:time]; [sender sendElement:response]; return YES; } } return NO; } - (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error { [queryTracker removeAllIDs]; } #if INTEGRATE_WITH_CAPABILITIES /** * If an XMPPCapabilites instance is used we want to advertise our support for XEP-0202. **/ - (void)xmppCapabilities:(XMPPCapabilities *)sender collectingMyCapabilities:(NSXMLElement *)query { // This method is invoked on the moduleQueue. if (respondsToQueries) { // <query xmlns="http://jabber.org/protocol/disco#info"> // ... // <feature var="urn:xmpp:time"/> // ... // </query> NSXMLElement *feature = [NSXMLElement elementWithName:@"feature"]; [feature addAttributeWithName:@"var" stringValue:@"urn:xmpp:time"]; [query addChild:feature]; } } #endif + (NSDate *)dateFromResponse:(XMPPIQ *)iq { // <iq type="result" from="robbie@voalte.com/office" to="robbie@deusty.com/home" id="abc123"> // <time xmlns="urn:xmpp:time"> // <tzo>-06:00</tzo> // <utc>2006-12-19T17:58:35Z</utc> // </time> // </iq> NSXMLElement *time = [iq elementForName:@"time" xmlns:@"urn:xmpp:time"]; if (time == nil) return nil; NSString *utc = [[time elementForName:@"utc"] stringValue]; if (utc == nil) return nil; // Note: // // NSDate is a very simple class, but can be confusing at times. // NSDate simply stores an NSTimeInterval internally, // which is just a double representing the number of seconds since the reference date. // Since it's a double, it can yield sub-millisecond precision. // // In addition to this, it stores the values in UTC. // However, if you print the value using NSLog via "%@", // it will automatically print the date in the local timezone: // // NSDate *refDate = [NSDate dateWithTimeIntervalSinceReferenceDate:0.0]; // // NSLog(@"%f", [refDate timeIntervalSinceReferenceDate]); // Prints: 0.0 // NSLog(@"%@", refDate); // Prints: 2000-12-31 19:00:00 -05:00 // NSLog(@"%@", [utcDateFormatter stringFromDate:refDate]); // Prints: 2001-01-01 00:00:00 +00:00 // // Now the value we've received from XMPPDateTimeProfiles is correct. // If we print it out using a utcDateFormatter we would see it is correct. // If we printed it out generically using NSLog, then we would see it converted into our local time zone. return [XMPPDateTimeProfiles parseDateTime:utc]; } + (NSTimeZone *)timeZoneOffsetFromResponse:(XMPPIQ *)iq { // <iq type="result" from="robbie@voalte.com/office" to="robbie@deusty.com/home" id="abc123"> // <time xmlns="urn:xmpp:time"> // <tzo>-06:00</tzo> // <utc>2006-12-19T17:58:35Z</utc> // </time> // </iq> NSXMLElement *time = [iq elementForName:@"time" xmlns:@"urn:xmpp:time"]; if (time == nil) return 0; NSString *tzo = [[time elementForName:@"tzo"] stringValue]; if (tzo == nil) return 0; return [XMPPDateTimeProfiles parseTimeZoneOffset:tzo]; } + (NSTimeInterval)approximateTimeDifferenceFromResponse:(XMPPIQ *)iq andRTT:(NSTimeInterval)rtt { // First things first, get the current date and time NSDate *localDate = [NSDate date]; // Then worry about the calculations NSXMLElement *time = [iq elementForName:@"time" xmlns:@"urn:xmpp:time"]; if (time == nil) return 0.0; NSString *utc = [[time elementForName:@"utc"] stringValue]; if (utc == nil) return 0.0; NSDate *remoteDate = [XMPPDateTimeProfiles parseDateTime:utc]; if (remoteDate == nil) return 0.0; NSTimeInterval localTI = [localDate timeIntervalSinceReferenceDate]; NSTimeInterval remoteTI = [remoteDate timeIntervalSinceReferenceDate] - (rtt / 2.0); // Did the response contain millisecond precision? // This is an important consideration. // Imagine if both computers are perfectly synced, // but the remote response doesn't contain milliseconds. // This could possibly cause us to think the difference is close to a full second. // // DateTime examples (from XMPPDateTimeProfiles documentation): // // 1969-07-21T02:56:15 // 1969-07-21T02:56:15Z // 1969-07-20T21:56:15-05:00 // 1969-07-21T02:56:15.123 // 1969-07-21T02:56:15.123Z // 1969-07-20T21:56:15.123-05:00 BOOL hasMilliseconds = ([utc length] > 19) && ([utc characterAtIndex:19] == '.'); if (hasMilliseconds) { return remoteTI - localTI; } else { // No milliseconds. What to do? // // We could simply truncate the milliseconds from our time... // But this could make things much worse. // For example: // // local = 14:22:36.750 // remote = 14:22:37 // // If we truncate the result now we calculate a diff of 1.000 (a full second). // Considering the remote's milliseconds could have been anything from 000 to 999, // this means our calculations are: // // perfect : 0.1% chance // diff too big : 75.0% chance // diff too small : 24.9% chance // // Perhaps a better solution would give us a more even spread. // We can do this by calculating the range: // // 37.000 - 36.750 = 0.25 // 37.999 - 36.750 = 1.249 // // So a better guess of the diff is 0.750 (3/4 of a second): // // perfect : 0.1% chance // diff too big : 50.0% chance // diff too small : 49.9% chance NSTimeInterval diff1 = localTI - (remoteTI + 0.000); NSTimeInterval diff2 = localTI - (remoteTI + 0.999); return ((diff1 + diff2) / 2.0); } } + (NSXMLElement *)timeElement { return [self timeElementFromDate:[NSDate date]]; } + (NSXMLElement *)timeElementFromDate:(NSDate *)date { // <time xmlns="urn:xmpp:time"> // <tzo>-06:00</tzo> // <utc>2006-12-19T17:58:35Z</utc> // </time> NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setFormatterBehavior:NSDateFormatterBehavior10_4]; // Use unicode patterns (as opposed to 10_3) [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"]; [df setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; NSString *utcValue = [df stringFromDate:date]; [df release]; NSInteger tzoInSeconds = [[NSTimeZone systemTimeZone] secondsFromGMTForDate:date]; NSInteger tzoH = tzoInSeconds / (60 * 60); NSInteger tzoS = tzoInSeconds % (60 * 60); NSString *tzoValue = [NSString stringWithFormat:@"%+03li:%02li", (long)tzoH, (long)tzoS]; NSXMLElement *tzo = [NSXMLElement elementWithName:@"tzo" stringValue:tzoValue]; NSXMLElement *utc = [NSXMLElement elementWithName:@"utc" stringValue:utcValue]; NSXMLElement *time = [NSXMLElement elementWithName:@"time" xmlns:@"urn:xmpp:time"]; [time addChild:tzo]; [time addChild:utc]; return time; } @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @implementation XMPPTimeQueryInfo @synthesize timeSent; - (id)initWithTarget:(id)aTarget selector:(SEL)aSelector timeout:(NSTimeInterval)aTimeout { if ((self = [super initWithTarget:aTarget selector:aSelector timeout:aTimeout])) { timeSent = [[NSDate alloc] init]; } return self; } - (NSTimeInterval)rtt { return [timeSent timeIntervalSinceNow] * -1.0; } - (void)dealloc { [timeSent release]; [super dealloc]; } @end
04081337-xmpp
Extensions/XEP-0202/XMPPTime.m
Objective-C
bsd
14,437
#import "XMPPAutoTime.h" #import "XMPP.h" #import "XMPPLogging.h" // Log levels: off, error, warn, info, verbose // Log flags: trace #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN | XMPP_LOG_FLAG_TRACE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif @interface XMPPAutoTime () @property (nonatomic, retain) NSData *lastServerAddress; @property (nonatomic, retain) NSDate *systemUptimeChecked; - (void)updateRecalibrationTimer; - (void)startRecalibrationTimer; - (void)stopRecalibrationTimer; @end #pragma mark - @implementation XMPPAutoTime - (id)initWithDispatchQueue:(dispatch_queue_t)queue { if ((self = [super initWithDispatchQueue:queue])) { recalibrationInterval = (60 * 60 * 24); lastCalibrationTime = DISPATCH_TIME_FOREVER; xmppTime = [[XMPPTime alloc] initWithDispatchQueue:queue]; xmppTime.respondsToQueries = NO; [xmppTime addDelegate:self delegateQueue:moduleQueue]; } return self; } - (BOOL)activate:(XMPPStream *)aXmppStream { if ([super activate:aXmppStream]) { [xmppTime activate:aXmppStream]; self.systemUptimeChecked = [NSDate date]; systemUptime = [[NSProcessInfo processInfo] systemUptime]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(systemClockDidChange:) name:NSSystemClockDidChangeNotification object:nil]; return YES; } return NO; } - (void)deactivate { dispatch_block_t block = ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self stopRecalibrationTimer]; [xmppTime deactivate]; awaitingQueryResponse = NO; [[NSNotificationCenter defaultCenter] removeObserver:self]; [super deactivate]; [pool drain]; }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_sync(moduleQueue, block); } - (void)dealloc { // recalibrationTimer released in [self deactivate] [targetJID release]; [xmppTime removeDelegate:self]; [xmppTime release]; xmppTime = nil; // Might be referenced via [super dealloc] -> [self deactivate] [lastServerAddress release]; [systemUptimeChecked release]; [super dealloc]; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Properties //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @synthesize lastServerAddress; @synthesize systemUptimeChecked; - (NSTimeInterval)recalibrationInterval { if (dispatch_get_current_queue() == moduleQueue) { return recalibrationInterval; } else { __block NSTimeInterval result; dispatch_sync(moduleQueue, ^{ result = recalibrationInterval; }); return result; } } - (void)setRecalibrationInterval:(NSTimeInterval)interval { dispatch_block_t block = ^{ if (recalibrationInterval != interval) { recalibrationInterval = interval; // Update the recalibrationTimer. // // Depending on new value and current state of the recalibrationTimer, // this may mean starting, stoping, or simply updating the timer. if (recalibrationInterval > 0) { // Remember: Only start the timer after the xmpp stream is up and authenticated if ([xmppStream isAuthenticated]) [self startRecalibrationTimer]; } else { [self stopRecalibrationTimer]; } } }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (XMPPJID *)targetJID { if (dispatch_get_current_queue() == moduleQueue) { return targetJID; } else { __block XMPPJID *result; dispatch_sync(moduleQueue, ^{ result = [targetJID retain]; }); return [result autorelease]; } } - (void)setTargetJID:(XMPPJID *)jid { dispatch_block_t block = ^{ if (![targetJID isEqualToJID:jid]) { [targetJID release]; targetJID = [jid retain]; } }; if (dispatch_get_current_queue() == moduleQueue) block(); else dispatch_async(moduleQueue, block); } - (NSTimeInterval)timeDifference { if (dispatch_get_current_queue() == moduleQueue) { return timeDifference; } else { __block NSTimeInterval result; dispatch_sync(moduleQueue, ^{ result = timeDifference; }); return result; } } - (dispatch_time_t)lastCalibrationTime { if (dispatch_get_current_queue() == moduleQueue) { return lastCalibrationTime; } else { __block dispatch_time_t result; dispatch_sync(moduleQueue, ^{ result = lastCalibrationTime; }); return result; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Notifications //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)systemClockDidChange:(NSNotification *)notification { XMPPLogTrace(); XMPPLogVerbose(@"NSSystemClockDidChangeNotification: %@", notification); if (lastCalibrationTime == DISPATCH_TIME_FOREVER) { // Doesn't matter, we haven't done a calibration yet. return; } // When the system clock changes, this affects our timeDifference. // However, the notification doesn't tell us by how much the system clock has changed. // So here's how we figure it out: // // The systemUptime isn't affected by the system clock. // We previously recorded the system uptime, and simultaneously recoded the system clock time. // We can now grab the current system uptime and current system clock time. // Using the four data points we can calculate how much the system clock has changed. NSDate *now = [NSDate date]; NSTimeInterval sysUptime = [[NSProcessInfo processInfo] systemUptime]; dispatch_async(moduleQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Calculate system clock change NSDate *oldSysTime = systemUptimeChecked; NSDate *newSysTime = now; NSTimeInterval oldSysUptime = systemUptime; NSTimeInterval newSysUptime = sysUptime; NSTimeInterval sysTimeDiff = [newSysTime timeIntervalSinceDate:oldSysTime]; NSTimeInterval sysUptimeDiff = newSysUptime - oldSysUptime; NSTimeInterval sysClockChange = sysTimeDiff - sysUptimeDiff; // Modify timeDifference & notify delegate timeDifference += sysClockChange; [multicastDelegate xmppAutoTime:self didUpdateTimeDifference:timeDifference]; // Dont forget to update our variables self.systemUptimeChecked = now; systemUptime = sysUptime; [pool drain]; }); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Recalibration Timer //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)handleRecalibrationTimerFire { XMPPLogTrace(); if (awaitingQueryResponse) return; awaitingQueryResponse = YES; if (targetJID) [xmppTime sendQueryToJID:targetJID]; else [xmppTime sendQueryToServer]; } - (void)updateRecalibrationTimer { XMPPLogTrace(); NSAssert(recalibrationTimer != NULL, @"Broken logic (1)"); NSAssert(recalibrationInterval > 0, @"Broken logic (2)"); uint64_t interval = (recalibrationInterval * NSEC_PER_SEC); dispatch_time_t tt; if (lastCalibrationTime == DISPATCH_TIME_FOREVER) tt = dispatch_time(DISPATCH_TIME_NOW, 0); // First timer fire at (NOW) else tt = dispatch_time(lastCalibrationTime, interval); // First timer fire at (lastCalibrationTime + interval) dispatch_source_set_timer(recalibrationTimer, tt, interval, 0); } - (void)startRecalibrationTimer { XMPPLogTrace(); if (recalibrationInterval <= 0) { // Timer is disabled return; } BOOL newTimer = NO; if (recalibrationTimer == NULL) { newTimer = YES; recalibrationTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, moduleQueue); dispatch_source_set_event_handler(recalibrationTimer, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [self handleRecalibrationTimerFire]; [pool drain]; }); } [self updateRecalibrationTimer]; if (newTimer) { dispatch_resume(recalibrationTimer); } } - (void)stopRecalibrationTimer { XMPPLogTrace(); if (recalibrationTimer) { dispatch_release(recalibrationTimer); recalibrationTimer = NULL; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPTime Delegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)xmppTime:(XMPPTime *)sender didReceiveResponse:(XMPPIQ *)iq withRTT:(NSTimeInterval)rtt { XMPPLogTrace(); awaitingQueryResponse = NO; lastCalibrationTime = dispatch_time(DISPATCH_TIME_NOW, 0); timeDifference = [XMPPTime approximateTimeDifferenceFromResponse:iq andRTT:rtt]; [multicastDelegate xmppAutoTime:self didUpdateTimeDifference:timeDifference]; } - (void)xmppTime:(XMPPTime *)sender didNotReceiveResponse:(NSString *)queryID dueToTimeout:(NSTimeInterval)timeout { XMPPLogTrace(); awaitingQueryResponse = NO; // Nothing to do here really. Most likely the server doesn't support XEP-0202. } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark XMPPStream Delegate //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket { NSData *currentServerAddress = [socket connectedAddress]; if (lastServerAddress == nil) { self.lastServerAddress = currentServerAddress; } else if (![lastServerAddress isEqualToData:currentServerAddress]) { XMPPLogInfo(@"%@: Connected to a different server. Resetting calibration info.", [self class]); lastCalibrationTime = DISPATCH_TIME_FOREVER; timeDifference = 0.0; self.lastServerAddress = currentServerAddress; } } - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender { [self startRecalibrationTimer]; } - (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error { [self stopRecalibrationTimer]; awaitingQueryResponse = NO; // We do NOT reset the lastCalibrationTime here. // If we reconnect to the same server, the lastCalibrationTime remains valid. } @end
04081337-xmpp
Extensions/XEP-0202/XMPPAutoTime.m
Objective-C
bsd
10,555
#import <Foundation/Foundation.h> #import "XMPPModule.h" #if TARGET_OS_IPHONE #import "DDXML.h" #endif @class XMPPJID; @class XMPPStream; @class XMPPIQ; @class XMPPIDTracker; @protocol XMPPTimeDelegate; @interface XMPPTime : XMPPModule { BOOL respondsToQueries; XMPPIDTracker *queryTracker; } /** * Whether or not the module should respond to incoming time queries. * It you create multiple instances of this module, only one instance should respond to queries. * * It is recommended you set this (if needed) before you activate the module. * The default value is YES. **/ @property (readwrite) BOOL respondsToQueries; /** * Send query to the server or a specific JID. * The disco module may be used to detect if the target supports this XEP. * * The returned string is the queryID (the elementID of the query that was sent). * In other words: * * SEND: <iq id="<returned_string>" type="get" .../> * RECV: <iq id="<returned_string>" type="result" .../> * * This may be helpful if you are sending multiple simultaneous queries to the same target. **/ - (NSString *)sendQueryToServer; - (NSString *)sendQueryToServerWithTimeout:(NSTimeInterval)timeout; - (NSString *)sendQueryToJID:(XMPPJID *)jid; - (NSString *)sendQueryToJID:(XMPPJID *)jid withTimeout:(NSTimeInterval)timeout; /** * Extracts the utc date from the given response/time element, * and returns an NSDate representation of the time in the local time zone. * Since the returned date is in the local time zone, it is suitable for presentation. **/ + (NSDate *)dateFromResponse:(XMPPIQ *)iq; /** * Extracts the time zone offset from the given response/time element. **/ + (NSTimeZone *)timeZoneOffsetFromResponse:(XMPPIQ *)iq; /** * Given the returned time response from a remote party, and the approximate round trip time, * calculates the difference between our clock and the remote party's clock. * * This is NOT a reference to the difference in time zones. * Time zone differences generally shouldn't matter as xmpp standards mandate the use of UTC. * * Rather this is the difference between our UTC time, and the remote party's UTC time. * If the two clocks are not synchronized, then the result represents the approximate difference. * * If our clock is earlier than the remote clock, then the result will be negative. * If our clock is ahead of the remote clock, then the result will be positive. * * If you later receive a timestamp from the remote party, you could add the diff. * For example: * * myTime = [givenTimeFromRemoteParty dateByAddingTimeInterval:diff]; **/ + (NSTimeInterval)approximateTimeDifferenceFromResponse:(XMPPIQ *)iq andRTT:(NSTimeInterval)rtt; /** * Creates and returns a time element. **/ + (NSXMLElement *)timeElement; + (NSXMLElement *)timeElementFromDate:(NSDate *)date; @end @protocol XMPPTimeDelegate @optional - (void)xmppTime:(XMPPTime *)sender didReceiveResponse:(XMPPIQ *)iq withRTT:(NSTimeInterval)rtt; - (void)xmppTime:(XMPPTime *)sender didNotReceiveResponse:(NSString *)queryID dueToTimeout:(NSTimeInterval)timeout; // Note: If the xmpp stream is disconnected, no delegate methods will be called, and outstanding queries are forgotten. @end
04081337-xmpp
Extensions/XEP-0202/XMPPTime.h
Objective-C
bsd
3,209
#import "XMPP.h" #import "XMPPTime.h" @class XMPPJID; /** * The XMPPAutoTime module monitors the time difference between our machine and the target. * The target may simply be the server, or a specific resource. * * The module works by sending time queries to the target, and tracking the responses. * The module will automatically send multiple queuries, and take into account the average RTT. * It will also automatically update itself on a customizable interval, and whenever the machine's clock changes. * * This module is helpful when you are using timestamps from the target. * For example, you may be receiving offline messages from your server. * However, all these offline messages are timestamped from the server's clock. * And the current machine's clock may vary considerably from the server's clock. * Timezone differences don't matter as UTC is always used in XMPP, but clocks can easily differ. * This may cause the user some confusion as server timestamps may reflect a time in the future, * or much longer ago than in reality. **/ @interface XMPPAutoTime : XMPPModule { NSTimeInterval recalibrationInterval; XMPPJID *targetJID; NSTimeInterval timeDifference; dispatch_time_t lastCalibrationTime; dispatch_source_t recalibrationTimer; BOOL awaitingQueryResponse; XMPPTime *xmppTime; NSData *lastServerAddress; NSDate *systemUptimeChecked; NSTimeInterval systemUptime; } /** * How often to recalibrate the time difference. * * The module will automatically calculate the time difference when it is activated, * or when it first sees the xmppStream become authenticated (whichever occurs first). * After that first calculation, it will update itself according to this interval. * * To temporarily disable recalibration, set the interval to zero. * * The default recalibrationInterval is 24 hours. **/ @property (readwrite) NSTimeInterval recalibrationInterval; /** * The target to query. * * If the targetJID is nil, this implies the target is the xmpp server we're connected to. * If the targetJID is non-nil, it must be a full JID (user@domain.tld/rsrc). * * The default targetJID is nil. **/ @property (readwrite, retain) XMPPJID *targetJID; /** * Returns the calculated time difference between our machine and the target. * * This is NOT a reference to the difference in time zones. * Time zone differences generally shouldn't matter as xmpp standards mandate the use of UTC. * * Rather this is the difference between our UTC time, and the remote party's UTC time. * If the two clocks are not synchronized, then the result represents the approximate difference. * * If our clock is earlier than the remote clock, then the value will be negative. * If our clock is ahead of the remote clock, then the value will be positive. * * If you later receive a timestamp from the remote party, you can simply add the diff. * For example: * * myTime = [givenTimeFromRemoteParty dateByAddingTimeInterval:diff]; **/ @property (readonly) NSTimeInterval timeDifference; /** * The last time we've completed a calibration. **/ @property (readonly) dispatch_time_t lastCalibrationTime; @end //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @protocol XMPPAutoTimeDelegate @optional - (void)xmppAutoTime:(XMPPAutoTime *)sender didUpdateTimeDifference:(NSTimeInterval)timeDifference; @end
04081337-xmpp
Extensions/XEP-0202/XMPPAutoTime.h
Objective-C
bsd
3,580
#import "XMPPCoreDataStorage.h" #import "XMPPStream.h" #import "XMPPInternal.h" #import "XMPPJID.h" #import "XMPPLogging.h" #import "NSNumber+XMPP.h" #import <objc/runtime.h> #import <libkern/OSAtomic.h> // Log levels: off, error, warn, info, verbose #if DEBUG static const int xmppLogLevel = XMPP_LOG_LEVEL_VERBOSE; #else static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN; #endif @implementation XMPPCoreDataStorage static NSMutableSet *databaseFileNames; + (void)initialize { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ databaseFileNames = [[NSMutableSet alloc] init]; }); } + (BOOL)registerDatabaseFileName:(NSString *)dbFileName { BOOL result = NO; @synchronized(databaseFileNames) { if (![databaseFileNames containsObject:dbFileName]) { [databaseFileNames addObject:dbFileName]; result = YES; } } return result; } + (void)unregisterDatabaseFileName:(NSString *)dbFileName { @synchronized(databaseFileNames) { [databaseFileNames removeObject:dbFileName]; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Override Me //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSString *)managedObjectModelName { // Override me, if needed, to provide customized behavior. // // This method is queried to get the name of the ManagedObjectModel within the app bundle. // It should return the name of the appropriate file (*.xdatamodel / *.mom / *.momd) sans file extension. // // The default implementation returns the name of the subclass, stripping any suffix of "CoreDataStorage". // E.g., if your subclass was named "XMPPExtensionCoreDataStorage", then this method would return "XMPPExtension". // // Note that a file extension should NOT be included. NSString *className = NSStringFromClass([self class]); NSString *suffix = @"CoreDataStorage"; if ([className hasSuffix:suffix] && ([className length] > [suffix length])) { return [className substringToIndex:([className length] - [suffix length])]; } else { return className; } } - (NSString *)defaultDatabaseFileName { // Override me, if needed, to provide customized behavior. // // This method is queried if the initWithDatabaseFileName method is invoked with a nil parameter. // // You are encouraged to use the sqlite file extension. return [NSString stringWithFormat:@"%@.sqlite", [self managedObjectModelName]]; } - (void)willCreatePersistentStoreWithPath:(NSString *)storePath { // Override me, if needed, to provide customized behavior. // // If you are using a database file with non-persistent data (e.g. for memory optimization purposes on iOS), // you may want to delete the database file if it already exists on disk. // // If this instance was created via initWithDatabaseFilename, then the storePath parameter will be non-nil. // If this instance was created via initWithInMemoryStore, then the storePath parameter will be nil. } - (BOOL)addPersistentStoreWithPath:(NSString *)storePath error:(NSError **)errorPtr { // Override me, if needed, to completely customize the persistent store. // // Adds the persistent store path to the persistent store coordinator. // Returns true if the persistent store is created. // // If this instance was created via initWithDatabaseFilename, then the storePath parameter will be non-nil. // If this instance was created via initWithInMemoryStore, then the storePath parameter will be nil. NSPersistentStore *persistentStore; if (storePath) { // SQLite persistent store NSURL *storeUrl = [NSURL fileURLWithPath:storePath]; // Default support for automatic lightweight migrations NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; persistentStore = [persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:errorPtr]; } else { // In-Memory persistent store persistentStore = [persistentStoreCoordinator addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:errorPtr]; } return persistentStore != nil; } - (void)didNotAddPersistentStoreWithPath:(NSString *)storePath error:(NSError *)error { // Override me, if needed, to provide customized behavior. // // For example, if you are using the database for non-persistent data and the model changes, // you may want to delete the database file if it already exists on disk. #if TARGET_OS_IPHONE XMPPLogError(@"%@:\n" @"=====================================================================================\n" @"Error creating persistent store:\n%@\n" @"Chaned core data model recently?\n" @"Quick Fix: Delete the app from device and reinstall.\n" @"=====================================================================================", [self class], error); #else XMPPLogError(@"%@:\n" @"=====================================================================================\n" @"Error creating persistent store:\n%@\n" @"Chaned core data model recently?\n" @"Quick Fix: Delete the database: %@\n" @"=====================================================================================", [self class], error, storePath); #endif } - (void)didCreateManagedObjectContext { // Override me to provide customized behavior. // // For example, you may want to perform cleanup of any non-persistent data before you start using the database. } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Setup //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @synthesize databaseFileName; - (void)commonInit { saveThreshold = 500; storageQueue = dispatch_queue_create(class_getName([self class]), NULL); myJidCache = [[NSMutableDictionary alloc] init]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateJidCache:) name:XMPPStreamDidChangeMyJIDNotification object:nil]; } - (id)init { return [self initWithDatabaseFilename:nil]; } - (id)initWithDatabaseFilename:(NSString *)aDatabaseFileName { if ((self = [super init])) { if (aDatabaseFileName) databaseFileName = [aDatabaseFileName copy]; else databaseFileName = [self defaultDatabaseFileName]; if (![[self class] registerDatabaseFileName:databaseFileName]) { [self dealloc]; return nil; } [self commonInit]; } return self; } - (id)initWithInMemoryStore { if ((self = [super init])) { [self commonInit]; } return self; } - (BOOL)configureWithParent:(id)aParent queue:(dispatch_queue_t)queue { // This is the standard configure method used by xmpp extensions to configure a storage class. // // Feel free to override this method if needed, // and just invoke super at some point to make sure everything is kosher at this level as well. NSParameterAssert(aParent != nil); NSParameterAssert(queue != NULL); if (queue == storageQueue) { // This class is designed to be run on a separate dispatch queue from its parent. // This allows us to optimize the database save operations by buffering them, // and executing them when demand on the storage instance is low. return NO; } return YES; } - (NSUInteger)saveThreshold { if (dispatch_get_current_queue() == storageQueue) { return saveThreshold; } else { __block NSUInteger result; dispatch_sync(storageQueue, ^{ result = saveThreshold; }); return result; } } - (void)setSaveThreshold:(NSUInteger)newSaveThreshold { dispatch_block_t block = ^{ saveThreshold = newSaveThreshold; }; if (dispatch_get_current_queue() == storageQueue) block(); else dispatch_async(storageQueue, block); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Stream JID Caching //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // We cache a stream's myJID to avoid constantly querying the xmppStream for it. // // The motivation behind this is the fact that to query the xmppStream for its myJID // requires going through the xmppStream's internal dispatch queue. (A dispatch_sync). // It's not necessarily that this is an expensive operation, // but the storage classes sometimes require this information for just about every operation they perform. // For a variable that changes infrequently, caching the value can reduce some overhead. // In addition, if we can stay out of xmppStream's internal dispatch queue, // we free it to perform more xmpp processing tasks. - (XMPPJID *)myJIDForXMPPStream:(XMPPStream *)stream { NSAssert(dispatch_get_current_queue() == storageQueue, @"Invoked on incorrect queue"); NSNumber *key = [[NSNumber alloc] initWithPtr:stream]; XMPPJID *result = (XMPPJID *)[myJidCache objectForKey:key]; if (!result) { result = [stream myJID]; if (result) [myJidCache setObject:result forKey:key]; else [myJidCache removeObjectForKey:key]; } [key release]; return result; } - (void)updateJidCache:(NSNotification *)notification { // Notifications are delivered on the thread/queue that posted them. // In this case, they are delivered on xmppStream's internal processing queue. XMPPStream *stream = (XMPPStream *)[notification object]; dispatch_async(storageQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSNumber *key = [NSNumber numberWithPtr:stream]; if ([myJidCache objectForKey:key]) { XMPPJID *newMyJID = [stream myJID]; if (newMyJID) [myJidCache setObject:newMyJID forKey:key]; else [myJidCache removeObjectForKey:key]; } [pool drain]; }); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Core Data Setup //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSString *)persistentStoreDirectory { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory(); // Attempt to find a name for this application NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]; if (appName == nil) { appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"]; } if (appName == nil) { appName = @"xmppframework"; } NSString *result = [basePath stringByAppendingPathComponent:appName]; NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:result]) { [fileManager createDirectoryAtPath:result withIntermediateDirectories:YES attributes:nil error:nil]; } return result; } - (NSManagedObjectModel *)managedObjectModel { // This is a public method. // It may be invoked on any thread/queue. dispatch_block_t block = ^{ if (managedObjectModel) { return; } NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPLogVerbose(@"%@: Creating managedObjectModel", [self class]); NSString *momName = [self managedObjectModelName]; NSString *momPath = [[NSBundle mainBundle] pathForResource:momName ofType:@"mom"]; if (momPath == nil) { // The model may be versioned or created with Xcode 4, try momd as an extension. momPath = [[NSBundle mainBundle] pathForResource:momName ofType:@"momd"]; } if (momPath) { // If path is nil, then NSURL or NSManagedObjectModel will throw an exception NSURL *momUrl = [NSURL fileURLWithPath:momPath]; managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:momUrl]; } else { XMPPLogWarn(@"%@: Couldn't find managedObjectModel file - %@", [self class], momName); } [pool drain]; }; if (dispatch_get_current_queue() == storageQueue) block(); else dispatch_sync(storageQueue, block); return managedObjectModel; } - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { // This is a public method. // It may be invoked on any thread/queue. dispatch_block_t block = ^{ if (persistentStoreCoordinator) { return; } NSManagedObjectModel *mom = [self managedObjectModel]; if (mom == nil) { return; } NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; XMPPLogVerbose(@"%@: Creating persistentStoreCoordinator", [self class]); persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom]; if (databaseFileName) { // SQLite persistent store NSString *docsPath = [self persistentStoreDirectory]; NSString *storePath = [docsPath stringByAppendingPathComponent:databaseFileName]; if (storePath) { // If storePath is nil, then NSURL will throw an exception [self willCreatePersistentStoreWithPath:storePath]; NSError *error = nil; if (![self addPersistentStoreWithPath:storePath error:&error]) { [self didNotAddPersistentStoreWithPath:storePath error:error]; } } else { XMPPLogWarn(@"%@: Error creating persistentStoreCoordinator - Nil persistentStoreDirectory", [self class]); } } else { // In-Memory persistent store [self willCreatePersistentStoreWithPath:nil]; NSError *error = nil; if (![self addPersistentStoreWithPath:nil error:&error]) { [self didNotAddPersistentStoreWithPath:nil error:error]; } } [pool drain]; }; if (dispatch_get_current_queue() == storageQueue) block(); else dispatch_sync(storageQueue, block); return persistentStoreCoordinator; } - (NSManagedObjectContext *)managedObjectContext { // This is a private method. // // NSManagedObjectContext is NOT thread-safe. // Therefore it is VERY VERY BAD to use our private managedObjectContext outside our private storageQueue. // // You should NOT remove the assert statement below! // You should NOT give external classes access to the storageQueue! (Excluding subclasses obviously.) // // When you want a managedObjectContext of your own (again, excluding subclasses), // you should create your own using the public persistentStoreCoordinator. // // If you even comtemplate ignoring this warning, // then you need to go read the documentation for core data, // specifically the section entitled "Concurrency with Core Data". // NSAssert(dispatch_get_current_queue() == storageQueue, @"Invoked on incorrect queue"); // // Do NOT remove the assert statment above! // Read the comments above! // if (managedObjectContext) { return managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator) { XMPPLogVerbose(@"%@: Creating managedObjectContext", [self class]); managedObjectContext = [[NSManagedObjectContext alloc] init]; [managedObjectContext setPersistentStoreCoordinator:coordinator]; [self didCreateManagedObjectContext]; } return managedObjectContext; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Utilities //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (NSUInteger)numberOfUnsavedChanges { NSManagedObjectContext *moc = [self managedObjectContext]; NSUInteger unsavedCount = 0; unsavedCount += [[moc updatedObjects] count]; unsavedCount += [[moc insertedObjects] count]; unsavedCount += [[moc deletedObjects] count]; return unsavedCount; } - (void)save { // I'm fairly confident that the implementation of [NSManagedObjectContext save:] // internally checks to see if it has anything to save before it actually does anthing. // So there's no need for us to do it here, especially since this method is usually // called from maybeSave below, which already does this check. NSError *error = nil; if (![[self managedObjectContext] save:&error]) { XMPPLogWarn(@"%@: Error saving - %@ %@", [self class], error, [error userInfo]); [[self managedObjectContext] rollback]; } } - (void)maybeSave:(int32_t)currentPendingRequests { NSAssert(dispatch_get_current_queue() == storageQueue, @"Invoked on incorrect queue"); if ([[self managedObjectContext] hasChanges]) { if (currentPendingRequests == 0) { XMPPLogVerbose(@"%@: Triggering save (pendingRequests=%i)", [self class], currentPendingRequests); [self save]; } else { NSUInteger unsavedCount = [self numberOfUnsavedChanges]; if (unsavedCount >= saveThreshold) { XMPPLogVerbose(@"%@: Triggering save (unsavedCount=%lu)", [self class], (unsigned long)unsavedCount); [self save]; } } } } - (void)maybeSave { // Convenience method in the very rare case that a subclass would need to invoke maybeSave manually. [self maybeSave:OSAtomicAdd32(0, &pendingRequests)]; } - (void)executeBlock:(dispatch_block_t)block { // By design this method should not be invoked from the storageQueue. // // If you remove the assert statement below, you are destroying the sole purpose for this class, // which is to optimize the disk IO by buffering save operations. // NSAssert(dispatch_get_current_queue() != storageQueue, @"Invoked on incorrect queue"); // // For a full discussion of this method, please see XMPPCoreDataStorageProtocol.h // // dispatch_Sync // ^ OSAtomicIncrement32(&pendingRequests); dispatch_sync(storageQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; block(); // Since this is a synchronous request, we want to return as quickly as possible. // So we delay the maybeSave operation til later. dispatch_async(storageQueue, ^{ NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init]; [self maybeSave:OSAtomicDecrement32(&pendingRequests)]; [innerPool drain]; }); [pool drain]; }); } - (void)scheduleBlock:(dispatch_block_t)block { // By design this method should not be invoked from the storageQueue. // // If you remove the assert statement below, you are destroying the sole purpose for this class, // which is to optimize the disk IO by buffering save operations. // NSAssert(dispatch_get_current_queue() != storageQueue, @"Invoked on incorrect queue"); // // For a full discussion of this method, please see XMPPCoreDataStorageProtocol.h // // dispatch_Async // ^ OSAtomicIncrement32(&pendingRequests); dispatch_async(storageQueue, ^{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; block(); [self maybeSave:OSAtomicDecrement32(&pendingRequests)]; [pool drain]; }); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma mark Memory Management //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; if (databaseFileName) { [[self class] unregisterDatabaseFileName:databaseFileName]; [databaseFileName release]; } [myJidCache release]; if (storageQueue) { dispatch_release(storageQueue); } [managedObjectContext release]; [persistentStoreCoordinator release]; [managedObjectModel release]; [super dealloc]; } @end
04081337-xmpp
Extensions/CoreDataStorage/XMPPCoreDataStorage.m
Objective-C
bsd
20,820