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 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /*
  2. * Reddit.m
  3. *
  4. * Copyright (c) 2013, Thomas Buck <xythobuz@xythobuz.de>
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. *
  10. * - Redistributions of source code must retain the above copyright notice,
  11. * this list of conditions and the following disclaimer.
  12. *
  13. * - Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in the
  15. * documentation and/or other materials provided with the distribution.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  19. * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  20. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
  21. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  22. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  23. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  24. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  25. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  26. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. #import "Reddit.h"
  30. #import "AppDelegate.h"
  31. @implementation Reddit
  32. NSString *replaceTextForTitle = @"...";
  33. NSString *subredditFormat = @" [r/%@]";
  34. #define AUTHOR @"xythobuz"
  35. @synthesize username, modhash, password, version, appName, author, length, subreddits, titleLength;
  36. -(id)initWithUsername:(NSString *)name Modhash:(NSString *)hash Length:(NSInteger)leng TitleLength:(NSInteger)title {
  37. self = [super init];
  38. if (self) {
  39. username = name;
  40. modhash = hash;
  41. password = nil;
  42. length = leng;
  43. version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
  44. appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  45. author = AUTHOR;
  46. titleLength = title;
  47. }
  48. return self;
  49. }
  50. -(id)initWithUsername:(NSString *)name Password:(NSString *)pass {
  51. self = [super init];
  52. if (self) {
  53. username = name;
  54. modhash = nil;
  55. password = pass;
  56. length = 0;
  57. version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
  58. appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  59. author = AUTHOR;
  60. titleLength = 66;
  61. }
  62. return self;
  63. }
  64. -(NSString *)queryModhash {
  65. NSMutableString *stringData = [NSMutableString stringWithString:@"api_type=json"];
  66. [stringData appendFormat:@"&user=%@", [self urlencode: username]];
  67. [stringData appendFormat:@"&passwd=%@", [self urlencode: password]];
  68. [stringData appendString:@"&rem=True"];
  69. NSHTTPURLResponse *response;
  70. NSData *data = [self queryAPI:@"api/login" withData:stringData andResponse:&response];
  71. if (data == nil) {
  72. return nil;
  73. } else {
  74. long code = [response statusCode];
  75. if (code == 200) {
  76. NSError *error;
  77. id object = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  78. if (error)
  79. return nil;
  80. if([object isKindOfClass:[NSDictionary class]]) {
  81. NSDictionary *results = object;
  82. NSDictionary *json = [results valueForKey:@"json"];
  83. if (json == nil)
  84. return nil;
  85. NSDictionary *data = [json valueForKey:@"data"];
  86. if (data == nil)
  87. return nil;
  88. return [data valueForKey:@"modhash"];
  89. } else {
  90. return nil;
  91. }
  92. } else {
  93. return nil;
  94. }
  95. }
  96. }
  97. -(NSArray *)convertJSONToItemArray:(NSData *)data ShowSubs:(Boolean)showSubs {
  98. NSError *error;
  99. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  100. NSDictionary *dat = [json valueForKey:@"data"];
  101. if (dat == nil)
  102. return nil;
  103. NSArray *children = [dat valueForKey:@"children"];
  104. if (children == nil)
  105. return nil;
  106. NSMutableArray *array = [NSMutableArray arrayWithCapacity:[children count]];
  107. for (NSUInteger i = 0; i < [children count]; i++) {
  108. NSDictionary *child = [children objectAtIndex:i];
  109. NSDictionary *current = [child valueForKey:@"data"];
  110. NSString *name = [current valueForKey:@"title"];
  111. NSString *link = [current valueForKey:@"url"];
  112. NSString *comments = nil;
  113. NSNumber *num = [current valueForKey:@"is_self"];
  114. BOOL isSelf = [num boolValue];
  115. if (!isSelf) {
  116. comments = [NSString stringWithFormat:@"http://www.reddit.com%@", [current valueForKey:@"permalink"]];
  117. }
  118. NSString *subreddit = [NSString stringWithFormat:subredditFormat, [current valueForKey:@"subreddit"]];
  119. NSInteger maxLen = titleLength;
  120. if ([subreddit length] >= titleLength)
  121. showSubs = FALSE;
  122. if (showSubs)
  123. maxLen -= [subreddit length];
  124. if ([name length] > maxLen)
  125. name = [NSString stringWithFormat:@"%@%@", [name substringToIndex:(maxLen - [replaceTextForTitle length])], replaceTextForTitle];
  126. if (showSubs)
  127. name = [NSString stringWithFormat:@"%@%@", name, subreddit];
  128. RedditItem *r = [RedditItem itemWithName:name Link:link Comments:comments Self:isSelf];
  129. NSString *fullName = [current valueForKey:@"title"];
  130. if (showSubs)
  131. fullName = [NSString stringWithFormat:@"%@%@", fullName, subreddit];
  132. [r setFullName:fullName];
  133. [array insertObject:r atIndex:i];
  134. if (i == ([children count] - 1)) {
  135. NSString *name = [NSString stringWithFormat:@"%@_%@", [child valueForKey:@"kind"], [current valueForKey:@"id"]];
  136. [array insertObject:name atIndex:i + 1];
  137. }
  138. }
  139. return array;
  140. }
  141. -(void)readFrontpage:(id)parent {
  142. NSHTTPURLResponse *response;
  143. NSString *after = ((AppDelegate *)parent).lastFullName;
  144. Boolean showSubreddits = ((AppDelegate *)parent).currentState.showSubreddit;
  145. NSString *url;
  146. if (after == nil)
  147. url = [NSString stringWithFormat:@"hot.json?limit=%ld", (long)length];
  148. else
  149. url = [NSString stringWithFormat:@"hot.json?limit=%ld&after=%@", (long)length, after];
  150. NSData *data = [self queryAPI:url withResponse:&response];
  151. if ((data == nil) || ([response statusCode] != 200)) {
  152. [parent performSelectorOnMainThread:@selector(reloadListHasFrontpageCallback:) withObject:nil waitUntilDone:false];
  153. } else {
  154. [parent performSelectorOnMainThread:@selector(reloadListHasFrontpageCallback:) withObject:[self convertJSONToItemArray:data ShowSubs:showSubreddits] waitUntilDone:false];
  155. }
  156. }
  157. -(void)readSubreddits:(id)parent {
  158. NSMutableString *subs = [NSMutableString stringWithString:@"r/"];
  159. for (NSUInteger i = 0; i < [subreddits count]; i++) {
  160. [subs appendString:[subreddits objectAtIndex:i]];
  161. if (i < ([subreddits count] - 1)) {
  162. [subs appendString:@"+"];
  163. }
  164. }
  165. NSString *after = ((AppDelegate *)parent).lastFullName;
  166. Boolean showSubreddits = ((AppDelegate *)parent).currentState.showSubreddit;
  167. NSString *url;
  168. if (after == nil)
  169. url = [NSString stringWithFormat:@"%@/hot.json?limit=%ld", subs, (long)length];
  170. else
  171. url = [NSString stringWithFormat:@"%@/hot.json?limit=%ld&after=%@", subs, (long)length, after];
  172. NSHTTPURLResponse *response;
  173. NSData *data = [self queryAPI:url withResponse:&response];
  174. if ((data == nil) || ([response statusCode] != 200)) {
  175. [parent performSelectorOnMainThread:@selector(reloadListHasSubredditsCallback:) withObject:nil waitUntilDone:false];
  176. } else {
  177. [parent performSelectorOnMainThread:@selector(reloadListHasSubredditsCallback:) withObject:[self convertJSONToItemArray:data ShowSubs:showSubreddits] waitUntilDone:false];
  178. }
  179. }
  180. -(void)isAuthenticatedNewModhash:(id)parent {
  181. NSHTTPURLResponse *response;
  182. NSData *dat = [self queryAPI:@"api/me.json" withResponse:&response];
  183. if ((dat != nil) && ([response statusCode] == 200)) {
  184. NSError *error;
  185. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:dat options:0 error:&error];
  186. NSDictionary *data = [json valueForKey:@"data"];
  187. if (data == nil) {
  188. NSLog(@"Error loading me.json: not logged in!\n");
  189. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  190. return;
  191. }
  192. NSString *newHash = [data valueForKey:@"modhash"];
  193. if ((newHash == nil) || ([newHash isEqualToString:@""])) {
  194. NSLog(@"Error interpreting me.json: did not receive modhash!\n");
  195. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  196. return;
  197. }
  198. if (![newHash isEqualToString:modhash]) {
  199. modhash = newHash;
  200. }
  201. [parent performSelectorOnMainThread:@selector(reloadListIsAuthenticatedCallback) withObject:nil waitUntilDone:false];
  202. return;
  203. }
  204. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  205. }
  206. -(NSData *)queryAPI:(NSString *)api withResponse:(NSHTTPURLResponse **)res {
  207. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self getAPIPoint:api]];
  208. [request setTimeoutInterval:5.0];
  209. [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
  210. [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
  211. [request setValue:[NSString stringWithFormat:@"%@/%@ by %@", appName, version, author] forHTTPHeaderField:@"User-Agent"];
  212. if ((modhash != nil) && (![modhash isEqualToString:@""]))
  213. [request addValue:modhash forHTTPHeaderField:@"X-Modhash"];
  214. [request setHTTPMethod:@"GET"];
  215. NSError *error = nil;
  216. NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:res error:&error];
  217. if (error)
  218. return nil;
  219. return data;
  220. }
  221. -(NSData *)queryAPI:(NSString *)api withData:(NSString *)string andResponse:(NSHTTPURLResponse **)res {
  222. NSData *requestBodyData = [string dataUsingEncoding:NSUTF8StringEncoding];
  223. NSString *requestBodyLength = [NSString stringWithFormat:@"%lu", (unsigned long)[requestBodyData length]];
  224. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self getAPIPoint:api]];
  225. [request setTimeoutInterval:5.0];
  226. [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
  227. [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
  228. [request setValue:requestBodyLength forHTTPHeaderField:@"Content-Length"];
  229. [request setValue:[NSString stringWithFormat:@"%@/%@ by %@", appName, version, author] forHTTPHeaderField:@"User-Agent"];
  230. if ((modhash != nil) && (![modhash isEqualToString:@""]))
  231. [request addValue:modhash forHTTPHeaderField:@"X-Modhash"];
  232. [request setHTTPMethod:@"POST"];
  233. [request setHTTPBody:requestBodyData];
  234. NSError *error = nil;
  235. NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:res error:&error];
  236. if (error)
  237. return nil;
  238. return data;
  239. }
  240. -(NSURL *)getAPIPoint:(NSString *)where {
  241. return [NSURL URLWithString:[NSString stringWithFormat:@"https://ssl.reddit.com/%@", where]];
  242. }
  243. -(NSString *)urlencode:(NSString *)string {
  244. NSMutableString *output = [NSMutableString string];
  245. const unsigned char *source = (const unsigned char *)[string UTF8String];
  246. long sourceLen = strlen((const char *)source);
  247. for (int i = 0; i < sourceLen; i++) {
  248. const unsigned char thisChar = source[i];
  249. if (thisChar == ' '){
  250. [output appendString:@"+"];
  251. } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
  252. (thisChar >= 'a' && thisChar <= 'z') ||
  253. (thisChar >= 'A' && thisChar <= 'Z') ||
  254. (thisChar >= '0' && thisChar <= '9')) {
  255. [output appendFormat:@"%c", thisChar];
  256. } else {
  257. [output appendFormat:@"%%%02X", thisChar];
  258. }
  259. }
  260. return output;
  261. }
  262. @end