aka RedditBar, Mac OS X menu bar reddit client
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Reddit.m 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. //
  2. // Reddit.m
  3. // RedditBar
  4. //
  5. // Created by Thomas Buck on 01.12.13.
  6. // Copyright (c) 2013 xythobuz. All rights reserved.
  7. //
  8. #import "Reddit.h"
  9. #import "AppDelegate.h"
  10. @implementation Reddit
  11. NSString *version = @"1.0.0";
  12. NSString *author = @"xythobuz";
  13. NSString *appName = @"RedditBar";
  14. NSInteger maxTitleLength = 50;
  15. NSString *replaceTextForTitle = @"...";
  16. @synthesize username, modhash, password, length, subreddits;
  17. -(id)initWithUsername:(NSString *)name Modhash:(NSString *)hash Length:(NSInteger)leng {
  18. self = [super init];
  19. if (self) {
  20. username = name;
  21. modhash = hash;
  22. password = nil;
  23. length = leng;
  24. }
  25. return self;
  26. }
  27. -(id)initWithUsername:(NSString *)name Password:(NSString *)pass {
  28. self = [super init];
  29. if (self) {
  30. username = name;
  31. modhash = nil;
  32. password = pass;
  33. }
  34. return self;
  35. }
  36. -(NSString *)queryModhash {
  37. NSMutableString *stringData = [NSMutableString stringWithString:@"api_type=json"];
  38. [stringData appendFormat:@"&user=%@", [self urlencode: username]];
  39. [stringData appendFormat:@"&passwd=%@", [self urlencode: password]];
  40. [stringData appendString:@"&rem=True"];
  41. NSHTTPURLResponse *response;
  42. NSData *data = [self queryAPI:@"api/login" withData:stringData andResponse:&response];
  43. if (data == nil) {
  44. return nil;
  45. } else {
  46. long code = [response statusCode];
  47. if (code == 200) {
  48. NSError *error;
  49. id object = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  50. if (error)
  51. return nil;
  52. if([object isKindOfClass:[NSDictionary class]]) {
  53. NSDictionary *results = object;
  54. NSDictionary *json = [results valueForKey:@"json"];
  55. if (json == nil)
  56. return nil;
  57. NSDictionary *data = [json valueForKey:@"data"];
  58. if (data == nil)
  59. return nil;
  60. return [data valueForKey:@"modhash"];
  61. } else {
  62. return nil;
  63. }
  64. } else {
  65. return nil;
  66. }
  67. }
  68. }
  69. -(NSArray *)convertJSONToItemArray:(NSData *)data {
  70. NSError *error;
  71. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  72. NSDictionary *dat = [json valueForKey:@"data"];
  73. if (dat == nil)
  74. return nil;
  75. NSArray *children = [dat valueForKey:@"children"];
  76. if (children == nil)
  77. return nil;
  78. NSMutableArray *array = [NSMutableArray arrayWithCapacity:[children count]];
  79. for (NSUInteger i = 0; i < [children count]; i++) {
  80. NSDictionary *child = [children objectAtIndex:i];
  81. NSDictionary *current = [child valueForKey:@"data"];
  82. NSString *name = [current valueForKey:@"title"];
  83. NSString *link = [current valueForKey:@"url"];
  84. NSString *comments = nil;
  85. NSNumber *num = [current valueForKey:@"is_self"];
  86. BOOL isSelf = [num boolValue];
  87. if (!isSelf) {
  88. comments = [NSString stringWithFormat:@"http://www.reddit.com%@", [current valueForKey:@"permalink"]];
  89. }
  90. if ([name length] > maxTitleLength) {
  91. name = [NSString stringWithFormat:@"%@%@", [name substringToIndex:(maxTitleLength - [replaceTextForTitle length])], replaceTextForTitle];
  92. }
  93. RedditItem *r = [RedditItem itemWithName:name Link:link Comments:comments Self:isSelf];
  94. [r setFullName:[current valueForKey:@"title"]];
  95. [array insertObject:r atIndex:i];
  96. }
  97. return array;
  98. }
  99. -(void)readFrontpage:(id)parent {
  100. NSHTTPURLResponse *response;
  101. NSString *url = [NSString stringWithFormat:@"hot.json?limit=%ld", (long)length];
  102. NSData *data = [self queryAPI:url withResponse:&response];
  103. if ((data == nil) || ([response statusCode] != 200)) {
  104. [parent performSelectorOnMainThread:@selector(reloadListHasFrontpageCallback:) withObject:nil waitUntilDone:false];
  105. } else {
  106. [parent performSelectorOnMainThread:@selector(reloadListHasFrontpageCallback:) withObject:[self convertJSONToItemArray:data] waitUntilDone:false];
  107. }
  108. }
  109. -(void)readSubreddits:(id)parent {
  110. // TODO read subreddits (as multireddit?)
  111. // TODO if implemented, enable checkbox in prefs
  112. }
  113. -(void)isAuthenticatedNewModhash:(id)parent {
  114. NSHTTPURLResponse *response;
  115. NSData *data = [self queryAPI:@"api/me.json" withResponse:&response];
  116. if ((data != nil) && ([response statusCode] == 200)) {
  117. NSError *error;
  118. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  119. NSDictionary *data = [json valueForKey:@"data"];
  120. if (data == nil) {
  121. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  122. return;
  123. }
  124. NSString *newHash = [data valueForKey:@"modhash"];
  125. if ((newHash == nil) || ([newHash isEqualToString:@""])) {
  126. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  127. return;
  128. }
  129. if (![newHash isEqualToString:modhash]) {
  130. modhash = newHash;
  131. }
  132. [parent performSelectorOnMainThread:@selector(reloadListIsAuthenticatedCallback) withObject:nil waitUntilDone:false];
  133. return;
  134. }
  135. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  136. }
  137. -(NSData *)queryAPI:(NSString *)api withResponse:(NSHTTPURLResponse **)res {
  138. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self getAPIPoint:api]];
  139. [request setTimeoutInterval:5.0];
  140. [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
  141. [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
  142. [request setValue:[NSString stringWithFormat:@"%@/%@ by %@", appName, version, author] forHTTPHeaderField:@"User-Agent"];
  143. if ((modhash != nil) && (![modhash isEqualToString:@""]))
  144. [request addValue:modhash forHTTPHeaderField:@"X-Modhash"];
  145. [request setHTTPMethod:@"GET"];
  146. NSError *error = nil;
  147. NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:res error:&error];
  148. if (error)
  149. return nil;
  150. else
  151. return data;
  152. }
  153. -(NSData *)queryAPI:(NSString *)api withData:(NSString *)string andResponse:(NSHTTPURLResponse **)res {
  154. NSData *requestBodyData = [string dataUsingEncoding:NSUTF8StringEncoding];
  155. NSString *requestBodyLength = [NSString stringWithFormat:@"%lu", (unsigned long)[requestBodyData length]];
  156. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self getAPIPoint:api]];
  157. [request setTimeoutInterval:5.0];
  158. [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
  159. [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
  160. [request setValue:requestBodyLength forHTTPHeaderField:@"Content-Length"];
  161. [request setValue:[NSString stringWithFormat:@"%@/%@ by %@", appName, version, author] forHTTPHeaderField:@"User-Agent"];
  162. if ((modhash != nil) && (![modhash isEqualToString:@""]))
  163. [request addValue:modhash forHTTPHeaderField:@"X-Modhash"];
  164. [request setHTTPMethod:@"POST"];
  165. [request setHTTPBody:requestBodyData];
  166. NSError *error = nil;
  167. NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:res error:&error];
  168. if (error)
  169. return nil;
  170. else
  171. return data;
  172. }
  173. -(NSURL *)getAPIPoint:(NSString *)where {
  174. return [NSURL URLWithString:[NSString stringWithFormat:@"https://ssl.reddit.com/%@", where]];
  175. }
  176. -(NSString *)urlencode:(NSString *)string {
  177. NSMutableString *output = [NSMutableString string];
  178. const unsigned char *source = (const unsigned char *)[string UTF8String];
  179. long sourceLen = strlen((const char *)source);
  180. for (int i = 0; i < sourceLen; i++) {
  181. const unsigned char thisChar = source[i];
  182. if (thisChar == ' '){
  183. [output appendString:@"+"];
  184. } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
  185. (thisChar >= 'a' && thisChar <= 'z') ||
  186. (thisChar >= 'A' && thisChar <= 'Z') ||
  187. (thisChar >= '0' && thisChar <= '9')) {
  188. [output appendFormat:@"%c", thisChar];
  189. } else {
  190. [output appendFormat:@"%%%02X", thisChar];
  191. }
  192. }
  193. return output;
  194. }
  195. @end