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
|
|---|---|---|---|---|---|
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
/**
* This class provides an optional base class that may be used to implement
* a CoreDataStorage class for an xmpp extension (or perhaps any core data storage class).
*
* It operates on its own dispatch queue which allows it to easily provide storage for multiple extension instance.
* More importantly, it smartly buffers its save operations to maximize performance!
*
* It does this using two techniques:
*
* First, it monitors the number of pending requests.
* When a operation is requested of the class, it increments an atomic variable, and schedules the request.
* After the request has been processed, it decrements the atomic variable.
* At this point it knows if there are other pending requests,
* and it uses the information to decide if it should save now,
* or postpone the save operation until the pending requests have been executed.
*
* Second, it monitors the number of unsaved changes.
* Since NSManagedObjectContext retains any changed objects until they are saved to disk
* it is an important memory management concern to keep the number of changed objects within a healthy range.
* This class uses a configurable saveThreshold to save at appropriate times.
*
* This class also offers several useful features such as
* preventing multiple instances from using the same database file (conflict)
* and caching of xmppStream.myJID to improve performance.
*
* For more information on how to extend this class,
* please see the XMPPCoreDataStorageProtected.h header file.
*
* The framework comes with several classes that extend this base class such as:
* - XMPPRosterCoreDataStorage (Extensions/Roster)
* - XMPPCapabilitiesCoreDataStorage (Extensions/XEP-0115)
* - XMPPvCardCoreDataStorage (Extensions/XEP-0054)
*
* Feel free to skim over these as reference implementations.
**/
@interface XMPPCoreDataStorage : NSObject {
@private
NSMutableDictionary *myJidCache;
int32_t pendingRequests;
NSManagedObjectModel *managedObjectModel;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
NSManagedObjectContext *managedObjectContext;
@protected
NSString *databaseFileName;
NSUInteger saveThreshold;
dispatch_queue_t storageQueue;
}
/**
* Initializes a core data storage instance, backed by SQLite, with the given database store filename.
* It is recommended your database filname use the "sqlite" file extension (e.g. "XMPPRoster.sqlite").
* If you pass nil, a default database filename is automatically used.
* This default is derived from the classname,
* meaning subclasses will get a default database filename derived from the subclass classname.
*
* If you attempt to create an instance of this class with the same databaseFileName as another existing instance,
* this method will return nil.
**/
- (id)initWithDatabaseFilename:(NSString *)databaseFileName;
/**
* Initializes a core data storage instance, backed by an in-memory store.
**/
- (id)initWithInMemoryStore;
/**
* Readonly access to the databaseFileName used during initialization.
* If nil was passed to the init method, returns the actual databaseFileName being used (the default filename).
**/
@property (readonly) NSString *databaseFileName;
/**
* The saveThreshold specifies the maximum number of unsaved changes to NSManagedObjects before a save is triggered.
*
* Since NSManagedObjectContext retains any changed objects until they are saved to disk
* it is an important memory management concern to keep the number of changed objects within a healthy range.
**/
@property (readwrite) NSUInteger saveThreshold;
/**
* Provides access the the thread-safe components of the CoreData stack.
*
* Please note:
* The managedObjectContext is private to the storageQueue.
* You must create and use your own managedObjectContext.
*
* If you think you can simply add a property for the private managedObjectContext,
* then you need to go read the documentation for core data,
* specifically the section entitled "Concurrency with Core Data".
**/
@property (readonly) NSManagedObjectModel *managedObjectModel;
@property (readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@end
|
04081337-xmpp
|
Extensions/CoreDataStorage/XMPPCoreDataStorage.h
|
Objective-C
|
bsd
| 4,249
|
#import "XMPPCoreDataStorage.h"
@class XMPPJID;
@class XMPPStream;
/**
* The methods in this class are to be used ONLY by subclasses of XMPPCoreDataStorage.
**/
@interface XMPPCoreDataStorage (Protected)
#pragma mark Override Me
/**
* 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 *)managedObjectModelName;
/**
* Override me, if needed, to provide customized behavior.
*
* This method is queried if the initWithDatabaseFileName method is invoked with a nil parameter.
* The default implementation returns:
*
* [NSString stringWithFormat:@"%@.sqlite", [self defaultFileName]];
*
* You are encouraged to use the sqlite file extension.
**/
- (NSString *)defaultDatabaseFileName;
/**
* 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.
*
* The default implementation does nothing.
**/
- (void)willCreatePersistentStoreWithPath:(NSString *)storePath;
/**
* 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.
**/
- (BOOL)addPersistentStoreWithPath:(NSString *)storePath error:(NSError **)errorPtr;
/**
* 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 and a core data migration is not worthwhile.
*
* 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.
*
* The default implementation simply writes to the XMPP error log.
**/
- (void)didNotAddPersistentStoreWithPath:(NSString *)storePath error:(NSError *)error;
/**
* Override me, if needed, to provide customized behavior.
*
* For example, you may want to perform cleanup of any non-persistent data before you start using the database.
*
* The default implementation does nothing.
**/
- (void)didCreateManagedObjectContext;
#pragma mark Setup
/**
* 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.
*
* Note that the default implementation allows the storage class to be used by multiple xmpp streams.
* If you design your storage class to be used by a single stream, then you should implement this method
* to ensure that your class can only be configured by one parent.
* If you do, again, don't forget to invoke super at some point.
**/
- (BOOL)configureWithParent:(id)aParent queue:(dispatch_queue_t)queue;
#pragma mark Stream JID caching
/**
* This class provides a caching service for xmppStream.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 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.
*
* If the xmppStream.myJID changes, the cache will automatically be updated.
*
* If you store any variant of xmppStream.myJID (bare, full, domain, etc) in your database
* you are strongly encouraged to use the caching service.
*
* For example, say you're implementing a core data storage caching mechanism for Private XML Storage (XEP-0049).
* The data you're caching is explictly tied to the stream's bare myJID. ([xmppStream.myJID bare])
* You want your storage class to support multiple xmpp streams,
* so you add a field to the database called streamBareJidStr (or whatever).
* Given an xmppStream, you can use the built-in cache to quickly get the xmppStream.myJid property:
*
* [self myJidForXMPPStream:stream]
*
* This method will retrieve the myJID property of the given xmppStream the first time,
* and then cache it for future lookups. The cache is automatically updated if the xmppStream.myJID ever changes.
**/
- (XMPPJID *)myJIDForXMPPStream:(XMPPStream *)stream;
#pragma mark Core Data
/**
* The standard persistentStoreDirectory method.
**/
- (NSString *)persistentStoreDirectory;
/**
* Provides access to the managedObjectContext.
*
* Keep in mind that NSManagedObjectContext is NOT thread-safe.
* So you can ONLY access this property from within the context of the storageQueue.
*
* Important:
* The primary purpose of this class is to optimize disk IO by buffering save operations to the managedObjectContext.
* It does this using the methods outlined in the 'Performance Optimizations' section below.
* If you manually save the managedObjectContext you are destroying these optimizations.
**/
@property (readonly) NSManagedObjectContext *managedObjectContext;
#pragma mark Performance Optimizations
/**
* Queries the managedObjectContext to determine the number of unsaved managedObjects.
**/
- (NSUInteger)numberOfUnsavedChanges;
/**
* You will not often need to manually call this method.
* It is called automatically, at appropriate and optimized times, via the executeBlock and scheduleBlock methods.
*
* The one exception to this is when you are inserting/deleting/updating a large number of objects in a loop.
* It is recommended that you invoke save from within the loop.
* E.g.:
*
* NSUInteger unsavedCount = [self numberOfUnsavedChanges];
* for (NSManagedObject *obj in fetchResults)
* {
* [[self managedObjectContext] deleteObject:obj];
*
* if (++unsavedCount >= saveThreshold)
* {
* [self save];
* unsavedCount = 0;
* }
* }
*
* See also the documentation for executeBlock and scheduleBlock below.
**/
- (void)save; // Read the comments above !
/**
* You will rarely need to manually call this method.
* It is called automatically, at appropriate and optimized times, via the executeBlock and scheduleBlock methods.
*
* This method makes informed decisions as to whether it should save the managedObjectContext changes to disk.
* Since this disk IO is a slow process, it is better to buffer writes during high demand.
* This method takes into account the number of pending requests waiting on the storage instance,
* as well as the number of unsaved changes (which reside in NSManagedObjectContext's internal memory).
*
* Please see the documentation for executeBlock and scheduleBlock below.
**/
- (void)maybeSave; // Read the comments above !
/**
* This method synchronously invokes the given block (dispatch_sync) on the storageQueue.
*
* Prior to dispatching the block it increments (atomically) the number of pending requests.
* After the block has been executed, it decrements (atomically) the number of pending requests,
* and then invokes the maybeSave method which implements the logic behind the optimized disk IO.
*
* If you use the executeBlock and scheduleBlock methods for all your database operations,
* you will automatically inherit optimized disk IO for free.
*
* If you manually invoke [managedObjectContext save:] you are destroying the optimizations provided by this class.
*
* The block handed to this method is automatically wrapped in a NSAutoreleasePool,
* so there is no need to create these yourself as this method automatically handles it for you.
*
* The architecture of this class purposefully puts the CoreDataStorage instance on a separate dispatch_queue
* from the parent XmppExtension. Not only does this allow a single storage instance to service multiple extension
* instances, but it provides the mechanism for the disk IO optimizations. The theory behind the optimizations
* is to delay a save of the data (a slow operation) until the storage class is no longer being used. With xmpp
* it is often the case that a burst of data causes a flurry of queries and/or updates for a storage class.
* Thus the theory is to delay the slow save operation until later when the flurry has ended and the storage
* class no longer has any pending requests.
*
* This method is designed to be invoked from within the XmppExtension storage protocol methods.
* In other words, it is expecting to be invoked from a dispatch_queue other than the storageQueue.
* If you attempt to invoke this method from within the storageQueue, an exception is thrown.
* Therefore care should be taken when designing your implementation.
* The recommended procedure is as follows:
*
* All of the methods that implement the XmppExtension storage protocol invoke either executeBlock or scheduleBlock.
* However, none of these methods invoke each other (they are only to be invoked from the XmppExtension instance).
* Instead, create internal utility methods that may be invoked.
*
* For an example, see the XMPPRosterCoreDataStorage implementation's _userForJID:xmppStream: method.
**/
- (void)executeBlock:(dispatch_block_t)block;
/**
* This method asynchronously invokes the given block (dispatch_async) on the storageQueue.
*
* It works very similarly to the executeBlock method.
* See the executeBlock method above for a full discussion.
**/
- (void)scheduleBlock:(dispatch_block_t)block;
@end
|
04081337-xmpp
|
Extensions/CoreDataStorage/XMPPCoreDataStorageProtected.h
|
Objective-C
|
bsd
| 10,705
|
#import "StreamController.h"
#import "ServerlessDemoAppDelegate.h"
#import "GCDAsyncSocket.h"
#import "XMPPStream.h"
#import "Service.h"
#import "Message.h"
#import "NSXMLElement+XMPP.h"
#import "NSString+DDXML.h"
#import "DDLog.h"
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
@implementation StreamController
static StreamController *sharedInstance;
+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
sharedInstance = [[StreamController alloc] init];
}
}
- (id)init
{
// Only allow one instance of this class to ever be created
if(sharedInstance)
{
[self release];
return nil;
}
if((self = [super init]))
{
xmppStreams = [[NSMutableArray alloc] initWithCapacity:4];
serviceDict = [[NSMutableDictionary alloc] initWithCapacity:4];
}
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Public API
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ (StreamController *)sharedInstance
{
return sharedInstance;
}
- (void)startListening
{
if (listeningSocket == nil)
{
listeningSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
}
NSError *error = nil;
if (![listeningSocket acceptOnPort:0 error:&error])
{
DDLogError(@"Error setting up socket: %@", error);
}
}
- (void)stopListening
{
[listeningSocket disconnect];
}
- (UInt16)listeningPort
{
return [listeningSocket localPort];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Private API
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (NSManagedObjectContext *)managedObjectContext
{
ServerlessDemoAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
return appDelegate.managedObjectContext;
}
- (XMPPJID *)myJID
{
ServerlessDemoAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
return appDelegate.myJID;
}
- (Service *)serviceWithAddress:(NSString *)addrStr
{
if (addrStr == nil) return nil;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Service"
inManagedObjectContext:[self managedObjectContext]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"lastResolvedAddress == %@", addrStr];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:predicate];
[fetchRequest setFetchLimit:1];
NSError *error = nil;
NSArray *results = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
if (results == nil)
{
DDLogError(@"Error searching for service with address \"%@\": %@, %@", addrStr, error, [error userInfo]);
return nil;
}
else if ([results count] == 0)
{
DDLogWarn(@"Unable to find service with address \"%@\"", addrStr);
return nil;
}
else
{
return [results objectAtIndex:0];
}
}
- (id)nextXMPPStreamTag
{
static NSInteger tag = 0;
NSNumber *result = [NSNumber numberWithInteger:tag];
tag++;
return result;
}
- (Service *)serviceWithXMPPStream:(XMPPStream *)xmppStream
{
NSManagedObjectID *managedObjectID = [serviceDict objectForKey:[xmppStream tag]];
return (Service *)[[self managedObjectContext] objectWithID:managedObjectID];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark GCDAsyncSocket Delegate Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)socket:(GCDAsyncSocket *)listenSock didAcceptNewSocket:(GCDAsyncSocket *)acceptedSock
{
NSString *addrStr = [acceptedSock connectedHost];
Service *service = [self serviceWithAddress:addrStr];
if (service)
{
DDLogInfo(@"Accepting connection from service: %@", service.serviceDescription);
id tag = [self nextXMPPStreamTag];
XMPPStream *xmppStream = [[XMPPStream alloc] initP2PFrom:[self myJID]];
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
xmppStream.tag = tag;
[xmppStream connectP2PWithSocket:acceptedSock error:nil];
[xmppStreams addObject:xmppStream];
[serviceDict setObject:[service objectID] forKey:tag];
}
else
{
DDLogWarn(@"Ignoring connection from unknown service (%@)", addrStr);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark XMPPStream Delegate Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender willSendP2PFeatures:(NSXMLElement *)streamFeatures
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender didReceiveP2PFeatures:(NSXMLElement *)streamFeatures
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
return NO;
}
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
Service *service = [self serviceWithXMPPStream:sender];
if (service)
{
NSString *msgBody = [[[message elementForName:@"body"] stringValue] stringByTrimming];
if ([msgBody length] > 0)
{
Message *msg = [NSEntityDescription insertNewObjectForEntityForName:@"Message"
inManagedObjectContext:[self managedObjectContext]];
msg.content = msgBody;
msg.isOutbound = NO;
msg.hasBeenRead = NO;
msg.timeStamp = [NSDate date];
msg.service = service;
[[self managedObjectContext] save:nil];
}
}
}
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error
{
DDLogVerbose(@"%@: %@ %@", THIS_FILE, THIS_METHOD, error);
}
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
[serviceDict removeObjectForKey:sender.tag];
[xmppStreams removeObject:sender];
}
@end
|
04081337-xmpp
|
Xcode/ServerlessDemo/StreamController.m
|
Objective-C
|
bsd
| 6,675
|
#import "Message.h"
#import "Service.h"
@implementation Message
@dynamic content;
@dynamic outbound;
@dynamic read;
@dynamic timeStamp;
@dynamic service;
@dynamic isOutbound;
@dynamic hasBeenRead;
- (BOOL)isOutbound
{
return [[self outbound] boolValue];
}
- (void)setIsOutbound:(BOOL)flag
{
[self setOutbound:[NSNumber numberWithBool:flag]];
}
- (BOOL)hasBeenRead
{
return [[self read] boolValue];
}
- (void)setHasBeenRead:(BOOL)flag
{
if (flag != [self hasBeenRead])
{
[self.service willChangeValueForKey:@"messages"];
[self setRead:[NSNumber numberWithBool:flag]];
[self.service didChangeValueForKey:@"messages"];
}
}
@end
|
04081337-xmpp
|
Xcode/ServerlessDemo/Message.m
|
Objective-C
|
bsd
| 661
|
//
// main.m
// ServerlessDemo
//
// Created by Robbie Hanson on 1/8/10.
// Copyright Deusty Designs, LLC. 2010. All rights reserved.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
|
04081337-xmpp
|
Xcode/ServerlessDemo/main.m
|
Objective-C
|
bsd
| 371
|
#import <CoreData/CoreData.h>
@class Service;
@interface Message : NSManagedObject
// Properties
@property (nonatomic, retain) NSString * content;
@property (nonatomic, retain) NSNumber * outbound;
@property (nonatomic, retain) NSNumber * read;
@property (nonatomic, retain) NSDate * timeStamp;
// Relationships
@property (nonatomic, retain) Service * service;
// Convenience Properties
@property (nonatomic, assign) BOOL isOutbound;
@property (nonatomic, assign) BOOL hasBeenRead;
@end
|
04081337-xmpp
|
Xcode/ServerlessDemo/Message.h
|
Objective-C
|
bsd
| 499
|
#import <CoreData/CoreData.h>
enum StatusType
{
StatusOffline = 0,
StatusDND = 1,
StatusAvailable = 2,
};
typedef enum StatusType StatusType;
@interface Service : NSManagedObject
// NSNetService Properties
@property (nonatomic, retain) NSString * serviceType;
@property (nonatomic, retain) NSString * serviceName;
@property (nonatomic, retain) NSString * serviceDomain;
@property (nonatomic, retain) NSString * serviceDescription;
// TXTRecord Properties
@property (nonatomic, retain) NSNumber * status;
@property (nonatomic, retain) NSString * statusMessage;
@property (nonatomic, retain) NSString * firstName;
@property (nonatomic, retain) NSString * lastName;
@property (nonatomic, retain) NSString * nickname;
@property (nonatomic, retain) NSString * displayName;
@property (nonatomic, retain) NSString * lastResolvedAddress;
// Relationship Properties
@property (nonatomic, retain) NSSet * messages;
// Convenience Properties
@property (nonatomic, assign) StatusType statusType;
// Utility Methods
+ (NSString *)statusTxtTitleForStatusType:(StatusType)type;
+ (NSString *)statusDisplayTitleForStatusType:(StatusType)type;
+ (StatusType)statusTypeForStatusTxtTitle:(NSString *)statusTxtTitle;
- (NSString *)statusTxtTitle;
- (NSString *)statusDisplayTitle;
- (void)updateDisplayName;
- (NSUInteger)numberOfUnreadMessages;
@end
|
04081337-xmpp
|
Xcode/ServerlessDemo/Service.h
|
Objective-C
|
bsd
| 1,360
|
#import <Foundation/Foundation.h>
@class GCDAsyncSocket;
@class Service;
@interface StreamController : NSObject
{
GCDAsyncSocket *listeningSocket;
NSMutableArray *xmppStreams;
NSMutableDictionary *serviceDict;
}
+ (StreamController *)sharedInstance;
- (void)startListening;
- (void)stopListening;
- (UInt16)listeningPort;
@end
|
04081337-xmpp
|
Xcode/ServerlessDemo/StreamController.h
|
Objective-C
|
bsd
| 336
|
#import "DDString.h"
@implementation NSString (DDString)
+ (id)stringWithUTF8Data:(NSData *)data
{
return [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
}
@end
|
04081337-xmpp
|
Xcode/ServerlessDemo/DDString.m
|
Objective-C
|
bsd
| 200
|
#import "Service.h"
@implementation Service
@dynamic serviceType;
@dynamic serviceName;
@dynamic serviceDomain;
@dynamic serviceDescription;
@dynamic status;
@dynamic statusMessage;
@dynamic firstName;
@dynamic lastName;
@dynamic nickname;
@dynamic displayName;
@dynamic lastResolvedAddress;
@dynamic messages;
@dynamic statusType;
- (StatusType)statusType
{
switch ([[self status] intValue])
{
case StatusAvailable: return StatusAvailable;
case StatusDND : return StatusDND;
default : return StatusOffline;
}
}
- (void)setStatusType:(StatusType)type
{
switch (type)
{
case StatusAvailable:
[self setStatus:[NSNumber numberWithInt:StatusAvailable]];
break;
case StatusDND:
[self setStatus:[NSNumber numberWithInt:StatusDND]];
break;
default:
[self setStatus:[NSNumber numberWithInt:StatusOffline]];
break;
}
}
+ (NSString *)statusTxtTitleForStatusType:(StatusType)type
{
switch (type)
{
case StatusAvailable: return @"avail";
case StatusDND : return @"dnd";
default : return @"offline";
}
}
+ (NSString *)statusDisplayTitleForStatusType:(StatusType)type
{
switch (type)
{
case StatusAvailable: return @"Available";
case StatusDND : return @"Away";
default : return @"Offline";
}
}
+ (StatusType)statusTypeForStatusTxtTitle:(NSString *)statusTxtTitle
{
if ([statusTxtTitle caseInsensitiveCompare:@"avail"] == NSOrderedSame)
{
return StatusAvailable;
}
if ([statusTxtTitle caseInsensitiveCompare:@"dnd"] == NSOrderedSame)
{
return StatusDND;
}
return StatusOffline;
}
- (NSString *)statusTxtTitle
{
return [[self class] statusTxtTitleForStatusType:[self statusType]];
}
- (NSString *)statusDisplayTitle
{
return [[self class] statusDisplayTitleForStatusType:[self statusType]];
}
- (void)updateDisplayName
{
NSString *nickname = self.nickname;
NSString *firstName = self.firstName;
NSString *lastName = self.lastName;
// If the firstName or lastName isn't properly entered, we shouldn't have goofy leading/trailing whitespace.
if([nickname length] > 0)
{
self.displayName = nickname;
}
else if([firstName length] > 0)
{
if([lastName length] > 0)
self.displayName = [firstName stringByAppendingFormat:@" %@", lastName];
else
self.displayName = firstName;
}
else if([lastName length] > 0)
{
self.displayName = lastName;
}
else
{
self.displayName = self.serviceName;
}
}
- (NSUInteger)numberOfUnreadMessages
{
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Message"
inManagedObjectContext:self.managedObjectContext];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"service == %@ AND read == NO", self];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:predicate];
NSError *error = nil;
NSUInteger count = 0;
count = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error];
[fetchRequest release];
if (error)
{
NSLog(@"Error getting unread count: %@, %@", error, [error userInfo]);
}
return count;
}
@end
|
04081337-xmpp
|
Xcode/ServerlessDemo/Service.m
|
Objective-C
|
bsd
| 3,198
|
#import <Foundation/Foundation.h>
@interface NSString (DDString)
+ (id)stringWithUTF8Data:(NSData *)data;
@end
|
04081337-xmpp
|
Xcode/ServerlessDemo/DDString.h
|
Objective-C
|
bsd
| 115
|
#import <UIKit/UIKit.h>
@class Service;
@class XMPPStream;
@interface ChatViewController : UIViewController <UITableViewDelegate,
UITextFieldDelegate,
NSNetServiceDelegate,
NSFetchedResultsControllerDelegate>
{
IBOutlet UITextField *textField;
IBOutlet UITableView *tableView;
Service *service;
NSNetService *netService;
XMPPStream *xmppStream;
// Core data
NSFetchedResultsController *fetchedResultsController;
NSManagedObjectContext *managedObjectContext;
}
@property (nonatomic, retain) Service *service;
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
- (void)sendMessage:(id)sender;
@end
|
04081337-xmpp
|
Xcode/ServerlessDemo/Classes/ChatViewController.h
|
Objective-C
|
bsd
| 789
|
#import <UIKit/UIKit.h>
@interface RootViewController : UITableViewController <NSFetchedResultsControllerDelegate>
{
NSFetchedResultsController *fetchedResultsController;
NSManagedObjectContext *managedObjectContext;
}
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
@end
|
04081337-xmpp
|
Xcode/ServerlessDemo/Classes/RootViewController.h
|
Objective-C
|
bsd
| 306
|
#import "ChatViewController.h"
#import "ServerlessDemoAppDelegate.h"
#import "Service.h"
#import "Message.h"
#import "DDXML.h"
#import "XMPPStream.h"
#import "XMPPJID.h"
#import "XMPPIQ.h"
#import "XMPPMessage.h"
#import "XMPPPresence.h"
#import "NSXMLElement+XMPP.h"
#import "NSString+DDXML.h"
#import "DDLog.h"
#import <arpa/inet.h>
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
// The BlueBubble and GreenBubble images are used as stretchable images.
// Stretchable images are defined using a leftCapWidth and topCapHeight.
// The rightCapWidth and bottomCapHeight are implicitly defined,
// assuming that the middle (stretchable) portion is 1 pixel.
#define kImageWidth 32
#define kImageHeight 29
#define kBlueLeftCapWidth 17
#define kBlueRightCapWidth (kImageWidth - kBlueLeftCapWidth - 1)
#define kGreenLeftCapWidth 14
#define kGreenRightCapWidth (kImageWidth - kGreenLeftCapWidth - 1)
#define kTopCapHeight 15
#define kBottomCapHeight (kImageHeight - kTopCapHeight - 1)
#define kMaxMessageContentWidth (320 - 17 - 14 - 20)
#define kTimeStampHeight 21
#define kAContentOffset 6
#define kBContentOffset kAContentOffset - 3
#define kBlueLeftContentOffset (kBlueLeftCapWidth - kAContentOffset)
#define kBlueRightContentOffset (kBlueRightCapWidth - kBContentOffset)
#define kGreenLeftContentOffset (kGreenLeftCapWidth - kBContentOffset)
#define kGreenRightContentOffset (kGreenRightCapWidth - kAContentOffset)
#define kTopContentOffset (3)
#define kBottomContentOffset (3)
#define kNonContentWidth (kImageWidth - kAContentOffset - kBContentOffset)
#define kNonContentHeight (kImageHeight - kTopContentOffset - kBottomContentOffset)
#define kBubbleImageViewTag 1
#define kContentLabelTag 2
#define kTimestampLabelTag 3
@interface ChatViewController (PrivateAPI)
- (void)scrollToBottomAnimated:(BOOL)animated;
- (UITableViewCell *)newMessageBubbleCellWithIdentifier:(NSString *)cellIdentifier;
- (UIFont *)messageFont;
- (CGSize)sizeForMessageIndexPath:(NSIndexPath *)indexPath;
- (BOOL)shouldDisplayTimeStampForMessageAtIndexPath:(NSIndexPath *)indexPath;
- (void)configureCell:(UITableViewCell *)theCell atIndexPath:(NSIndexPath *)indexPath;
- (NSFetchedResultsController *)fetchedResultsController;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation ChatViewController
@synthesize service;
@synthesize managedObjectContext;
- (void)viewDidLoad
{
textField.placeholder = @"Tap here to chat";
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
netService = [[NSNetService alloc] initWithDomain:[service serviceDomain]
type:[service serviceType]
name:[service serviceName]];
[netService setDelegate:self];
[netService resolveWithTimeout:5.0];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self scrollToBottomAnimated:NO];
}
- (void)viewDidAppear:(BOOL)animated
{
// From the documentation:
//
// You can override this method to perform additional tasks associated with presenting the view.
// If you override this method, you must call super at some point in your implementation.
[super viewDidAppear:animated];
if([[service messages] count] == 0)
{
[textField becomeFirstResponder];
}
else
{
// [service markUnreadMessagesAsRead];
// // Update roster table view to eliminate the unread indicator
// Todo...
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Notifications
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)keyboardWillShow:(NSNotification *)notification
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
// Extract information about the keyboard change.
float keyboardHeight;
double animationDuration;
// UIKeyboardBoundsUserInfoKey:
// The key for an NSValue object containing a CGRect that identifies the bounds rectangle of the keyboard.
CGRect beginRect = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
CGRect endRect = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardHeight = ABS(beginRect.origin.y - endRect.origin.y);
// UIKeyboardAnimationDurationUserInfoKey
// The key for an NSValue object containing a double that identifies the duration of the animation in seconds.
animationDuration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// Resize the view
CGRect viewFrame = [self.view frame];
viewFrame.size.height -= keyboardHeight;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:animationDuration];
self.view.frame = viewFrame;
[UIView commitAnimations];
[self performSelector:@selector(delayedScrollToBottomAnimated:)
withObject:[NSNumber numberWithBool:YES]
afterDelay:0.3];
}
- (void)keyboardWillHide:(NSNotification *)notification
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
// Extract information about the keyboard change.
float keyboardHeight;
double animationDuration;
// UIKeyboardBoundsUserInfoKey:
// The key for an NSValue object containing a CGRect that identifies the bounds rectangle of the keyboard.
CGRect beginRect = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
CGRect endRect = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardHeight = ABS(beginRect.origin.y - endRect.origin.y);
// UIKeyboardAnimationDurationUserInfoKey
// The key for an NSValue object containing a double that identifies the duration of the animation in seconds.
animationDuration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// Reset the height of the scroll view to its original value
CGRect viewFrame = [[self view] frame];
viewFrame.size.height += keyboardHeight;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:animationDuration];
self.view.frame = viewFrame;
[UIView commitAnimations];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Actions
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)sendMessage:(NSString *)msgContent
{
NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
[body setStringValue:msgContent];
NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
[message addAttributeWithName:@"type" stringValue:@"chat"];
[message addChild:body];
[xmppStream sendElement:message];
Message *msg = [NSEntityDescription insertNewObjectForEntityForName:@"Message"
inManagedObjectContext:[self managedObjectContext]];
msg.content = msgContent;
msg.isOutbound = YES;
msg.hasBeenRead = YES;
msg.timeStamp = [NSDate date];
msg.service = service;
[[self managedObjectContext] save:nil];
}
- (BOOL)textFieldShouldReturn:(UITextField *)sender
{
NSString *msgContent = [[textField text] stringByTrimming];
if([msgContent length] > 0)
{
[self sendMessage:msgContent];
}
textField.text = @"";
return NO;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark UITableView Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)delayedScrollToBottomAnimated:(NSNumber *)animated
{
[self scrollToBottomAnimated:[animated boolValue]];
}
- (void)scrollToBottomAnimated:(BOOL)animated
{
NSInteger numRows = [tableView numberOfRowsInSection:0];
if (numRows > 0)
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(numRows - 1) inSection:0];
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:animated];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)sender
{
return [[[self fetchedResultsController] sections] count];
}
- (NSInteger)tableView:(UITableView *)sender numberOfRowsInSection:(NSInteger)sectionIndex
{
NSArray *sections = [[self fetchedResultsController] sections];
if (sectionIndex < [sections count])
{
id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:sectionIndex];
return [sectionInfo numberOfObjects];
}
return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGSize cellSize = [self sizeForMessageIndexPath:indexPath];
return cellSize.height;
}
- (UITableViewCell *)tableView:(UITableView *)sender cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"ChatViewController_Cell";
UITableViewCell *cell = [sender dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[self newMessageBubbleCellWithIdentifier:CellIdentifier] autorelease];
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Message Cell
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (UITableViewCell *)newMessageBubbleCellWithIdentifier:(NSString *)cellIdentifier
{
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.backgroundColor = [UIColor colorWithRed:(219/255.0) green:(226/255.0) blue:(237/255.0) alpha:1.0];
UILabel *timestampLabel;
UILabel *contentLabel;
UIImageView *bubbleImageView;
// Add text label for timestamp
timestampLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, kTimeStampHeight)];
timestampLabel.font = [UIFont systemFontOfSize:13];
timestampLabel.textAlignment = UITextAlignmentCenter;
timestampLabel.backgroundColor = cell.backgroundColor;
timestampLabel.opaque = YES;
timestampLabel.tag = kTimestampLabelTag;
timestampLabel.shadowOffset = CGSizeMake(0,1);
timestampLabel.textColor = [UIColor colorWithRed:(33/255.0F) green:(40/255.0F) blue:(53/255.0F) alpha:1.0F];
timestampLabel.shadowColor = [UIColor whiteColor];
contentLabel = [[UILabel alloc] init];
contentLabel.font = [self messageFont];
contentLabel.numberOfLines = 0;
contentLabel.backgroundColor = [UIColor clearColor];
contentLabel.tag = kContentLabelTag;
bubbleImageView = [[UIImageView alloc] initWithImage:nil];
bubbleImageView.tag = kBubbleImageViewTag;
// Note: Order matters - The contentLabel must be above the bubbleImageView
[cell.contentView addSubview:timestampLabel];
[cell.contentView addSubview:bubbleImageView];
[cell.contentView addSubview:contentLabel];
[timestampLabel release];
[contentLabel release];
[bubbleImageView release];
return cell;
}
- (UIFont *)messageFont
{
return [UIFont systemFontOfSize:([UIFont systemFontSize] - 1.0F)];
}
- (CGSize)sizeForMessageIndexPath:(NSIndexPath *)indexPath
{
Message *message = [[self fetchedResultsController] objectAtIndexPath:indexPath];
NSString *content = message.content;
UIFont *font = [self messageFont];
CGSize maxContentSize = CGSizeMake(kMaxMessageContentWidth, INFINITY);
CGSize contentSize = [content sizeWithFont:font constrainedToSize:maxContentSize];
CGSize cellSize = contentSize;
cellSize.width = MAX(contentSize.width + kNonContentWidth, kImageWidth);
cellSize.height = MAX(contentSize.height + kNonContentHeight, kImageHeight);
if([self shouldDisplayTimeStampForMessageAtIndexPath:indexPath])
{
// Add room for timestamp
cellSize.height += kTimeStampHeight;
}
return cellSize;
}
- (BOOL)shouldDisplayTimeStampForMessageAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0)
{
// Show interval for first message
return YES;
}
// Otherwise, show stamp if messages are seperated by more than 60 seconds
NSIndexPath *previousIndexPath = [NSIndexPath indexPathForRow:(indexPath.row - 1)
inSection:indexPath.section];
Message *currentMessage = [[self fetchedResultsController] objectAtIndexPath:indexPath];
Message *previousMessage = [[self fetchedResultsController] objectAtIndexPath:previousIndexPath];
NSDate *currentMessageDate = currentMessage.timeStamp;
NSDate *previousMessageDate = previousMessage.timeStamp;
NSTimeInterval interval = ABS([currentMessageDate timeIntervalSinceDate:previousMessageDate]);
return (interval > 60.0);
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
// Date formatter for the time stamp
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil)
{
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
}
cell.userInteractionEnabled = NO;
// Get message and cell views
Message *message = [[self fetchedResultsController] objectAtIndexPath:indexPath];
UILabel *timeStampLabel = (UILabel *)[cell viewWithTag:kTimestampLabelTag];
UILabel *contentLabel = (UILabel *)[cell viewWithTag:kContentLabelTag];
UIImageView *bubbleImageView = (UIImageView *)[cell viewWithTag:kBubbleImageViewTag];
// Update message if needed
if (![message hasBeenRead])
{
message.hasBeenRead = YES;
}
// Configure frames for everything
CGSize messageSize = [self sizeForMessageIndexPath:indexPath];
CGRect textFrame;
CGRect bubbleFrame;
if ([message isOutbound])
{
// Outgoing = GreenBubble (Right Side)
bubbleFrame.origin.x = cell.frame.size.width - messageSize.width;
bubbleFrame.origin.y = 0;
bubbleFrame.size.width = messageSize.width;
bubbleFrame.size.height = messageSize.height;
textFrame.origin.x = bubbleFrame.origin.x + kGreenLeftContentOffset;
textFrame.origin.y = bubbleFrame.origin.y + kTopContentOffset;
textFrame.size.width = messageSize.width - kGreenLeftContentOffset - kGreenRightContentOffset;
textFrame.size.height = messageSize.height - kTopContentOffset - kBottomContentOffset;
}
else
{
// Incoming = BlueBubble (Left Side)
bubbleFrame.origin.x = 0;
bubbleFrame.origin.y = 0;
bubbleFrame.size.width = messageSize.width;
bubbleFrame.size.height = messageSize.height;
textFrame.origin.x = bubbleFrame.origin.x + kBlueLeftContentOffset;
textFrame.origin.y = bubbleFrame.origin.y + kTopContentOffset;
textFrame.size.width = messageSize.width - kBlueLeftContentOffset - kBlueRightContentOffset;
textFrame.size.height = messageSize.height - kTopContentOffset - kBottomContentOffset;
}
// Timestamp
if ([self shouldDisplayTimeStampForMessageAtIndexPath:indexPath])
{
textFrame.size.height -= kTimeStampHeight;
textFrame.origin.y += kTimeStampHeight;
bubbleFrame.origin.y += kTimeStampHeight;
bubbleFrame.size.height -= kTimeStampHeight;
timeStampLabel.hidden = NO;
timeStampLabel.text = [dateFormatter stringFromDate:[message timeStamp]];
}
else
{
timeStampLabel.hidden = YES;
}
// Content
contentLabel.text = message.content;
contentLabel.font = [self messageFont];
// Bubble Image
if ([message isOutbound])
{
UIImage *img = [[UIImage imageNamed:@"GreenBubble.png"] stretchableImageWithLeftCapWidth:kGreenLeftCapWidth
topCapHeight:kTopCapHeight];
bubbleImageView.image = img;
contentLabel.textAlignment = UITextAlignmentRight;
}
else
{
UIImage *img = [[UIImage imageNamed:@"BlueBubble.png"] stretchableImageWithLeftCapWidth:kBlueLeftCapWidth
topCapHeight:kTopCapHeight];
bubbleImageView.image = img;
contentLabel.textAlignment = UITextAlignmentLeft;
}
contentLabel.frame = textFrame;
bubbleImageView.frame = bubbleFrame;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark FetchedResultsController
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController == nil)
{
NSSortDescriptor *dateSD;
NSArray *sortDescriptors;
NSFetchRequest *fetchRequest;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Message"
inManagedObjectContext:managedObjectContext];
dateSD = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:YES];
sortDescriptors = [[NSArray alloc] initWithObjects:dateSD, nil];
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"service = %@", service];
fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:10];
[fetchRequest setPredicate:predicate];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
fetchedResultsController.delegate = self;
NSError *error = nil;
if (![fetchedResultsController performFetch:&error])
{
DDLogError(@"Error fetching messages: %@ %@", error, [error userInfo]);
}
[dateSD release];
[sortDescriptors release];
[fetchRequest release];
}
return fetchedResultsController;
}
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
if (![self isViewLoaded]) return;
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
[tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller
didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath
forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
if (![self isViewLoaded]) return;
switch(type)
{
case NSFetchedResultsChangeInsert:
DDLogVerbose(@"%@: NSFetchedResultsChangeInsert: %@", THIS_FILE, newIndexPath);
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
DDLogVerbose(@"%@: NSFetchedResultsChangeDelete: %@", THIS_FILE, indexPath);
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
DDLogVerbose(@"%@: NSFetchedResultsChangeUpdate: %@", THIS_FILE, indexPath);
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationNone];
break;
case NSFetchedResultsChangeMove:
DDLogVerbose(@"%@: NSFetchedResultsChangeMove: %@ -> %@", THIS_FILE, indexPath, newIndexPath);
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
if (![self isViewLoaded]) return;
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
[tableView endUpdates];
[self scrollToBottomAnimated:YES];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark NSNetService Delegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)netServiceDidResolveAddress:(NSNetService *)ns
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
// The iPhone only supports IPv4, so we need to get the IPv4 address from the resolve operation.
ServerlessDemoAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSData *address = [appDelegate IPv4AddressFromAddresses:[ns addresses]];
NSString *addrStr = [appDelegate stringFromAddress:address];
if (address)
{
// Update the lastResolvedAddress for the service
service.lastResolvedAddress = addrStr;
// Create an xmpp stream to the service with the resolved address
XMPPJID *myJID = [appDelegate myJID];
XMPPJID *serviceJID = [XMPPJID jidWithString:[service serviceName]];
DDLogVerbose(@"%@: myJID(%@) serviceJID(%@)", THIS_FILE, myJID, serviceJID);
xmppStream = [[XMPPStream alloc] initP2PFrom:myJID];
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
[xmppStream connectTo:serviceJID withAddress:address error:nil];
}
[ns stop];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark XMPPStream Delegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender willSendP2PFeatures:(NSXMLElement *)streamFeatures
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender didReceiveP2PFeatures:(NSXMLElement *)streamFeatures
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
return NO;
}
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
NSString *msgBody = [[[message elementForName:@"body"] stringValue] stringByTrimming];
if ([msgBody length] > 0)
{
Message *msg = [NSEntityDescription insertNewObjectForEntityForName:@"Message"
inManagedObjectContext:[self managedObjectContext]];
msg.content = msgBody;
msg.isOutbound = NO;
msg.hasBeenRead = NO;
msg.timeStamp = [NSDate date];
msg.service = service;
[[self managedObjectContext] save:nil];
}
}
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error
{
DDLogVerbose(@"%@: %@ %@", THIS_FILE, THIS_METHOD, error);
}
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Memory Management
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)dealloc
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
[service release];
[netService setDelegate:nil];
[netService stop];
[netService release];
[xmppStream removeDelegate:self];
[xmppStream disconnect];
[xmppStream release];
[fetchedResultsController release];
[managedObjectContext release];
[super dealloc];
}
@end
|
04081337-xmpp
|
Xcode/ServerlessDemo/Classes/ChatViewController.m
|
Objective-C
|
bsd
| 25,238
|
#import <UIKit/UIKit.h>
@class XMPPJID;
@interface ServerlessDemoAppDelegate : NSObject <UIApplicationDelegate>
{
XMPPJID *myJID;
NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
UIWindow *window;
UINavigationController *navigationController;
}
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
@property (nonatomic, retain) XMPPJID *myJID;
- (NSString *)applicationDocumentsDirectory;
- (NSData *)IPv4AddressFromAddresses:(NSArray *)addresses;
- (NSString *)stringFromAddress:(NSData *)address;
@end
|
04081337-xmpp
|
Xcode/ServerlessDemo/Classes/ServerlessDemoAppDelegate.h
|
Objective-C
|
bsd
| 979
|
#import <Foundation/Foundation.h>
@interface BonjourClient : NSObject <NSNetServiceDelegate, NSNetServiceBrowserDelegate>
{
NSNetServiceBrowser *serviceBrowser;
NSMutableArray *services;
NSNetService *localService;
}
+ (BonjourClient *)sharedInstance;
- (void)startBrowsing;
- (void)stopBrowsing;
- (void)publishServiceOnPort:(UInt16)port;
@end
|
04081337-xmpp
|
Xcode/ServerlessDemo/Classes/BonjourClient.h
|
Objective-C
|
bsd
| 356
|
#import "BonjourClient.h"
#import "ServerlessDemoAppDelegate.h"
#import "Service.h"
#import "DDString.h"
#import "DDLog.h"
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#define SERVICE_TYPE @"_presence._tcp."
@interface BonjourClient (PrivateAPI)
- (NSDictionary *)dictionaryFromTXTRecordData:(NSData *)txtData;
- (NSData *)txtRecordDataFromDictionary:(NSDictionary *)dict;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation BonjourClient
static BonjourClient *sharedInstance;
+ (void)initialize
{
static BOOL initialized = NO;
if(!initialized)
{
initialized = YES;
sharedInstance = [[BonjourClient alloc] init];
}
}
- (id)init
{
// Only allow one instance of this class to ever be created
if(sharedInstance)
{
[self release];
return nil;
}
if((self = [super init]))
{
// Initialize Bonjour NSNetServiceBrowser - this listens for advertised services
serviceBrowser = [[NSNetServiceBrowser alloc] init];
[serviceBrowser setDelegate:self];
services = [[NSMutableArray alloc] initWithCapacity:15];
}
return self;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Public API
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+ (BonjourClient *)sharedInstance
{
return sharedInstance;
}
- (void)startBrowsing
{
[serviceBrowser searchForServicesOfType:SERVICE_TYPE inDomain:@""];
}
- (void)stopBrowsing
{
[serviceBrowser stop];
}
- (void)publishServiceOnPort:(UInt16)port
{
localService = [[NSNetService alloc] initWithDomain:@"local." type:SERVICE_TYPE name:@"robbie@demo" port:port];
[localService setDelegate:self];
[localService publish];
NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithCapacity:8];
[mDict setObject:@"1" forKey:@"txtvers"];
[mDict setObject:@"Quack" forKey:@"1st"];
[mDict setObject:@"Tastic" forKey:@"last"];
[mDict setObject:@"Coding" forKey:@"msg"];
[mDict setObject:@"dnd" forKey:@"status"];
[localService setTXTRecordData:[self txtRecordDataFromDictionary:mDict]];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Private API
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (NSManagedObjectContext *)managedObjectContext
{
ServerlessDemoAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
return appDelegate.managedObjectContext;
}
- (NSString *)descriptionForNetService:(NSNetService *)ns
{
return [NSString stringWithFormat:@"%@.%@%@", [ns name], [ns type], [ns domain]];
}
- (NSDictionary *)dictionaryFromTXTRecordData:(NSData *)txtData
{
NSDictionary *dict = [NSNetService dictionaryFromTXTRecordData:txtData];
NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithCapacity:[dict count]];
// The dictionary all the values encoded in UTF8.
// So we need to loop through each key/value pair, and convert from the UTF8 data to a string.
for (id key in dict)
{
NSData *data = [dict objectForKey:key];
NSString *str = [NSString stringWithUTF8Data:data];
if (str)
{
[mDict setObject:str forKey:key];
}
else
{
DDLogWarn(@"%@: Unable to get string from key \"%@\"", THIS_FILE, key);
}
}
return mDict;
}
- (NSData *)txtRecordDataFromDictionary:(NSDictionary *)dict
{
NSMutableDictionary *mDict = [NSMutableDictionary dictionaryWithCapacity:[dict count]];
// We need to encode all the values into UTF8.
for (id key in dict)
{
NSString *str = [dict objectForKey:key];
if ([str isKindOfClass:[NSString class]])
{
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[mDict setObject:data forKey:key];
}
else
{
DDLogWarn(@"%@: Value for key \"%@\" is not a string.", THIS_FILE, key);
}
}
return [NSNetService dataFromTXTRecordDictionary:mDict];
}
- (Service *)serviceForNetService:(NSNetService *)ns
{
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Service"
inManagedObjectContext:[self managedObjectContext]];
NSString *serviceDescription = [self descriptionForNetService:ns];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"serviceDescription == %@", serviceDescription];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:predicate];
[fetchRequest setFetchLimit:1];
NSError *error = nil;
NSArray *results = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
if (results == nil)
{
DDLogError(@"%@: Error searching for service \"%@\": %@, %@",
THIS_FILE, serviceDescription, error, [error userInfo]);
return nil;
}
else if ([results count] == 0)
{
DDLogWarn(@"%@: Unable to find service \"%@\"", THIS_FILE, serviceDescription);
return nil;
}
else
{
return [results objectAtIndex:0];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Bonjour Browsing
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)netServiceBrowser:(NSNetServiceBrowser *)sb didFindService:(NSNetService *)ns moreComing:(BOOL)moreComing
{
DDLogVerbose(@"%@: netServiceBrowser:didFindService: %@", THIS_FILE, ns);
// Add service to database (if it's not our own service)
if (![ns isEqual:localService])
{
Service *service = [NSEntityDescription insertNewObjectForEntityForName:@"Service"
inManagedObjectContext:[self managedObjectContext]];
service.serviceType = [ns type];
service.serviceName = [ns name];
service.serviceDomain = [ns domain];
service.serviceDescription = [self descriptionForNetService:ns];
[service updateDisplayName];
// if (!moreComing)
// {
[[self managedObjectContext] save:nil];
// }
// Start monitoring the service so we receive TXT Record updates.
// Note: We must retain the service or it will get deallocated, and we won't receive updates.
[services addObject:ns];
[ns setDelegate:self];
[ns startMonitoring];
[ns resolveWithTimeout:10.0];
}
}
- (void)netServiceBrowser:(NSNetServiceBrowser *)sb didRemoveService:(NSNetService *)ns moreComing:(BOOL)moreComing
{
Service *service = [self serviceForNetService:ns];
if (service)
{
[[self managedObjectContext] deleteObject:service];
[[self managedObjectContext] save:nil];
[ns stop];
[ns stopMonitoring];
[services removeObject:ns];
}
}
- (void)netService:(NSNetService *)ns didUpdateTXTRecordData:(NSData *)data
{
Service *service = [self serviceForNetService:ns];
if (service)
{
NSDictionary *dict = [self dictionaryFromTXTRecordData:data];
// Example:
//
// dict: {
// 1st = Robbie;
// email = "robbiehanson@deusty.com";
// ext = 5I;
// last = Hanson;
// msg = Away;
// phsh = ba4d75ea096ee90d1669ff8f4e5d0fade19183af;
// "port.p2pj" = 55425;
// status = dnd;
// txtvers = 1;
// url = "";
// vc = "MSDCURA!XN";
// }
service.nickname = [dict objectForKey:@"nick"];
service.firstName = [dict objectForKey:@"1st"];
service.lastName = [dict objectForKey:@"last"];
[service updateDisplayName];
service.statusType = [Service statusTypeForStatusTxtTitle:[dict objectForKey:@"status"]];
service.statusMessage = [dict objectForKey:@"msg"];
[[self managedObjectContext] save:nil];
}
}
- (void)netServiceDidResolveAddress:(NSNetService *)ns
{
Service *service = [self serviceForNetService:ns];
if (service)
{
ServerlessDemoAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSData *address = [appDelegate IPv4AddressFromAddresses:[ns addresses]];
NSString *addrStr = [appDelegate stringFromAddress:address];
DDLogVerbose(@"%@: ns(%@) -> %@", THIS_FILE, [self descriptionForNetService:ns], addrStr);
service.lastResolvedAddress = addrStr;
[[self managedObjectContext] save:nil];
}
[ns stop];
}
- (void)netService:(NSNetService *)ns didNotResolve:(NSDictionary *)errorDict
{
DDLogVerbose(@"%@: netService:%@ didNotResolve:%@", THIS_FILE, ns, errorDict);
[ns stop];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Bonjour Publishing
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)netServiceDidPublish:(NSNetService *)sender
{
DDLogVerbose(@"%@: netServiceDidPublish", THIS_FILE);
}
- (void)netService:(NSNetService *)sender didNotPublish:(NSDictionary *)errorDict
{
DDLogVerbose(@"%@: netService:didNotPublish: %@", THIS_FILE, errorDict);
}
@end
|
04081337-xmpp
|
Xcode/ServerlessDemo/Classes/BonjourClient.m
|
Objective-C
|
bsd
| 9,357
|
#import "RootViewController.h"
#import "ChatViewController.h"
#import "Service.h"
#import "DDLog.h"
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
@interface RootViewController (PrivateAPI)
- (NSFetchedResultsController *)fetchedResultsController;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation RootViewController
@synthesize managedObjectContext;
- (void)viewDidLoad
{
// Configure UI
self.title = @"Roster";
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Table view methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (NSInteger)numberOfSectionsInTableView:(UITableView *)sender
{
return [[[self fetchedResultsController] sections] count];
}
- (NSString *)tableView:(UITableView *)sender titleForHeaderInSection:(NSInteger)sectionIndex
{
NSArray *sections = [[self fetchedResultsController] sections];
if ([sections count] > sectionIndex)
{
id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:sectionIndex];
StatusType statusType = [sectionInfo.name intValue];
return [Service statusDisplayTitleForStatusType:statusType];
}
return @"";
}
- (NSInteger)tableView:(UITableView *)sender numberOfRowsInSection:(NSInteger)sectionIndex
{
NSArray *sections = [[self fetchedResultsController] sections];
if ([sections count] > sectionIndex)
{
id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:sectionIndex];
return [sectionInfo numberOfObjects];
}
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)sender cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"RootViewController_Cell";
UITableViewCell *cell = [sender dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
// UIButton *unreadIndicator = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 33, 22)];
UIButton *unreadIndicator = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 20)];
[unreadIndicator setEnabled:NO];
[unreadIndicator setTitleColor:[UIColor whiteColor]
forState:UIControlStateDisabled];
[unreadIndicator setBackgroundImage:[UIImage imageNamed:@"UnreadIndicator.png"]
forState:UIControlStateDisabled];
cell.accessoryView = unreadIndicator;
[unreadIndicator release];
}
Service *service = [fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [service displayName];
cell.detailTextLabel.text = [service statusMessage];
NSUInteger numberOfUnreadMessages = [service numberOfUnreadMessages];
if (numberOfUnreadMessages > 0)
{
UIButton *unreadIndicator = (UIButton *)cell.accessoryView;
NSString *unreadTitle = [NSString stringWithFormat:@"%lu", numberOfUnreadMessages];
[unreadIndicator setTitle:unreadTitle forState:UIControlStateDisabled];
cell.accessoryView.hidden = NO;
}
else
{
cell.accessoryView.hidden = YES;
}
return cell;
}
- (void)tableView:(UITableView *)sender didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
Service *service = (Service *)[[self fetchedResultsController] objectAtIndexPath:indexPath];
ChatViewController *chatVC = [[ChatViewController alloc] initWithNibName:@"ChatViewController" bundle:nil];
chatVC.managedObjectContext = self.managedObjectContext;
chatVC.service = service;
[self.navigationController pushViewController:chatVC animated:YES];
[chatVC release];
[sender deselectRowAtIndexPath:indexPath animated:YES];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Fetched results controller
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController == nil)
{
NSSortDescriptor *statusSD;
NSSortDescriptor *nameSD;
NSArray *sortDescriptors;
NSFetchRequest *fetchRequest;
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Service"
inManagedObjectContext:managedObjectContext];
statusSD = [[NSSortDescriptor alloc] initWithKey:@"status" ascending:NO];
nameSD = [[NSSortDescriptor alloc] initWithKey:@"displayName" ascending:NO];
sortDescriptors = [[NSArray alloc] initWithObjects:statusSD, nameSD, nil];
fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setFetchBatchSize:10];
[fetchRequest setEntity:entity];
[fetchRequest setSortDescriptors:sortDescriptors];
fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:@"status"
cacheName:nil];
fetchedResultsController.delegate = self;
NSError *error = nil;
if (![fetchedResultsController performFetch:&error])
{
DDLogError(@"%@: Error fetching messages: %@ %@", THIS_FILE, error, [error userInfo]);
}
[statusSD release];
[nameSD release];
[sortDescriptors release];
[fetchRequest release];
}
return fetchedResultsController;
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
if(![self isViewLoaded]) return;
DDLogVerbose(@"%@: controllerDidChangeContent", THIS_FILE);
[self.tableView reloadData];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Memory management
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)dealloc
{
[fetchedResultsController release];
[managedObjectContext release];
[super dealloc];
}
@end
|
04081337-xmpp
|
Xcode/ServerlessDemo/Classes/RootViewController.m
|
Objective-C
|
bsd
| 6,684
|
#import "ServerlessDemoAppDelegate.h"
#import "RootViewController.h"
#import "BonjourClient.h"
#import "StreamController.h"
#import "XMPPJID.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
#import <arpa/inet.h>
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
@implementation ServerlessDemoAppDelegate
@synthesize window;
@synthesize navigationController;
@synthesize myJID;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark App Delegate Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
// Configure logging
[DDLog addLogger:[DDTTYLogger sharedInstance]];
// Configure UI
RootViewController *rootViewController = (RootViewController *)[navigationController topViewController];
rootViewController.managedObjectContext = self.managedObjectContext;
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
// Configure everything else
NSString *jidStr = [NSString stringWithFormat:@"demo@%@", [[UIDevice currentDevice] name]];
self.myJID = [XMPPJID jidWithString:jidStr];
BonjourClient *bonjourClient = [BonjourClient sharedInstance];
StreamController *streamController = [StreamController sharedInstance];
[streamController startListening];
[bonjourClient startBrowsing];
[bonjourClient publishServiceOnPort:[streamController listeningPort]];
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Don't bother saving the data.
// We currently delete the SQL database file on app launch.
// if (managedObjectContext && [managedObjectContext hasChanges])
// {
// NSError *error = nil;
//
// if (![managedObjectContext save:&error])
// {
// DDLogError(@"Unresolved error %@, %@", error, [error userInfo]);
// abort();
// }
// }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Core Data stack
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Returns the managed object model for the application.
* If the model doesn't already exist, it is created by merging all of the models found in the application bundle.
**/
- (NSManagedObjectModel *)managedObjectModel
{
if (managedObjectModel != nil) {
return managedObjectModel;
}
managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
return managedObjectModel;
}
/**
* Returns the persistent store coordinator for the application.
* If the coordinator doesn't already exist, it is created and the application's store added to it.
**/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSString *storeName = @"ServerlessDemo.sqlite";
NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:storeName];
if ([[NSFileManager defaultManager] fileExistsAtPath:storePath])
{
[[NSFileManager defaultManager] removeItemAtPath:storePath error:NULL];
}
NSURL *storeUrl = [NSURL fileURLWithPath:storePath];
NSManagedObjectModel *mom = [self managedObjectModel];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
NSPersistentStore *persistentStore = [persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeUrl
options:nil
error:&error];
if (persistentStore == nil)
{
DDLogError(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator;
}
/**
* Returns the managed object context for the application.
* If the context doesn't already exist, it is created and
* bound to the persistent store coordinator for the application.
**/
- (NSManagedObjectContext *)managedObjectContext
{
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return managedObjectContext;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Common Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Returns the path to the application's Documents directory.
**/
- (NSString *)applicationDocumentsDirectory
{
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
/**
* The iPhone only supports IPv4, so we often need to filter a list
* of resolved addresses into just the IPv4 address.
**/
- (NSData *)IPv4AddressFromAddresses:(NSArray *)addresses
{
// The iPhone only supports IPv4, so we need to get the IPv4 address from the resolve operation.
for (NSData *address in addresses)
{
struct sockaddr *sa = (struct sockaddr *)[address bytes];
if(sa->sa_family == AF_INET)
{
return address;
}
}
return nil;
}
/**
* Returns the human readable version of the given address.
* Does not include the port number.
**/
- (NSString *)stringFromAddress:(NSData *)address
{
struct sockaddr *sa = (struct sockaddr *)[address bytes];
if(sa->sa_family == AF_INET)
{
char addr[INET_ADDRSTRLEN];
struct sockaddr_in *sin = (struct sockaddr_in *)sa;
if(inet_ntop(AF_INET, &sin->sin_addr, addr, sizeof(addr)))
{
return [NSString stringWithUTF8String:addr];
}
}
else if(sa->sa_family == AF_INET6)
{
char addr[INET6_ADDRSTRLEN];
struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
if(inet_ntop(AF_INET6, &sin6->sin6_addr, addr, sizeof(addr)))
{
return [NSString stringWithUTF8String:addr];
}
}
return nil;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Memory management
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)dealloc
{
[managedObjectContext release];
[managedObjectModel release];
[persistentStoreCoordinator release];
[navigationController release];
[window release];
[super dealloc];
}
@end
|
04081337-xmpp
|
Xcode/ServerlessDemo/Classes/ServerlessDemoAppDelegate.m
|
Objective-C
|
bsd
| 7,057
|
#import "RequestController.h"
#import "RosterController.h"
#import "AppDelegate.h"
@implementation RequestController
- (id)init
{
if((self = [super init]))
{
jids = [[NSMutableArray alloc] init];
jidIndex = -1;
}
return self;
}
- (XMPPStream *)xmppStream
{
return [[NSApp delegate] xmppStream];
}
- (XMPPRoster *)xmppRoster
{
return [[NSApp delegate] xmppRoster];
}
- (void)awakeFromNib
{
[[self xmppStream] addDelegate:self delegateQueue:dispatch_get_main_queue()];
[[self xmppRoster] addDelegate:self delegateQueue:dispatch_get_main_queue()];
NSRect visibleFrame = [[window screen] visibleFrame];
NSRect windowFrame = [window frame];
NSPoint windowPosition;
windowPosition.x = visibleFrame.origin.x + visibleFrame.size.width - windowFrame.size.width - 5;
windowPosition.y = visibleFrame.origin.y + visibleFrame.size.height - windowFrame.size.height - 5;
[window setFrameOrigin:windowPosition];
}
- (void)dealloc
{
[[self xmppStream] removeDelegate:self];
[[self xmppRoster] removeDelegate:self];
[jids release];
[super dealloc];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// NSWindow Delegate Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)windowWillClose:(NSNotification *)notification
{
// User chose to ignore requests by closing the window
[jids removeAllObjects];
jidIndex = -1;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Helper Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)nextRequest
{
NSLog(@"RequestController: nextRequest");
if(++jidIndex < [jids count])
{
XMPPJID *jid = [jids objectAtIndex:jidIndex];
[jidField setStringValue:[jid bare]];
[xofyField setStringValue:[NSString stringWithFormat:@"%i of %i", (jidIndex+1), [jids count]]];
}
else
{
[jids removeAllObjects];
jidIndex = -1;
[window close];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// XMPPClient Delegate Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)xmppRoster:(XMPPRoster *)sender didReceiveBuddyRequest:(XMPPPresence *)presence
{
XMPPJID *jid = [presence from];
if(![jids containsObject:jid])
{
[jids addObject:jid];
if([jids count] == 1)
{
jidIndex = 0;
[jidField setStringValue:[jid bare]];
[xofyField setHidden:YES];
[window setAlphaValue:0.85F];
[window makeKeyAndOrderFront:self];
}
else
{
[xofyField setStringValue:[NSString stringWithFormat:@"%i of %i", (jidIndex+1), [jids count]]];
[xofyField setHidden:NO];
}
}
}
- (void)xmppRosterDidChange:(XMPPRosterMemoryStorage *)sender
{
// Often times XMPP servers send presence requests prior to sending the roster.
// That is, after you authenticate, they immediately send you presence requests,
// meaning that we receive them before we've had a chance to request and receive our roster.
// The result is that we may not know, upon receiving a presence request,
// if we've already requested this person to be our buddy.
// We make up for that by fixing our mistake as soon as possible.
NSArray *roster = [sender sortedUsersByAvailabilityName];
// Remember: Our roster contains only those users we've added.
// If the server tries to include buddies that we haven't added, but have asked to subscribe to us,
// the xmpp client filters them out.
NSUInteger i;
for(i = 0; i < [roster count]; i++)
{
id <XMPPUser> user = [roster objectAtIndex:i];
NSUInteger currentIndex = [jids indexOfObject:[user jid]];
if(currentIndex != NSNotFound)
{
// Now we may be getting a notification of an updated roster due to an accept/reject we just sent.
// The simplest way to check is if the index isn't pointing to a jid we've already processed.
if(currentIndex >= jidIndex)
{
NSLog(@"Auto-accepting buddy request, since they already accepted us");
[[self xmppRoster] acceptBuddyRequest:[user jid]];
[jids removeObjectAtIndex:currentIndex];
// We need to calll nextRequest, but we want jidIndex to remain at it's current jid
if(currentIndex >= jidIndex)
{
// Subtract 1, because nextRequest will immediately add 1
jidIndex = jidIndex - 1;
}
else
{
// Subtract 2, because the current jid will go down 1
// and because nextRequest will immediately add 1
jidIndex = jidIndex - 2;
}
[self nextRequest];
}
}
}
}
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
// We can't accept or reject any requests when we're disconnected from the server.
// We may as well close the window.
[jids removeAllObjects];
jidIndex = -1;
[window close];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Interface Builder Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (IBAction)accept:(id)sender
{
XMPPJID *jid = [jids objectAtIndex:jidIndex];
[[self xmppRoster] acceptBuddyRequest:jid];
[self nextRequest];
}
- (IBAction)reject:(id)sender
{
XMPPJID *jid = [jids objectAtIndex:jidIndex];
[[self xmppRoster] rejectBuddyRequest:jid];
[self nextRequest];
}
@end
|
04081337-xmpp
|
Xcode/DesktopXMPP/RequestController.m
|
Objective-C
|
bsd
| 5,658
|
#import "RosterController.h"
#import "RequestController.h"
#import "ChatWindowManager.h"
#import "AppDelegate.h"
#import "DDLog.h"
#import <SystemConfiguration/SystemConfiguration.h>
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
@implementation RosterController
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Setup:
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (XMPPStream *)xmppStream
{
return [[NSApp delegate] xmppStream];
}
- (XMPPRoster *)xmppRoster
{
return [[NSApp delegate] xmppRoster];
}
- (XMPPRosterMemoryStorage *)xmppRosterStorage
{
return [[NSApp delegate] xmppRosterStorage];
}
- (void)awakeFromNib
{
DDLogInfo(@"%@: %@", THIS_FILE, THIS_METHOD);
[[self xmppRoster] setAutoRoster:YES];
[[self xmppStream] addDelegate:self delegateQueue:dispatch_get_main_queue()];
[[self xmppRoster] addDelegate:self delegateQueue:dispatch_get_main_queue()];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Sign In Sheet
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)displaySignInSheet
{
NSUserDefaults *dflts = [NSUserDefaults standardUserDefaults];
[serverField setObjectValue:[dflts objectForKey:@"Account.Server"]];
[resourceField setObjectValue:[dflts objectForKey:@"Account.Resource"]];
[portField setObjectValue:[dflts objectForKey:@"Account.Port"]];
[jidField setObjectValue:[dflts objectForKey:@"Account.JID"]];
[sslButton setObjectValue:[dflts objectForKey:@"Account.UseSSL"]];
[selfSignedButton setObjectValue:[dflts objectForKey:@"Account.AllowSelfSignedCert"]];
[mismatchButton setObjectValue:[dflts objectForKey:@"Account.AllowSSLHostNameMismatch"]];
[NSApp beginSheet:signInSheet
modalForWindow:window
modalDelegate:self
didEndSelector:nil
contextInfo:nil];
if ([[portField stringValue] length] > 0)
{
if ([[jidField stringValue] length] > 0)
{
[signInSheet makeFirstResponder:passwordField];
}
else
{
[signInSheet makeFirstResponder:jidField];
}
}
else
{
if ([[serverField stringValue] length] > 0)
{
[signInSheet makeFirstResponder:portField];
}
}
[self jidDidChange:nil];
}
- (IBAction)jidDidChange:(id)sender
{
NSString *jidStr = [jidField stringValue];
if ([jidStr length] > 0)
{
NSString *domain = [serverField stringValue];
if ([jidStr rangeOfString:@"@"].location == NSNotFound)
{
// People often forget to type in the full JID.
// In other words, they type in "username" instead of "username@domain.tld"
//
// So we automatically append a domain to the JID.
if ([domain length] > 0)
{
[jidField setStringValue:[jidStr stringByAppendingFormat:@"@%@", domain]];
}
}
else if ([domain length] == 0)
{
// Update the domain placeholder string to match the JID domain
XMPPJID *jid = [XMPPJID jidWithString:jidStr];
if (jid)
{
[[serverField cell] setPlaceholderString:[jid domain]];
}
}
}
}
- (void)enableSignInUI:(BOOL)enabled
{
[serverField setEnabled:enabled];
[portField setEnabled:enabled];
[sslButton setEnabled:enabled];
[selfSignedButton setEnabled:enabled];
[mismatchButton setEnabled:enabled];
[jidField setEnabled:enabled];
[passwordField setEnabled:enabled];
[resourceField setEnabled:enabled];
[signInButton setEnabled:enabled];
[registerButton setEnabled:enabled];
}
- (void)lockSignInUI
{
[self enableSignInUI:NO];
}
- (void)unlockSignInUI
{
[self enableSignInUI:YES];
}
- (void)updateAccountInfo
{
NSString *domain = [serverField stringValue];
[[self xmppStream] setHostName:domain];
int port = [portField intValue];
[[self xmppStream] setHostPort:port];
useSSL = ([sslButton state] == NSOnState);
allowSelfSignedCertificates = ([selfSignedButton state] == NSOnState);
allowSSLHostNameMismatch = ([mismatchButton state] == NSOnState);
NSString *resource = [resourceField stringValue];
if([resource length] == 0)
{
resource = [(NSString *)SCDynamicStoreCopyComputerName(NULL, NULL) autorelease];
}
XMPPJID *jid = [XMPPJID jidWithString:[jidField stringValue] resource:resource];
[[self xmppStream] setMyJID:jid];
// Update persistent defaults:
NSUserDefaults *dflts = [NSUserDefaults standardUserDefaults];
[dflts setObject:domain forKey:@"Account.Server"];
[dflts setObject:[resourceField stringValue]
forKey:@"Account.Resource"];
[dflts setObject:(port ? [NSNumber numberWithInt:port] : nil)
forKey:@"Account.Port"];
[dflts setObject:[jidField stringValue]
forKey:@"Account.JID"];
[dflts setBool:useSSL
forKey:@"Account.UseSSL"];
[dflts setBool:allowSelfSignedCertificates
forKey:@"Account.AllowSelfSignedCert"];
[dflts setBool:allowSSLHostNameMismatch
forKey:@"Account.AllowSSLHostNameMismatch"];
[dflts synchronize];
}
- (IBAction)createAccount:(id)sender
{
[self updateAccountInfo];
NSError *error = nil;
BOOL success;
if(![[self xmppStream] isConnected])
{
if (useSSL)
success = [[self xmppStream] oldSchoolSecureConnect:&error];
else
success = [[self xmppStream] connect:&error];
}
else
{
NSString *password = [passwordField stringValue];
success = [[self xmppStream] registerWithPassword:password error:&error];
}
if (success)
{
isRegistering = YES;
[self lockSignInUI];
}
else
{
[messageField setStringValue:[error localizedDescription]];
}
}
- (IBAction)signIn:(id)sender
{
[self updateAccountInfo];
NSError *error = nil;
BOOL success;
if(![[self xmppStream] isConnected])
{
if (useSSL)
success = [[self xmppStream] oldSchoolSecureConnect:&error];
else
success = [[self xmppStream] connect:&error];
}
else
{
NSString *password = [passwordField stringValue];
success = [[self xmppStream] authenticateWithPassword:password error:&error];
}
if (success)
{
isAuthenticating = YES;
[self lockSignInUI];
}
else
{
[messageField setStringValue:[error localizedDescription]];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Presence Management
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)goOnline
{
NSXMLElement *presence = [NSXMLElement elementWithName:@"presence"];
[[self xmppStream] sendElement:presence];
}
- (void)goOffline
{
NSXMLElement *presence = [NSXMLElement elementWithName:@"presence"];
[presence addAttributeWithName:@"type" stringValue:@"unavailable"];
[[self xmppStream] sendElement:presence];
}
- (IBAction)changePresence:(id)sender
{
if([[sender titleOfSelectedItem] isEqualToString:@"Offline"])
{
[self goOffline];
}
else
{
[self goOnline];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Buddy Management
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (IBAction)addBuddy:(id)sender
{
XMPPJID *jid = [XMPPJID jidWithString:[buddyField stringValue]];
[[self xmppRoster] addBuddy:jid withNickname:nil];
// Clear buddy text field
[buddyField setStringValue:@""];
}
- (IBAction)removeBuddy:(id)sender
{
XMPPJID *jid = [XMPPJID jidWithString:[buddyField stringValue]];
[[self xmppRoster] removeBuddy:jid];
// Clear buddy text field
[buddyField setStringValue:@""];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Messages:
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (IBAction)chat:(id)sender
{
int selectedRow = [rosterTable selectedRow];
if(selectedRow >= 0)
{
XMPPStream *stream = [self xmppStream];
id <XMPPUser> user = [roster objectAtIndex:selectedRow];
[ChatWindowManager openChatWindowWithStream:stream forUser:user];
}
}
- (IBAction)connectViaXEP65:(id)sender
{
int selectedRow = [rosterTable selectedRow];
if(selectedRow >= 0)
{
id <XMPPUser> user = [roster objectAtIndex:selectedRow];
id <XMPPResource> resource = [user primaryResource];
[[NSApp delegate] connectViaXEP65:[resource jid]];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Roster Table Data Source
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (int)numberOfRowsInTableView:(NSTableView *)tableView
{
return [roster count];
}
- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)rowIndex
{
id <XMPPUser> user = [roster objectAtIndex:rowIndex];
if([[tableColumn identifier] isEqualToString:@"name"])
return [user nickname];
else
return [user jid];
return nil;
}
- (void)tableView:(NSTableView *)tableView
setObjectValue:(id)anObject
forTableColumn:(NSTableColumn *)tableColumn
row:(int)rowIndex
{
id <XMPPUser> user = [roster objectAtIndex:rowIndex];
NSString *newName = (NSString *)anObject;
[[self xmppRoster] setNickname:newName forBuddy:[user jid]];
}
- (void)tableView:(NSTableView *)tableView
willDisplayCell:(id)cell
forTableColumn:(NSTableColumn *)tableColumn
row:(int)rowIndex
{
id <XMPPUser> user = [roster objectAtIndex:rowIndex];
BOOL isRowSelected = ([tableView isRowSelected:rowIndex]);
BOOL isFirstResponder = [[[tableView window] firstResponder] isEqual:tableView];
BOOL isKeyWindow = [[tableView window] isKeyWindow];
BOOL isApplicationActive = [NSApp isActive];
BOOL isRowHighlighted = (isRowSelected && isFirstResponder && isKeyWindow && isApplicationActive);
if([user isOnline])
{
[cell setTextColor:[NSColor blackColor]];
}
else
{
NSColor *grayColor;
if(isRowHighlighted)
grayColor = [NSColor colorWithCalibratedRed:(184.0F / 255.0F)
green:(175.0F / 255.0F)
blue:(184.0F / 255.0F)
alpha:1.0F];
else
grayColor = [NSColor colorWithCalibratedRed:(134.0F / 255.0F)
green:(125.0F / 255.0F)
blue:(134.0F / 255.0F)
alpha:1.0F];
[cell setTextColor:grayColor];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark XMPPClient Delegate Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
if (allowSelfSignedCertificates)
{
[settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];
}
if (allowSSLHostNameMismatch)
{
[settings setObject:[NSNull null] forKey:(NSString *)kCFStreamSSLPeerName];
}
else
{
// Google does things incorrectly (does not conform to RFC).
// Because so many people ask questions about this (assume xmpp framework is broken),
// I've explicitly added code that shows how other xmpp clients "do the right thing"
// when connecting to a google server (gmail, or google apps for domains).
NSString *expectedCertName = nil;
NSString *serverHostName = [sender hostName];
NSString *virtualHostName = [[sender myJID] domain];
if ([serverHostName isEqualToString:@"talk.google.com"])
{
if ([virtualHostName isEqualToString:@"gmail.com"])
{
expectedCertName = virtualHostName;
}
else
{
expectedCertName = serverHostName;
}
}
else
{
expectedCertName = serverHostName;
}
[settings setObject:expectedCertName forKey:(NSString *)kCFStreamSSLPeerName];
}
}
- (void)xmppStreamDidSecure:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
isOpen = YES;
NSString *password = [passwordField stringValue];
NSError *error = nil;
BOOL success;
if(isRegistering)
{
success = [[self xmppStream] registerWithPassword:password error:&error];
}
else
{
success = [[self xmppStream] authenticateWithPassword:password error:&error];
}
if (!success)
{
[messageField setStringValue:[error localizedDescription]];
}
}
- (void)xmppStreamDidRegister:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
// Update tracking variables
isRegistering = NO;
// Update GUI
[self unlockSignInUI];
[messageField setStringValue:@"Registered new user"];
}
- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
// Update tracking variables
isRegistering = NO;
// Update GUI
[self unlockSignInUI];
[messageField setStringValue:@"Username is taken"];
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
// Update tracking variables
isAuthenticating = NO;
// Close the sheet
[signInSheet orderOut:self];
[NSApp endSheet:signInSheet];
// Send presence
[self goOnline];
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
// Update tracking variables
isAuthenticating = NO;
// Update GUI
[self unlockSignInUI];
[messageField setStringValue:@"Invalid username/password"];
}
- (void)xmppRosterDidChange:(XMPPRosterMemoryStorage *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
[roster release];
roster = [[sender sortedUsersByAvailabilityName] retain];
[rosterTable abortEditing];
[rosterTable selectRowIndexes:[NSIndexSet indexSet] byExtendingSelection:NO];
[rosterTable reloadData];
}
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
if([message isChatMessageWithBody])
{
[ChatWindowManager handleChatMessage:message withStream:sender];
}
}
- (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
if (!isOpen)
{
[messageField setStringValue:@"Cannot connect to server"];
}
// Update tracking variables
isOpen = NO;
isRegistering = NO;
isAuthenticating = NO;
// Update GUI
[self unlockSignInUI];
}
@end
|
04081337-xmpp
|
Xcode/DesktopXMPP/RosterController.m
|
Objective-C
|
bsd
| 14,917
|
#import <Cocoa/Cocoa.h>
@interface RequestController : NSObject
{
NSMutableArray *jids;
int jidIndex;
IBOutlet id jidField;
IBOutlet id window;
IBOutlet id xofyField;
}
- (IBAction)accept:(id)sender;
- (IBAction)reject:(id)sender;
@end
|
04081337-xmpp
|
Xcode/DesktopXMPP/RequestController.h
|
Objective-C
|
bsd
| 254
|
#import <Cocoa/Cocoa.h>
#import "XMPP.h"
#import "XMPPReconnect.h"
#import "XMPPRoster.h"
#import "XMPPRosterMemoryStorage.h"
#import "XMPPCapabilities.h"
#import "XMPPCapabilitiesCoreDataStorage.h"
#import "XMPPPing.h"
#import "XMPPTime.h"
@class RosterController;
@interface AppDelegate : NSObject
{
XMPPStream *xmppStream;
XMPPReconnect *xmppReconnect;
XMPPRoster *xmppRoster;
XMPPRosterMemoryStorage *xmppRosterStorage;
XMPPCapabilities *xmppCapabilities;
XMPPCapabilitiesCoreDataStorage *xmppCapabilitiesStorage;
XMPPPing *xmppPing;
XMPPTime *xmppTime;
NSMutableArray *turnSockets;
IBOutlet RosterController *rosterController;
}
@property (nonatomic, readonly) XMPPStream *xmppStream;
@property (nonatomic, readonly) XMPPReconnect *xmppReconnect;
@property (nonatomic, readonly) XMPPRoster *xmppRoster;
@property (nonatomic, readonly) XMPPRosterMemoryStorage *xmppRosterStorage;
@property (nonatomic, readonly) XMPPCapabilities *xmppCapabilities;
@property (nonatomic, readonly) XMPPCapabilitiesCoreDataStorage *xmppCapabilitiesStorage;
@property (nonatomic, readonly) XMPPPing *xmppPing;
- (void)connectViaXEP65:(XMPPJID *)jid;
@end
|
04081337-xmpp
|
Xcode/DesktopXMPP/AppDelegate.h
|
Objective-C
|
bsd
| 1,160
|
#import <Cocoa/Cocoa.h>
@class XMPPStream;
@class XMPPMessage;
@protocol XMPPUser;
@interface ChatWindowManager : NSObject
+ (void)openChatWindowWithStream:(XMPPStream *)xmppStream forUser:(id <XMPPUser>)user;
+ (void)handleChatMessage:(XMPPMessage *)message withStream:(XMPPStream *)xmppStream;
@end
|
04081337-xmpp
|
Xcode/DesktopXMPP/ChatWindowManager.h
|
Objective-C
|
bsd
| 307
|
#import <Cocoa/Cocoa.h>
@interface RosterController : NSObject
{
BOOL useSSL;
BOOL allowSelfSignedCertificates;
BOOL allowSSLHostNameMismatch;
BOOL isOpen;
BOOL isRegistering;
BOOL isAuthenticating;
NSArray *roster;
IBOutlet id buddyField;
IBOutlet id jidField;
IBOutlet id messageField;
IBOutlet id mismatchButton;
IBOutlet id passwordField;
IBOutlet id portField;
IBOutlet id registerButton;
IBOutlet id resourceField;
IBOutlet id rosterTable;
IBOutlet id selfSignedButton;
IBOutlet id serverField;
IBOutlet id signInButton;
IBOutlet id signInSheet;
IBOutlet id sslButton;
IBOutlet id window;
}
- (void)displaySignInSheet;
- (IBAction)jidDidChange:(id)sender;
- (IBAction)createAccount:(id)sender;
- (IBAction)signIn:(id)sender;
- (IBAction)changePresence:(id)sender;
- (IBAction)chat:(id)sender;
- (IBAction)addBuddy:(id)sender;
- (IBAction)removeBuddy:(id)sender;
- (IBAction)connectViaXEP65:(id)sender;
@end
|
04081337-xmpp
|
Xcode/DesktopXMPP/RosterController.h
|
Objective-C
|
bsd
| 987
|
#import "ChatController.h"
#import "XMPP.h"
@interface ChatController (PrivateAPI)
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation ChatController
@synthesize xmppStream;
@synthesize jid;
- (id)initWithStream:(XMPPStream *)stream jid:(XMPPJID *)fullJID
{
return [self initWithStream:stream jid:fullJID message:nil];
}
- (id)initWithStream:(XMPPStream *)stream jid:(XMPPJID *)fullJID message:(XMPPMessage *)message
{
if((self = [super initWithWindowNibName:@"ChatWindow"]))
{
xmppStream = [stream retain];
jid = [fullJID retain];
firstMessage = [message retain];
}
return self;
}
- (void)awakeFromNib
{
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
[messageView setString:@""];
[[self window] setTitle:[jid full]];
[[self window] makeFirstResponder:messageField];
if(firstMessage)
{
[self xmppStream:xmppStream didReceiveMessage:firstMessage];
[firstMessage release];
firstMessage = nil;
}
}
/**
* Called immediately before the window closes.
*
* This method's job is to release the WindowController (self)
* This is so that the nib file is released from memory.
**/
- (void)windowWillClose:(NSNotification *)aNotification
{
NSLog(@"ChatController: windowWillClose");
[xmppStream removeDelegate:self];
[self autorelease];
}
- (void)dealloc
{
NSLog(@"Destroying self: %@", self);
[xmppStream release];
[jid release];
[firstMessage release];
[super dealloc];
}
- (void)scrollToBottom
{
NSScrollView *scrollView = [messageView enclosingScrollView];
NSPoint newScrollOrigin;
if ([[scrollView documentView] isFlipped])
newScrollOrigin = NSMakePoint(0.0F, NSMaxY([[scrollView documentView] frame]));
else
newScrollOrigin = NSMakePoint(0.0F, 0.0F);
[[scrollView documentView] scrollPoint:newScrollOrigin];
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
[messageField setEnabled:YES];
}
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
if(![jid isEqual:[message from]]) return;
if([message isChatMessageWithBody])
{
NSString *messageStr = [[message elementForName:@"body"] stringValue];
NSString *paragraph = [NSString stringWithFormat:@"%@\n\n", messageStr];
NSMutableParagraphStyle *mps = [[[NSMutableParagraphStyle alloc] init] autorelease];
[mps setAlignment:NSLeftTextAlignment];
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithCapacity:2];
[attributes setObject:mps forKey:NSParagraphStyleAttributeName];
[attributes setObject:[NSColor colorWithCalibratedRed:250 green:250 blue:250 alpha:1] forKey:NSBackgroundColorAttributeName];
NSAttributedString *as = [[NSAttributedString alloc] initWithString:paragraph attributes:attributes];
[as autorelease];
[[messageView textStorage] appendAttributedString:as];
}
}
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
[messageField setEnabled:NO];
}
- (IBAction)sendMessage:(id)sender
{
NSString *messageStr = [messageField stringValue];
if([messageStr length] > 0)
{
NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
[body setStringValue:messageStr];
NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
[message addAttributeWithName:@"type" stringValue:@"chat"];
[message addAttributeWithName:@"to" stringValue:[jid full]];
[message addChild:body];
[xmppStream sendElement:message];
NSString *paragraph = [NSString stringWithFormat:@"%@\n\n", messageStr];
NSMutableParagraphStyle *mps = [[[NSMutableParagraphStyle alloc] init] autorelease];
[mps setAlignment:NSRightTextAlignment];
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithCapacity:2];
[attributes setObject:mps forKey:NSParagraphStyleAttributeName];
NSAttributedString *as = [[NSAttributedString alloc] initWithString:paragraph attributes:attributes];
[as autorelease];
[[messageView textStorage] appendAttributedString:as];
[self scrollToBottom];
[messageField setStringValue:@""];
[[self window] makeFirstResponder:messageField];
}
}
@end
|
04081337-xmpp
|
Xcode/DesktopXMPP/ChatController.m
|
Objective-C
|
bsd
| 4,416
|
//
// main.m
// XMPPStream
//
// Created by Robert Hanson on 4/22/07.
// Copyright __MyCompanyName__ 2007. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **) argv);
}
|
04081337-xmpp
|
Xcode/DesktopXMPP/main.m
|
Objective-C
|
bsd
| 257
|
#import <Cocoa/Cocoa.h>
@class XMPPStream;
@class XMPPMessage;
@class XMPPJID;
@interface ChatController : NSWindowController
{
XMPPStream *xmppStream;
XMPPJID *jid;
XMPPMessage *firstMessage;
IBOutlet id messageField;
IBOutlet id messageView;
}
- (id)initWithStream:(XMPPStream *)xmppStream jid:(XMPPJID *)fullJID;
- (id)initWithStream:(XMPPStream *)xmppStream jid:(XMPPJID *)fullJID message:(XMPPMessage *)message;
@property (nonatomic, readonly) XMPPStream *xmppStream;
@property (nonatomic, readonly) XMPPJID *jid;
- (IBAction)sendMessage:(id)sender;
@end
|
04081337-xmpp
|
Xcode/DesktopXMPP/ChatController.h
|
Objective-C
|
bsd
| 580
|
#import "AppDelegate.h"
#import "RosterController.h"
#import "XMPP.h"
#import "TURNSocket.h"
#import "GCDAsyncSocket.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
@implementation AppDelegate
@synthesize xmppStream;
@synthesize xmppReconnect;
@synthesize xmppRoster;
@synthesize xmppRosterStorage;
@synthesize xmppCapabilities;
@synthesize xmppCapabilitiesStorage;
@synthesize xmppPing;
- (id)init
{
if ((self = [super init]))
{
// Configure logging framework
[DDLog addLogger:[DDTTYLogger sharedInstance]];
// Initialize variables
xmppStream = [[XMPPStream alloc] init];
// xmppReconnect = [[XMPPReconnect alloc] init];
xmppRosterStorage = [[XMPPRosterMemoryStorage alloc] init];
xmppRoster = [[XMPPRoster alloc] initWithRosterStorage:xmppRosterStorage];
xmppCapabilitiesStorage = [[XMPPCapabilitiesCoreDataStorage alloc] init];
xmppCapabilities = [[XMPPCapabilities alloc] initWithCapabilitiesStorage:xmppCapabilitiesStorage];
// xmppCapabilities.autoFetchHashedCapabilities = YES;
// xmppCapabilities.autoFetchNonHashedCapabilities = NO;
// xmppPing = [[XMPPPing alloc] init];
// xmppTime = [[XMPPTime alloc] init];
turnSockets = [[NSMutableArray alloc] init];
}
return self;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
DDLogInfo(@"%@: %@", THIS_FILE, THIS_METHOD);
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
// Activate xmpp modules
[xmppReconnect activate:xmppStream];
[xmppRoster activate:xmppStream];
[xmppCapabilities activate:xmppStream];
[xmppPing activate:xmppStream];
[xmppTime activate:xmppStream];
// Add ourself as a delegate to anything we may be interested in
// [xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
[xmppReconnect addDelegate:self delegateQueue:dispatch_get_main_queue()];
[xmppCapabilities addDelegate:self delegateQueue:dispatch_get_main_queue()];
[xmppPing addDelegate:self delegateQueue:dispatch_get_main_queue()];
[xmppTime addDelegate:self delegateQueue:dispatch_get_main_queue()];
// Start the GUI stuff
[rosterController displaySignInSheet];
}
- (void)xmppStream:(XMPPStream *)sender didRegisterModule:(id)module
{
DDLogVerbose(@"%@: xmppStream:didRegisterModule: %@", THIS_FILE, module);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark XEP-0065 Support
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)connectViaXEP65:(XMPPJID *)jid
{
if(jid == nil) return;
DDLogInfo(@"Attempting TURN connection to %@", jid);
TURNSocket *turnSocket = [[TURNSocket alloc] initWithStream:xmppStream toJID:jid];
[turnSockets addObject:turnSocket];
[turnSocket startWithDelegate:self delegateQueue:dispatch_get_main_queue()];
[turnSocket release];
}
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
DDLogVerbose(@"---------- xmppStream:didReceiveIQ: ----------");
if ([TURNSocket isNewStartTURNRequest:iq])
{
TURNSocket *turnSocket = [[TURNSocket alloc] initWithStream:sender incomingTURNRequest:iq];
[turnSockets addObject:turnSocket];
[turnSocket startWithDelegate:self delegateQueue:dispatch_get_main_queue()];
[turnSocket release];
return YES;
}
return NO;
}
- (void)turnSocket:(TURNSocket *)sender didSucceed:(GCDAsyncSocket *)socket
{
DDLogInfo(@"TURN Connection succeeded!");
DDLogInfo(@"You now have a socket that you can use to send/receive data to/from the other person.");
// Now retain and use the socket.
[turnSockets removeObject:sender];
}
- (void)turnSocketDidFail:(TURNSocket *)sender
{
DDLogInfo(@"TURN Connection failed!");
[turnSockets removeObject:sender];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Auto Reconnect
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)xmppReconnect:(XMPPReconnect *)sender shouldAttemptAutoReconnect:(SCNetworkReachabilityFlags)reachabilityFlags
{
DDLogVerbose(@"---------- xmppReconnect:shouldAttemptAutoReconnect: ----------");
return YES;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Capabilities
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)xmppCapabilities:(XMPPCapabilities *)sender didDiscoverCapabilities:(NSXMLElement *)caps forJID:(XMPPJID *)jid
{
DDLogVerbose(@"---------- xmppCapabilities:didDiscoverCapabilities:forJID: ----------");
DDLogVerbose(@"jid: %@", jid);
DDLogVerbose(@"capabilities:\n%@",
[caps XMLStringWithOptions:(NSXMLNodeCompactEmptyElement | NSXMLNodePrettyPrint)]);
}
@end
|
04081337-xmpp
|
Xcode/DesktopXMPP/AppDelegate.m
|
Objective-C
|
bsd
| 5,052
|
#import "ChatWindowManager.h"
#import "ChatController.h"
#import "XMPP.h"
#import "XMPPRoster.h"
@implementation ChatWindowManager
+ (ChatController *)chatControllerForJID:(XMPPJID *)jid matchResource:(BOOL)matchResource
{
// Loop through all the open windows, and see if any of them are the one we want...
NSArray *windows = [NSApp windows];
int i;
for(i = 0; i < [windows count]; i++)
{
NSWindow *currentWindow = [windows objectAtIndex:i];
ChatController *currentWC = [currentWindow windowController];
if([currentWC isKindOfClass:[ChatController class]])
{
if(matchResource)
{
XMPPJID *currentJID = [currentWC jid];
if([currentJID isEqual:jid])
{
return currentWC;
}
}
else
{
XMPPJID *currentJID = [[currentWC jid] bareJID];
if([currentJID isEqual:[jid bareJID]])
{
return currentWC;
}
}
}
}
return nil;
}
+ (void)openChatWindowWithStream:(XMPPStream *)xmppStream forUser:(id <XMPPUser>)user
{
ChatController *cc = [[self class] chatControllerForJID:[user jid] matchResource:NO];
if(cc)
{
[[cc window] makeKeyAndOrderFront:self];
}
else
{
// Create Manual Sync Window
XMPPJID *jid = [[user primaryResource] jid];
ChatController *temp = [[ChatController alloc] initWithStream:xmppStream jid:jid];
[temp showWindow:self];
// Note: ChatController will automatically release itself when the user closes the window
}
}
+ (void)handleChatMessage:(XMPPMessage *)message withStream:(XMPPStream *)xmppStream
{
NSLog(@"ChatWindowManager: handleChatMessage");
ChatController *cc = [[self class] chatControllerForJID:[message from] matchResource:YES];
if(!cc)
{
// Create new chat window
XMPPJID *jid = [message from];
ChatController *newCC = [[ChatController alloc] initWithStream:xmppStream jid:jid message:message];
[newCC showWindow:self];
// Note: ChatController will automatically release itself when the user closes the window.
}
}
@end
|
04081337-xmpp
|
Xcode/DesktopXMPP/ChatWindowManager.m
|
Objective-C
|
bsd
| 1,985
|
//
// main.m
// iPhoneXMPP
//
// Created by Robbie Hanson on 3/18/10.
// Copyright __MyCompanyName__ 2010. All rights reserved.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
|
04081337-xmpp
|
Xcode/iPhoneXMPP/main.m
|
Objective-C
|
bsd
| 365
|
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
@class iPhoneXMPPAppDelegate;
@interface RootViewController : UITableViewController <NSFetchedResultsControllerDelegate>
{
NSManagedObjectContext *managedObjectContext;
NSFetchedResultsController *fetchedResultsController;
}
- (IBAction)settings:(id)sender;
@end
|
04081337-xmpp
|
Xcode/iPhoneXMPP/Classes/RootViewController.h
|
Objective-C
|
bsd
| 325
|
#import "iPhoneXMPPAppDelegate.h"
#import "RootViewController.h"
#import "SettingsViewController.h"
#import "GCDAsyncSocket.h"
#import "XMPP.h"
#import "XMPPReconnect.h"
#import "XMPPCapabilitiesCoreDataStorage.h"
#import "XMPPRosterCoreDataStorage.h"
#import "XMPPvCardAvatarModule.h"
#import "XMPPvCardCoreDataStorage.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
#import <CFNetwork/CFNetwork.h>
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
@interface iPhoneXMPPAppDelegate()
- (void)setupStream;
- (void)goOnline;
- (void)goOffline;
@end
#pragma mark -
@implementation iPhoneXMPPAppDelegate
@synthesize xmppStream;
@synthesize xmppReconnect;
@synthesize xmppCapabilities;
@synthesize xmppRoster;
@synthesize xmppvCardAvatarModule;
@synthesize xmppvCardTempModule;
@synthesize window;
@synthesize navigationController;
@synthesize settingsViewController;
@synthesize loginButton;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Configure logging framework
[DDLog addLogger:[DDTTYLogger sharedInstance]];
// Setup the view controllers
[window setRootViewController:navigationController];
[window makeKeyAndVisible];
// Setup the XMPP stream
[self setupStream];
if (![self connect]) {
[navigationController presentModalViewController:settingsViewController animated:YES];
}
return YES;
}
- (void)dealloc
{
[xmppStream removeDelegate:self];
[xmppRoster removeDelegate:self];
[xmppStream disconnect];
[xmppReconnect release];
[xmppvCardAvatarModule release];
[xmppvCardTempModule release];
[xmppCapabilities release];
[xmppStream release];
[xmppRoster release];
[password release];
[loginButton release];
[settingsViewController release];
[navigationController release];
[window release];
[super dealloc];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Private
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Configure the xmpp stream
- (void)setupStream
{
// Setup xmpp stream
//
// The XMPPStream is the base class for all activity.
// Everything else plugs into the xmppStream, such as modules/extensions and delegates.
xmppStream = [[XMPPStream alloc] init];
#if !TARGET_IPHONE_SIMULATOR
{
// Want xmpp to run in the background?
//
// P.S. - The simulator doesn't support backgrounding yet.
// When you try to set the associated property on the simulator, it simply fails.
// And when you background an app on the simulator,
// it just queues network traffic til the app is foregrounded again.
// We are patiently waiting for a fix from Apple.
// If you do enableBackgroundingOnSocket on the simulator,
// you will simply see an error message from the xmpp stack when it fails to set the property.
xmppStream.enableBackgroundingOnSocket = YES;
}
#endif
// Setup roster
//
// The XMPPRoster handles the xmpp protocol stuff related to the roster.
// The storage for the roster is abstracted.
// So you can use any storage mechanism you want.
// You can store it all in memory, or use core data and store it on disk, or use core data with an in-memory store,
// or setup your own using raw SQLite, or create your own storage mechanism.
// You can do it however you like! It's your application.
// But you do need to provide the roster with some storage facility.
id <XMPPRosterStorage> rosterStorage = [[[XMPPRosterCoreDataStorage alloc] init] autorelease];
// id <XMPPRosterStorage> rosterStorage = [[[XMPPRosterCoreDataStorage alloc] initWithInMemoryStore] autorelease];
xmppRoster = [[XMPPRoster alloc] initWithRosterStorage:rosterStorage];
// Setup vCard support
// We 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.
id <XMPPvCardTempModuleStorage> vcardStorage = [XMPPvCardCoreDataStorage sharedInstance];
xmppvCardTempModule = [[XMPPvCardTempModule alloc] initWithvCardStorage:vcardStorage];
xmppvCardAvatarModule = [[XMPPvCardAvatarModule alloc] initWithvCardTempModule:xmppvCardTempModule];
[xmppvCardAvatarModule addDelegate:xmppRoster delegateQueue:xmppRoster.moduleQueue];
// Setup reconnect
//
// The XMPPReconnect module monitors for "accidental disconnections" and
// automatically reconnects the stream for you.
// There's a bunch more information in the XMPPReconnect header file.
xmppReconnect = [[XMPPReconnect alloc] init];
// Setup capabilities
//
// The XMPPCapabilities module handles all the complex hashing of the caps protocol (XEP-0115).
// Basically, when other clients broadcast their presence on the network
// they include information about what capabilities their client supports (audio, video, file transfer, etc).
// But as you can imagine, this list starts to get pretty big.
// This is where the hashing stuff comes into play.
// Most people running the same version of the same client are going to have the same list of capabilities.
// So the protocol defines a standardized way to hash the list of capabilities.
// Clients then broadcast the tiny hash instead of the big list.
// The XMPPCapabilities protocol automatically handles figuring out what these hashes mean,
// and also persistently storing the hashes so lookups aren't needed in the future.
//
// Similarly to the roster, the storage of the module is abstracted.
// You are strongly encouraged to persist caps information across sessions.
//
// The XMPPCapabilitiesCoreDataStorage is an ideal solution.
// It can also be shared amongst multiple streams to further reduce hash lookups.
id <XMPPCapabilitiesStorage> capsStorage = [XMPPCapabilitiesCoreDataStorage sharedInstance];
xmppCapabilities = [[XMPPCapabilities alloc] initWithCapabilitiesStorage:capsStorage];
xmppCapabilities.autoFetchHashedCapabilities = YES;
xmppCapabilities.autoFetchNonHashedCapabilities = NO;
[xmppRoster setAutoRoster:YES];
// Activate xmpp modules
[xmppReconnect activate:xmppStream];
[xmppCapabilities activate:xmppStream];
[xmppRoster activate:xmppStream];
[xmppvCardTempModule activate:xmppStream];
[xmppvCardAvatarModule activate:xmppStream];
// Add ourself as a delegate to anything we may be interested in
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
[xmppRoster addDelegate:self delegateQueue:dispatch_get_main_queue()];
// Optional:
//
// Replace me with the proper domain and port.
// The example below is setup for a typical google talk account.
//
// If you don't supply a hostName, then it will be automatically resolved using the JID (below).
// For example, if you supply a JID like 'user@quack.com/rsrc'
// then the xmpp framework will follow the xmpp specification, and do a SRV lookup for quack.com.
//
// If you don't specify a hostPort, then the default (5222) will be used.
// [xmppStream setHostName:@"talk.google.com"];
// [xmppStream setHostPort:5222];
// You may need to alter these settings depending on the server you're connecting to
allowSelfSignedCertificates = NO;
allowSSLHostNameMismatch = NO;
}
// It's easy to create XML elments to send and to read received XML elements.
// You have the entire NSXMLElement and NSXMLNode API's.
//
// In addition to this, the NSXMLElement+XMPP category provides some very handy methods for working with XMPP.
//
// On the iPhone, Apple chose not to include the full NSXML suite.
// No problem - we use the KissXML library as a drop in replacement.
//
// For more information on working with XML elements, see the Wiki article:
// http://code.google.com/p/xmppframework/wiki/WorkingWithElements
- (void)goOnline
{
XMPPPresence *presence = [XMPPPresence presence]; // type="available" is implicit
[[self xmppStream] sendElement:presence];
}
- (void)goOffline
{
XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
[[self xmppStream] sendElement:presence];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Connect/disconnect
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)connect
{
if (![xmppStream isDisconnected]) {
return YES;
}
NSString *myJID = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyJID];
NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyPassword];
//
// If you don't want to use the Settings view to set the JID,
// uncomment the section below to hard code a JID and password.
//
// Replace me with the proper JID and password:
// myJID = @"user@gmail.com/xmppframework";
// myPassword = @"";
if (myJID == nil || myPassword == nil) {
DDLogWarn(@"JID and password must be set before connecting!");
return NO;
}
[xmppStream setMyJID:[XMPPJID jidWithString:myJID]];
password = myPassword;
NSError *error = nil;
if (![xmppStream connect:&error])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error connecting"
message:@"See console for error details."
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
[alertView release];
DDLogError(@"Error connecting: %@", error);
return NO;
}
return YES;
}
- (void)disconnect {
[self goOffline];
[xmppStream disconnect];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark UIApplicationDelegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)applicationDidEnterBackground:(UIApplication *)application
{
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state
information to restore your application to its current state in case it is terminated later.
If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
*/
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
#if TARGET_IPHONE_SIMULATOR
DDLogError(@"The iPhone simulator does not process background network traffic. Inbound traffic is queued until the keepAliveTimeout:handler: fires.");
#endif
if ([application respondsToSelector:@selector(setKeepAliveTimeout:handler:)])
{
[application setKeepAliveTimeout:600 handler:^{
DDLogVerbose(@"KeepAliveHandler");
// Do other keep alive stuff here.
}];
}
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark XMPPRosterDelegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)xmppRoster:(XMPPRoster *)sender didReceiveBuddyRequest:(XMPPPresence *)presence
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
NSString *displayName = [[xmppRoster userForJID:[presence from]] displayName];
NSString *jidStrBare = [presence fromStr];
NSString *body = nil;
if (![displayName isEqualToString:jidStrBare])
{
body = [NSString stringWithFormat:@"Buddy request from %@ <%@>", displayName, jidStrBare];
}
else
{
body = [NSString stringWithFormat:@"Buddy request from %@", displayName];
}
if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:displayName
message:body
delegate:nil
cancelButtonTitle:@"Not implemented"
otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else
{
// We are not active, so use a local notification instead
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.alertAction = @"Not implemented";
localNotification.alertBody = body;
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
[localNotification release];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark XMPPStream Delegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
if (allowSelfSignedCertificates)
{
[settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];
}
if (allowSSLHostNameMismatch)
{
[settings setObject:[NSNull null] forKey:(NSString *)kCFStreamSSLPeerName];
}
else
{
// Google does things incorrectly (does not conform to RFC).
// Because so many people ask questions about this (assume xmpp framework is broken),
// I've explicitly added code that shows how other xmpp clients "do the right thing"
// when connecting to a google server (gmail, or google apps for domains).
NSString *expectedCertName = nil;
NSString *serverDomain = xmppStream.hostName;
NSString *virtualDomain = [xmppStream.myJID domain];
if ([serverDomain isEqualToString:@"talk.google.com"])
{
if ([virtualDomain isEqualToString:@"gmail.com"])
{
expectedCertName = virtualDomain;
}
else
{
expectedCertName = serverDomain;
}
}
else if (serverDomain == nil)
{
expectedCertName = virtualDomain;
}
else
{
expectedCertName = serverDomain;
}
if (expectedCertName)
{
[settings setObject:expectedCertName forKey:(NSString *)kCFStreamSSLPeerName];
}
}
}
- (void)xmppStreamDidSecure:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
isOpen = YES;
NSError *error = nil;
if (![[self xmppStream] authenticateWithPassword:password error:&error])
{
DDLogError(@"Error authenticating: %@", error);
}
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
[self goOnline];
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
DDLogVerbose(@"%@: %@ - %@", THIS_FILE, THIS_METHOD, [iq elementID]);
return NO;
}
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
// A simple example of inbound message handling.
if ([message isChatMessageWithBody])
{
NSString *body = [[message elementForName:@"body"] stringValue];
NSString *displayName = [[xmppRoster userForJID:[message from]] displayName];
if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:displayName
message:body
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
[alertView release];
} else {
// We are not active, so use a local notification instead
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.alertAction = @"Ok";
localNotification.alertBody = [NSString stringWithFormat:@"From: %@\n\n%@",displayName,body];
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
[localNotification release];
}
}
}
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
DDLogVerbose(@"%@: %@ - %@", THIS_FILE, THIS_METHOD, [presence fromStr]);
}
- (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
if (!isOpen)
{
DDLogError(@"Unable to connect to server. Check xmppStream.hostName");
}
}
@end
|
04081337-xmpp
|
Xcode/iPhoneXMPP/Classes/iPhoneXMPPAppDelegate.m
|
Objective-C
|
bsd
| 17,335
|
//
// SettingsViewController.h
// iPhoneXMPP
//
// Created by Eric Chamberlain on 3/18/11.
// Copyright 2011 RF.com. All rights reserved.
//
#import <UIKit/UIKit.h>
extern NSString *const kXMPPmyJID;
extern NSString *const kXMPPmyPassword;
@interface SettingsViewController : UIViewController
{
UITextField *jidField;
UITextField *passwordField;
}
@property (nonatomic,retain) IBOutlet UITextField *jidField;
@property (nonatomic,retain) IBOutlet UITextField *passwordField;
- (IBAction)done:(id)sender;
- (IBAction)hideKeyboard:(id)sender;
@end
|
04081337-xmpp
|
Xcode/iPhoneXMPP/Classes/SettingsViewController.h
|
Objective-C
|
bsd
| 563
|
//
// SettingsViewController.m
// iPhoneXMPP
//
// Created by Eric Chamberlain on 3/18/11.
// Copyright 2011 RF.com. All rights reserved.
//
#import "SettingsViewController.h"
NSString *const kXMPPmyJID = @"kXMPPmyJID";
NSString *const kXMPPmyPassword = @"kXMPPmyPassword";
@implementation SettingsViewController
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Init/dealloc methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)awakeFromNib {
self.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
}
- (void)dealloc
{
[jidField release];
[passwordField release];
[super dealloc];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark View lifecycle
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
jidField.text = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyJID];
passwordField.text = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyPassword];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Private
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setField:(UITextField *)field forKey:(NSString *)key
{
if (field.text != nil)
{
[[NSUserDefaults standardUserDefaults] setObject:field.text forKey:key];
} else {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Actions
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (IBAction)done:(id)sender
{
[self setField:jidField forKey:kXMPPmyJID];
[self setField:passwordField forKey:kXMPPmyPassword];
[self dismissModalViewControllerAnimated:YES];
}
- (IBAction)hideKeyboard:(id)sender {
[sender resignFirstResponder];
[self done:sender];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Getter/setter methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@synthesize jidField;
@synthesize passwordField;
@end
|
04081337-xmpp
|
Xcode/iPhoneXMPP/Classes/SettingsViewController.m
|
Objective-C
|
bsd
| 2,709
|
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#import "XMPPRoster.h"
@class SettingsViewController;
@class XMPPStream;
@class XMPPReconnect;
@class XMPPCapabilities;
@class XMPPRosterCoreDataStorage;
@class XMPPvCardAvatarModule;
@class XMPPvCardTempModule;
@interface iPhoneXMPPAppDelegate : NSObject <UIApplicationDelegate, XMPPRosterDelegate>
{
XMPPStream *xmppStream;
XMPPReconnect *xmppReconnect;
XMPPCapabilities *xmppCapabilities;
XMPPRoster *xmppRoster;
XMPPvCardAvatarModule *xmppvCardAvatarModule;
XMPPvCardTempModule *xmppvCardTempModule;
NSString *password;
BOOL allowSelfSignedCertificates;
BOOL allowSSLHostNameMismatch;
BOOL isOpen;
UIWindow *window;
UINavigationController *navigationController;
SettingsViewController *loginViewController;
UIBarButtonItem *loginButton;
}
@property (nonatomic, readonly) XMPPStream *xmppStream;
@property (nonatomic, readonly) XMPPReconnect *xmppReconnect;
@property (nonatomic, readonly) XMPPCapabilities *xmppCapabilities;
@property (nonatomic, readonly) XMPPRoster *xmppRoster;
@property (nonatomic, readonly) XMPPvCardAvatarModule *xmppvCardAvatarModule;
@property (nonatomic, readonly) XMPPvCardTempModule *xmppvCardTempModule;
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
@property (nonatomic, retain) IBOutlet SettingsViewController *settingsViewController;
@property (nonatomic, retain) IBOutlet UIBarButtonItem *loginButton;
- (BOOL)connect;
- (void)disconnect;
@end
|
04081337-xmpp
|
Xcode/iPhoneXMPP/Classes/iPhoneXMPPAppDelegate.h
|
Objective-C
|
bsd
| 1,579
|
#import "RootViewController.h"
#import "SettingsViewController.h"
#import "iPhoneXMPPAppDelegate.h"
#import "XMPP.h"
#import "XMPPRosterCoreDataStorage.h"
#import "XMPPUserCoreDataStorageObject.h"
#import "XMPPResourceCoreDataStorageObject.h"
#import "XMPPvCardAvatarModule.h"
#import "DDLog.h"
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
@implementation RootViewController
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Accessors
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (iPhoneXMPPAppDelegate *)appDelegate
{
return (iPhoneXMPPAppDelegate *)[[UIApplication sharedApplication] delegate];
}
- (XMPPStream *)xmppStream
{
return [[self appDelegate] xmppStream];
}
- (XMPPRoster *)xmppRoster
{
return [[self appDelegate] xmppRoster];
}
- (XMPPRosterCoreDataStorage *)xmppRosterStorage
{
return [[self xmppRoster] xmppRosterStorage];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark View lifecycle
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 400, 44)];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textColor = [UIColor whiteColor];
titleLabel.font = [UIFont boldSystemFontOfSize:20.0];
titleLabel.numberOfLines = 1;
titleLabel.adjustsFontSizeToFitWidth = YES;
titleLabel.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
titleLabel.textAlignment = UITextAlignmentCenter;
if ([[self appDelegate] connect])
{
titleLabel.text = [[[[self appDelegate] xmppStream] myJID] bare];
} else
{
titleLabel.text = @"No JID";
}
self.navigationItem.titleView = titleLabel;
[titleLabel release];
}
- (void)viewWillDisappear:(BOOL)animated {
[[self appDelegate] disconnect];
[[[self appDelegate] xmppvCardTempModule] removeDelegate:self];
[super viewWillDisappear:animated];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Core Data
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (NSManagedObjectContext *)managedObjectContext
{
if (managedObjectContext == nil)
{
managedObjectContext = [[NSManagedObjectContext alloc] init];
NSPersistentStoreCoordinator *psc = [[self xmppRosterStorage] persistentStoreCoordinator];
[managedObjectContext setPersistentStoreCoordinator:psc];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(contextDidSave:)
name:NSManagedObjectContextDidSaveNotification
object:nil];
}
return managedObjectContext;
}
- (void)contextDidSave:(NSNotification *)notification
{
NSManagedObjectContext *sender = (NSManagedObjectContext *)[notification object];
if (sender != managedObjectContext &&
[sender persistentStoreCoordinator] == [managedObjectContext persistentStoreCoordinator])
{
DDLogError(@"%@: %@", THIS_FILE, THIS_METHOD);
[managedObjectContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)
withObject:notification
waitUntilDone:NO];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark NSFetchedResultsController
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController == nil)
{
NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPUserCoreDataStorageObject"
inManagedObjectContext:[self managedObjectContext]];
NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"sectionNum" ascending:YES];
NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"displayName" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, sd2, nil];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
[fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setFetchBatchSize:10];
fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:[self managedObjectContext]
sectionNameKeyPath:@"sectionNum"
cacheName:nil];
[fetchedResultsController setDelegate:self];
[sd1 release];
[sd2 release];
[fetchRequest release];
NSError *error = nil;
if (![fetchedResultsController performFetch:&error])
{
NSLog(@"Error performing fetch: %@", error);
}
}
return fetchedResultsController;
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[[self tableView] reloadData];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark UITableViewCell helpers
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)configurePhotoForCell:(UITableViewCell *)cell user:(id <XMPPUser>)user
{
// XMPPRoster will cache photos as they arrive from the xmppvCardAvatarModule, we only need to
// ask the avatar module for a photo, if the roster doesn't have it.
if (user.photo != nil)
{
cell.imageView.image = user.photo;
}
else
{
NSData *photoData = [[[self appDelegate] xmppvCardAvatarModule] photoDataForJID:user.jid];
if (photoData != nil) {
cell.imageView.image = [UIImage imageWithData:photoData];
} else {
cell.imageView.image = [UIImage imageNamed:@"defaultPerson"];
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark UITableView
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[[self fetchedResultsController] sections] count];
}
- (NSString *)tableView:(UITableView *)sender titleForHeaderInSection:(NSInteger)sectionIndex
{
NSArray *sections = [[self fetchedResultsController] sections];
if (sectionIndex < [sections count])
{
id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:sectionIndex];
int section = [sectionInfo.name intValue];
switch (section)
{
case 0 : return @"Available";
case 1 : return @"Away";
default : return @"Offline";
}
}
return @"";
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex
{
NSArray *sections = [[self fetchedResultsController] sections];
if (sectionIndex < [sections count])
{
id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:sectionIndex];
return sectionInfo.numberOfObjects;
}
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
XMPPUserCoreDataStorageObject *user = [[self fetchedResultsController] objectAtIndexPath:indexPath];
cell.textLabel.text = user.displayName;
[self configurePhotoForCell:cell user:user];
return cell;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Actions
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (IBAction)settings:(id)sender {
[self.navigationController presentModalViewController:[[self appDelegate] settingsViewController] animated:YES];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Init/dealloc
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)dealloc
{
[super dealloc];
}
@end
|
04081337-xmpp
|
Xcode/iPhoneXMPP/Classes/RootViewController.m
|
Objective-C
|
bsd
| 9,087
|
#import "Class2.h"
#define dispatch_current_queue_label() dispatch_queue_get_label(dispatch_get_current_queue())
@implementation Class2
- (void)didSomething
{
NSLog(@"Class2(%s): didSomething", dispatch_current_queue_label());
}
- (void)didSomethingElse:(BOOL)flag
{
NSLog(@"Class2(%s): didSomethingElse:%@", dispatch_current_queue_label(), (flag ? @"YES" : @"NO"));
}
- (void)foundString:(NSString *)str
{
NSLog(@"Class2(%s): foundString:\"%@\"", dispatch_current_queue_label(), str);
}
- (void)foundString:(NSString *)str andNumber:(NSNumber *)num
{
NSLog(@"Class2(%s): foundString:\"%@\" andNumber:%@", dispatch_current_queue_label(), str, num);
}
- (BOOL)shouldSing
{
BOOL answer = YES;
NSLog(@"Class2(%s): shouldSing: returning %@", dispatch_current_queue_label(), (answer ? @"YES" : @"NO"));
return answer;
}
- (BOOL)shouldDance
{
BOOL answer = YES;
NSLog(@"Class2(%s): shouldDance: returning %@", dispatch_current_queue_label(), (answer ? @"YES" : @"NO"));
return answer;
}
@end
|
04081337-xmpp
|
Xcode/Testing/MulticastDelegateTest/Class2.m
|
Objective-C
|
bsd
| 1,013
|
#import <Cocoa/Cocoa.h>
@protocol MyProtocol
@optional
- (void)didSomething;
- (void)didSomethingElse:(BOOL)flag;
- (void)foundString:(NSString *)str;
- (void)foundString:(NSString *)str andNumber:(NSNumber *)num;
- (BOOL)shouldSing;
- (BOOL)shouldDance;
- (void)fastTrack;
@end
|
04081337-xmpp
|
Xcode/Testing/MulticastDelegateTest/MyProtocol.h
|
Objective-C
|
bsd
| 285
|
#import <Cocoa/Cocoa.h>
@interface Class1 : NSObject
@end
|
04081337-xmpp
|
Xcode/Testing/MulticastDelegateTest/Class1.h
|
Objective-C
|
bsd
| 61
|
#import <Cocoa/Cocoa.h>
#import "MyProtocol.h"
#import "GCDMulticastDelegate.h"
@class Class1;
@class Class2;
@interface MulticastDelegateTestAppDelegate : NSObject <NSApplicationDelegate>
{
GCDMulticastDelegate <MyProtocol> *multicastDelegate;
dispatch_queue_t queue1;
dispatch_queue_t queue2;
dispatch_queue_t queue3;
Class1 *del1;
Class2 *del2;
NSWindow *window;
}
@property (assign) IBOutlet NSWindow *window;
@end
|
04081337-xmpp
|
Xcode/Testing/MulticastDelegateTest/MulticastDelegateTestAppDelegate.h
|
Objective-C
|
bsd
| 439
|
#import <Cocoa/Cocoa.h>
@interface Class2 : NSObject
@end
|
04081337-xmpp
|
Xcode/Testing/MulticastDelegateTest/Class2.h
|
Objective-C
|
bsd
| 61
|
#import "Class1.h"
#define dispatch_current_queue_label() dispatch_queue_get_label(dispatch_get_current_queue())
@implementation Class1
- (void)didSomething
{
NSLog(@"Class1(%s): didSomething", dispatch_current_queue_label());
}
- (void)didSomethingElse:(BOOL)flag
{
NSLog(@"Class1(%s): didSomethingElse:%@", dispatch_current_queue_label(), (flag ? @"YES" : @"NO"));
}
- (void)foundString:(NSString *)str
{
NSLog(@"Class1(%s): foundString:\"%@\"", dispatch_current_queue_label(), str);
[NSThread sleepForTimeInterval:0.2];
}
- (void)foundString:(NSString *)str andNumber:(NSNumber *)num
{
NSLog(@"Class1(%s): foundString:\"%@\" andNumber:%@", dispatch_current_queue_label(), str, num);
}
- (BOOL)shouldSing
{
BOOL answer = NO;
NSLog(@"Class1(%s): shouldSing: returning %@", dispatch_current_queue_label(), (answer ? @"YES" : @"NO"));
return answer;
}
- (BOOL)shouldDance
{
BOOL answer = YES;
NSLog(@"Class1(%s): shouldDance: returning %@", dispatch_current_queue_label(), (answer ? @"YES" : @"NO"));
return answer;
}
@end
|
04081337-xmpp
|
Xcode/Testing/MulticastDelegateTest/Class1.m
|
Objective-C
|
bsd
| 1,052
|
//
// main.m
// MulticastDelegateTest
//
// Created by Robbie Hanson on 12/18/09.
// Copyright 2009 Deusty Designs, LLC.. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **) argv);
}
|
04081337-xmpp
|
Xcode/Testing/MulticastDelegateTest/main.m
|
Objective-C
|
bsd
| 272
|
#import "MulticastDelegateTestAppDelegate.h"
#import "Class1.h"
#import "Class2.h"
#import <libkern/OSAtomic.h>
#define dispatch_current_queue_label() dispatch_queue_get_label(dispatch_get_current_queue())
@interface MulticastDelegateTestAppDelegate (PrivateAPI)
- (void)testVoidMethods;
- (void)testAnyBoolMethod;
- (void)testAllBoolMethod;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation MulticastDelegateTestAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
multicastDelegate = [[GCDMulticastDelegate alloc] init];
del1 = [[Class1 alloc] init];
del2 = [[Class2 alloc] init];
queue1 = dispatch_queue_create("S", NULL);
queue2 = dispatch_queue_create("1", NULL);
queue3 = dispatch_queue_create("2", NULL);
[multicastDelegate addDelegate:self delegateQueue:queue1];
[multicastDelegate addDelegate:del1 delegateQueue:queue2];
[multicastDelegate addDelegate:del2 delegateQueue:queue3];
[self testVoidMethods];
[self testAnyBoolMethod];
[self testAllBoolMethod];
}
- (void)testVoidMethods
{
[multicastDelegate didSomething];
[multicastDelegate didSomethingElse:YES];
[multicastDelegate foundString:@"I like cheese"];
[multicastDelegate foundString:@"The lucky number is" andNumber:[NSNumber numberWithInt:15]];
}
- (void)testAnyBoolMethod
{
// If ANY of the delegates return YES, then the result is YES.
// Otherwise the result is NO.
// If there are no delegates, the default result is NO.
SEL selector = @selector(shouldSing);
BOOL result = NO;
GCDMulticastDelegateEnumerator *delegateEnum = [multicastDelegate delegateEnumerator];
dispatch_group_t delGroup = dispatch_group_create();
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
id del;
dispatch_queue_t dq;
while ([delegateEnum getNextDelegate:&del delegateQueue:&dq forSelector:selector])
{
dispatch_group_async(delGroup, dq, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if ([del shouldSing])
{
dispatch_semaphore_signal(semaphore);
}
[pool drain];
});
}
dispatch_group_wait(delGroup, DISPATCH_TIME_FOREVER);
if (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW) == 0)
result = YES;
else
result = NO;
dispatch_release(delGroup);
dispatch_release(semaphore);
NSLog(@"%@ (ANY) = %@", NSStringFromSelector(selector), (result ? @"YES" : @"NO"));
}
- (void)testAllBoolMethod
{
// If ALL of the delegates return YES, then the result is YES.
// If ANY of the delegates returns NO, then the result is NO.
// If there are no delegates, the default answer is YES.
SEL selector = @selector(shouldDance);
BOOL result = YES;
GCDMulticastDelegateEnumerator *delegateEnum = [multicastDelegate delegateEnumerator];
int32_t total = (int32_t)[delegateEnum countForSelector:selector];
dispatch_group_t delGroup = dispatch_group_create();
__block int32_t value = 0;
id del;
dispatch_queue_t dq;
while ([delegateEnum getNextDelegate:&del delegateQueue:&dq forSelector:selector])
{
dispatch_group_async(delGroup, dq, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if ([del shouldDance])
{
OSAtomicIncrement32(&value);
}
[pool drain];
});
}
dispatch_group_wait(delGroup, DISPATCH_TIME_FOREVER);
OSMemoryBarrier();
if (OSAtomicCompareAndSwap32(total, total, &value))
result = YES;
else
result = NO;
NSLog(@"%@ (ALL) = %@", NSStringFromSelector(selector), (result ? @"YES" : @"NO"));
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Delegate Methods
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)didSomething
{
NSLog(@"Self(%s) : didSomething", dispatch_current_queue_label());
}
- (void)didSomethingElse:(BOOL)flag
{
NSLog(@"Self(%s) : didSomethingElse:%@", dispatch_current_queue_label(), (flag ? @"YES" : @"NO"));
}
- (void)foundString:(NSString *)str
{
NSLog(@"Self(%s) : foundString:\"%@\"", dispatch_current_queue_label(), str);
// [multicastDelegate removeDelegate:self];
// [multicastDelegate removeDelegate:del2];
}
- (void)foundString:(NSString *)str andNumber:(NSNumber *)num
{
NSLog(@"Self(%s) : foundString:\"%@\" andNumber:%@", dispatch_current_queue_label(), str, num);
}
- (BOOL)shouldSing
{
BOOL answer = NO;
NSLog(@"Self(%s) : shouldSing: returning %@", dispatch_current_queue_label(), (answer ? @"YES" : @"NO"));
return answer;
}
- (BOOL)shouldDance
{
BOOL answer = NO;
NSLog(@"Self(%s) : shouldDance: returning %@", dispatch_current_queue_label(), (answer ? @"YES" : @"NO"));
return answer;
}
- (void)fastTrack
{
NSLog(@"Self(%s) : fastTrack", dispatch_current_queue_label());
}
@end
|
04081337-xmpp
|
Xcode/Testing/MulticastDelegateTest/MulticastDelegateTestAppDelegate.m
|
Objective-C
|
bsd
| 5,059
|
#import "TestSRVResolverAppDelegate.h"
#import "XMPPSRVResolver.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
@implementation TestSRVResolverAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[DDLog addLogger:[DDTTYLogger sharedInstance]];
srvResolver = [[XMPPSRVResolver alloc] initWithdDelegate:self
delegateQueue:dispatch_get_main_queue()
resolverQueue:NULL];
// srvResolver = [[XMPPSRVResolver alloc] initWithdDelegate:self
// delegateQueue:dispatch_get_main_queue()
// resolverQueue:dispatch_get_main_queue()];
NSString *domain = @"gmail.com";
// NSString *domain = @"chat.facebook.com";
// NSString *domain = @"deusty.com";
// NSString *domain = @"someNonExistentDomain_moocow";
// NSString *domain = nil;
NSString *srvName = [XMPPSRVResolver srvNameFromXMPPDomain:domain];
DDLogVerbose(@"XMPP Domain: %@", domain);
DDLogVerbose(@"SRV Name: %@", srvName);
[srvResolver startWithSRVName:srvName timeout:5.0];
// [srvResolver stop];
}
- (void)srvResolver:(XMPPSRVResolver *)sender didResolveRecords:(NSArray *)records
{
DDLogInfo(@"srvResolver:%p didResolveRecords:\n%@", sender, records);
}
- (void)srvResolver:(XMPPSRVResolver *)sender didNotResolveDueToError:(NSError *)error
{
DDLogInfo(@"srvResolver:%p didNotResolveDueToError:\n%@", sender, error);
}
@end
|
04081337-xmpp
|
Xcode/Testing/TestSRVResolver/TestSRVResolverAppDelegate.m
|
Objective-C
|
bsd
| 1,611
|
#import <Cocoa/Cocoa.h>
@class XMPPSRVResolver;
@interface TestSRVResolverAppDelegate : NSObject <NSApplicationDelegate>
{
XMPPSRVResolver *srvResolver;
NSWindow *window;
}
@property (assign) IBOutlet NSWindow *window;
@end
|
04081337-xmpp
|
Xcode/Testing/TestSRVResolver/TestSRVResolverAppDelegate.h
|
Objective-C
|
bsd
| 231
|
//
// main.m
// TestSRVResolver
//
// Created by Robbie Hanson on 1/30/11.
// Copyright 2011 Voalte. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **) argv);
}
|
04081337-xmpp
|
Xcode/Testing/TestSRVResolver/main.m
|
Objective-C
|
bsd
| 251
|
//
// AutoPingTestAppDelegate.m
// AutoPingTest
//
// Created by Robbie Hanson on 4/13/11.
// Copyright 2011 Deusty, LLC. All rights reserved.
//
#import "AutoPingTestAppDelegate.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#define MY_JID @"robbie@robbiehanson.com/rsrc"
#define MY_PASSWORD @""
@implementation AutoPingTestAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[DDLog addLogger:[DDTTYLogger sharedInstance]];
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
xmppStream = [[XMPPStream alloc] init];
[xmppStream setMyJID:[XMPPJID jidWithString:MY_JID]];
xmppAutoPing = [[XMPPAutoPing alloc] init];
xmppAutoPing.pingInterval = 15;
xmppAutoPing.pingTimeout = 5;
xmppAutoPing.targetJID = nil;
[xmppAutoPing activate:xmppStream];
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
[xmppAutoPing addDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
if (![xmppStream connect:&error])
{
DDLogError(@"%@: Error connecting: %@", [self class], error);
}
}
- (void)goOnline:(NSTimer *)aTimer
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
[xmppStream sendElement:[XMPPPresence presence]];
}
- (void)goOffline:(NSTimer *)aTimer
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
[xmppStream sendElement:[XMPPPresence presenceWithType:@"unavailable"]];
}
- (void)changeAutoPingInterval:(NSTimer *)aTimer
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
xmppAutoPing.pingInterval = 30;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
NSError *error = nil;
if (![xmppStream authenticateWithPassword:MY_PASSWORD error:&error])
{
DDLogError(@"%@: Error authenticating: %@", [self class], error);
}
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(goOnline:) userInfo:nil repeats:NO];
[NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(goOffline:) userInfo:nil repeats:NO];
[NSTimer scheduledTimerWithTimeInterval:35 target:self selector:@selector(changeAutoPingInterval:) userInfo:nil repeats:NO];
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
}
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)xmppAutoPingDidSendPing:(XMPPAutoPing *)sender
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
}
- (void)xmppAutoPingDidReceivePong:(XMPPAutoPing *)sender
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
}
- (void)xmppAutoPingDidTimeout:(XMPPAutoPing *)sender
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
}
@end
|
04081337-xmpp
|
Xcode/Testing/AutoPingTest/AutoPingTest/AutoPingTestAppDelegate.m
|
Objective-C
|
bsd
| 3,274
|
{\rtf0\ansi{\fonttbl\f0\fswiss Helvetica;}
{\colortbl;\red255\green255\blue255;}
\paperw9840\paperh8400
\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural
\f0\b\fs24 \cf0 Engineering:
\b0 \
Some people\
\
\b Human Interface Design:
\b0 \
Some other people\
\
\b Testing:
\b0 \
Hopefully not nobody\
\
\b Documentation:
\b0 \
Whoever\
\
\b With special thanks to:
\b0 \
Mom\
}
|
04081337-xmpp
|
Xcode/Testing/AutoPingTest/AutoPingTest/en.lproj/Credits.rtf
|
Rich Text Format
|
bsd
| 436
|
//
// main.m
// AutoPingTest
//
// Created by Robbie Hanson on 4/13/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **)argv);
}
|
04081337-xmpp
|
Xcode/Testing/AutoPingTest/AutoPingTest/main.m
|
Objective-C
|
bsd
| 254
|
//
// AutoPingTestAppDelegate.h
// AutoPingTest
//
// Created by Robbie Hanson on 4/13/11.
// Copyright 2011 Deusty, LLC. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import "XMPP.h"
#import "XMPPAutoPing.h"
@interface AutoPingTestAppDelegate : NSObject <NSApplicationDelegate> {
@private
XMPPStream *xmppStream;
XMPPAutoPing *xmppAutoPing;
NSWindow *window;
}
@property (assign) IBOutlet NSWindow *window;
@end
|
04081337-xmpp
|
Xcode/Testing/AutoPingTest/AutoPingTest/AutoPingTestAppDelegate.h
|
Objective-C
|
bsd
| 430
|
#import <UIKit/UIKit.h>
#import "FBConnect.h"
@class XMPPStreamFacebook;
@class FacebookTestViewController;
@interface FacebookTestAppDelegate : NSObject <UIApplicationDelegate, FBSessionDelegate>
{
Facebook *facebook;
XMPPStreamFacebook *xmppStream;
BOOL allowSelfSignedCertificates;
BOOL allowSSLHostNameMismatch;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet FacebookTestViewController *viewController;
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FacebookTest/FacebookTestAppDelegate.h
|
Objective-C
|
bsd
| 474
|
#import <UIKit/UIKit.h>
@interface FacebookTestViewController : UIViewController {
}
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FacebookTest/FacebookTestViewController.h
|
Objective-C
|
bsd
| 97
|
#import "FacebookTestViewController.h"
@implementation FacebookTestViewController
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
*/
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FacebookTest/FacebookTestViewController.m
|
Objective-C
|
bsd
| 865
|
//
// main.m
// FacebookTest
//
// Created by Robbie Hanson on 3/17/11.
// Copyright 2011 Voalte. All rights reserved.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FacebookTest/main.m
|
Objective-C
|
bsd
| 338
|
#import "FacebookTestAppDelegate.h"
#import "FacebookTestViewController.h"
#import "XMPP.h"
#import "XMPPStreamFacebook.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
// This is step #1 of X
//
// But I just want to hit build and go and have everything work for me... <whine/> <pout/>
//
// Too bad. You're a developer. Get over it.
//
// Now go read this:
// http://developers.facebook.com/docs/guides/mobile/
//
// And also this:
// http://code.google.com/p/xmppframework/wiki/FacebookChatHowTo
//
//#define FACEBOOK_APP_ID @"PUT_YOUR_FACEBOOK_ID_HERE_FOR_EXAMPLE_123456789012345"
@implementation FacebookTestAppDelegate
@synthesize window = _window;
@synthesize viewController = _viewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[DDLog addLogger:[DDTTYLogger sharedInstance]];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
xmppStream = [[XMPPStreamFacebook alloc] init];
xmppStream.myJID = [XMPPJID jidWithUser:@"user" domain:@"chat.facebook.com" resource:nil];
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
allowSelfSignedCertificates = NO;
allowSSLHostNameMismatch = YES;
facebook = [[Facebook alloc] initWithAppId:FACEBOOK_APP_ID]; // Go set FACEBOOK_APP_ID at top of file
// Note: Be sure to invoke this AFTER the [self.window makeKeyAndVisible] method call above,
// or nothing will happen.
[facebook authorize:[XMPPStreamFacebook permissions]
delegate:self
appAuth:NO
safariAuth:NO];
return YES;
}
- (void)dealloc
{
[_window release];
[_viewController release];
[super dealloc];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Facebook Delegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
return [facebook handleOpenURL:url];
}
- (void)fbDidLogin
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
DDLogVerbose(@"%@: facebook.accessToken(%@)", THIS_FILE, facebook.accessToken);
DDLogVerbose(@"%@: facebook.expirationDate(%@)", THIS_FILE, facebook.expirationDate);
NSError *error = nil;
if (![xmppStream connect:&error])
{
DDLogError(@"%@: Error in xmpp connection: %@", THIS_FILE, error);
}
}
- (void)fbDidNotLogin:(BOOL)cancelled
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark XMPPStream Delegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
if (allowSelfSignedCertificates)
{
[settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];
}
if (allowSSLHostNameMismatch)
{
[settings setObject:[NSNull null] forKey:(NSString *)kCFStreamSSLPeerName];
}
else
{
NSString *expectedCertName = [sender hostName];
if (expectedCertName == nil)
{
expectedCertName = [[sender myJID] domain];
}
[settings setObject:expectedCertName forKey:(NSString *)kCFStreamSSLPeerName];
}
}
- (void)xmppStreamDidSecure:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
NSError *error = nil;
BOOL result = [xmppStream authenticateWithAppId:FACEBOOK_APP_ID // Go set FACEBOOK_APP_ID at top of file
accessToken:facebook.accessToken
expirationDate:facebook.expirationDate
error:&error];
if (result == NO)
{
DDLogError(@"%@: Error in xmpp auth: %@", THIS_FILE, error);
}
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
DDLogVerbose(@"%@: %@ - error: %@", THIS_FILE, THIS_METHOD, error);
}
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FacebookTest/FacebookTestAppDelegate.m
|
Objective-C
|
bsd
| 4,602
|
/*
* Copyright 2010 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "FBDialog.h"
@protocol FBLoginDialogDelegate;
/**
* Do not use this interface directly, instead, use authorize in Facebook.h
*
* Facebook Login Dialog interface for start the facebook webView login dialog.
* It start pop-ups prompting for credentials and permissions.
*/
@interface FBLoginDialog : FBDialog {
id<FBLoginDialogDelegate> _loginDelegate;
}
-(id) initWithURL:(NSString *) loginURL
loginParams:(NSMutableDictionary *) params
delegate:(id <FBLoginDialogDelegate>) delegate;
@end
///////////////////////////////////////////////////////////////////////////////////////////////////
@protocol FBLoginDialogDelegate <NSObject>
- (void)fbDialogLogin:(NSString*)token expirationDate:(NSDate*)expirationDate;
- (void)fbDialogNotLogin:(BOOL)cancelled;
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/FBLoginDialog.h
|
Objective-C
|
bsd
| 1,387
|
/*
* Copyright 2010 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "FBDialog.h"
#import "Facebook.h"
///////////////////////////////////////////////////////////////////////////////////////////////////
// global
static NSString* kDefaultTitle = @"Connect to Facebook";
static CGFloat kFacebookBlue[4] = {0.42578125, 0.515625, 0.703125, 1.0};
static CGFloat kBorderGray[4] = {0.3, 0.3, 0.3, 0.8};
static CGFloat kBorderBlack[4] = {0.3, 0.3, 0.3, 1};
static CGFloat kBorderBlue[4] = {0.23, 0.35, 0.6, 1.0};
static CGFloat kTransitionDuration = 0.3;
static CGFloat kTitleMarginX = 8;
static CGFloat kTitleMarginY = 4;
static CGFloat kPadding = 10;
static CGFloat kBorderWidth = 10;
///////////////////////////////////////////////////////////////////////////////////////////////////
BOOL FBIsDeviceIPad() {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
return YES;
}
#endif
return NO;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
@implementation FBDialog
@synthesize delegate = _delegate,
params = _params;
///////////////////////////////////////////////////////////////////////////////////////////////////
// private
- (void)addRoundedRectToPath:(CGContextRef)context rect:(CGRect)rect radius:(float)radius {
CGContextBeginPath(context);
CGContextSaveGState(context);
if (radius == 0) {
CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGContextAddRect(context, rect);
} else {
rect = CGRectOffset(CGRectInset(rect, 0.5, 0.5), 0.5, 0.5);
CGContextTranslateCTM(context, CGRectGetMinX(rect)-0.5, CGRectGetMinY(rect)-0.5);
CGContextScaleCTM(context, radius, radius);
float fw = CGRectGetWidth(rect) / radius;
float fh = CGRectGetHeight(rect) / radius;
CGContextMoveToPoint(context, fw, fh/2);
CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);
}
CGContextClosePath(context);
CGContextRestoreGState(context);
}
- (void)drawRect:(CGRect)rect fill:(const CGFloat*)fillColors radius:(CGFloat)radius {
CGContextRef context = UIGraphicsGetCurrentContext();
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
if (fillColors) {
CGContextSaveGState(context);
CGContextSetFillColor(context, fillColors);
if (radius) {
[self addRoundedRectToPath:context rect:rect radius:radius];
CGContextFillPath(context);
} else {
CGContextFillRect(context, rect);
}
CGContextRestoreGState(context);
}
CGColorSpaceRelease(space);
}
- (void)strokeLines:(CGRect)rect stroke:(const CGFloat*)strokeColor {
CGContextRef context = UIGraphicsGetCurrentContext();
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGContextSaveGState(context);
CGContextSetStrokeColorSpace(context, space);
CGContextSetStrokeColor(context, strokeColor);
CGContextSetLineWidth(context, 1.0);
{
CGPoint points[] = {{rect.origin.x+0.5, rect.origin.y-0.5},
{rect.origin.x+rect.size.width, rect.origin.y-0.5}};
CGContextStrokeLineSegments(context, points, 2);
}
{
CGPoint points[] = {{rect.origin.x+0.5, rect.origin.y+rect.size.height-0.5},
{rect.origin.x+rect.size.width-0.5, rect.origin.y+rect.size.height-0.5}};
CGContextStrokeLineSegments(context, points, 2);
}
{
CGPoint points[] = {{rect.origin.x+rect.size.width-0.5, rect.origin.y},
{rect.origin.x+rect.size.width-0.5, rect.origin.y+rect.size.height}};
CGContextStrokeLineSegments(context, points, 2);
}
{
CGPoint points[] = {{rect.origin.x+0.5, rect.origin.y},
{rect.origin.x+0.5, rect.origin.y+rect.size.height}};
CGContextStrokeLineSegments(context, points, 2);
}
CGContextRestoreGState(context);
CGColorSpaceRelease(space);
}
- (BOOL)shouldRotateToOrientation:(UIDeviceOrientation)orientation {
if (orientation == _orientation) {
return NO;
} else {
return orientation == UIDeviceOrientationLandscapeLeft
|| orientation == UIDeviceOrientationLandscapeRight
|| orientation == UIDeviceOrientationPortrait
|| orientation == UIDeviceOrientationPortraitUpsideDown;
}
}
- (CGAffineTransform)transformForOrientation {
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (orientation == UIInterfaceOrientationLandscapeLeft) {
return CGAffineTransformMakeRotation(M_PI*1.5);
} else if (orientation == UIInterfaceOrientationLandscapeRight) {
return CGAffineTransformMakeRotation(M_PI/2);
} else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
return CGAffineTransformMakeRotation(-M_PI);
} else {
return CGAffineTransformIdentity;
}
}
- (void)sizeToFitOrientation:(BOOL)transform {
if (transform) {
self.transform = CGAffineTransformIdentity;
}
CGRect frame = [UIScreen mainScreen].applicationFrame;
CGPoint center = CGPointMake(
frame.origin.x + ceil(frame.size.width/2),
frame.origin.y + ceil(frame.size.height/2));
CGFloat scale_factor = 1.0f;
if (FBIsDeviceIPad()) {
// On the iPad the dialog's dimensions should only be 60% of the screen's
scale_factor = 0.6f;
}
CGFloat width = floor(scale_factor * frame.size.width) - kPadding * 2;
CGFloat height = floor(scale_factor * frame.size.height) - kPadding * 2;
_orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsLandscape(_orientation)) {
self.frame = CGRectMake(kPadding, kPadding, height, width);
} else {
self.frame = CGRectMake(kPadding, kPadding, width, height);
}
self.center = center;
if (transform) {
self.transform = [self transformForOrientation];
}
}
- (void)updateWebOrientation {
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsLandscape(orientation)) {
[_webView stringByEvaluatingJavaScriptFromString:
@"document.body.setAttribute('orientation', 90);"];
} else {
[_webView stringByEvaluatingJavaScriptFromString:
@"document.body.removeAttribute('orientation');"];
}
}
- (void)bounce1AnimationStopped {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:kTransitionDuration/2];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(bounce2AnimationStopped)];
self.transform = CGAffineTransformScale([self transformForOrientation], 0.9, 0.9);
[UIView commitAnimations];
}
- (void)bounce2AnimationStopped {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:kTransitionDuration/2];
self.transform = [self transformForOrientation];
[UIView commitAnimations];
}
- (NSURL*)generateURL:(NSString*)baseURL params:(NSDictionary*)params {
if (params) {
NSMutableArray* pairs = [NSMutableArray array];
for (NSString* key in params.keyEnumerator) {
NSString* value = [params objectForKey:key];
NSString* escaped_value = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL, /* allocator */
(CFStringRef)value,
NULL, /* charactersToLeaveUnescaped */
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8);
[pairs addObject:[NSString stringWithFormat:@"%@=%@", key, escaped_value]];
[escaped_value release];
}
NSString* query = [pairs componentsJoinedByString:@"&"];
NSString* url = [NSString stringWithFormat:@"%@?%@", baseURL, query];
return [NSURL URLWithString:url];
} else {
return [NSURL URLWithString:baseURL];
}
}
- (void)addObservers {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(deviceOrientationDidChange:)
name:@"UIDeviceOrientationDidChangeNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:) name:@"UIKeyboardWillShowNotification" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:) name:@"UIKeyboardWillHideNotification" object:nil];
}
- (void)removeObservers {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:@"UIDeviceOrientationDidChangeNotification" object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:@"UIKeyboardWillShowNotification" object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:@"UIKeyboardWillHideNotification" object:nil];
}
- (void)postDismissCleanup {
[self removeObservers];
[self removeFromSuperview];
[_modalBackgroundView removeFromSuperview];
}
- (void)dismiss:(BOOL)animated {
[self dialogWillDisappear];
[_loadingURL release];
_loadingURL = nil;
if (animated) {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:kTransitionDuration];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(postDismissCleanup)];
self.alpha = 0;
[UIView commitAnimations];
} else {
[self postDismissCleanup];
}
}
- (void)cancel {
[self dialogDidCancel:nil];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// NSObject
- (id)init {
if (self = [super initWithFrame:CGRectZero]) {
_delegate = nil;
_loadingURL = nil;
_orientation = UIDeviceOrientationUnknown;
_showingKeyboard = NO;
self.backgroundColor = [UIColor clearColor];
self.autoresizesSubviews = YES;
self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.contentMode = UIViewContentModeRedraw;
UIImage* iconImage = [UIImage imageNamed:@"FBDialog.bundle/images/fbicon.png"];
UIImage* closeImage = [UIImage imageNamed:@"FBDialog.bundle/images/close.png"];
_iconView = [[UIImageView alloc] initWithImage:iconImage];
[self addSubview:_iconView];
UIColor* color = [UIColor colorWithRed:167.0/255 green:184.0/255 blue:216.0/255 alpha:1];
_closeButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
[_closeButton setImage:closeImage forState:UIControlStateNormal];
[_closeButton setTitleColor:color forState:UIControlStateNormal];
[_closeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
[_closeButton addTarget:self action:@selector(cancel)
forControlEvents:UIControlEventTouchUpInside];
// To be compatible with OS 2.x
#if __IPHONE_OS_VERSION_MAX_ALLOWED <= __IPHONE_2_2
_closeButton.font = [UIFont boldSystemFontOfSize:12];
#else
_closeButton.titleLabel.font = [UIFont boldSystemFontOfSize:12];
#endif
_closeButton.showsTouchWhenHighlighted = YES;
_closeButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin
| UIViewAutoresizingFlexibleBottomMargin;
[self addSubview:_closeButton];
CGFloat titleLabelFontSize = (FBIsDeviceIPad() ? 18 : 14);
_titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
_titleLabel.text = kDefaultTitle;
_titleLabel.backgroundColor = [UIColor clearColor];
_titleLabel.textColor = [UIColor whiteColor];
_titleLabel.font = [UIFont boldSystemFontOfSize:titleLabelFontSize];
_titleLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin
| UIViewAutoresizingFlexibleBottomMargin;
[self addSubview:_titleLabel];
_webView = [[UIWebView alloc] initWithFrame:CGRectMake(kPadding, kPadding, 480, 480)];
_webView.delegate = self;
_webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self addSubview:_webView];
_spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:
UIActivityIndicatorViewStyleWhiteLarge];
_spinner.autoresizingMask =
UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin
| UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
[self addSubview:_spinner];
_modalBackgroundView = [[UIView alloc] init];
}
return self;
}
- (void)dealloc {
_webView.delegate = nil;
[_webView release];
[_params release];
[_serverURL release];
[_spinner release];
[_titleLabel release];
[_iconView release];
[_closeButton release];
[_loadingURL release];
[_modalBackgroundView release];
[super dealloc];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// UIView
- (void)drawRect:(CGRect)rect {
CGRect grayRect = CGRectOffset(rect, -0.5, -0.5);
[self drawRect:grayRect fill:kBorderGray radius:10];
CGRect headerRect = CGRectMake(
ceil(rect.origin.x + kBorderWidth), ceil(rect.origin.y + kBorderWidth),
rect.size.width - kBorderWidth*2, _titleLabel.frame.size.height);
[self drawRect:headerRect fill:kFacebookBlue radius:0];
[self strokeLines:headerRect stroke:kBorderBlue];
CGRect webRect = CGRectMake(
ceil(rect.origin.x + kBorderWidth), headerRect.origin.y + headerRect.size.height,
rect.size.width - kBorderWidth*2, _webView.frame.size.height+1);
[self strokeLines:webRect stroke:kBorderBlack];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
NSURL* url = request.URL;
if ([url.scheme isEqualToString:@"fbconnect"]) {
if ([[url.resourceSpecifier substringToIndex:8] isEqualToString:@"//cancel"]) {
NSString * errorCode = [self getStringFromUrl:[url absoluteString] needle:@"error_code="];
NSString * errorStr = [self getStringFromUrl:[url absoluteString] needle:@"error_msg="];
if (errorCode) {
NSDictionary * errorData = [NSDictionary dictionaryWithObject:errorStr forKey:@"error_msg"];
NSError * error = [NSError errorWithDomain:@"facebookErrDomain"
code:[errorCode intValue]
userInfo:errorData];
[self dismissWithError:error animated:YES];
} else {
[self dialogDidCancel:url];
}
} else {
[self dialogDidSucceed:url];
}
return NO;
} else if ([_loadingURL isEqual:url]) {
return YES;
} else if (navigationType == UIWebViewNavigationTypeLinkClicked) {
if ([_delegate respondsToSelector:@selector(dialog:shouldOpenURLInExternalBrowser:)]) {
if (![_delegate dialog:self shouldOpenURLInExternalBrowser:url]) {
return NO;
}
}
[[UIApplication sharedApplication] openURL:request.URL];
return NO;
} else {
return YES;
}
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[_spinner stopAnimating];
_spinner.hidden = YES;
self.title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
[self updateWebOrientation];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
// 102 == WebKitErrorFrameLoadInterruptedByPolicyChange
if (!([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102)) {
[self dismissWithError:error animated:YES];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// UIDeviceOrientationDidChangeNotification
- (void)deviceOrientationDidChange:(void*)object {
UIDeviceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (!_showingKeyboard && [self shouldRotateToOrientation:orientation]) {
[self updateWebOrientation];
CGFloat duration = [UIApplication sharedApplication].statusBarOrientationAnimationDuration;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:duration];
[self sizeToFitOrientation:YES];
[UIView commitAnimations];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// UIKeyboardNotifications
- (void)keyboardWillShow:(NSNotification*)notification {
_showingKeyboard = YES;
if (FBIsDeviceIPad()) {
// On the iPad the screen is large enough that we don't need to
// resize the dialog to accomodate the keyboard popping up
return;
}
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsLandscape(orientation)) {
_webView.frame = CGRectInset(_webView.frame,
-(kPadding + kBorderWidth),
-(kPadding + kBorderWidth) - _titleLabel.frame.size.height);
}
}
- (void)keyboardWillHide:(NSNotification*)notification {
_showingKeyboard = NO;
if (FBIsDeviceIPad()) {
return;
}
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsLandscape(orientation)) {
_webView.frame = CGRectInset(_webView.frame,
kPadding + kBorderWidth,
kPadding + kBorderWidth + _titleLabel.frame.size.height);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// public
/**
* Find a specific parameter from the url
*/
- (NSString *) getStringFromUrl: (NSString*) url needle:(NSString *) needle {
NSString * str = nil;
NSRange start = [url rangeOfString:needle];
if (start.location != NSNotFound) {
NSRange end = [[url substringFromIndex:start.location+start.length] rangeOfString:@"&"];
NSUInteger offset = start.location+start.length;
str = end.location == NSNotFound
? [url substringFromIndex:offset]
: [url substringWithRange:NSMakeRange(offset, end.location)];
str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
return str;
}
- (id)initWithURL: (NSString *) serverURL
params: (NSMutableDictionary *) params
delegate: (id <FBDialogDelegate>) delegate {
self = [self init];
_serverURL = [serverURL retain];
_params = [params retain];
_delegate = delegate;
return self;
}
- (NSString*)title {
return _titleLabel.text;
}
- (void)setTitle:(NSString*)title {
_titleLabel.text = title;
}
- (void)load {
[self loadURL:_serverURL get:_params];
}
- (void)loadURL:(NSString*)url get:(NSDictionary*)getParams {
[_loadingURL release];
_loadingURL = [[self generateURL:url params:getParams] retain];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:_loadingURL];
[_webView loadRequest:request];
}
- (void)show {
[self load];
[self sizeToFitOrientation:NO];
CGFloat innerWidth = self.frame.size.width - (kBorderWidth+1)*2;
[_iconView sizeToFit];
[_titleLabel sizeToFit];
[_closeButton sizeToFit];
_titleLabel.frame = CGRectMake(
kBorderWidth + kTitleMarginX + _iconView.frame.size.width + kTitleMarginX,
kBorderWidth,
innerWidth - (_titleLabel.frame.size.height + _iconView.frame.size.width + kTitleMarginX*2),
_titleLabel.frame.size.height + kTitleMarginY*2);
_iconView.frame = CGRectMake(
kBorderWidth + kTitleMarginX,
kBorderWidth + floor(_titleLabel.frame.size.height/2 - _iconView.frame.size.height/2),
_iconView.frame.size.width,
_iconView.frame.size.height);
_closeButton.frame = CGRectMake(
self.frame.size.width - (_titleLabel.frame.size.height + kBorderWidth),
kBorderWidth,
_titleLabel.frame.size.height,
_titleLabel.frame.size.height);
_webView.frame = CGRectMake(
kBorderWidth+1,
kBorderWidth + _titleLabel.frame.size.height,
innerWidth,
self.frame.size.height - (_titleLabel.frame.size.height + 1 + kBorderWidth*2));
[_spinner sizeToFit];
[_spinner startAnimating];
_spinner.center = _webView.center;
UIWindow* window = [UIApplication sharedApplication].keyWindow;
if (!window) {
window = [[UIApplication sharedApplication].windows objectAtIndex:0];
}
_modalBackgroundView.frame = window.frame;
[_modalBackgroundView addSubview:self];
[window addSubview:_modalBackgroundView];
[window addSubview:self];
[self dialogWillAppear];
self.transform = CGAffineTransformScale([self transformForOrientation], 0.001, 0.001);
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:kTransitionDuration/1.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(bounce1AnimationStopped)];
self.transform = CGAffineTransformScale([self transformForOrientation], 1.1, 1.1);
[UIView commitAnimations];
[self addObservers];
}
- (void)dismissWithSuccess:(BOOL)success animated:(BOOL)animated {
if (success) {
if ([_delegate respondsToSelector:@selector(dialogDidComplete:)]) {
[_delegate dialogDidComplete:self];
}
} else {
if ([_delegate respondsToSelector:@selector(dialogDidNotComplete:)]) {
[_delegate dialogDidNotComplete:self];
}
}
[self dismiss:animated];
}
- (void)dismissWithError:(NSError*)error animated:(BOOL)animated {
if ([_delegate respondsToSelector:@selector(dialog:didFailWithError:)]) {
[_delegate dialog:self didFailWithError:error];
}
[self dismiss:animated];
}
- (void)dialogWillAppear {
}
- (void)dialogWillDisappear {
}
- (void)dialogDidSucceed:(NSURL *)url {
if ([_delegate respondsToSelector:@selector(dialogCompleteWithUrl:)]) {
[_delegate dialogCompleteWithUrl:url];
}
[self dismissWithSuccess:YES animated:YES];
}
- (void)dialogDidCancel:(NSURL *)url {
if ([_delegate respondsToSelector:@selector(dialogDidNotCompleteWithUrl:)]) {
[_delegate dialogDidNotCompleteWithUrl:url];
}
[self dismissWithSuccess:NO animated:YES];
}
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/FBDialog.m
|
Objective-C
|
bsd
| 22,383
|
/*
* Copyright 2010 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "FBDialog.h"
#import "FBLoginDialog.h"
///////////////////////////////////////////////////////////////////////////////////////////////////
@implementation FBLoginDialog
///////////////////////////////////////////////////////////////////////////////////////////////////
// public
/*
* initialize the FBLoginDialog with url and parameters
*/
- (id)initWithURL:(NSString*) loginURL
loginParams:(NSMutableDictionary*) params
delegate:(id <FBLoginDialogDelegate>) delegate{
self = [super init];
_serverURL = [loginURL retain];
_params = [params retain];
_loginDelegate = delegate;
return self;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// FBDialog
/**
* Override FBDialog : to call when the webView Dialog did succeed
*/
- (void) dialogDidSucceed:(NSURL*)url {
NSString *q = [url absoluteString];
NSString *token = [self getStringFromUrl:q needle:@"access_token="];
NSString *expTime = [self getStringFromUrl:q needle:@"expires_in="];
NSDate *expirationDate =nil;
if (expTime != nil) {
int expVal = [expTime intValue];
if (expVal == 0) {
expirationDate = [NSDate distantFuture];
} else {
expirationDate = [NSDate dateWithTimeIntervalSinceNow:expVal];
}
}
if ((token == (NSString *) [NSNull null]) || (token.length == 0)) {
[self dialogDidCancel:url];
[self dismissWithSuccess:NO animated:YES];
} else {
if ([_loginDelegate respondsToSelector:@selector(fbDialogLogin:expirationDate:)]) {
[_loginDelegate fbDialogLogin:token expirationDate:expirationDate];
}
[self dismissWithSuccess:YES animated:YES];
}
}
/**
* Override FBDialog : to call with the login dialog get canceled
*/
- (void)dialogDidCancel:(NSURL *)url {
[self dismissWithSuccess:NO animated:YES];
if ([_loginDelegate respondsToSelector:@selector(fbDialogNotLogin:)]) {
[_loginDelegate fbDialogNotLogin:YES];
}
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
if (!(([error.domain isEqualToString:@"NSURLErrorDomain"] && error.code == -999) ||
([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102))) {
[super webView:webView didFailLoadWithError:error];
if ([_loginDelegate respondsToSelector:@selector(fbDialogNotLogin:)]) {
[_loginDelegate fbDialogNotLogin:NO];
}
}
}
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/FBLoginDialog.m
|
Objective-C
|
bsd
| 3,012
|
/*
* Copyright 2010 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Facebook.h"
#include "FBDialog.h"
#include "FBLoginDialog.h"
#include "FBRequest.h"
#include "SBJSON.h"
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/FBConnect.h
|
C
|
bsd
| 706
|
/*
* Copyright 2010 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "FBLoginDialog.h"
#import "FBRequest.h"
@protocol FBSessionDelegate;
/**
* Main Facebook interface for interacting with the Facebook developer API.
* Provides methods to log in and log out a user, make requests using the REST
* and Graph APIs, and start user interface interactions (such as
* pop-ups promoting for credentials, permissions, stream posts, etc.)
*/
@interface Facebook : NSObject<FBLoginDialogDelegate>{
NSString* _accessToken;
NSDate* _expirationDate;
id<FBSessionDelegate> _sessionDelegate;
FBRequest* _request;
FBDialog* _loginDialog;
FBDialog* _fbDialog;
NSString* _appId;
NSArray* _permissions;
}
@property(nonatomic, copy) NSString* accessToken;
@property(nonatomic, copy) NSDate* expirationDate;
@property(nonatomic, assign) id<FBSessionDelegate> sessionDelegate;
- (id)initWithAppId:(NSString *)app_id;
- (void)authorize:(NSArray *)permissions
delegate:(id<FBSessionDelegate>)delegate;
- (void)authorize:(NSArray *)permissions
delegate:(id<FBSessionDelegate>)delegate
appAuth:(BOOL)tryFBAppAuth
safariAuth:(BOOL)trySafariAuth;
- (BOOL)handleOpenURL:(NSURL *)url;
- (void)logout:(id<FBSessionDelegate>)delegate;
- (FBRequest*)requestWithParams:(NSMutableDictionary *)params
andDelegate:(id <FBRequestDelegate>)delegate;
- (FBRequest*)requestWithMethodName:(NSString *)methodName
andParams:(NSMutableDictionary *)params
andHttpMethod:(NSString *)httpMethod
andDelegate:(id <FBRequestDelegate>)delegate;
- (FBRequest*)requestWithGraphPath:(NSString *)graphPath
andDelegate:(id <FBRequestDelegate>)delegate;
- (FBRequest*)requestWithGraphPath:(NSString *)graphPath
andParams:(NSMutableDictionary *)params
andDelegate:(id <FBRequestDelegate>)delegate;
- (FBRequest*)requestWithGraphPath:(NSString *)graphPath
andParams:(NSMutableDictionary *)params
andHttpMethod:(NSString *)httpMethod
andDelegate:(id <FBRequestDelegate>)delegate;
- (void)dialog:(NSString *)action
andDelegate:(id<FBDialogDelegate>)delegate;
- (void)dialog:(NSString *)action
andParams:(NSMutableDictionary *)params
andDelegate:(id <FBDialogDelegate>)delegate;
- (BOOL)isSessionValid;
@end
////////////////////////////////////////////////////////////////////////////////
/**
* Your application should implement this delegate to receive session callbacks.
*/
@protocol FBSessionDelegate <NSObject>
@optional
/**
* Called when the user successfully logged in.
*/
- (void)fbDidLogin;
/**
* Called when the user dismissed the dialog without logging in.
*/
- (void)fbDidNotLogin:(BOOL)cancelled;
/**
* Called when the user logged out.
*/
- (void)fbDidLogout;
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/Facebook.h
|
Objective-C
|
bsd
| 3,478
|
/*
* Copyright 2010 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "FBRequest.h"
#import "JSON.h"
///////////////////////////////////////////////////////////////////////////////////////////////////
// global
static NSString* kUserAgent = @"FacebookConnect";
static NSString* kStringBoundary = @"3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
static const int kGeneralErrorCode = 10000;
static const NSTimeInterval kTimeoutInterval = 180.0;
///////////////////////////////////////////////////////////////////////////////////////////////////
@implementation FBRequest
@synthesize delegate = _delegate,
url = _url,
httpMethod = _httpMethod,
params = _params,
connection = _connection,
responseText = _responseText;
//////////////////////////////////////////////////////////////////////////////////////////////////
// class public
+ (FBRequest *)getRequestWithParams:(NSMutableDictionary *) params
httpMethod:(NSString *) httpMethod
delegate:(id<FBRequestDelegate>) delegate
requestURL:(NSString *) url {
FBRequest* request = [[[FBRequest alloc] init] autorelease];
request.delegate = delegate;
request.url = url;
request.httpMethod = httpMethod;
request.params = params;
request.connection = nil;
request.responseText = nil;
return request;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// private
+ (NSString *)serializeURL:(NSString *)baseUrl
params:(NSDictionary *)params {
return [self serializeURL:baseUrl params:params httpMethod:@"GET"];
}
/**
* Generate get URL
*/
+ (NSString*)serializeURL:(NSString *)baseUrl
params:(NSDictionary *)params
httpMethod:(NSString *)httpMethod {
NSURL* parsedURL = [NSURL URLWithString:baseUrl];
NSString* queryPrefix = parsedURL.query ? @"&" : @"?";
NSMutableArray* pairs = [NSMutableArray array];
for (NSString* key in [params keyEnumerator]) {
if (([[params valueForKey:key] isKindOfClass:[UIImage class]])
||([[params valueForKey:key] isKindOfClass:[NSData class]])) {
if ([httpMethod isEqualToString:@"GET"]) {
NSLog(@"can not use GET to upload a file");
}
continue;
}
NSString* escaped_value = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL, /* allocator */
(CFStringRef)[params objectForKey:key],
NULL, /* charactersToLeaveUnescaped */
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8);
[pairs addObject:[NSString stringWithFormat:@"%@=%@", key, escaped_value]];
[escaped_value release];
}
NSString* query = [pairs componentsJoinedByString:@"&"];
return [NSString stringWithFormat:@"%@%@%@", baseUrl, queryPrefix, query];
}
/**
* Body append for POST method
*/
- (void)utfAppendBody:(NSMutableData *)body data:(NSString *)data {
[body appendData:[data dataUsingEncoding:NSUTF8StringEncoding]];
}
/**
* Generate body for POST method
*/
- (NSMutableData *)generatePostBody {
NSMutableData *body = [NSMutableData data];
NSString *endLine = [NSString stringWithFormat:@"\r\n--%@\r\n", kStringBoundary];
NSMutableDictionary *dataDictionary = [NSMutableDictionary dictionary];
[self utfAppendBody:body data:[NSString stringWithFormat:@"--%@\r\n", kStringBoundary]];
for (id key in [_params keyEnumerator]) {
if (([[_params valueForKey:key] isKindOfClass:[UIImage class]])
||([[_params valueForKey:key] isKindOfClass:[NSData class]])) {
[dataDictionary setObject:[_params valueForKey:key] forKey:key];
continue;
}
[self utfAppendBody:body
data:[NSString
stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",
key]];
[self utfAppendBody:body data:[_params valueForKey:key]];
[self utfAppendBody:body data:endLine];
}
if ([dataDictionary count] > 0) {
for (id key in dataDictionary) {
NSObject *dataParam = [dataDictionary valueForKey:key];
if ([dataParam isKindOfClass:[UIImage class]]) {
NSData* imageData = UIImagePNGRepresentation((UIImage*)dataParam);
[self utfAppendBody:body
data:[NSString stringWithFormat:
@"Content-Disposition: form-data; filename=\"%@\"\r\n", key]];
[self utfAppendBody:body
data:[NSString stringWithString:@"Content-Type: image/png\r\n\r\n"]];
[body appendData:imageData];
} else {
NSAssert([dataParam isKindOfClass:[NSData class]],
@"dataParam must be a UIImage or NSData");
[self utfAppendBody:body
data:[NSString stringWithFormat:
@"Content-Disposition: form-data; filename=\"%@\"\r\n", key]];
[self utfAppendBody:body
data:[NSString stringWithString:@"Content-Type: content/unknown\r\n\r\n"]];
[body appendData:(NSData*)dataParam];
}
[self utfAppendBody:body data:endLine];
}
}
return body;
}
/**
* Formulate the NSError
*/
- (id)formError:(NSInteger)code userInfo:(NSDictionary *) errorData {
return [NSError errorWithDomain:@"facebookErrDomain" code:code userInfo:errorData];
}
/**
* parse the response data
*/
- (id)parseJsonResponse:(NSData *)data error:(NSError **)error {
NSString* responseString = [[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding]
autorelease];
SBJSON *jsonParser = [[SBJSON new] autorelease];
if ([responseString isEqualToString:@"true"]) {
return [NSDictionary dictionaryWithObject:@"true" forKey:@"result"];
} else if ([responseString isEqualToString:@"false"]) {
if (error != nil) {
*error = [self formError:kGeneralErrorCode
userInfo:[NSDictionary
dictionaryWithObject:@"This operation can not be completed"
forKey:@"error_msg"]];
}
return nil;
}
id result = [jsonParser objectWithString:responseString];
if (![result isKindOfClass:[NSArray class]]) {
if ([result objectForKey:@"error"] != nil) {
if (error != nil) {
*error = [self formError:kGeneralErrorCode
userInfo:result];
}
return nil;
}
if ([result objectForKey:@"error_code"] != nil) {
if (error != nil) {
*error = [self formError:[[result objectForKey:@"error_code"] intValue] userInfo:result];
}
return nil;
}
if ([result objectForKey:@"error_msg"] != nil) {
if (error != nil) {
*error = [self formError:kGeneralErrorCode userInfo:result];
}
}
if ([result objectForKey:@"error_reason"] != nil) {
if (error != nil) {
*error = [self formError:kGeneralErrorCode userInfo:result];
}
}
}
return result;
}
/*
* private helper function: call the delegate function when the request
* fails with error
*/
- (void)failWithError:(NSError *)error {
if ([_delegate respondsToSelector:@selector(request:didFailWithError:)]) {
[_delegate request:self didFailWithError:error];
}
}
/*
* private helper function: handle the response data
*/
- (void)handleResponseData:(NSData *)data {
if ([_delegate respondsToSelector:
@selector(request:didLoadRawResponse:)]) {
[_delegate request:self didLoadRawResponse:data];
}
if ([_delegate respondsToSelector:@selector(request:didLoad:)] ||
[_delegate respondsToSelector:
@selector(request:didFailWithError:)]) {
NSError* error = nil;
id result = [self parseJsonResponse:data error:&error];
if (error) {
[self failWithError:error];
} else if ([_delegate respondsToSelector:
@selector(request:didLoad:)]) {
[_delegate request:self didLoad:(result == nil ? data : result)];
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// public
/**
* @return boolean - whether this request is processing
*/
- (BOOL)loading {
return !!_connection;
}
/**
* make the Facebook request
*/
- (void)connect {
if ([_delegate respondsToSelector:@selector(requestLoading:)]) {
[_delegate requestLoading:self];
}
NSString* url = [[self class] serializeURL:_url params:_params httpMethod:_httpMethod];
NSMutableURLRequest* request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:kTimeoutInterval];
[request setValue:kUserAgent forHTTPHeaderField:@"User-Agent"];
[request setHTTPMethod:self.httpMethod];
if ([self.httpMethod isEqualToString: @"POST"]) {
NSString* contentType = [NSString
stringWithFormat:@"multipart/form-data; boundary=%@", kStringBoundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[self generatePostBody]];
}
_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
/**
* Free internal structure
*/
- (void)dealloc {
[_connection cancel];
[_connection release];
[_responseText release];
[_url release];
[_httpMethod release];
[_params release];
[super dealloc];
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
_responseText = [[NSMutableData alloc] init];
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
if ([_delegate respondsToSelector:
@selector(request:didReceiveResponse:)]) {
[_delegate request:self didReceiveResponse:httpResponse];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_responseText appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[self handleResponseData:_responseText];
[_responseText release];
_responseText = nil;
[_connection release];
_connection = nil;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[self failWithError:error];
[_responseText release];
_responseText = nil;
[_connection release];
_connection = nil;
}
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/FBRequest.m
|
Objective-C
|
bsd
| 11,386
|
/*
* Copyright 2010 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@protocol FBRequestDelegate;
/**
* Do not use this interface directly, instead, use method in Facebook.h
*/
@interface FBRequest : NSObject {
id<FBRequestDelegate> _delegate;
NSString* _url;
NSString* _httpMethod;
NSMutableDictionary* _params;
NSURLConnection* _connection;
NSMutableData* _responseText;
}
@property(nonatomic,assign) id<FBRequestDelegate> delegate;
/**
* The URL which will be contacted to execute the request.
*/
@property(nonatomic,copy) NSString* url;
/**
* The API method which will be called.
*/
@property(nonatomic,copy) NSString* httpMethod;
/**
* The dictionary of parameters to pass to the method.
*
* These values in the dictionary will be converted to strings using the
* standard Objective-C object-to-string conversion facilities.
*/
@property(nonatomic,retain) NSMutableDictionary* params;
@property(nonatomic,assign) NSURLConnection* connection;
@property(nonatomic,assign) NSMutableData* responseText;
+ (NSString*)serializeURL:(NSString *)baseUrl
params:(NSDictionary *)params;
+ (NSString*)serializeURL:(NSString *)baseUrl
params:(NSDictionary *)params
httpMethod:(NSString *)httpMethod;
+ (FBRequest*)getRequestWithParams:(NSMutableDictionary *) params
httpMethod:(NSString *) httpMethod
delegate:(id<FBRequestDelegate>)delegate
requestURL:(NSString *) url;
- (BOOL) loading;
- (void) connect;
@end
////////////////////////////////////////////////////////////////////////////////
/*
*Your application should implement this delegate
*/
@protocol FBRequestDelegate <NSObject>
@optional
/**
* Called just before the request is sent to the server.
*/
- (void)requestLoading:(FBRequest *)request;
/**
* Called when the server responds and begins to send back data.
*/
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response;
/**
* Called when an error prevents the request from completing successfully.
*/
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error;
/**
* 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 *)request didLoad:(id)result;
/**
* Called when a request returns a response.
*
* The result object is the raw response from the server of type NSData
*/
- (void)request:(FBRequest *)request didLoadRawResponse:(NSData *)data;
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/FBRequest.h
|
Objective-C
|
bsd
| 3,287
|
/*
* Copyright 2010 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@protocol FBDialogDelegate;
/**
* Do not use this interface directly, instead, use dialog in Facebook.h
*
* Facebook dialog interface for start the facebook webView UIServer Dialog.
*/
@interface FBDialog : UIView <UIWebViewDelegate> {
id<FBDialogDelegate> _delegate;
NSMutableDictionary *_params;
NSString * _serverURL;
NSURL* _loadingURL;
UIWebView* _webView;
UIActivityIndicatorView* _spinner;
UIImageView* _iconView;
UILabel* _titleLabel;
UIButton* _closeButton;
UIDeviceOrientation _orientation;
BOOL _showingKeyboard;
// Ensures that UI elements behind the dialog are disabled.
UIView* _modalBackgroundView;
}
/**
* The delegate.
*/
@property(nonatomic,assign) id<FBDialogDelegate> delegate;
/**
* The parameters.
*/
@property(nonatomic, retain) NSMutableDictionary* params;
/**
* The title that is shown in the header atop the view.
*/
@property(nonatomic,copy) NSString* title;
- (NSString *) getStringFromUrl: (NSString*) url needle:(NSString *) needle;
- (id)initWithURL: (NSString *) loadingURL
params: (NSMutableDictionary *) params
delegate: (id <FBDialogDelegate>) delegate;
/**
* Displays the view with an animation.
*
* The view will be added to the top of the current key window.
*/
- (void)show;
/**
* Displays the first page of the dialog.
*
* Do not ever call this directly. It is intended to be overriden by subclasses.
*/
- (void)load;
/**
* Displays a URL in the dialog.
*/
- (void)loadURL:(NSString*)url
get:(NSDictionary*)getParams;
/**
* Hides the view and notifies delegates of success or cancellation.
*/
- (void)dismissWithSuccess:(BOOL)success animated:(BOOL)animated;
/**
* Hides the view and notifies delegates of an error.
*/
- (void)dismissWithError:(NSError*)error animated:(BOOL)animated;
/**
* Subclasses may override to perform actions just prior to showing the dialog.
*/
- (void)dialogWillAppear;
/**
* Subclasses may override to perform actions just after the dialog is hidden.
*/
- (void)dialogWillDisappear;
/**
* Subclasses should override to process data returned from the server in a 'fbconnect' url.
*
* Implementations must call dismissWithSuccess:YES at some point to hide the dialog.
*/
- (void)dialogDidSucceed:(NSURL *)url;
/**
* Subclasses should override to process data returned from the server in a 'fbconnect' url.
*
* Implementations must call dismissWithSuccess:YES at some point to hide the dialog.
*/
- (void)dialogDidCancel:(NSURL *)url;
@end
///////////////////////////////////////////////////////////////////////////////////////////////////
/*
*Your application should implement this delegate
*/
@protocol FBDialogDelegate <NSObject>
@optional
/**
* Called when the dialog succeeds and is about to be dismissed.
*/
- (void)dialogDidComplete:(FBDialog *)dialog;
/**
* Called when the dialog succeeds with a returning url.
*/
- (void)dialogCompleteWithUrl:(NSURL *)url;
/**
* Called when the dialog get canceled by the user.
*/
- (void)dialogDidNotCompleteWithUrl:(NSURL *)url;
/**
* Called when the dialog is cancelled and is about to be dismissed.
*/
- (void)dialogDidNotComplete:(FBDialog *)dialog;
/**
* Called when dialog failed to load due to an error.
*/
- (void)dialog:(FBDialog*)dialog didFailWithError:(NSError *)error;
/**
* Asks if a link touched by a user should be opened in an external browser.
*
* If a user touches a link, the default behavior is to open the link in the Safari browser,
* which will cause your app to quit. You may want to prevent this from happening, open the link
* in your own internal browser, or perhaps warn the user that they are about to leave your app.
* If so, implement this method on your delegate and return NO. If you warn the user, you
* should hold onto the URL and once you have received their acknowledgement open the URL yourself
* using [[UIApplication sharedApplication] openURL:].
*/
- (BOOL)dialog:(FBDialog*)dialog shouldOpenURLInExternalBrowser:(NSURL *)url;
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/FBDialog.h
|
Objective-C
|
bsd
| 4,678
|
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Foundation/Foundation.h>
extern NSString * SBJSONErrorDomain;
enum {
EUNSUPPORTED = 1,
EPARSENUM,
EPARSE,
EFRAGMENT,
ECTRL,
EUNICODE,
EDEPTH,
EESCAPE,
ETRAILCOMMA,
ETRAILGARBAGE,
EEOF,
EINPUT
};
/**
@brief Common base class for parsing & writing.
This class contains the common error-handling code and option between the parser/writer.
*/
@interface SBJsonBase : NSObject {
NSMutableArray *errorTrace;
@protected
NSUInteger depth, maxDepth;
}
/**
@brief The maximum recursing depth.
Defaults to 512. If the input is nested deeper than this the input will be deemed to be
malicious and the parser returns nil, signalling an error. ("Nested too deep".) You can
turn off this security feature by setting the maxDepth value to 0.
*/
@property NSUInteger maxDepth;
/**
@brief Return an error trace, or nil if there was no errors.
Note that this method returns the trace of the last method that failed.
You need to check the return value of the call you're making to figure out
if the call actually failed, before you know call this method.
*/
@property(copy,readonly) NSArray* errorTrace;
/// @internal for use in subclasses to add errors to the stack trace
- (void)addErrorWithCode:(NSUInteger)code description:(NSString*)str;
/// @internal for use in subclasess to clear the error before a new parsing attempt
- (void)clearErrorTrace;
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/JSON/SBJsonBase.h
|
Objective-C
|
bsd
| 2,946
|
/*
Copyright (C) 2007-2009 Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Foundation/Foundation.h>
#import "SBJsonParser.h"
#import "SBJsonWriter.h"
/**
@brief Facade for SBJsonWriter/SBJsonParser.
Requests are forwarded to instances of SBJsonWriter and SBJsonParser.
*/
@interface SBJSON : SBJsonBase <SBJsonParser, SBJsonWriter> {
@private
SBJsonParser *jsonParser;
SBJsonWriter *jsonWriter;
}
/// Return the fragment represented by the given string
- (id)fragmentWithString:(NSString*)jsonrep
error:(NSError**)error;
/// Return the object represented by the given string
- (id)objectWithString:(NSString*)jsonrep
error:(NSError**)error;
/// Parse the string and return the represented object (or scalar)
- (id)objectWithString:(id)value
allowScalar:(BOOL)x
error:(NSError**)error;
/// Return JSON representation of an array or dictionary
- (NSString*)stringWithObject:(id)value
error:(NSError**)error;
/// Return JSON representation of any legal JSON value
- (NSString*)stringWithFragment:(id)value
error:(NSError**)error;
/// Return JSON representation (or fragment) for the given object
- (NSString*)stringWithObject:(id)value
allowScalar:(BOOL)x
error:(NSError**)error;
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/JSON/SBJSON.h
|
Objective-C
|
bsd
| 2,797
|
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Foundation/Foundation.h>
#import "SBJsonBase.h"
/**
@brief Options for the writer class.
This exists so the SBJSON facade can implement the options in the writer without having to re-declare them.
*/
@protocol SBJsonWriter
/**
@brief Whether we are generating human-readable (multiline) JSON.
Set whether or not to generate human-readable JSON. The default is NO, which produces
JSON without any whitespace. (Except inside strings.) If set to YES, generates human-readable
JSON with linebreaks after each array value and dictionary key/value pair, indented two
spaces per nesting level.
*/
@property BOOL humanReadable;
/**
@brief Whether or not to sort the dictionary keys in the output.
If this is set to YES, the dictionary keys in the JSON output will be in sorted order.
(This is useful if you need to compare two structures, for example.) The default is NO.
*/
@property BOOL sortKeys;
/**
@brief Return JSON representation (or fragment) for the given object.
Returns a string containing JSON representation of the passed in value, or nil on error.
If nil is returned and @p error is not NULL, @p *error can be interrogated to find the cause of the error.
@param value any instance that can be represented as a JSON fragment
*/
- (NSString*)stringWithObject:(id)value;
@end
/**
@brief The JSON writer class.
Objective-C types are mapped to JSON types in the following way:
@li NSNull -> Null
@li NSString -> String
@li NSArray -> Array
@li NSDictionary -> Object
@li NSNumber (-initWithBool:) -> Boolean
@li NSNumber -> Number
In JSON the keys of an object must be strings. NSDictionary keys need
not be, but attempting to convert an NSDictionary with non-string keys
into JSON will throw an exception.
NSNumber instances created with the +initWithBool: method are
converted into the JSON boolean "true" and "false" values, and vice
versa. Any other NSNumber instances are converted to a JSON number the
way you would expect.
*/
@interface SBJsonWriter : SBJsonBase <SBJsonWriter> {
@private
BOOL sortKeys, humanReadable;
}
@end
// don't use - exists for backwards compatibility. Will be removed in 2.3.
@interface SBJsonWriter (Private)
- (NSString*)stringWithFragment:(id)value;
@end
/**
@brief Allows generation of JSON for otherwise unsupported classes.
If you have a custom class that you want to create a JSON representation for you can implement
this method in your class. It should return a representation of your object defined
in terms of objects that can be translated into JSON. For example, a Person
object might implement it like this:
@code
- (id)jsonProxyObject {
return [NSDictionary dictionaryWithObjectsAndKeys:
name, @"name",
phone, @"phone",
email, @"email",
nil];
}
@endcode
*/
@interface NSObject (SBProxyForJson)
- (id)proxyForJson;
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/JSON/SBJsonWriter.h
|
Objective-C
|
bsd
| 4,416
|
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "SBJsonParser.h"
@interface SBJsonParser ()
- (BOOL)scanValue:(NSObject **)o;
- (BOOL)scanRestOfArray:(NSMutableArray **)o;
- (BOOL)scanRestOfDictionary:(NSMutableDictionary **)o;
- (BOOL)scanRestOfNull:(NSNull **)o;
- (BOOL)scanRestOfFalse:(NSNumber **)o;
- (BOOL)scanRestOfTrue:(NSNumber **)o;
- (BOOL)scanRestOfString:(NSMutableString **)o;
// Cannot manage without looking at the first digit
- (BOOL)scanNumber:(NSNumber **)o;
- (BOOL)scanHexQuad:(unichar *)x;
- (BOOL)scanUnicodeChar:(unichar *)x;
- (BOOL)scanIsAtEnd;
@end
#define skipWhitespace(c) while (isspace(*c)) c++
#define skipDigits(c) while (isdigit(*c)) c++
@implementation SBJsonParser
static char ctrl[0x22];
+ (void)initialize {
ctrl[0] = '\"';
ctrl[1] = '\\';
for (int i = 1; i < 0x20; i++)
ctrl[i+1] = i;
ctrl[0x21] = 0;
}
/**
@deprecated This exists in order to provide fragment support in older APIs in one more version.
It should be removed in the next major version.
*/
- (id)fragmentWithString:(id)repr {
[self clearErrorTrace];
if (!repr) {
[self addErrorWithCode:EINPUT description:@"Input was 'nil'"];
return nil;
}
depth = 0;
c = [repr UTF8String];
id o;
if (![self scanValue:&o]) {
return nil;
}
// We found some valid JSON. But did it also contain something else?
if (![self scanIsAtEnd]) {
[self addErrorWithCode:ETRAILGARBAGE description:@"Garbage after JSON"];
return nil;
}
NSAssert1(o, @"Should have a valid object from %@", repr);
return o;
}
- (id)objectWithString:(NSString *)repr {
id o = [self fragmentWithString:repr];
if (!o)
return nil;
// Check that the object we've found is a valid JSON container.
if (![o isKindOfClass:[NSDictionary class]] && ![o isKindOfClass:[NSArray class]]) {
[self addErrorWithCode:EFRAGMENT description:@"Valid fragment, but not JSON"];
return nil;
}
return o;
}
/*
In contrast to the public methods, it is an error to omit the error parameter here.
*/
- (BOOL)scanValue:(NSObject **)o
{
skipWhitespace(c);
switch (*c++) {
case '{':
return [self scanRestOfDictionary:(NSMutableDictionary **)o];
break;
case '[':
return [self scanRestOfArray:(NSMutableArray **)o];
break;
case '"':
return [self scanRestOfString:(NSMutableString **)o];
break;
case 'f':
return [self scanRestOfFalse:(NSNumber **)o];
break;
case 't':
return [self scanRestOfTrue:(NSNumber **)o];
break;
case 'n':
return [self scanRestOfNull:(NSNull **)o];
break;
case '-':
case '0'...'9':
c--; // cannot verify number correctly without the first character
return [self scanNumber:(NSNumber **)o];
break;
case '+':
[self addErrorWithCode:EPARSENUM description: @"Leading + disallowed in number"];
return NO;
break;
case 0x0:
[self addErrorWithCode:EEOF description:@"Unexpected end of string"];
return NO;
break;
default:
[self addErrorWithCode:EPARSE description: @"Unrecognised leading character"];
return NO;
break;
}
NSAssert(0, @"Should never get here");
return NO;
}
- (BOOL)scanRestOfTrue:(NSNumber **)o
{
if (!strncmp(c, "rue", 3)) {
c += 3;
*o = [NSNumber numberWithBool:YES];
return YES;
}
[self addErrorWithCode:EPARSE description:@"Expected 'true'"];
return NO;
}
- (BOOL)scanRestOfFalse:(NSNumber **)o
{
if (!strncmp(c, "alse", 4)) {
c += 4;
*o = [NSNumber numberWithBool:NO];
return YES;
}
[self addErrorWithCode:EPARSE description: @"Expected 'false'"];
return NO;
}
- (BOOL)scanRestOfNull:(NSNull **)o {
if (!strncmp(c, "ull", 3)) {
c += 3;
*o = [NSNull null];
return YES;
}
[self addErrorWithCode:EPARSE description: @"Expected 'null'"];
return NO;
}
- (BOOL)scanRestOfArray:(NSMutableArray **)o {
if (maxDepth && ++depth > maxDepth) {
[self addErrorWithCode:EDEPTH description: @"Nested too deep"];
return NO;
}
*o = [NSMutableArray arrayWithCapacity:8];
for (; *c ;) {
id v;
skipWhitespace(c);
if (*c == ']' && c++) {
depth--;
return YES;
}
if (![self scanValue:&v]) {
[self addErrorWithCode:EPARSE description:@"Expected value while parsing array"];
return NO;
}
[*o addObject:v];
skipWhitespace(c);
if (*c == ',' && c++) {
skipWhitespace(c);
if (*c == ']') {
[self addErrorWithCode:ETRAILCOMMA description: @"Trailing comma disallowed in array"];
return NO;
}
}
}
[self addErrorWithCode:EEOF description: @"End of input while parsing array"];
return NO;
}
- (BOOL)scanRestOfDictionary:(NSMutableDictionary **)o
{
if (maxDepth && ++depth > maxDepth) {
[self addErrorWithCode:EDEPTH description: @"Nested too deep"];
return NO;
}
*o = [NSMutableDictionary dictionaryWithCapacity:7];
for (; *c ;) {
id k, v;
skipWhitespace(c);
if (*c == '}' && c++) {
depth--;
return YES;
}
if (!(*c == '\"' && c++ && [self scanRestOfString:&k])) {
[self addErrorWithCode:EPARSE description: @"Object key string expected"];
return NO;
}
skipWhitespace(c);
if (*c != ':') {
[self addErrorWithCode:EPARSE description: @"Expected ':' separating key and value"];
return NO;
}
c++;
if (![self scanValue:&v]) {
NSString *string = [NSString stringWithFormat:@"Object value expected for key: %@", k];
[self addErrorWithCode:EPARSE description: string];
return NO;
}
[*o setObject:v forKey:k];
skipWhitespace(c);
if (*c == ',' && c++) {
skipWhitespace(c);
if (*c == '}') {
[self addErrorWithCode:ETRAILCOMMA description: @"Trailing comma disallowed in object"];
return NO;
}
}
}
[self addErrorWithCode:EEOF description: @"End of input while parsing object"];
return NO;
}
- (BOOL)scanRestOfString:(NSMutableString **)o
{
*o = [NSMutableString stringWithCapacity:16];
do {
// First see if there's a portion we can grab in one go.
// Doing this caused a massive speedup on the long string.
size_t len = strcspn(c, ctrl);
if (len) {
// check for
id t = [[NSString alloc] initWithBytesNoCopy:(char*)c
length:len
encoding:NSUTF8StringEncoding
freeWhenDone:NO];
if (t) {
[*o appendString:t];
[t release];
c += len;
}
}
if (*c == '"') {
c++;
return YES;
} else if (*c == '\\') {
unichar uc = *++c;
switch (uc) {
case '\\':
case '/':
case '"':
break;
case 'b': uc = '\b'; break;
case 'n': uc = '\n'; break;
case 'r': uc = '\r'; break;
case 't': uc = '\t'; break;
case 'f': uc = '\f'; break;
case 'u':
c++;
if (![self scanUnicodeChar:&uc]) {
[self addErrorWithCode:EUNICODE description: @"Broken unicode character"];
return NO;
}
c--; // hack.
break;
default:
[self addErrorWithCode:EESCAPE description: [NSString stringWithFormat:@"Illegal escape sequence '0x%x'", uc]];
return NO;
break;
}
CFStringAppendCharacters((CFMutableStringRef)*o, &uc, 1);
c++;
} else if (*c < 0x20) {
[self addErrorWithCode:ECTRL description: [NSString stringWithFormat:@"Unescaped control character '0x%x'", *c]];
return NO;
} else {
NSLog(@"should not be able to get here");
}
} while (*c);
[self addErrorWithCode:EEOF description:@"Unexpected EOF while parsing string"];
return NO;
}
- (BOOL)scanUnicodeChar:(unichar *)x
{
unichar hi, lo;
if (![self scanHexQuad:&hi]) {
[self addErrorWithCode:EUNICODE description: @"Missing hex quad"];
return NO;
}
if (hi >= 0xd800) { // high surrogate char?
if (hi < 0xdc00) { // yes - expect a low char
if (!(*c == '\\' && ++c && *c == 'u' && ++c && [self scanHexQuad:&lo])) {
[self addErrorWithCode:EUNICODE description: @"Missing low character in surrogate pair"];
return NO;
}
if (lo < 0xdc00 || lo >= 0xdfff) {
[self addErrorWithCode:EUNICODE description:@"Invalid low surrogate char"];
return NO;
}
hi = (hi - 0xd800) * 0x400 + (lo - 0xdc00) + 0x10000;
} else if (hi < 0xe000) {
[self addErrorWithCode:EUNICODE description:@"Invalid high character in surrogate pair"];
return NO;
}
}
*x = hi;
return YES;
}
- (BOOL)scanHexQuad:(unichar *)x
{
*x = 0;
for (int i = 0; i < 4; i++) {
unichar uc = *c;
c++;
int d = (uc >= '0' && uc <= '9')
? uc - '0' : (uc >= 'a' && uc <= 'f')
? (uc - 'a' + 10) : (uc >= 'A' && uc <= 'F')
? (uc - 'A' + 10) : -1;
if (d == -1) {
[self addErrorWithCode:EUNICODE description:@"Missing hex digit in quad"];
return NO;
}
*x *= 16;
*x += d;
}
return YES;
}
- (BOOL)scanNumber:(NSNumber **)o
{
const char *ns = c;
// The logic to test for validity of the number formatting is relicensed
// from JSON::XS with permission from its author Marc Lehmann.
// (Available at the CPAN: http://search.cpan.org/dist/JSON-XS/ .)
if ('-' == *c)
c++;
if ('0' == *c && c++) {
if (isdigit(*c)) {
[self addErrorWithCode:EPARSENUM description: @"Leading 0 disallowed in number"];
return NO;
}
} else if (!isdigit(*c) && c != ns) {
[self addErrorWithCode:EPARSENUM description: @"No digits after initial minus"];
return NO;
} else {
skipDigits(c);
}
// Fractional part
if ('.' == *c && c++) {
if (!isdigit(*c)) {
[self addErrorWithCode:EPARSENUM description: @"No digits after decimal point"];
return NO;
}
skipDigits(c);
}
// Exponential part
if ('e' == *c || 'E' == *c) {
c++;
if ('-' == *c || '+' == *c)
c++;
if (!isdigit(*c)) {
[self addErrorWithCode:EPARSENUM description: @"No digits after exponent"];
return NO;
}
skipDigits(c);
}
id str = [[NSString alloc] initWithBytesNoCopy:(char*)ns
length:c - ns
encoding:NSUTF8StringEncoding
freeWhenDone:NO];
[str autorelease];
if (str && (*o = [NSDecimalNumber decimalNumberWithString:str]))
return YES;
[self addErrorWithCode:EPARSENUM description: @"Failed creating decimal instance"];
return NO;
}
- (BOOL)scanIsAtEnd
{
skipWhitespace(c);
return !*c;
}
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/JSON/SBJsonParser.m
|
Objective-C
|
bsd
| 14,032
|
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "NSObject+SBJSON.h"
#import "SBJsonWriter.h"
@implementation NSObject (NSObject_SBJSON)
- (NSString *)JSONFragment {
SBJsonWriter *jsonWriter = [SBJsonWriter new];
NSString *json = [jsonWriter stringWithFragment:self];
if (!json)
NSLog(@"-JSONFragment failed. Error trace is: %@", [jsonWriter errorTrace]);
[jsonWriter release];
return json;
}
- (NSString *)JSONRepresentation {
SBJsonWriter *jsonWriter = [SBJsonWriter new];
NSString *json = [jsonWriter stringWithObject:self];
if (!json)
NSLog(@"-JSONRepresentation failed. Error trace is: %@", [jsonWriter errorTrace]);
[jsonWriter release];
return json;
}
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/JSON/NSObject+SBJSON.m
|
Objective-C
|
bsd
| 2,206
|
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
@mainpage A strict JSON parser and generator for Objective-C
JSON (JavaScript Object Notation) is a lightweight data-interchange
format. This framework provides two apis for parsing and generating
JSON. One standard object-based and a higher level api consisting of
categories added to existing Objective-C classes.
Learn more on the http://code.google.com/p/json-framework project site.
This framework does its best to be as strict as possible, both in what it
accepts and what it generates. For example, it does not support trailing commas
in arrays or objects. Nor does it support embedded comments, or
anything else not in the JSON specification. This is considered a feature.
*/
#import "SBJSON.h"
#import "NSObject+SBJSON.h"
#import "NSString+SBJSON.h"
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/JSON/JSON.h
|
Objective-C
|
bsd
| 2,297
|
/*
Copyright (C) 2007-2009 Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "SBJSON.h"
@implementation SBJSON
- (id)init {
self = [super init];
if (self) {
jsonWriter = [SBJsonWriter new];
jsonParser = [SBJsonParser new];
[self setMaxDepth:512];
}
return self;
}
- (void)dealloc {
[jsonWriter release];
[jsonParser release];
[super dealloc];
}
#pragma mark Writer
- (NSString *)stringWithObject:(id)obj {
NSString *repr = [jsonWriter stringWithObject:obj];
if (repr)
return repr;
[errorTrace release];
errorTrace = [[jsonWriter errorTrace] mutableCopy];
return nil;
}
/**
Returns a string containing JSON representation of the passed in value, or nil on error.
If nil is returned and @p error is not NULL, @p *error can be interrogated to find the cause of the error.
@param value any instance that can be represented as a JSON fragment
@param allowScalar wether to return json fragments for scalar objects
@param error used to return an error by reference (pass NULL if this is not desired)
@deprecated Given we bill ourselves as a "strict" JSON library, this method should be removed.
*/
- (NSString*)stringWithObject:(id)value allowScalar:(BOOL)allowScalar error:(NSError**)error {
NSString *json = allowScalar ? [jsonWriter stringWithFragment:value] : [jsonWriter stringWithObject:value];
if (json)
return json;
[errorTrace release];
errorTrace = [[jsonWriter errorTrace] mutableCopy];
if (error)
*error = [errorTrace lastObject];
return nil;
}
/**
Returns a string containing JSON representation of the passed in value, or nil on error.
If nil is returned and @p error is not NULL, @p error can be interrogated to find the cause of the error.
@param value any instance that can be represented as a JSON fragment
@param error used to return an error by reference (pass NULL if this is not desired)
@deprecated Given we bill ourselves as a "strict" JSON library, this method should be removed.
*/
- (NSString*)stringWithFragment:(id)value error:(NSError**)error {
return [self stringWithObject:value
allowScalar:YES
error:error];
}
/**
Returns a string containing JSON representation of the passed in value, or nil on error.
If nil is returned and @p error is not NULL, @p error can be interrogated to find the cause of the error.
@param value a NSDictionary or NSArray instance
@param error used to return an error by reference (pass NULL if this is not desired)
*/
- (NSString*)stringWithObject:(id)value error:(NSError**)error {
return [self stringWithObject:value
allowScalar:NO
error:error];
}
#pragma mark Parsing
- (id)objectWithString:(NSString *)repr {
id obj = [jsonParser objectWithString:repr];
if (obj)
return obj;
[errorTrace release];
errorTrace = [[jsonParser errorTrace] mutableCopy];
return nil;
}
/**
Returns the object represented by the passed-in string or nil on error. The returned object can be
a string, number, boolean, null, array or dictionary.
@param value the json string to parse
@param allowScalar whether to return objects for JSON fragments
@param error used to return an error by reference (pass NULL if this is not desired)
@deprecated Given we bill ourselves as a "strict" JSON library, this method should be removed.
*/
- (id)objectWithString:(id)value allowScalar:(BOOL)allowScalar error:(NSError**)error {
id obj = allowScalar ? [jsonParser fragmentWithString:value] : [jsonParser objectWithString:value];
if (obj)
return obj;
[errorTrace release];
errorTrace = [[jsonParser errorTrace] mutableCopy];
if (error)
*error = [errorTrace lastObject];
return nil;
}
/**
Returns the object represented by the passed-in string or nil on error. The returned object can be
a string, number, boolean, null, array or dictionary.
@param repr the json string to parse
@param error used to return an error by reference (pass NULL if this is not desired)
@deprecated Given we bill ourselves as a "strict" JSON library, this method should be removed.
*/
- (id)fragmentWithString:(NSString*)repr error:(NSError**)error {
return [self objectWithString:repr
allowScalar:YES
error:error];
}
/**
Returns the object represented by the passed-in string or nil on error. The returned object
will be either a dictionary or an array.
@param repr the json string to parse
@param error used to return an error by reference (pass NULL if this is not desired)
*/
- (id)objectWithString:(NSString*)repr error:(NSError**)error {
return [self objectWithString:repr
allowScalar:NO
error:error];
}
#pragma mark Properties - parsing
- (NSUInteger)maxDepth {
return jsonParser.maxDepth;
}
- (void)setMaxDepth:(NSUInteger)d {
jsonWriter.maxDepth = jsonParser.maxDepth = d;
}
#pragma mark Properties - writing
- (BOOL)humanReadable {
return jsonWriter.humanReadable;
}
- (void)setHumanReadable:(BOOL)x {
jsonWriter.humanReadable = x;
}
- (BOOL)sortKeys {
return jsonWriter.sortKeys;
}
- (void)setSortKeys:(BOOL)x {
jsonWriter.sortKeys = x;
}
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/JSON/SBJSON.m
|
Objective-C
|
bsd
| 6,844
|
/*
Copyright (C) 2007-2009 Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "NSString+SBJSON.h"
#import "SBJsonParser.h"
@implementation NSString (NSString_SBJSON)
- (id)JSONFragmentValue
{
SBJsonParser *jsonParser = [SBJsonParser new];
id repr = [jsonParser fragmentWithString:self];
if (!repr)
NSLog(@"-JSONFragmentValue failed. Error trace is: %@", [jsonParser errorTrace]);
[jsonParser release];
return repr;
}
- (id)JSONValue
{
SBJsonParser *jsonParser = [SBJsonParser new];
id repr = [jsonParser objectWithString:self];
if (!repr)
NSLog(@"-JSONValue failed. Error trace is: %@", [jsonParser errorTrace]);
[jsonParser release];
return repr;
}
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/JSON/NSString+SBJSON.m
|
Objective-C
|
bsd
| 2,173
|
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Foundation/Foundation.h>
#import "SBJsonBase.h"
/**
@brief Options for the parser class.
This exists so the SBJSON facade can implement the options in the parser without having to re-declare them.
*/
@protocol SBJsonParser
/**
@brief Return the object represented by the given string.
Returns the object represented by the passed-in string or nil on error. The returned object can be
a string, number, boolean, null, array or dictionary.
@param repr the json string to parse
*/
- (id)objectWithString:(NSString *)repr;
@end
/**
@brief The JSON parser class.
JSON is mapped to Objective-C types in the following way:
@li Null -> NSNull
@li String -> NSMutableString
@li Array -> NSMutableArray
@li Object -> NSMutableDictionary
@li Boolean -> NSNumber (initialised with -initWithBool:)
@li Number -> NSDecimalNumber
Since Objective-C doesn't have a dedicated class for boolean values, these turns into NSNumber
instances. These are initialised with the -initWithBool: method, and
round-trip back to JSON properly. (They won't silently suddenly become 0 or 1; they'll be
represented as 'true' and 'false' again.)
JSON numbers turn into NSDecimalNumber instances,
as we can thus avoid any loss of precision. (JSON allows ridiculously large numbers.)
*/
@interface SBJsonParser : SBJsonBase <SBJsonParser> {
@private
const char *c;
}
@end
// don't use - exists for backwards compatibility with 2.1.x only. Will be removed in 2.3.
@interface SBJsonParser (Private)
- (id)fragmentWithString:(id)repr;
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/JSON/SBJsonParser.h
|
Objective-C
|
bsd
| 3,083
|
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "SBJsonWriter.h"
@interface SBJsonWriter ()
- (BOOL)appendValue:(id)fragment into:(NSMutableString*)json;
- (BOOL)appendArray:(NSArray*)fragment into:(NSMutableString*)json;
- (BOOL)appendDictionary:(NSDictionary*)fragment into:(NSMutableString*)json;
- (BOOL)appendString:(NSString*)fragment into:(NSMutableString*)json;
- (NSString*)indent;
@end
@implementation SBJsonWriter
static NSMutableCharacterSet *kEscapeChars;
+ (void)initialize {
kEscapeChars = [[NSMutableCharacterSet characterSetWithRange: NSMakeRange(0,32)] retain];
[kEscapeChars addCharactersInString: @"\"\\"];
}
@synthesize sortKeys;
@synthesize humanReadable;
/**
@deprecated This exists in order to provide fragment support in older APIs in one more version.
It should be removed in the next major version.
*/
- (NSString*)stringWithFragment:(id)value {
[self clearErrorTrace];
depth = 0;
NSMutableString *json = [NSMutableString stringWithCapacity:128];
if ([self appendValue:value into:json])
return json;
return nil;
}
- (NSString*)stringWithObject:(id)value {
if ([value isKindOfClass:[NSDictionary class]] || [value isKindOfClass:[NSArray class]]) {
return [self stringWithFragment:value];
}
if ([value respondsToSelector:@selector(proxyForJson)]) {
NSString *tmp = [self stringWithObject:[value proxyForJson]];
if (tmp)
return tmp;
}
[self clearErrorTrace];
[self addErrorWithCode:EFRAGMENT description:@"Not valid type for JSON"];
return nil;
}
- (NSString*)indent {
return [@"\n" stringByPaddingToLength:1 + 2 * depth withString:@" " startingAtIndex:0];
}
- (BOOL)appendValue:(id)fragment into:(NSMutableString*)json {
if ([fragment isKindOfClass:[NSDictionary class]]) {
if (![self appendDictionary:fragment into:json])
return NO;
} else if ([fragment isKindOfClass:[NSArray class]]) {
if (![self appendArray:fragment into:json])
return NO;
} else if ([fragment isKindOfClass:[NSString class]]) {
if (![self appendString:fragment into:json])
return NO;
} else if ([fragment isKindOfClass:[NSNumber class]]) {
if ('c' == *[fragment objCType])
[json appendString:[fragment boolValue] ? @"true" : @"false"];
else
[json appendString:[fragment stringValue]];
} else if ([fragment isKindOfClass:[NSNull class]]) {
[json appendString:@"null"];
} else if ([fragment respondsToSelector:@selector(proxyForJson)]) {
[self appendValue:[fragment proxyForJson] into:json];
} else {
[self addErrorWithCode:EUNSUPPORTED description:[NSString stringWithFormat:@"JSON serialisation not supported for %@", [fragment class]]];
return NO;
}
return YES;
}
- (BOOL)appendArray:(NSArray*)fragment into:(NSMutableString*)json {
if (maxDepth && ++depth > maxDepth) {
[self addErrorWithCode:EDEPTH description: @"Nested too deep"];
return NO;
}
[json appendString:@"["];
BOOL addComma = NO;
for (id value in fragment) {
if (addComma)
[json appendString:@","];
else
addComma = YES;
if ([self humanReadable])
[json appendString:[self indent]];
if (![self appendValue:value into:json]) {
return NO;
}
}
depth--;
if ([self humanReadable] && [fragment count])
[json appendString:[self indent]];
[json appendString:@"]"];
return YES;
}
- (BOOL)appendDictionary:(NSDictionary*)fragment into:(NSMutableString*)json {
if (maxDepth && ++depth > maxDepth) {
[self addErrorWithCode:EDEPTH description: @"Nested too deep"];
return NO;
}
[json appendString:@"{"];
NSString *colon = [self humanReadable] ? @" : " : @":";
BOOL addComma = NO;
NSArray *keys = [fragment allKeys];
if (self.sortKeys)
keys = [keys sortedArrayUsingSelector:@selector(compare:)];
for (id value in keys) {
if (addComma)
[json appendString:@","];
else
addComma = YES;
if ([self humanReadable])
[json appendString:[self indent]];
if (![value isKindOfClass:[NSString class]]) {
[self addErrorWithCode:EUNSUPPORTED description: @"JSON object key must be string"];
return NO;
}
if (![self appendString:value into:json])
return NO;
[json appendString:colon];
if (![self appendValue:[fragment objectForKey:value] into:json]) {
[self addErrorWithCode:EUNSUPPORTED description:[NSString stringWithFormat:@"Unsupported value for key %@ in object", value]];
return NO;
}
}
depth--;
if ([self humanReadable] && [fragment count])
[json appendString:[self indent]];
[json appendString:@"}"];
return YES;
}
- (BOOL)appendString:(NSString*)fragment into:(NSMutableString*)json {
[json appendString:@"\""];
NSRange esc = [fragment rangeOfCharacterFromSet:kEscapeChars];
if ( !esc.length ) {
// No special chars -- can just add the raw string:
[json appendString:fragment];
} else {
NSUInteger length = [fragment length];
for (NSUInteger i = 0; i < length; i++) {
unichar uc = [fragment characterAtIndex:i];
switch (uc) {
case '"': [json appendString:@"\\\""]; break;
case '\\': [json appendString:@"\\\\"]; break;
case '\t': [json appendString:@"\\t"]; break;
case '\n': [json appendString:@"\\n"]; break;
case '\r': [json appendString:@"\\r"]; break;
case '\b': [json appendString:@"\\b"]; break;
case '\f': [json appendString:@"\\f"]; break;
default:
if (uc < 0x20) {
[json appendFormat:@"\\u%04x", uc];
} else {
CFStringAppendCharacters((CFMutableStringRef)json, &uc, 1);
}
break;
}
}
}
[json appendString:@"\""];
return YES;
}
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/JSON/SBJsonWriter.m
|
Objective-C
|
bsd
| 7,974
|
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "SBJsonBase.h"
NSString * SBJSONErrorDomain = @"org.brautaset.JSON.ErrorDomain";
@implementation SBJsonBase
@synthesize errorTrace;
@synthesize maxDepth;
- (id)init {
self = [super init];
if (self)
self.maxDepth = 512;
return self;
}
- (void)dealloc {
[errorTrace release];
[super dealloc];
}
- (void)addErrorWithCode:(NSUInteger)code description:(NSString*)str {
NSDictionary *userInfo;
if (!errorTrace) {
errorTrace = [NSMutableArray new];
userInfo = [NSDictionary dictionaryWithObject:str forKey:NSLocalizedDescriptionKey];
} else {
userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
str, NSLocalizedDescriptionKey,
[errorTrace lastObject], NSUnderlyingErrorKey,
nil];
}
NSError *error = [NSError errorWithDomain:SBJSONErrorDomain code:code userInfo:userInfo];
[self willChangeValueForKey:@"errorTrace"];
[errorTrace addObject:error];
[self didChangeValueForKey:@"errorTrace"];
}
- (void)clearErrorTrace {
[self willChangeValueForKey:@"errorTrace"];
[errorTrace release];
errorTrace = nil;
[self didChangeValueForKey:@"errorTrace"];
}
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/JSON/SBJsonBase.m
|
Objective-C
|
bsd
| 2,753
|
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Foundation/Foundation.h>
/**
@brief Adds JSON generation to Foundation classes
This is a category on NSObject that adds methods for returning JSON representations
of standard objects to the objects themselves. This means you can call the
-JSONRepresentation method on an NSArray object and it'll do what you want.
*/
@interface NSObject (NSObject_SBJSON)
/**
@brief Returns a string containing the receiver encoded as a JSON fragment.
This method is added as a category on NSObject but is only actually
supported for the following objects:
@li NSDictionary
@li NSArray
@li NSString
@li NSNumber (also used for booleans)
@li NSNull
@deprecated Given we bill ourselves as a "strict" JSON library, this method should be removed.
*/
- (NSString *)JSONFragment;
/**
@brief Returns a string containing the receiver encoded in JSON.
This method is added as a category on NSObject but is only actually
supported for the following objects:
@li NSDictionary
@li NSArray
*/
- (NSString *)JSONRepresentation;
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/JSON/NSObject+SBJSON.h
|
Objective-C
|
bsd
| 2,561
|
/*
Copyright (C) 2009 Stig Brautaset. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Foundation/Foundation.h>
/**
@brief Adds JSON parsing methods to NSString
This is a category on NSString that adds methods for parsing the target string.
*/
@interface NSString (NSString_SBJSON)
/**
@brief Returns the object represented in the receiver, or nil on error.
Returns a a scalar object represented by the string's JSON fragment representation.
@deprecated Given we bill ourselves as a "strict" JSON library, this method should be removed.
*/
- (id)JSONFragmentValue;
/**
@brief Returns the NSDictionary or NSArray represented by the current string's JSON representation.
Returns the dictionary or array represented in the receiver, or nil on error.
Returns the NSDictionary or NSArray represented by the current string's JSON representation.
*/
- (id)JSONValue;
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/JSON/NSString+SBJSON.h
|
Objective-C
|
bsd
| 2,326
|
/*
* Copyright 2010 Facebook
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import "Facebook.h"
#import "FBLoginDialog.h"
#import "FBRequest.h"
static NSString* kDialogBaseURL = @"https://m.facebook.com/dialog/";
static NSString* kGraphBaseURL = @"https://graph.facebook.com/";
static NSString* kRestserverBaseURL = @"https://api.facebook.com/method/";
static NSString* kFBAppAuthURL = @"fbauth://authorize";
static NSString* kRedirectURL = @"fbconnect://success";
static NSString* kLogin = @"oauth";
static NSString* kSDK = @"ios";
static NSString* kSDKVersion = @"2";
///////////////////////////////////////////////////////////////////////////////////////////////////
@implementation Facebook
@synthesize accessToken = _accessToken,
expirationDate = _expirationDate,
sessionDelegate = _sessionDelegate;
///////////////////////////////////////////////////////////////////////////////////////////////////
// private
/**
* Initialize the Facebook object with application ID.
*/
- (id)initWithAppId:(NSString *)app_id {
self = [super init];
if (self) {
[_appId release];
_appId = [app_id copy];
}
return self;
}
/**
* Override NSObject : free the space
*/
- (void)dealloc {
[_accessToken release];
[_expirationDate release];
[_request release];
[_loginDialog release];
[_fbDialog release];
[_appId release];
[_permissions release];
[super dealloc];
}
/**
* A private helper function for sending HTTP requests.
*
* @param url
* url to send http request
* @param params
* parameters to append to the url
* @param httpMethod
* http method @"GET" or @"POST"
* @param delegate
* Callback interface for notifying the calling application when
* the request has received response
*/
- (FBRequest*)openUrl:(NSString *)url
params:(NSMutableDictionary *)params
httpMethod:(NSString *)httpMethod
delegate:(id<FBRequestDelegate>)delegate {
[params setValue:@"json" forKey:@"format"];
[params setValue:kSDK forKey:@"sdk"];
[params setValue:kSDKVersion forKey:@"sdk_version"];
if ([self isSessionValid]) {
[params setValue:self.accessToken forKey:@"access_token"];
}
[_request release];
_request = [[FBRequest getRequestWithParams:params
httpMethod:httpMethod
delegate:delegate
requestURL:url] retain];
[_request connect];
return _request;
}
/**
* A private function for opening the authorization dialog.
*/
- (void)authorizeWithFBAppAuth:(BOOL)tryFBAppAuth
safariAuth:(BOOL)trySafariAuth {
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
_appId, @"client_id",
@"user_agent", @"type",
kRedirectURL, @"redirect_uri",
@"touch", @"display",
kSDKVersion, @"sdk",
nil];
NSString *loginDialogURL = [kDialogBaseURL stringByAppendingString:kLogin];
if (_permissions != nil) {
NSString* scope = [_permissions componentsJoinedByString:@","];
[params setValue:scope forKey:@"scope"];
}
// If the device is running a version of iOS that supports multitasking,
// try to obtain the access token from the Facebook app installed
// on the device.
// If the Facebook app isn't installed or it doesn't support
// the fbauth:// URL scheme, fall back on Safari for obtaining the access token.
// This minimizes the chance that the user will have to enter his or
// her credentials in order to authorize the application.
BOOL didOpenOtherApp = NO;
UIDevice *device = [UIDevice currentDevice];
if ([device respondsToSelector:@selector(isMultitaskingSupported)] && [device isMultitaskingSupported]) {
if (tryFBAppAuth) {
NSString *fbAppUrl = [FBRequest serializeURL:kFBAppAuthURL params:params];
didOpenOtherApp = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:fbAppUrl]];
}
if (trySafariAuth && !didOpenOtherApp) {
NSString *nextUrl = [NSString stringWithFormat:@"fb%@://authorize", _appId];
[params setValue:nextUrl forKey:@"redirect_uri"];
NSString *fbAppUrl = [FBRequest serializeURL:loginDialogURL params:params];
didOpenOtherApp = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:fbAppUrl]];
}
}
// If single sign-on failed, open an inline login dialog. This will require the user to
// enter his or her credentials.
if (!didOpenOtherApp) {
[_loginDialog release];
_loginDialog = [[FBLoginDialog alloc] initWithURL:loginDialogURL
loginParams:params
delegate:self];
[_loginDialog show];
}
}
/**
* A private function for parsing URL parameters.
*/
- (NSDictionary*)parseURLParams:(NSString *)query {
NSArray *pairs = [query componentsSeparatedByString:@"&"];
NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
for (NSString *pair in pairs) {
NSArray *kv = [pair componentsSeparatedByString:@"="];
NSString *val =
[[kv objectAtIndex:1]
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[params setObject:val forKey:[kv objectAtIndex:0]];
}
return params;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//public
/**
* Starts a dialog which prompts the user to log in to Facebook and grant
* the requested permissions to the application.
*
* If the device supports multitasking, we use fast app switching to show
* the dialog in the Facebook app or, if the Facebook app isn't installed,
* in Safari (this enables single sign-on by allowing multiple apps on
* the device to share the same user session).
* When the user grants or denies the permissions, the app that
* showed the dialog (the Facebook app or Safari) redirects back to
* the calling application, passing in the URL the access token
* and/or any other parameters the Facebook backend includes in
* the result (such as an error code if an error occurs).
*
* See http://developers.facebook.com/docs/authentication/ for more details.
*
* Also note that requests may be made to the API without calling
* authorize() first, in which case only public information is returned.
*
* @param application_id
* The Facebook application id, e.g. "350685531728".
* @param permissions
* A list of permission required for this application: e.g.
* "read_stream", "publish_stream", or "offline_access". see
* http://developers.facebook.com/docs/authentication/permissions
* This parameter should not be null -- if you do not require any
* permissions, then pass in an empty String array.
* @param delegate
* Callback interface for notifying the calling application when
* the user has logged in.
*/
- (void)authorize:(NSArray *)permissions
delegate:(id<FBSessionDelegate>)delegate {
[self authorize:permissions delegate:delegate appAuth:YES safariAuth:YES];
}
- (void)authorize:(NSArray *)permissions
delegate:(id<FBSessionDelegate>)delegate
appAuth:(BOOL)tryFBAppAuth
safariAuth:(BOOL)trySafariAuth {
[_permissions release];
_permissions = [permissions retain];
_sessionDelegate = delegate;
[self authorizeWithFBAppAuth:tryFBAppAuth safariAuth:trySafariAuth];
}
/**
* This function processes the URL the Facebook application or Safari used to
* open your application during a single sign-on flow.
*
* You MUST call this function in your UIApplicationDelegate's handleOpenURL
* method (see
* http://developer.apple.com/library/ios/#documentation/uikit/reference/UIApplicationDelegate_Protocol/Reference/Reference.html
* for more info).
*
* This will ensure that the authorization process will proceed smoothly once the
* Facebook application or Safari redirects back to your application.
*
* @param URL the URL that was passed to the application delegate's handleOpenURL method.
*
* @return YES if the URL starts with 'fb[app_id]://authorize and hence was handled
* by SDK, NO otherwise.
*/
- (BOOL)handleOpenURL:(NSURL *)url {
// If the URL's structure doesn't match the structure used for Facebook authorization, abort.
if (![[url absoluteString] hasPrefix:[NSString stringWithFormat:@"fb%@://authorize", _appId]]) {
return NO;
}
NSString *query = [url fragment];
// Version 3.2.3 of the Facebook app encodes the parameters in the query but
// version 3.3 and above encode the parameters in the fragment. To support
// both versions of the Facebook app, we try to parse the query if
// the fragment is missing.
if (!query) {
query = [url query];
}
NSDictionary *params = [self parseURLParams:query];
NSString *accessToken = [params valueForKey:@"access_token"];
// If the URL doesn't contain the access token, an error has occurred.
if (!accessToken) {
NSString *errorReason = [params valueForKey:@"error"];
// If the error response indicates that we should try again using Safari, open
// the authorization dialog in Safari.
if (errorReason && [errorReason isEqualToString:@"service_disabled_use_browser"]) {
[self authorizeWithFBAppAuth:NO safariAuth:YES];
return YES;
}
// If the error response indicates that we should try the authorization flow
// in an inline dialog, do that.
if (errorReason && [errorReason isEqualToString:@"service_disabled"]) {
[self authorizeWithFBAppAuth:NO safariAuth:NO];
return YES;
}
// The facebook app may return an error_code parameter in case it
// encounters a UIWebViewDelegate error. This should not be treated
// as a cancel.
NSString *errorCode = [params valueForKey:@"error_code"];
BOOL userDidCancel =
!errorCode && (!errorReason || [errorReason isEqualToString:@"access_denied"]);
[self fbDialogNotLogin:userDidCancel];
return YES;
}
// We have an access token, so parse the expiration date.
NSString *expTime = [params valueForKey:@"expires_in"];
NSDate *expirationDate = [NSDate distantFuture];
if (expTime != nil) {
int expVal = [expTime intValue];
if (expVal != 0) {
expirationDate = [NSDate dateWithTimeIntervalSinceNow:expVal];
}
}
[self fbDialogLogin:accessToken expirationDate:expirationDate];
return YES;
}
/**
* Invalidate the current user session by removing the access token in
* memory, clearing the browser cookie, and calling auth.expireSession
* through the API.
*
* Note that this method dosen't unauthorize the application --
* it just invalidates the access token. To unauthorize the application,
* the user must remove the app in the app settings page under the privacy
* settings screen on facebook.com.
*
* @param delegate
* Callback interface for notifying the calling application when
* the application has logged out
*/
- (void)logout:(id<FBSessionDelegate>)delegate {
_sessionDelegate = delegate;
NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
[self requestWithMethodName:@"auth.expireSession"
andParams:params andHttpMethod:@"GET"
andDelegate:nil];
[params release];
[_accessToken release];
_accessToken = nil;
[_expirationDate release];
_expirationDate = nil;
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* facebookCookies = [cookies cookiesForURL:
[NSURL URLWithString:@"http://login.facebook.com"]];
for (NSHTTPCookie* cookie in facebookCookies) {
[cookies deleteCookie:cookie];
}
if ([self.sessionDelegate respondsToSelector:@selector(fbDidLogout)]) {
[_sessionDelegate fbDidLogout];
}
}
/**
* Make a request to Facebook's REST API with the given
* parameters. One of the parameter keys must be "method" and its value
* should be a valid REST server API method.
*
* See http://developers.facebook.com/docs/reference/rest/
*
* @param parameters
* Key-value pairs of parameters to the request. Refer to the
* documentation: one of the parameters must be "method".
* @param delegate
* Callback interface for notifying the calling application when
* the request has received response
* @return FBRequest*
* Returns a pointer to the FBRequest object.
*/
- (FBRequest*)requestWithParams:(NSMutableDictionary *)params
andDelegate:(id <FBRequestDelegate>)delegate {
if ([params objectForKey:@"method"] == nil) {
NSLog(@"API Method must be specified");
return nil;
}
NSString * methodName = [params objectForKey:@"method"];
[params removeObjectForKey:@"method"];
return [self requestWithMethodName:methodName
andParams:params
andHttpMethod:@"GET"
andDelegate:delegate];
}
/**
* Make a request to Facebook's REST API with the given method name and
* parameters.
*
* See http://developers.facebook.com/docs/reference/rest/
*
*
* @param methodName
* a valid REST server API method.
* @param parameters
* Key-value pairs of parameters to the request. Refer to the
* documentation: one of the parameters must be "method". To upload
* a file, you should specify the httpMethod to be "POST" and the
* “params” you passed in should contain a value of the type
* (UIImage *) or (NSData *) which contains the content that you
* want to upload
* @param delegate
* Callback interface for notifying the calling application when
* the request has received response
* @return FBRequest*
* Returns a pointer to the FBRequest object.
*/
- (FBRequest*)requestWithMethodName:(NSString *)methodName
andParams:(NSMutableDictionary *)params
andHttpMethod:(NSString *)httpMethod
andDelegate:(id <FBRequestDelegate>)delegate {
NSString * fullURL = [kRestserverBaseURL stringByAppendingString:methodName];
return [self openUrl:fullURL
params:params
httpMethod:httpMethod
delegate:delegate];
}
/**
* Make a request to the Facebook Graph API without any parameters.
*
* See http://developers.facebook.com/docs/api
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @param delegate
* Callback interface for notifying the calling application when
* the request has received response
* @return FBRequest*
* Returns a pointer to the FBRequest object.
*/
- (FBRequest*)requestWithGraphPath:(NSString *)graphPath
andDelegate:(id <FBRequestDelegate>)delegate {
return [self requestWithGraphPath:graphPath
andParams:[NSMutableDictionary dictionary]
andHttpMethod:@"GET"
andDelegate:delegate];
}
/**
* Make a request to the Facebook Graph API with the given string
* parameters using an HTTP GET (default method).
*
* See http://developers.facebook.com/docs/api
*
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @param parameters
* key-value string parameters, e.g. the path "search" with
* parameters "q" : "facebook" would produce a query for the
* following graph resource:
* https://graph.facebook.com/search?q=facebook
* @param delegate
* Callback interface for notifying the calling application when
* the request has received response
* @return FBRequest*
* Returns a pointer to the FBRequest object.
*/
- (FBRequest*)requestWithGraphPath:(NSString *)graphPath
andParams:(NSMutableDictionary *)params
andDelegate:(id <FBRequestDelegate>)delegate {
return [self requestWithGraphPath:graphPath
andParams:params
andHttpMethod:@"GET"
andDelegate:delegate];
}
/**
* Make a request to the Facebook Graph API with the given
* HTTP method and string parameters. Note that binary data parameters
* (e.g. pictures) are not yet supported by this helper function.
*
* See http://developers.facebook.com/docs/api
*
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @param parameters
* key-value string parameters, e.g. the path "search" with
* parameters {"q" : "facebook"} would produce a query for the
* following graph resource:
* https://graph.facebook.com/search?q=facebook
* To upload a file, you should specify the httpMethod to be
* "POST" and the “params” you passed in should contain a value
* of the type (UIImage *) or (NSData *) which contains the
* content that you want to upload
* @param httpMethod
* http verb, e.g. "GET", "POST", "DELETE"
* @param delegate
* Callback interface for notifying the calling application when
* the request has received response
* @return FBRequest*
* Returns a pointer to the FBRequest object.
*/
- (FBRequest*)requestWithGraphPath:(NSString *)graphPath
andParams:(NSMutableDictionary *)params
andHttpMethod:(NSString *)httpMethod
andDelegate:(id <FBRequestDelegate>)delegate {
NSString * fullURL = [kGraphBaseURL stringByAppendingString:graphPath];
return [self openUrl:fullURL
params:params
httpMethod:httpMethod
delegate:delegate];
}
/**
* Generate a UI dialog for the request action.
*
* @param action
* String representation of the desired method: e.g. "login",
* "feed", ...
* @param delegate
* Callback interface to notify the calling application when the
* dialog has completed.
*/
- (void)dialog:(NSString *)action
andDelegate:(id<FBDialogDelegate>)delegate {
NSMutableDictionary * params = [NSMutableDictionary dictionary];
[self dialog:action andParams:params andDelegate:delegate];
}
/**
* Generate a UI dialog for the request action with the provided parameters.
*
* @param action
* String representation of the desired method: e.g. "login",
* "feed", ...
* @param parameters
* key-value string parameters
* @param delegate
* Callback interface to notify the calling application when the
* dialog has completed.
*/
- (void)dialog:(NSString *)action
andParams:(NSMutableDictionary *)params
andDelegate:(id <FBDialogDelegate>)delegate {
[_fbDialog release];
NSString *dialogURL = [kDialogBaseURL stringByAppendingString:action];
[params setObject:@"touch" forKey:@"display"];
[params setObject:kSDKVersion forKey:@"sdk"];
[params setObject:kRedirectURL forKey:@"redirect_uri"];
if (action == kLogin) {
[params setObject:@"user_agent" forKey:@"type"];
_fbDialog = [[FBLoginDialog alloc] initWithURL:dialogURL loginParams:params delegate:self];
} else {
[params setObject:_appId forKey:@"app_id"];
if ([self isSessionValid]) {
[params setValue:[self.accessToken stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
forKey:@"access_token"];
}
_fbDialog = [[FBDialog alloc] initWithURL:dialogURL params:params delegate:delegate];
}
[_fbDialog show];
}
/**
* @return boolean - whether this object has an non-expired session token
*/
- (BOOL)isSessionValid {
return (self.accessToken != nil && self.expirationDate != nil
&& NSOrderedDescending == [self.expirationDate compare:[NSDate date]]);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//FBLoginDialogDelegate
/**
* Set the authToken and expirationDate after login succeed
*/
- (void)fbDialogLogin:(NSString *)token expirationDate:(NSDate *)expirationDate {
self.accessToken = token;
self.expirationDate = expirationDate;
if ([self.sessionDelegate respondsToSelector:@selector(fbDidLogin)]) {
[_sessionDelegate fbDidLogin];
}
}
/**
* Did not login call the not login delegate
*/
- (void)fbDialogNotLogin:(BOOL)cancelled {
if ([self.sessionDelegate respondsToSelector:@selector(fbDidNotLogin:)]) {
[_sessionDelegate fbDidNotLogin:cancelled];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//FBRequestDelegate
/**
* Handle the auth.ExpireSession api call failure
*/
- (void)request:(FBRequest*)request didFailWithError:(NSError*)error{
NSLog(@"Failed to expire the session");
}
@end
|
04081337-xmpp
|
Xcode/Testing/FacebookTest/FBConnect/Facebook.m
|
Objective-C
|
bsd
| 22,068
|
#import <Cocoa/Cocoa.h>
@interface TestXEP82AppDelegate : NSObject <NSApplicationDelegate>
{
NSWindow *window;
}
@property (assign) IBOutlet NSWindow *window;
@end
|
04081337-xmpp
|
Xcode/Testing/TestXEP82/Mac/TestXEP82AppDelegate.h
|
Objective-C
|
bsd
| 168
|
#import "TestXEP82AppDelegate.h"
#import "TestXEP82.h"
@implementation TestXEP82AppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[TestXEP82 runTests];
}
@end
|
04081337-xmpp
|
Xcode/Testing/TestXEP82/Mac/TestXEP82AppDelegate.m
|
Objective-C
|
bsd
| 219
|
//
// main.m
// TestXEP82
//
// Created by Robbie Hanson on 9/17/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **) argv);
}
|
04081337-xmpp
|
Xcode/Testing/TestXEP82/Mac/main.m
|
Objective-C
|
bsd
| 256
|
//
// TestXEP82.m
// TestXEP82
//
// Created by Robbie Hanson on 4/12/11.
// Copyright 2011 Deusty, LLC. All rights reserved.
//
#import "TestXEP82.h"
#import "XMPPDateTimeProfiles.h"
@implementation TestXEP82
static NSDateFormatter *df;
+ (void)initialize
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
df = [[NSDateFormatter alloc] init];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS z"];
});
}
+ (void)testParseDate
{
// Should Succeed
//
// Notice the proper time zones in the output.
// The first date will be classified as standard GMT+HHMM as this is before DST was invented.
// The second date takes place during daylight saving time.
// The third date takes place during standard time.
NSString *d1s = @"1776-07-04";
NSString *d2s = @"1969-01-21";
NSString *d3s = @"1969-07-21";
NSString *d4s = @"2010-04-04";
NSString *d5s = @"2010-12-25";
NSLog(@"S parseDate(%@) = %@", d1s, [df stringFromDate:[XMPPDateTimeProfiles parseDate:d1s]]);
NSLog(@"S parseDate(%@) = %@", d2s, [df stringFromDate:[XMPPDateTimeProfiles parseDate:d2s]]);
NSLog(@"S parseDate(%@) = %@", d3s, [df stringFromDate:[XMPPDateTimeProfiles parseDate:d3s]]);
NSLog(@"S parseDate(%@) = %@", d4s, [df stringFromDate:[XMPPDateTimeProfiles parseDate:d4s]]);
NSLog(@"S parseDate(%@) = %@", d5s, [df stringFromDate:[XMPPDateTimeProfiles parseDate:d5s]]);
NSLog(@" ");
// Should Fail
NSString *d1f = nil;
NSString *d2f = @"1776-7-4";
NSString *d3f = @"cheese";
NSLog(@"F parseDate(%@) = %@", d1f, [df stringFromDate:[XMPPDateTimeProfiles parseDate:d1f]]);
NSLog(@"F parseDate(%@) = %@", d2f, [df stringFromDate:[XMPPDateTimeProfiles parseDate:d2f]]);
NSLog(@"F parseDate(%@) = %@", d3f, [df stringFromDate:[XMPPDateTimeProfiles parseDate:d3f]]);
}
+ (void)testParseTime
{
// Should Succeed
//
// Notice the proper time zones in the output.
// All have been converted to the local time zone as needed.
NSString *t1s = @"16:00:00";
NSString *t2s = @"16:00:00Z";
NSString *t3s = @"16:00:00-06:00";
NSString *t4s = @"16:00:00.123";
NSString *t5s = @"16:00:00.123Z";
NSString *t6s = @"16:00:00.123-06:00";
NSLog(@"S parseTime(%@) = %@", t1s, [df stringFromDate:[XMPPDateTimeProfiles parseTime:t1s]]);
NSLog(@"S parseTime(%@) = %@", t2s, [df stringFromDate:[XMPPDateTimeProfiles parseTime:t2s]]);
NSLog(@"S parseTime(%@) = %@", t3s, [df stringFromDate:[XMPPDateTimeProfiles parseTime:t3s]]);
NSLog(@"S parseTime(%@) = %@", t4s, [df stringFromDate:[XMPPDateTimeProfiles parseTime:t4s]]);
NSLog(@"S parseTime(%@) = %@", t5s, [df stringFromDate:[XMPPDateTimeProfiles parseTime:t5s]]);
NSLog(@"S parseTime(%@) = %@", t6s, [df stringFromDate:[XMPPDateTimeProfiles parseTime:t6s]]);
NSLog(@" ");
// Should Fail
NSString *t1f = nil;
NSString *t2f = @"16-00-00";
NSString *t3f = @"16:00:00-0600";
NSString *t4f = @"16:00:00.1";
NSString *t5f = @"16:00.123";
NSString *t6f = @"cheese";
NSLog(@"F parseTime(%@) = %@", t1f, [df stringFromDate:[XMPPDateTimeProfiles parseTime:t1f]]);
NSLog(@"F parseTime(%@) = %@", t2f, [df stringFromDate:[XMPPDateTimeProfiles parseTime:t2f]]);
NSLog(@"F parseTime(%@) = %@", t3f, [df stringFromDate:[XMPPDateTimeProfiles parseTime:t3f]]);
NSLog(@"F parseTime(%@) = %@", t4f, [df stringFromDate:[XMPPDateTimeProfiles parseTime:t4f]]);
NSLog(@"F parseTime(%@) = %@", t5f, [df stringFromDate:[XMPPDateTimeProfiles parseTime:t5f]]);
NSLog(@"F parseTime(%@) = %@", t6f, [df stringFromDate:[XMPPDateTimeProfiles parseTime:t6f]]);
}
+ (void)testParseDateTime
{
// Should Succeed
//
// Notice the proper time zones in the output.
NSString *dt01s = @"1776-07-04T02:56:15Z";
NSString *dt02s = @"1776-07-04T21:56:15-05:00";
NSString *dt03s = @"1776-07-04T02:56:15.123Z";
NSString *dt04s = @"1776-07-04T21:56:15.123-05:00";
NSLog(@"S parseDateTime(%@) = %@", dt01s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt01s]]);
NSLog(@"S parseDateTime(%@) = %@", dt02s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt02s]]);
NSLog(@"S parseDateTime(%@) = %@", dt03s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt03s]]);
NSLog(@"S parseDateTime(%@) = %@", dt04s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt04s]]);
NSLog(@" ");
NSString *dt05s = @"1969-01-21T02:56:15Z";
NSString *dt06s = @"1969-01-20T21:56:15-05:00";
NSString *dt07s = @"1969-01-21T02:56:15.123Z";
NSString *dt08s = @"1969-01-21T21:56:15.123-05:00";
NSLog(@"S parseDateTime(%@) = %@", dt05s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt05s]]);
NSLog(@"S parseDateTime(%@) = %@", dt06s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt06s]]);
NSLog(@"S parseDateTime(%@) = %@", dt07s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt07s]]);
NSLog(@"S parseDateTime(%@) = %@", dt08s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt08s]]);
NSLog(@" ");
NSString *dt09s = @"1969-07-21T02:56:15Z";
NSString *dt10s = @"1969-07-20T21:56:15-05:00";
NSString *dt11s = @"1969-07-21T02:56:15.123Z";
NSString *dt12s = @"1969-07-21T21:56:15.123-05:00";
NSLog(@"S parseDateTime(%@) = %@", dt09s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt09s]]);
NSLog(@"S parseDateTime(%@) = %@", dt10s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt10s]]);
NSLog(@"S parseDateTime(%@) = %@", dt11s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt11s]]);
NSLog(@"S parseDateTime(%@) = %@", dt12s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt12s]]);
NSLog(@" ");
NSString *dt13s = @"2010-04-04T02:56:15Z";
NSString *dt14s = @"2010-04-04T21:56:15-05:00";
NSString *dt15s = @"2010-04-04T02:56:15.123Z";
NSString *dt16s = @"2010-04-04T21:56:15.123-05:00";
NSLog(@"S parseDateTime(%@) = %@", dt13s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt13s]]);
NSLog(@"S parseDateTime(%@) = %@", dt14s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt14s]]);
NSLog(@"S parseDateTime(%@) = %@", dt15s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt15s]]);
NSLog(@"S parseDateTime(%@) = %@", dt16s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt16s]]);
NSLog(@" ");
NSString *dt17s = @"2010-12-25T02:56:15Z";
NSString *dt18s = @"2010-12-25T21:56:15-05:00";
NSString *dt19s = @"2010-12-25T02:56:15.123Z";
NSString *dt20s = @"2010-12-25T21:56:15.123-05:00";
NSLog(@"S parseDateTime(%@) = %@", dt17s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt17s]]);
NSLog(@"S parseDateTime(%@) = %@", dt18s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt18s]]);
NSLog(@"S parseDateTime(%@) = %@", dt19s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt19s]]);
NSLog(@"S parseDateTime(%@) = %@", dt20s, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt20s]]);
NSLog(@" ");
// Should Fail
NSString *dt1f = nil;
NSString *dt2f = @"1969-07-20 21:56:15Z";
NSString *dt3f = @"1969-7-4T02:56:15.123Z";
NSString *dt4f = @"cheese";
NSLog(@"F parseDateTime(%@) = %@", dt1f, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt1f]]);
NSLog(@"F parseDateTime(%@) = %@", dt2f, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt2f]]);
NSLog(@"F parseDateTime(%@) = %@", dt3f, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt3f]]);
NSLog(@"F parseDateTime(%@) = %@", dt4f, [df stringFromDate:[XMPPDateTimeProfiles parseDateTime:dt4f]]);
}
+ (void)testCategory
{
NSDate *now = [NSDate date];
NSLog(@"now(%@).xmppDateString = %@", now, [now xmppDateString]);
NSLog(@"now(%@).xmppTimeString = %@", now, [now xmppTimeString]);
NSLog(@"now(%@).xmppDateTimeString = %@", now, [now xmppDateTimeString]);
}
+ (void)runTests
{
NSLog(@"now = %@", [df stringFromDate:[NSDate date]]);
NSLog(@"---------------------------------------------------------------------------------------------------------");
[self testParseDate];
NSLog(@"---------------------------------------------------------------------------------------------------------");
[self testParseTime];
NSLog(@"---------------------------------------------------------------------------------------------------------");
[self testParseDateTime];
NSLog(@"---------------------------------------------------------------------------------------------------------");
[self testCategory];
NSLog(@"---------------------------------------------------------------------------------------------------------");
}
@end
|
04081337-xmpp
|
Xcode/Testing/TestXEP82/TestXEP82.m
|
Objective-C
|
bsd
| 8,549
|
//
// TestXEP82.h
// TestXEP82
//
// Created by Robbie Hanson on 4/12/11.
// Copyright 2011 Deusty, LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface TestXEP82 : NSObject
+ (void)runTests;
@end
|
04081337-xmpp
|
Xcode/Testing/TestXEP82/TestXEP82.h
|
Objective-C
|
bsd
| 227
|
#import "TestXEP82ViewController.h"
@implementation TestXEP82ViewController
@end
|
04081337-xmpp
|
Xcode/Testing/TestXEP82/iOS/TestXEP82/TestXEP82ViewController.m
|
Objective-C
|
bsd
| 86
|
#import <UIKit/UIKit.h>
@class TestXEP82ViewController;
@interface TestXEP82AppDelegate : NSObject <UIApplicationDelegate> {
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet TestXEP82ViewController *viewController;
@end
|
04081337-xmpp
|
Xcode/Testing/TestXEP82/iOS/TestXEP82/TestXEP82AppDelegate.h
|
Objective-C
|
bsd
| 275
|
#import "TestXEP82AppDelegate.h"
#import "TestXEP82ViewController.h"
#import "TestXEP82.h"
@implementation TestXEP82AppDelegate
@synthesize window=_window;
@synthesize viewController=_viewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[TestXEP82 runTests];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)dealloc
{
[_window release];
[_viewController release];
[super dealloc];
}
@end
|
04081337-xmpp
|
Xcode/Testing/TestXEP82/iOS/TestXEP82/TestXEP82AppDelegate.m
|
Objective-C
|
bsd
| 544
|
//
// main.m
// TestXEP82
//
// Created by Robbie Hanson on 4/12/11.
// Copyright 2011 Voalte. All rights reserved.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
|
04081337-xmpp
|
Xcode/Testing/TestXEP82/iOS/TestXEP82/main.m
|
Objective-C
|
bsd
| 335
|
#import <UIKit/UIKit.h>
@interface TestXEP82ViewController : UIViewController {
}
@end
|
04081337-xmpp
|
Xcode/Testing/TestXEP82/iOS/TestXEP82/TestXEP82ViewController.h
|
Objective-C
|
bsd
| 95
|
#import "AutoTimeTestAppDelegate.h"
#import "DDLog.h"
#import "DDTTYLogger.h"
// Log levels: off, error, warn, info, verbose
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#define MY_JID @"user@gmail.com/xmppFramework"
#define MY_PASSWORD @""
@implementation AutoTimeTestAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[DDLog addLogger:[DDTTYLogger sharedInstance]];
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
xmppStream = [[XMPPStream alloc] init];
xmppStream.myJID = [XMPPJID jidWithString:MY_JID];
xmppAutoTime = [[XMPPAutoTime alloc] init];
xmppAutoTime.recalibrationInterval = 60;
xmppAutoTime.targetJID = nil;
[xmppAutoTime activate:xmppStream];
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
[xmppAutoTime addDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
if (![xmppStream connect:&error])
{
DDLogError(@"%@: Error connecting: %@", [self class], error);
}
}
- (void)goOnline:(NSTimer *)aTimer
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
[xmppStream sendElement:[XMPPPresence presence]];
}
- (void)goOffline:(NSTimer *)aTimer
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
[xmppStream sendElement:[XMPPPresence presenceWithType:@"unavailable"]];
}
- (void)changeAutoTimeInterval:(NSTimer *)aTimer
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
xmppAutoTime.recalibrationInterval = 30;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
NSError *error = nil;
if (![xmppStream authenticateWithPassword:MY_PASSWORD error:&error])
{
DDLogError(@"%@: Error authenticating: %@", [self class], error);
}
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
[NSTimer scheduledTimerWithTimeInterval:130
target:self
selector:@selector(changeAutoTimeInterval:)
userInfo:nil
repeats:NO];
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
}
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
DDLogVerbose(@"%@: %@", [self class], THIS_METHOD);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)xmppAutoTime:(XMPPAutoTime *)sender didUpdateTimeDifference:(NSTimeInterval)timeDifference
{
DDLogVerbose(@"%@: %@ %f <<<<<<<============", [self class], THIS_METHOD, timeDifference);
}
@end
|
04081337-xmpp
|
Xcode/Testing/AutoTimeTest/Desktop/AutoTimeTest/AutoTimeTest/AutoTimeTestAppDelegate.m
|
Objective-C
|
bsd
| 2,870
|
#import <Cocoa/Cocoa.h>
#import "XMPP.h"
#import "XMPPAutoTime.h"
@interface AutoTimeTestAppDelegate : NSObject <NSApplicationDelegate> {
@private
XMPPStream *xmppStream;
XMPPAutoTime *xmppAutoTime;
NSWindow *window;
}
@property (assign) IBOutlet NSWindow *window;
@end
|
04081337-xmpp
|
Xcode/Testing/AutoTimeTest/Desktop/AutoTimeTest/AutoTimeTest/AutoTimeTestAppDelegate.h
|
Objective-C
|
bsd
| 279
|
{\rtf0\ansi{\fonttbl\f0\fswiss Helvetica;}
{\colortbl;\red255\green255\blue255;}
\paperw9840\paperh8400
\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\ql\qnatural
\f0\b\fs24 \cf0 Engineering:
\b0 \
Some people\
\
\b Human Interface Design:
\b0 \
Some other people\
\
\b Testing:
\b0 \
Hopefully not nobody\
\
\b Documentation:
\b0 \
Whoever\
\
\b With special thanks to:
\b0 \
Mom\
}
|
04081337-xmpp
|
Xcode/Testing/AutoTimeTest/Desktop/AutoTimeTest/AutoTimeTest/en.lproj/Credits.rtf
|
Rich Text Format
|
bsd
| 436
|
//
// main.m
// AutoTimeTest
//
// Created by Robbie Hanson on 8/9/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **)argv);
}
|
04081337-xmpp
|
Xcode/Testing/AutoTimeTest/Desktop/AutoTimeTest/AutoTimeTest/main.m
|
Objective-C
|
bsd
| 253
|
//
// main.m
// TestCapabilitiesHashing
//
// Created by Robbie Hanson on 5/12/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
return NSApplicationMain(argc, (const char **) argv);
}
|
04081337-xmpp
|
Xcode/Testing/TestCapabilitiesHashing/Mac/TestCapabilitiesHashing/main.m
|
Objective-C
|
bsd
| 270
|
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#if TARGET_OS_IPHONE
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#import <UIKit/UIKit.h>
#import "TestCapabilitiesHashingViewController.h"
@class XMPPCapabilities;
@interface TestCapabilitiesHashingAppDelegate : NSObject <UIApplicationDelegate>
{
XMPPCapabilities *capabilities;
UIWindow *window;
TestCapabilitiesHashingViewController *viewController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet TestCapabilitiesHashingViewController *viewController;
@end
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#else
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#import <Cocoa/Cocoa.h>
@class XMPPCapabilities;
@interface TestCapabilitiesHashingAppDelegate : NSObject <NSApplicationDelegate>
{
XMPPCapabilities *capabilities;
NSWindow *window;
}
@property (assign) IBOutlet NSWindow *window;
@end
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
04081337-xmpp
|
Xcode/Testing/TestCapabilitiesHashing/TestCapabilitiesHashingAppDelegate.h
|
Objective-C
|
bsd
| 1,458
|
#import "TestCapabilitiesHashingAppDelegate.h"
#import "NSData+XMPP.h"
#import "NSXMLElement+XMPP.h"
#import "XMPPCapabilities.h"
#import "XMPPCapabilitiesCoreDataStorage.h"
@interface XMPPCapabilities (UnitTesting)
- (NSString *)hashCapabilitiesFromQuery:(NSXMLElement *)query;
@end
@implementation TestCapabilitiesHashingAppDelegate
#if TARGET_OS_IPHONE
@synthesize window;
@synthesize viewController;
#else
@synthesize window;
#endif
- (void)test1
{
NSLog(@"============================================================");
// From XEP-0115, Section 5.2
NSMutableString *s = [NSMutableString string];
[s appendString:@"<query xmlns='http://jabber.org/protocol/disco#info'>"];
[s appendString:@" <identity category='client' name='Exodus 0.9.1' type='pc'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/caps'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/disco#info'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/disco#items'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/muc'/>"];
[s appendString:@"</query>"];
NSXMLDocument *doc = [[[NSXMLDocument alloc] initWithXMLString:s options:0 error:nil] autorelease];
NSXMLElement *query = [doc rootElement];
// NSLog(@"query:\n%@", [query prettyXMLString]);
NSLog(@"test1 result : %@", [capabilities hashCapabilitiesFromQuery:query]);
NSLog(@"expected result: QgayPKawpkPSDYmwT/WM94uAlu0=");
NSLog(@"============================================================");
}
- (void)test2
{
NSLog(@"============================================================");
// From XEP-0115, Section 5.3
NSMutableString *s = [NSMutableString string];
[s appendString:@"<query xmlns='http://jabber.org/protocol/disco#info'>"];
[s appendString:@" <identity xml:lang='en' category='client' name='Psi 0.11' type='pc'/>"];
[s appendString:@" <identity xml:lang='el' category='client' name='Ψ 0.11' type='pc'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/caps'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/disco#info'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/disco#items'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/muc'/>"];
[s appendString:@" <x xmlns='jabber:x:data' type='result'>"];
[s appendString:@" <field var='FORM_TYPE' type='hidden'>"];
[s appendString:@" <value>urn:xmpp:dataforms:softwareinfo</value>"];
[s appendString:@" </field>"];
[s appendString:@" <field var='ip_version'>"];
[s appendString:@" <value>ipv4</value>"];
[s appendString:@" <value>ipv6</value>"];
[s appendString:@" </field>"];
[s appendString:@" <field var='os'>"];
[s appendString:@" <value>Mac</value>"];
[s appendString:@" </field>"];
[s appendString:@" <field var='os_version'>"];
[s appendString:@" <value>10.5.1</value>"];
[s appendString:@" </field>"];
[s appendString:@" <field var='software'>"];
[s appendString:@" <value>Psi</value>"];
[s appendString:@" </field>"];
[s appendString:@" <field var='software_version'>"];
[s appendString:@" <value>0.11</value>"];
[s appendString:@" </field>"];
[s appendString:@" </x>"];
[s appendString:@"</query>"];
NSXMLDocument *doc = [[[NSXMLDocument alloc] initWithXMLString:s options:0 error:nil] autorelease];
NSXMLElement *query = [doc rootElement];
// NSLog(@"query:\n%@", [query prettyXMLString]);
NSLog(@"test2 result : %@", [capabilities hashCapabilitiesFromQuery:query]);
NSLog(@"expected result: q07IKJEyjvHSyhy//CH0CxmKi8w=");
NSLog(@"============================================================");
}
- (void)test3
{
NSLog(@"============================================================");
NSMutableString *s = [NSMutableString string];
[s appendString:@"<query node='http://pidgin.im/#WsE3KKs1gYLeYKAn5zQHkTkRnUA='"];
[s appendString:@" xmlns='http://jabber.org/protocol/disco#info'>"];
[s appendString:@" <identity category='client' name='Pidgin' type='pc'/>"];
[s appendString:@" <feature var='jabber:iq:last'/>"];
[s appendString:@" <feature var='jabber:iq:oob'/>"];
[s appendString:@" <feature var='urn:xmpp:time'/>"];
[s appendString:@" <feature var='jabber:iq:version'/>"];
[s appendString:@" <feature var='jabber:x:conference'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/bytestreams'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/caps'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/chatstates'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/disco#info'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/disco#items'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/muc'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/muc#user'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/si'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/si/profile/file-transfer'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/xhtml-im'/>"];
[s appendString:@" <feature var='urn:xmpp:ping'/>"];
[s appendString:@" <feature var='urn:xmpp:bob'/>"];
[s appendString:@" <feature var='urn:xmpp:jingle:1'/>"];
[s appendString:@" <feature var='urn:xmpp:jingle:transports:raw-udp:1'/>"];
[s appendString:@" <feature var='http://www.google.com/xmpp/protocol/session'/>"];
[s appendString:@" <feature var='http://www.google.com/xmpp/protocol/voice/v1'/>"];
[s appendString:@" <feature var='http://www.google.com/xmpp/protocol/video/v1'/>"];
[s appendString:@" <feature var='http://www.google.com/xmpp/protocol/camera/v1'/>"];
[s appendString:@" <feature var='urn:xmpp:jingle:apps:rtp:audio'/>"];
[s appendString:@" <feature var='urn:xmpp:jingle:apps:rtp:video'/>"];
[s appendString:@" <feature var='urn:xmpp:jingle:transports:ice-udp:1'/>"];
[s appendString:@" <feature var='urn:xmpp:avatar:metadata'/>"];
[s appendString:@" <feature var='urn:xmpp:avatar:data'/>"];
[s appendString:@" <feature var='urn:xmpp:avatar:metadata+notify'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/mood'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/mood+notify'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/tune'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/tune+notify'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/nick'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/nick+notify'/>"];
[s appendString:@" <feature var='http://jabber.org/protocol/ibb'/>"];
[s appendString:@"</query>"];
NSXMLDocument *doc = [[[NSXMLDocument alloc] initWithXMLString:s options:0 error:nil] autorelease];
NSXMLElement *query = [doc rootElement];
// NSLog(@"query:\n%@", [query prettyXMLString]);
NSLog(@"test3 result : %@", [capabilities hashCapabilitiesFromQuery:query]);
NSLog(@"expected result: WsE3KKs1gYLeYKAn5zQHkTkRnUA=");
NSLog(@"============================================================");
}
#if TARGET_OS_IPHONE
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
// IPHONE TEST
XMPPCapabilitiesCoreDataStorage *storage = [[[XMPPCapabilitiesCoreDataStorage alloc] init] autorelease];
capabilities = [[XMPPCapabilities alloc] initWithCapabilitiesStorage:storage];
[self test1];
[self test2];
[self test3];
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
#else
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// MAC TEST
XMPPCapabilitiesCoreDataStorage *storage = [[[XMPPCapabilitiesCoreDataStorage alloc] init] autorelease];
capabilities = [[XMPPCapabilities alloc] initWithCapabilitiesStorage:storage];
[self test1];
[self test2];
[self test3];
}
#endif
@end
|
04081337-xmpp
|
Xcode/Testing/TestCapabilitiesHashing/TestCapabilitiesHashingAppDelegate.m
|
Objective-C
|
bsd
| 7,888
|
//
// main.m
// TestCapabilitiesHashing
//
// Created by Robbie Hanson on 5/12/10.
// Copyright __MyCompanyName__ 2010. All rights reserved.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
|
04081337-xmpp
|
Xcode/Testing/TestCapabilitiesHashing/iPhone/TestCapabilitiesHashing/main.m
|
Objective-C
|
bsd
| 378
|
//
// TestCapabilitiesHashingViewController.h
// TestCapabilitiesHashing
//
// Created by Robbie Hanson on 5/12/10.
// Copyright __MyCompanyName__ 2010. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TestCapabilitiesHashingViewController : UIViewController {
}
@end
|
04081337-xmpp
|
Xcode/Testing/TestCapabilitiesHashing/iPhone/TestCapabilitiesHashing/Classes/TestCapabilitiesHashingViewController.h
|
Objective-C
|
bsd
| 287
|
//
// TestCapabilitiesHashingViewController.m
// TestCapabilitiesHashing
//
// Created by Robbie Hanson on 5/12/10.
// Copyright __MyCompanyName__ 2010. All rights reserved.
//
#import "TestCapabilitiesHashingViewController.h"
@implementation TestCapabilitiesHashingViewController
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
|
04081337-xmpp
|
Xcode/Testing/TestCapabilitiesHashing/iPhone/TestCapabilitiesHashing/Classes/TestCapabilitiesHashingViewController.m
|
Objective-C
|
bsd
| 1,528
|
#import "ParserTestMacAppDelegate.h"
#import "XMPPParser.h"
#define PRINT_ELEMENTS NO
@interface ParserTestMacAppDelegate (PrivateAPI)
- (void)nonParserTest;
- (void)parserTest;
@end
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation ParserTestMacAppDelegate
@synthesize window;
- (NSString *)stringToParse:(BOOL)full
{
NSMutableString *mStr = [NSMutableString stringWithCapacity:500];
if(full)
{
[mStr appendString:@"<stream:stream from='gmail.com' id='CA0CB0D98FE6FA62' version='1.0' "
"xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client'>"];
}
[mStr appendString:@" <features>"];
[mStr appendString:@" <starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'>"];
[mStr appendString:@" <required/>"];
[mStr appendString:@" </starttls>"];
[mStr appendString:@" <mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>"];
[mStr appendString:@" <mechanism>X-GOOGLE-TOKEN</mechanism>"];
[mStr appendString:@" </mechanisms>"];
[mStr appendString:@" </features>"];
[mStr appendString:@" <proceed xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>"];
[mStr appendString:@" <success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>"];
[mStr appendString:@" <iq type='result'>"];
[mStr appendString:@" <bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'>"];
[mStr appendString:@" <jid>robbiehanson15@gmail.com/iPhoneTestBD221ED7</jid>"];
[mStr appendString:@" </bind>"];
[mStr appendString:@" </iq>"];
[mStr appendString:@" <team:deusty team:lead='robbie_hanson' xmlns:team='software'/>"];
[mStr appendString:@" <type><![CDATA[post]]></type>"];
[mStr appendString:@"<menu>"];
[mStr appendString:@" <food>"];
[mStr appendString:@" <pizza />"];
[mStr appendString:@" <spaghetti />"];
[mStr appendString:@" <turkey />"];
[mStr appendString:@" <pie />"];
[mStr appendString:@" <potatoes />"];
[mStr appendString:@" <gravy />"];
[mStr appendString:@" </food>"];
[mStr appendString:@" <drinks>"];
[mStr appendString:@" <sprite />"];
[mStr appendString:@" <drPepper />"];
[mStr appendString:@" <pepsi />"];
[mStr appendString:@" <coke />"];
[mStr appendString:@" <mtdew />"];
[mStr appendString:@" <beer />"];
[mStr appendString:@" <wine />"];
[mStr appendString:@" </drinks>"];
[mStr appendString:@"</menu>"];
if(full)
{
[mStr appendString:@"</stream:stream>"];
}
return mStr;
}
- (NSData *)dataToParse:(BOOL)full
{
return [[self stringToParse:full] dataUsingEncoding:NSUTF8StringEncoding];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[self nonParserTest];
[self parserTest];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Non Parser
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (NSData *)nextTryFromData:(NSData *)data atOffset:(NSUInteger *)offset
{
NSData *term = [@">" dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger termLength = [term length];
NSUInteger index = *offset;
while((index + termLength) <= [data length])
{
const void *dataBytes = (const void *)((void *)[data bytes] + index);
if(memcmp(dataBytes, [term bytes], termLength) == 0)
{
NSUInteger length = (index - *offset) + termLength;
NSRange range = NSMakeRange(*offset, length);
*offset += length;
return [data subdataWithRange:range];
}
else
{
index++;
}
}
*offset = index;
return nil;
}
- (void)nonParserTest
{
NSData *dataToParse = [self dataToParse:NO];
NSDate *start = [NSDate date];
NSMutableData *mData = [NSMutableData data];
NSUInteger offset = 0;
NSData *subdata = [self nextTryFromData:dataToParse atOffset:&offset];
while(subdata)
{
// NSString *str = [[NSString alloc] initWithData:subdata encoding:NSUTF8StringEncoding];
// NSLog(@"str: %@", str);
// [str release];
[mData appendData:subdata];
NSXMLDocument *doc = [[NSXMLDocument alloc] initWithData:mData options:0 error:nil];
if(doc)
{
if(PRINT_ELEMENTS)
{
NSLog(@"\n\n%@\n", [doc XMLStringWithOptions:(NSXMLNodeCompactEmptyElement | NSXMLNodePrettyPrint)]);
}
[doc release];
[mData setLength:0];
}
subdata = [self nextTryFromData:dataToParse atOffset:&offset];
}
NSTimeInterval ellapsed = [start timeIntervalSinceNow] * -1.0;
NSLog(@"NonParser test = %f seconds", ellapsed);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Parser
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)parserTest
{
NSData *dataToParse = [self dataToParse:YES];
NSDate *start = [NSDate date];
XMPPParser *parser = [[XMPPParser alloc] initWithDelegate:self];
[parser parseData:dataToParse];
NSTimeInterval ellapsed = [start timeIntervalSinceNow] * -1.0;
NSLog(@"Parser test = %f seconds", ellapsed);
}
- (void)xmppParser:(XMPPParser *)sender didReadRoot:(NSXMLElement *)root
{
if(PRINT_ELEMENTS)
{
NSLog(@"xmppParser:didReadRoot: \n\n%@",
[root XMLStringWithOptions:(NSXMLNodeCompactEmptyElement | NSXMLNodePrettyPrint)]);
}
}
- (void)xmppParser:(XMPPParser *)sender didReadElement:(NSXMLElement *)element
{
if(PRINT_ELEMENTS)
{
NSLog(@"xmppParser:didReadElement: \n\n%@",
[element XMLStringWithOptions:(NSXMLNodeCompactEmptyElement | NSXMLNodePrettyPrint)]);
}
}
- (void)xmppParserDidEnd:(XMPPParser *)sender
{
if(PRINT_ELEMENTS)
{
NSLog(@"xmppParserDidEnd");
}
}
- (void)xmppParser:(XMPPParser *)sender didFail:(NSError *)error
{
if(PRINT_ELEMENTS)
{
NSLog(@"xmppParser:didFail: %@", error);
}
}
@end
|
04081337-xmpp
|
Xcode/Testing/ParserTestMac/ParserTestMacAppDelegate.m
|
Objective-C
|
bsd
| 6,014
|