Skip to content
This repository
tree: ff9733ac39
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 580 lines (477 sloc) 14.05 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
//
// MGTwitterYAJLParser.m
// MGTwitterEngine
//
// Created by Matt Gemmell on 18/02/2008.
// Copyright 2008 Instinctive Code.

#import "MGTwitterYAJLParser.h"


@implementation MGTwitterYAJLParser

#pragma mark Callbacks

static NSString *currentKey;

int process_yajl_null(void *ctx)
{
id self = ctx;

if (currentKey)
{
[self addValue:[NSNull null] forKey:currentKey];
}

    return 1;
}

int process_yajl_boolean(void * ctx, int boolVal)
{
id self = ctx;

if (currentKey)
{
[self addValue:[NSNumber numberWithBool:(BOOL)boolVal] forKey:currentKey];

[currentKey release];
currentKey = nil;
}

    return 1;
}

int process_yajl_integer(void *ctx, long integerVal)
{
id self = ctx;

  if (currentKey)
{
[self addValue:[NSNumber numberWithLong:integerVal] forKey:currentKey];

[currentKey release];
currentKey = nil;
}

    return 1;
}

int process_yajl_double(void *ctx, double doubleVal)
{
id self = ctx;

  if (currentKey)
{
[self addValue:[NSNumber numberWithDouble:doubleVal] forKey:currentKey];

[currentKey release];
currentKey = nil;
}

   return 1;
}

int process_yajl_string(void *ctx, const unsigned char * stringVal, unsigned int stringLen)
{
id self = ctx;

if (currentKey)
{
NSString *value = [[[NSString alloc] initWithBytes:stringVal length:stringLen encoding:NSUTF8StringEncoding] autorelease];

if ([currentKey isEqualToString:@"created_at"])
{
// we have a priori knowledge that the value is a date, not a string
struct tm theTime;
strptime([value UTF8String], "%a %b %d %H:%M:%S +0000 %Y", &theTime);
time_t epochTime = timegm(&theTime);
[self addValue:[NSDate dateWithTimeIntervalSince1970:epochTime] forKey:currentKey];
}
else
{
[self addValue:value forKey:currentKey];
}

[currentKey release];
currentKey = nil;
}

    return 1;
}

int process_yajl_map_key(void *ctx, const unsigned char * stringVal, unsigned int stringLen)
{
if (currentKey)
{
[currentKey release];
currentKey = nil;
}

currentKey = [[NSString alloc] initWithBytes:stringVal length:stringLen encoding:NSUTF8StringEncoding];

    return 1;
}

int process_yajl_start_map(void *ctx)
{
id self = ctx;

[self startDictionaryWithKey:currentKey];

return 1;
}


int process_yajl_end_map(void *ctx)
{
id self = ctx;

[self endDictionary];

return 1;
}

int process_yajl_start_array(void *ctx)
{
id self = ctx;

[self startArrayWithKey:currentKey];

    return 1;
}

int process_yajl_end_array(void *ctx)
{
id self = ctx;

[self endArray];

    return 1;
}

static yajl_callbacks callbacks = {
    process_yajl_null,
    process_yajl_boolean,
    process_yajl_integer,
    process_yajl_double,
    NULL,
    process_yajl_string,
    process_yajl_start_map,
    process_yajl_map_key,
    process_yajl_end_map,
    process_yajl_start_array,
    process_yajl_end_array
};

#pragma mark Creation and Destruction


+ (id)parserWithJSON:(NSData *)theJSON delegate:(NSObject *)theDelegate
connectionIdentifier:(NSString *)identifier requestType:(MGTwitterRequestType)reqType
responseType:(MGTwitterResponseType)respType URL:(NSURL *)URL
{
id parser = [[self alloc] initWithJSON:theJSON
delegate:theDelegate
connectionIdentifier:identifier
requestType:reqType
responseType:respType
URL:URL];

return [parser autorelease];
}


