XMPPBlocking.m 16.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
#import "XMPP.h"
#import "XMPPLogging.h"
#import "XMPPBlocking.h"
#import "NSNumber+XMPP.h"

// Log levels: off, error, warn, info, verbose
// Log flags: trace
#ifdef DEBUG
static const int xmppLogLevel = XMPP_LOG_LEVEL_VERBOSE; // | XMPP_LOG_FLAG_TRACE;
#else
static const int xmppLogLevel = XMPP_LOG_LEVEL_WARN;
#endif

#define QUERY_TIMEOUT 30.0 // NSTimeInterval (double) = seconds

NSString *const XMPPBlockingErrorDomain = @"XMPPBlockingErrorDomain";

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

typedef enum XMPPBlockingQueryInfoType {
    FetchBlockingList,
	BlockUser,
    UnblockUser,
    UnblockAll,
	
} XMPPBlockingQueryInfoType;

@interface XMPPBlockingQueryInfo : NSObject
{
	XMPPBlockingQueryInfoType type;
    XMPPJID *blockingXMPPJID;
	NSArray *blockingListItems;
	
	dispatch_source_t timer;
}

@property (nonatomic, readonly) XMPPBlockingQueryInfoType type;
@property (nonatomic, readonly) NSArray *blockingListItems;

@property (nonatomic, readwrite) XMPPJID *blockingXMPPJID;
@property (nonatomic, readwrite) dispatch_source_t timer;

- (void)cancel;

+ (XMPPBlockingQueryInfo *)queryInfoWithType:(XMPPBlockingQueryInfoType)type;
+ (XMPPBlockingQueryInfo *)queryInfoWithType:(XMPPBlockingQueryInfoType)type jid:(XMPPJID *)jid;
+ (XMPPBlockingQueryInfo *)queryInfoWithType:(XMPPBlockingQueryInfoType)type jid:(XMPPJID *)jid items:(NSArray *)items;

@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

@interface XMPPBlocking (/* Must be nameless for properties */)

- (void)addQueryInfo:(XMPPBlockingQueryInfo *)qi withKey:(NSString *)uuid;
- (void)queryTimeout:(NSString *)uuid;

@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

@implementation XMPPBlocking

@synthesize blockingDict = _blockingDict;

- (id)init
{
	return [self initWithDispatchQueue:NULL];
}

- (id)initWithDispatchQueue:(dispatch_queue_t)queue
{
	if ((self = [super initWithDispatchQueue:queue]))
	{
		autoRetrieveBlockingListItems = YES;
		autoClearBlockingListInfo     = YES;
		
		blockingDict = [[NSMutableDictionary alloc] init];
		
		pendingQueries = [[NSMutableDictionary alloc] init];
	}
	return self;
}

- (BOOL)activate:(XMPPStream *)aXmppStream
{
	if ([super activate:aXmppStream])
	{
		// Reserved for possible future use.
		
		return YES;
	}
	
	return NO;
}

