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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. -(void)readFrontpage:(id)parent {
  98. NSHTTPURLResponse *response;
  99. NSString *after = ((AppDelegate *)parent).lastFullName;
  100. Boolean showSubreddits = ((AppDelegate *)parent).currentState.showSubreddit;
  101. NSString *where = ((AppDelegate *)parent).currentState.filter;
  102. NSString *url;
  103. if (after == nil)
  104. url = [NSString stringWithFormat:@"%@.json?limit=%ld", where, (long)length];
  105. else
  106. url = [NSString stringWithFormat:@"%@.json?limit=%ld&after=%@", where, (long)length, after];
  107. NSData *data = [self queryAPI:url withResponse:&response];
  108. if ((data == nil) || ([response statusCode] != 200)) {
  109. [parent performSelectorOnMainThread:@selector(reloadListHasFrontpageCallback:) withObject:nil waitUntilDone:false];
  110. } else {
  111. [parent performSelectorOnMainThread:@selector(reloadListHasFrontpageCallback:) withObject:[self convertJSONToItemArray:data ShowSubs:showSubreddits] waitUntilDone:false];
  112. }
  113. }
  114. -(void)readSubreddits:(id)parent {
  115. NSMutableString *subs = [NSMutableString stringWithString:@"r/"];
  116. for (NSUInteger i = 0; i < [subreddits count]; i++) {
  117. [subs appendString:[subreddits objectAtIndex:i]];
  118. if (i < ([subreddits count] - 1)) {
  119. [subs appendString:@"+"];
  120. }
  121. }
  122. NSString *after = ((AppDelegate *)parent).lastFullName;
  123. Boolean showSubreddits = ((AppDelegate *)parent).currentState.showSubreddit;
  124. NSString *where = ((AppDelegate *)parent).currentState.filter;
  125. NSString *url;
  126. if (after == nil)
  127. url = [NSString stringWithFormat:@"%@/%@.json?limit=%ld", subs, where, (long)length];
  128. else
  129. url = [NSString stringWithFormat:@"%@/%@.json?limit=%ld&after=%@", subs, where, (long)length, after];
  130. NSHTTPURLResponse *response;
  131. NSData *data = [self queryAPI:url withResponse:&response];
  132. if ((data == nil) || ([response statusCode] != 200)) {
  133. [(AppDelegate *)parent performSelectorOnMainThread:@selector(reloadListHasSubredditsCallback:) withObject:nil waitUntilDone:FALSE];
  134. } else {
  135. [(AppDelegate *)parent performSelectorOnMainThread:@selector(reloadListHasSubredditsCallback:) withObject:[self convertJSONToItemArray:data ShowSubs:showSubreddits] waitUntilDone:FALSE];
  136. }
  137. }
  138. -(NSArray *)convertJSONToItemArray:(NSData *)data ShowSubs:(Boolean)showSubs {
  139. NSError *error;
  140. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  141. NSDictionary *dat = [json valueForKey:@"data"];
  142. if (dat == nil)
  143. return nil;
  144. NSArray *children = [dat valueForKey:@"children"];
  145. if ((children == nil) || ([children count] == 0))
  146. return nil;
  147. NSMutableArray *array = [NSMutableArray arrayWithCapacity:[children count]];
  148. for (NSUInteger i = 0; i < [children count]; i++) {
  149. NSDictionary *child = [children objectAtIndex:i];
  150. NSDictionary *current = [child valueForKey:@"data"];
  151. NSString *name = [current valueForKey:@"title"];
  152. NSString *link = [current valueForKey:@"url"];
  153. NSString *comments = nil;
  154. NSNumber *num = [current valueForKey:@"is_self"];
  155. BOOL isSelf = [num boolValue];
  156. if (!isSelf) {
  157. comments = [NSString stringWithFormat:@"http://www.reddit.com%@", [current valueForKey:@"permalink"]];
  158. }
  159. NSString *subreddit = [NSString stringWithFormat:subredditFormat, [current valueForKey:@"subreddit"]];
  160. NSInteger maxLen = titleLength;
  161. if (titleLength == 0)
  162. maxLen = 1000; // Should be enough to not crop
  163. if ([subreddit length] >= maxLen)
  164. showSubs = FALSE;
  165. if (showSubs)
  166. maxLen -= [subreddit length];
  167. if ([name length] > maxLen)
  168. name = [NSString stringWithFormat:@"%@%@", [name substringToIndex:(maxLen - [replaceTextForTitle length])], replaceTextForTitle];
  169. if (showSubs)
  170. name = [NSString stringWithFormat:@"%@%@", name, subreddit];
  171. RedditItem *r = [RedditItem itemWithName:name Link:link Comments:comments Self:isSelf];
  172. NSString *fullName = [current valueForKey:@"title"];
  173. if (showSubs)
  174. fullName = [NSString stringWithFormat:@"%@%@", fullName, subreddit];
  175. [r setFullName:fullName];
  176. [array insertObject:r atIndex:i];
  177. if (i == ([children count] - 1)) {
  178. NSString *name = [NSString stringWithFormat:@"%@_%@", [child valueForKey:@"kind"], [current valueForKey:@"id"]];
  179. [array insertObject:name atIndex:i + 1];
  180. }
  181. }
  182. return array;
  183. }
  184. -(NSNumber *)messagesCount:(NSData *)data {
  185. NSError *error;
  186. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  187. NSDictionary *dat = [json valueForKey:@"data"];
  188. if (dat == nil)
  189. return nil;
  190. NSArray *children = [dat valueForKey:@"children"];
  191. if (children == nil)
  192. return nil;
  193. return [NSNumber numberWithInteger:[children count]];
  194. }
  195. -(void)readPMs:(id)parent {
  196. NSString *url = @"message/unread.json";
  197. NSHTTPURLResponse *response;
  198. NSData *data = [self queryAPI:url withResponse:&response];
  199. if ((data == nil) || ([response statusCode] != 200)) {
  200. [(AppDelegate *)parent performSelectorOnMainThread:@selector(readPMsCallback:) withObject:nil waitUntilDone:FALSE];
  201. } else {
  202. [(AppDelegate *)parent performSelectorOnMainThread:@selector(readPMsCallback:) withObject:[self messagesCount:data] waitUntilDone:FALSE];
  203. }
  204. }
  205. -(void)isAuthenticatedNewModhash:(id)parent {
  206. NSHTTPURLResponse *response;
  207. NSData *dat = [self queryAPI:@"api/me.json" withResponse:&response];
  208. if ((dat != nil) && ([response statusCode] == 200)) {
  209. NSError *error;
  210. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:dat options:0 error:&error];
  211. NSDictionary *data = [json valueForKey:@"data"];
  212. if (data == nil) {
  213. NSLog(@"Error loading me.json: not logged in!\n");
  214. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  215. return;
  216. }
  217. NSString *newHash = [data valueForKey:@"modhash"];
  218. if ((newHash == nil) || ([newHash isEqualToString:@""])) {
  219. NSLog(@"Error interpreting me.json: did not receive modhash!\n");
  220. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  221. return;
  222. }
  223. if (![newHash isEqualToString:modhash]) {
  224. modhash = newHash;
  225. }
  226. [parent performSelectorOnMainThread:@selector(reloadListIsAuthenticatedCallback) withObject:nil waitUntilDone:false];
  227. return;
  228. }
  229. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  230. }
  231. -(NSData *)queryAPI:(NSString *)api withResponse:(NSHTTPURLResponse **)res {
  232. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self getAPIPoint:api]];
  233. [request setTimeoutInterval:5.0];
  234. [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
  235. [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
  236. [request setValue:[NSString stringWithFormat:@"%@/%@ by %@", appName, version, author] forHTTPHeaderField:@"User-Agent"];
  237. if ((modhash != nil) && (![modhash isEqualToString:@""]))
  238. [request addValue:modhash forHTTPHeaderField:@"X-Modhash"];
  239. [request setHTTPMethod:@"GET"];
  240. NSError *error = nil;
  241. NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:res error:&error];
  242. if (error)
  243. return nil;
  244. return data;
  245. }
  246. -(NSData *)queryAPI:(NSString *)api withData:(NSString *)string andResponse:(NSHTTPURLResponse **)res {
  247. NSData *requestBodyData = [string dataUsingEncoding:NSUTF8StringEncoding];
  248. NSString *requestBodyLength = [NSString stringWithFormat:@"%lu", (unsigned long)[requestBodyData length]];
  249. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self getAPIPoint:api]];
  250. [request setTimeoutInterval:5.0];
  251. [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
  252. [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
  253. [request setValue:requestBodyLength forHTTPHeaderField:@"Content-Length"];
  254. [request setValue:[NSString stringWithFormat:@"%@/%@ by %@", appName, version, author] forHTTPHeaderField:@"User-Agent"];
  255. if ((modhash != nil) && (![modhash isEqualToString:@""]))
  256. [request addValue:modhash forHTTPHeaderField:@"X-Modhash"];
  257. [request setHTTPMethod:@"POST"];
  258. [request setHTTPBody:requestBodyData];
  259. NSError *error = nil;
  260. NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:res error:&error];
  261. if (error)
  262. return nil;
  263. return data;
  264. }
  265. -(NSURL *)getAPIPoint:(NSString *)where {
  266. return [NSURL URLWithString:[NSString stringWithFormat:@"https://ssl.reddit.com/%@", where]];
  267. }
  268. -(NSString *)urlencode:(NSString *)string {
  269. NSMutableString *output = [NSMutableString string];
  270. const unsigned char *source = (const unsigned char *)[string UTF8String];
  271. long sourceLen = strlen((const char *)source);
  272. for (int i = 0; i < sourceLen; i++) {
  273. const unsigned char thisChar = source[i];
  274. if (thisChar == ' '){
  275. [output appendString:@"+"];
  276. } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
  277. (thisChar >= 'a' && thisChar <= 'z') ||
  278. (thisChar >= 'A' && thisChar <= 'Z') ||
  279. (thisChar >= '0' && thisChar <= '9')) {
  280. [output appendFormat:@"%c", thisChar];
  281. } else {
  282. [output appendFormat:@"%%%02X", thisChar];
  283. }
  284. }
  285. return output;
  286. }
  287. @end