- (id)initWithJSON:(NSData *)theJSON delegate:(NSObject *)theDelegate
connectionIdentifier:(NSString *)theIdentifier requestType:(MGTwitterRequestType)reqType
responseType:(MGTwitterResponseType)respType URL:(NSURL *)theURL
{
if (self = [super init])
{
json = [theJSON retain];
identifier = [theIdentifier retain];
requestType = reqType;
responseType = respType;
URL = [theURL retain];
delegate = theDelegate;
parsedObjects = [[NSMutableArray alloc] initWithCapacity:0];

// this is a hack for the API methods that just return "true" or "false" and can't be parsed by YAJL
if ([json length] <= 5)
{
NSString *result = [[[NSString alloc] initWithBytes:[json bytes] length:[json length] encoding:NSUTF8StringEncoding] autorelease];
NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc] initWithCapacity:1] autorelease];
[dictionary setObject:[NSNumber numberWithBool:[result isEqualToString:@"true"]] forKey:@"result"];
[parsedObjects addObject:dictionary];
}
else
{
// setup the yajl parser
yajl_parser_config cfg = {
0, // allowComments: if nonzero, javascript style comments will be allowed in the input (both /* */ and //)
1 // checkUTF8: if nonzero, invalid UTF8 strings will cause a parse error
};
_handle = yajl_alloc(&callbacks, &cfg, self);
if (! _handle)
{
return nil;
}

// run the parser and create parsedObjects
//[self parse];

yajl_status status = yajl_parse(_handle, [json bytes], [json length]);
if (status != yajl_status_insufficient_data && status != yajl_status_ok)
{
unsigned char *errorMessage = yajl_get_error(_handle, 0, [json bytes], [json length]);
NSLog(@"MGTwitterYAJLParser: error = %s", errorMessage);
yajl_free_error(errorMessage);
}

// free the yajl parser
yajl_free(_handle);
}

// notify the delegate that parsing completed
[self _parsingDidEnd];
}

return self;
}


- (void)dealloc
{
[parsedObjects release];
[json release];
[identifier release];
[URL release];

delegate = nil;
[super dealloc];
}

- (void)parse
{
// empty implementation -- override in subclasses
}

#pragma mark Subclass utilities

- (void)addValue:(id)value forKey:(NSString *)key
{
// default implementation -- override in subclasses

NSLog(@"%@ = %@ (%@)", key, value, NSStringFromClass([value class]));
}

- (void)startDictionaryWithKey:(NSString *)key
{
// default implementation -- override in subclasses

NSLog(@"dictionary start = %@", key);
}

- (void)endDictionary
{
// default implementation -- override in subclasses

NSLog(@"dictionary end");
}

- (void)startArrayWithKey:(NSString *)key
{
// default implementation -- override in subclasses

NSLog(@"array start = %@", key);
}

- (void)endArray
{
// default implementation -- override in subclasses

NSLog(@"array end");
}