- (void)deactivate
{
	// Reserved for possible future use.
	
	[super deactivate];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Properties
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (BOOL)autoRetrieveBlockingListItems
{
	if (dispatch_get_specific(moduleQueueTag))
	{
		return autoRetrieveBlockingListItems;
	}
	else
	{
		__block BOOL result;
		
		dispatch_sync(moduleQueue, ^{
			result = autoRetrieveBlockingListItems;
		});
		
		return result;
	}
}

- (void)setAutoRetrieveBlockingListItems:(BOOL)flag
{
	dispatch_block_t block = ^{
		
		autoRetrieveBlockingListItems = flag;
	};
	
	if (dispatch_get_specific(moduleQueueTag))
		block();
	else
		dispatch_async(moduleQueue, block);
}

- (BOOL)autoClearBlockingListInfo
{
	if (dispatch_get_specific(moduleQueueTag))
	{
		return autoClearBlockingListInfo;
	}
	else
	{
		__block BOOL result;
		
		dispatch_sync(moduleQueue, ^{
			result = autoClearBlockingListInfo;
		});
		
		return result;
	}
}

- (void)setAutoClearBlockingListInfo:(BOOL)flag
{
	dispatch_block_t block = ^{
		
		autoClearBlockingListInfo = flag;
	};
	
	if (dispatch_get_specific(moduleQueueTag))
		block();
	else
		dispatch_async(moduleQueue, block);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Public API
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)retrieveBlockingListItems
{
    XMPPLogTrace();
	
    // <iq type='get' id='blocklist1'>
    // <blocklist xmlns='urn:xmpp:blocking'/>
    // </iq>

    NSXMLElement *block = [NSXMLElement elementWithName:@"blocklist" xmlns:@"urn:xmpp:blocking"];

    NSString *uuid = [xmppStream generateUUID];
    XMPPIQ *iq = [XMPPIQ iqWithType:@"get" to:nil elementID:uuid child:block];
    
    [xmppStream sendElement:iq];
    
    XMPPBlockingQueryInfo *qi = [XMPPBlockingQueryInfo queryInfoWithType:FetchBlockingList];
	[self addQueryInfo:qi withKey:uuid];
}

- (void)clearBlockingListInfo
{
	XMPPLogTrace();
	
	if (dispatch_get_specific(moduleQueueTag))
	{
		[blockingDict removeAllObjects];
	}
	else
	{
		dispatch_async(moduleQueue, ^{ @autoreleasepool {
			
			[blockingDict removeAllObjects];
		}});
	}
}

- (NSArray*)blockingList
{
	if (dispatch_get_specific(moduleQueueTag))
	{
		return [blockingDict allKeys];
	}
	else
	{
		__block NSArray *result;
		
		dispatch_sync(moduleQueue, ^{ @autoreleasepool {
			
			result = [[blockingDict allKeys] copy];
		}});
		
		return result;
	}
}

- (void)blockJID:(XMPPJID*)xmppJID
{
    XMPPLogTrace();
    
    id value = blockingDict[[xmppJID full]];
    if (value == nil)
    {
        blockingDict[[xmppJID full]] = [NSNull null];
    }
    
    // <iq from='juliet@capulet.com/chamber' type='set' id='block1'>
    // <block xmlns='urn:xmpp:blocking'>
    // <item jid='romeo@montague.net'/>
    // </block>
    // </iq>
    
    NSXMLElement *block = [NSXMLElement elementWithName:@"block" xmlns:@"urn:xmpp:blocking"];
    NSXMLElement *item = [NSXMLElement elementWithName:@"item"];
    [item addAttributeWithName:@"jid" stringValue:[xmppJID full]];
    [block addChild:item];
    
    NSString *uuid = [xmppStream generateUUID];
    XMPPIQ *iq = [XMPPIQ iqWithType:@"set" to:nil elementID:uuid child:block];
    [iq addAttributeWithName:@"from" stringValue:xmppStream.myJID.bare];
    
    [xmppStream sendElement:iq];
    
    XMPPBlockingQueryInfo *qi = [XMPPBlockingQueryInfo queryInfoWithType:BlockUser];
    qi.blockingXMPPJID = xmppJID;
    [self addQueryInfo:qi withKey:uuid];
}

- (void)unblockJID:(XMPPJID*)xmppJID
{
    XMPPLogTrace();
    
    id value = blockingDict[[xmppJID full]];
    if (value != nil)
    {
        [blockingDict removeObjectForKey:[xmppJID full]];
    }
    
    // <iq type='set' id='unblock1'>
    // <unblock xmlns='urn:xmpp:blocking'>
    // <item jid='romeo@montague.net'/>
    // </unblock>
    // </iq>
    
    NSXMLElement *block = [NSXMLElement elementWithName:@"unblock" xmlns:@"urn:xmpp:blocking"];
    NSXMLElement *item = [NSXMLElement elementWithName:@"item"];
    [item addAttributeWithName:@"jid" stringValue:[xmppJID full]];
    [block addChild:item];
    
    NSString *uuid = [xmppStream generateUUID];
    XMPPIQ *iq = [XMPPIQ iqWithType:@"set" to:nil elementID:uuid child:block];
    
    [xmppStream sendElement:iq];
    
    XMPPBlockingQueryInfo *qi = [XMPPBlockingQueryInfo queryInfoWithType:UnblockUser];
    qi.blockingXMPPJID = xmppJID;
	[self addQueryInfo:qi withKey:uuid];
}

- (BOOL)containsJID:(XMPPJID*)xmppJID
{
    if (blockingDict[[xmppJID full]])
    {
        return true;
    }
    return false;
}

/**
 * Unblock all.
 */
- (void)unblockAll
{
    XMPPLogTrace();
    
    // <iq type='set' id='unblock2'>
    // <unblock xmlns='urn:xmpp:blocking'/>
    // </iq>

     NSXMLElement *block = [NSXMLElement elementWithName:@"unblock" xmlns:@"urn:xmpp:blocking"];
    
    NSString *uuid = [xmppStream generateUUID];
    XMPPIQ *iq = [XMPPIQ iqWithType:@"set" to:nil elementID:uuid child:block];
    
    [xmppStream sendElement:iq];
    
    XMPPBlockingQueryInfo *qi = [XMPPBlockingQueryInfo queryInfoWithType:UnblockAll];
	[self addQueryInfo:qi withKey:uuid];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Query Processing
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)addQueryInfo:(XMPPBlockingQueryInfo *)queryInfo withKey:(NSString *)uuid
{
	// Setup timer
	
	dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, moduleQueue);
	
	dispatch_source_set_event_handler(timer, ^{ @autoreleasepool {
		
		[self queryTimeout:uuid];
	}});
	
	dispatch_time_t fireTime = dispatch_time(DISPATCH_TIME_NOW, (QUERY_TIMEOUT * NSEC_PER_SEC));
	
	dispatch_source_set_timer(timer, fireTime, DISPATCH_TIME_FOREVER, 1.0);
	dispatch_resume(timer);
	
	queryInfo.timer = timer;
	
	// Add to dictionary
	pendingQueries[uuid] = queryInfo;
}

- (void)removeQueryInfo:(XMPPBlockingQueryInfo *)queryInfo withKey:(NSString *)uuid
{
	// Invalidate timer
	[queryInfo cancel];
	
	// Remove from dictionary
	[pendingQueries removeObjectForKey:uuid];
}

- (void)processQuery:(XMPPBlockingQueryInfo *)queryInfo withFailureCode:(XMPPBlockingErrorCode)errorCode
{
	NSError *error = [NSError errorWithDomain:XMPPBlockingErrorDomain code:errorCode userInfo:nil];
    
	if (queryInfo.type == FetchBlockingList)
	{
		[multicastDelegate xmppBlocking:self didNotReceivedBlockingListDueToError:error];
	}
	else if (queryInfo.type == BlockUser)
	{
		[multicastDelegate xmppBlocking:self didNotBlockJID:queryInfo.blockingXMPPJID error:error];
	}
	else if (queryInfo.type == UnblockUser)
	{
		[multicastDelegate xmppBlocking:self didNotUnblockJID:queryInfo.blockingXMPPJID error:error];
	}
    else if (queryInfo.type == UnblockAll)
    {
        [multicastDelegate xmppBlocking:self didNotUnblockAllDueToError:error];
    }
}

- (void)queryTimeout:(NSString *)uuid
{
	XMPPBlockingQueryInfo *queryInfo = pendingQueries[uuid];
	if (queryInfo)
	{
		[self processQuery:queryInfo withFailureCode:XMPPBlockingQueryTimeout];
		[self removeQueryInfo:queryInfo withKey:uuid];
	}
}