/*
// get the value from the current node
- (xmlChar *)_nodeValue
{
if (xmlTextReaderIsEmptyElement(_reader))
{
return nil;
}

xmlChar *result = nil;
int nodeType = xmlTextReaderNodeType(_reader);
while (nodeType != XML_READER_TYPE_END_ELEMENT)
{
if (nodeType == XML_READER_TYPE_TEXT)
{
result = xmlTextReaderValue(_reader);
}
// advance reader
int readerResult = xmlTextReaderRead(_reader);
if (readerResult != 1)
{
break;
}
nodeType = xmlTextReaderNodeType(_reader);
}

//NSLog(@"node: %25s = %s", xmlTextReaderConstName(_reader), result);
return result;
}

- (NSString *)_nodeValueAsString
{
xmlChar *nodeValue = [self _nodeValue];
if (! nodeValue)
{
return nil;
}

NSMutableString *value = [NSMutableString stringWithUTF8String:(const char *)nodeValue];
xmlFree(nodeValue);
// convert HTML entities back into UTF-8
[value replaceOccurrencesOfString:@"&gt;" withString:@">" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [value length])];
[value replaceOccurrencesOfString:@"&lt;" withString:@"<" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [value length])];
NSString *result = [NSString stringWithString:value];
return result;
}

- (NSDate *)_nodeValueAsDate
{
xmlChar *nodeValue = [self _nodeValue];
if (! nodeValue)
{
return nil;
}

struct tm theTime;
strptime((char *)nodeValue, "%a %b %d %H:%M:%S +0000 %Y", &theTime);
xmlFree(nodeValue);
time_t epochTime = timegm(&theTime);
return [NSDate dateWithTimeIntervalSince1970:epochTime];
}

- (NSNumber *)_nodeValueAsInt
{
xmlChar *nodeValue = [self _nodeValue];
if (! nodeValue)
{
return nil;
}

NSString *intString = [NSString stringWithUTF8String:(const char *)nodeValue];
xmlFree(nodeValue);
return [NSNumber numberWithInt:[intString intValue]];
}

- (NSNumber *)_nodeValueAsBool
{
xmlChar *nodeValue = [self _nodeValue];
if (! nodeValue)
{
return nil;
}

NSString *boolString = [NSString stringWithUTF8String:(const char *)nodeValue];
xmlFree(nodeValue);
return [NSNumber numberWithBool:[boolString isEqualToString:@"true"]];
}

- (NSDictionary *)_statusDictionaryForNodeWithName:(const xmlChar *)parentNodeName
{
if (xmlTextReaderIsEmptyElement(_reader))
return nil;
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

int readerResult = xmlTextReaderRead(_reader);
if (readerResult != 1)
return nil;
int nodeType = xmlTextReaderNodeType(_reader);
const xmlChar *name = xmlTextReaderConstName(_reader);
while (! (nodeType == XML_READER_TYPE_END_ELEMENT && xmlStrEqual(parentNodeName, name)))
{
if (nodeType == XML_READER_TYPE_ELEMENT)
{
if (xmlStrEqual(name, BAD_CAST "user"))
{
// "user" is the name of a sub-dictionary in each <status> item
[dictionary setObject:[self _userDictionaryForNodeWithName:name] forKey:@"user"];
}
else if (xmlStrEqual(name, BAD_CAST "id") || xmlStrEqual(name, BAD_CAST "in_reply_to_user_id") || xmlStrEqual(name, BAD_CAST "in_reply_to_status_id"))
{
// process element as an integer
NSNumber *number = [self _nodeValueAsInt];
if (number)
{
[dictionary setObject:number forKey:[NSString stringWithUTF8String:(const char *)name]];
}
}
else if (xmlStrEqual(name, BAD_CAST "created_at"))
{
// process element as a date
NSDate *date = [self _nodeValueAsDate];
if (date)
{
[dictionary setObject:date forKey:[NSString stringWithUTF8String:(const char *)name]];
}
}
else if (xmlStrEqual(name, BAD_CAST "truncated") || xmlStrEqual(name, BAD_CAST "favorited"))
{
// process element as a boolean
NSNumber *number = [self _nodeValueAsBool];
if (number)
{
[dictionary setObject:number forKey:[NSString stringWithUTF8String:(const char *)name]];
}
}
else
{
// process element as a string
NSString *string = [self _nodeValueAsString];
if (string)
{
[dictionary setObject:string forKey:[NSString stringWithUTF8String:(const char *)name]];
}
}
}

// advance reader
int readerResult = xmlTextReaderRead(_reader);
if (readerResult != 1)
break;
nodeType = xmlTextReaderNodeType(_reader);
name = xmlTextReaderConstName(_reader);
}

// save the request type in the tweet
[dictionary setObject:[NSNumber numberWithInt:requestType] forKey:TWITTER_SOURCE_REQUEST_TYPE];

return dictionary;
}

- (NSDictionary *)_userDictionaryForNodeWithName:(const xmlChar *)parentNodeName
{
if (xmlTextReaderIsEmptyElement(_reader))
return nil;
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

int readerResult = xmlTextReaderRead(_reader);
if (readerResult != 1)
return nil;
int nodeType = xmlTextReaderNodeType(_reader);
const xmlChar *name = xmlTextReaderConstName(_reader);
while (! (nodeType == XML_READER_TYPE_END_ELEMENT && xmlStrEqual(parentNodeName, name)))
{
if (nodeType == XML_READER_TYPE_ELEMENT)
{
if (xmlStrEqual(name, BAD_CAST "id") || xmlStrEqual(name, BAD_CAST "followers_count")
|| xmlStrEqual(name, BAD_CAST "friends_count") || xmlStrEqual(name, BAD_CAST "favourites_count")
|| xmlStrEqual(name, BAD_CAST "statuses_count"))
{
// process element as an integer
NSNumber *number = [self _nodeValueAsInt];
if (number)
{
[dictionary setObject:number forKey:[NSString stringWithUTF8String:(const char *)name]];
}
}
else if (xmlStrEqual(name, BAD_CAST "protected"))
{
// process element as a boolean
NSNumber *number = [self _nodeValueAsBool];
if (number)
{
[dictionary setObject:number forKey:[NSString stringWithUTF8String:(const char *)name]];
}
}
else
{
// process element as a string
NSString *s = [self _nodeValueAsString];
if (s)
{
[dictionary setObject:s forKey:[NSString stringWithUTF8String:(const char *)name]];
}
}
}

// advance reader
int readerResult = xmlTextReaderRead(_reader);
if (readerResult != 1)
break;
nodeType = xmlTextReaderNodeType(_reader);
name = xmlTextReaderConstName(_reader);
}

return dictionary;
}

- (NSDictionary *)_hashDictionaryForNodeWithName:(const xmlChar *)parentNodeName
{
if (xmlTextReaderIsEmptyElement(_reader))
return nil;
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];

int readerResult = xmlTextReaderRead(_reader);
if (readerResult != 1)
return nil;
int nodeType = xmlTextReaderNodeType(_reader);
const xmlChar *name = xmlTextReaderConstName(_reader);
while (! (nodeType == XML_READER_TYPE_END_ELEMENT && xmlStrEqual(parentNodeName, name)))
{
if (nodeType == XML_READER_TYPE_ELEMENT)
{
if (xmlStrEqual(name, BAD_CAST "hourly-limit") || xmlStrEqual(name, BAD_CAST "remaining-hits")
|| xmlStrEqual(name, BAD_CAST "reset-time-in-seconds"))
{
// process element as an integer
NSNumber *number = [self _nodeValueAsInt];
if (number)
{
[dictionary setObject:number forKey:[NSString stringWithUTF8String:(const char *)name]];
}
}
else
{
// process element as a string
NSString *s = [self _nodeValueAsString];
if (s)
{
[dictionary setObject:s forKey:[NSString stringWithUTF8String:(const char *)name]];
}
}
}

// advance reader
int readerResult = xmlTextReaderRead(_reader);
if (readerResult != 1)
break;
nodeType = xmlTextReaderNodeType(_reader);
name = xmlTextReaderConstName(_reader);
}

return dictionary;
}
*/

#pragma mark Delegate callbacks

- (void)_parsingDidEnd
{
    //NSLog(@"Parsing complete: %@", parsedObjects);
    [delegate parsingSucceededForRequest:identifier ofResponseType:responseType withParsedObjects:parsedObjects];
}

- (void)_parsingErrorOccurred:(NSError *)parseError
{
//NSLog(@"Parsing error occurred: %@", parseError);
[delegate parsingFailedForRequest:identifier ofResponseType:responseType withError:parseError];
}

@end
Something went wrong with that request. Please try again.