- (void)processQueryResponse:(XMPPIQ *)iq withInfo:(XMPPBlockingQueryInfo *)queryInfo
{
	if (queryInfo.type == FetchBlockingList)
	{
        // Blocking List Query Response:
        //
        // <iq type='result' id='blocklist1'>
        // <blocklist xmlns='urn:xmpp:blocking'>
        // <item jid='romeo@montague.net'/>
        // <item jid='iago@shakespeare.lit'/>
        // </blocklist>
        // </iq>

		if ([[iq type] isEqualToString:@"result"])
		{
			NSXMLElement *blocklist = [iq elementForName:@"blocklist" xmlns:@"urn:xmpp:blocking"];
			if (blocklist == nil) return;

			NSArray *listItems = [blocklist elementsForName:@"item"];
			for (NSXMLElement *listItem in listItems)
			{
				NSString *name = [listItem attributeStringValueForName:@"jid"];
				if (name)
				{
					id value = blockingDict[name];
					if (value == nil)
					{
						blockingDict[name] = [NSNull null];
					}
				}
			}

			[multicastDelegate xmppBlocking:self didReceivedBlockingList:[self blockingList]];
            [self removeQueryInfo:queryInfo withKey:[iq elementID]];
		}
		else
		{
			[multicastDelegate xmppBlocking:self didNotReceivedBlockingListDueToError:iq];
		}
	}
    else if (queryInfo.type == BlockUser)
    {
        // <iq type='result' id='block1'/>
    
        if ([[iq type] isEqualToString:@"result"])
		{
            [self removeQueryInfo:queryInfo withKey:[iq elementID]];
            [multicastDelegate xmppBlocking:self didBlockJID:queryInfo.blockingXMPPJID];
        }
        else
        {
            [blockingDict removeObjectForKey:[queryInfo.blockingXMPPJID full]];
            [multicastDelegate xmppBlocking:self didNotBlockJID:queryInfo.blockingXMPPJID error:iq];
        }
    }
    else if (queryInfo.type == UnblockUser)
    {
        // <iq type='result' id='unblock1'/>
        
        if ([[iq type] isEqualToString:@"result"])
		{
             [self removeQueryInfo:queryInfo withKey:[iq elementID]];
            [multicastDelegate xmppBlocking:self didUnblockJID:queryInfo.blockingXMPPJID];
        }
        else
        {
            XMPPBlockingQueryInfo *queryInfo = pendingQueries[[iq elementID]];
            
            id value = blockingDict[[queryInfo.blockingXMPPJID full]];
            if (value == nil)
            {
                blockingDict[[queryInfo.blockingXMPPJID full]] = [NSNull null];
            }
            
            [multicastDelegate xmppBlocking:self didNotBlockJID:queryInfo.blockingXMPPJID error:iq];
        }
    }
    else if (queryInfo.type == UnblockAll)
    {
        // <iq type='result' id='unblock2'/>
        
        if ([[iq type] isEqualToString:@"result"])
		{
            [self removeQueryInfo:queryInfo withKey:[iq elementID]];
            [multicastDelegate xmppBlocking:self didUnblockAllWithError:nil];
        }
        else
        {
            XMPPBlockingQueryInfo *queryInfo = pendingQueries[[iq elementID]];
            
            id value = blockingDict[[queryInfo.blockingXMPPJID full]];
            if (value == nil)
            {
                blockingDict[queryInfo.blockingXMPPJID] = [NSNull null];
            }
            
            [multicastDelegate xmppBlocking:self didNotUnblockAllDueToError:iq];
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark XMPPStream Delegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
	if (self.autoRetrieveBlockingListItems)
	{
		[self retrieveBlockingListItems];
	}
}

- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
	NSString *type = [iq type];
	
	if ([type isEqualToString:@"set"])
	{
		NSXMLElement *block = [iq elementForName:@"block" xmlns:@"urn:xmpp:blocking"];
        NSXMLElement *unblock = [iq elementForName:@"unblock" xmlns:@"urn:xmpp:blocking"];

		if (block || unblock)
		{
            NSXMLElement *list = [block elementForName:@"item"];
            
            if (!list)
            {
                list = [unblock elementForName:@"item"];
            }
            
            NSString *itemName = [list attributeStringValueForName:@"jid"];
			if (itemName == nil)
			{
				return NO;
			}
            
            [multicastDelegate xmppBlocking:self didReceivePushWithBlockingList:itemName];
			
			XMPPIQ *iqResponse = [XMPPIQ iqWithType:@"result" to:[iq from] elementID:[iq elementID]];
			[xmppStream sendElement:iqResponse];
			
			if (self.autoRetrieveBlockingListItems)
			{
				[self retrieveBlockingListItems];
			}
			
			return YES;
		}
	}
	else
	{
		// This may be a response to a query we sent
		
		XMPPBlockingQueryInfo *queryInfo = pendingQueries[[iq elementID]];

        
		if (queryInfo)
		{
			[self processQueryResponse:iq withInfo:queryInfo];

			return YES;
		}
	}
	
	return NO;
}

-(void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
	// If there are any pending queries,
	// they just failed due to the disconnection.
	
	for (NSString *uuid in pendingQueries)
	{
		XMPPBlockingQueryInfo *queryInfo = pendingQueries[uuid];
		
		[self processQuery:queryInfo withFailureCode:XMPPBlockingDisconnect];
	}
	
	// Clear the list of pending queries
	
	[pendingQueries removeAllObjects];
	
	// Maybe clear all stored blocking info
	
	if (self.autoClearBlockingListInfo)
	{
		[self clearBlockingListInfo];
	}
}

@end

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

@implementation XMPPBlockingQueryInfo

@synthesize type;
@synthesize blockingXMPPJID;
@synthesize blockingListItems;
@synthesize timer;

- (id)initWithType:(XMPPBlockingQueryInfoType)aType jid:(XMPPJID *)jid items:(NSArray *)items
{
	if ((self = [super init]))
	{
		type = aType;
		blockingXMPPJID = [jid copy];
		blockingListItems = [items copy];
	}
	return self;
}

- (void)cancel
{
	if (timer)
	{
		dispatch_source_cancel(timer);
#if !OS_OBJECT_USE_OBJC
		dispatch_release(timer);
#endif
		timer = NULL;
	}
}

- (void)dealloc
{
	[self cancel];
}

+ (XMPPBlockingQueryInfo *)queryInfoWithType:(XMPPBlockingQueryInfoType)type
{
	return [self queryInfoWithType:type jid:nil items:nil];
}

+ (XMPPBlockingQueryInfo *)queryInfoWithType:(XMPPBlockingQueryInfoType)type jid:(XMPPJID *)jid
{
	return [self queryInfoWithType:type jid:jid items:nil];
}

+ (XMPPBlockingQueryInfo *)queryInfoWithType:(XMPPBlockingQueryInfoType)type jid:(XMPPJID *)jid items:(NSArray *)items
{
	return [[XMPPBlockingQueryInfo alloc] initWithType:type jid:jid items:items];
}

@end