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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. NSInteger maxTitleLength = 66;
  33. NSString *replaceTextForTitle = @"...";
  34. NSString *subredditFormat = @" [r/%@]";
  35. #define AUTHOR @"xythobuz"
  36. @synthesize username, modhash, password, version, appName, author, length, subreddits;
  37. -(id)initWithUsername:(NSString *)name Modhash:(NSString *)hash Length:(NSInteger)leng {
  38. self = [super init];
  39. if (self) {
  40. username = name;
  41. modhash = hash;
  42. password = nil;
  43. length = leng;
  44. version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
  45. appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  46. author = AUTHOR;
  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. }
  61. return self;
  62. }
  63. -(NSString *)queryModhash {
  64. NSMutableString *stringData = [NSMutableString stringWithString:@"api_type=json"];
  65. [stringData appendFormat:@"&user=%@", [self urlencode: username]];
  66. [stringData appendFormat:@"&passwd=%@", [self urlencode: password]];
  67. [stringData appendString:@"&rem=True"];
  68. NSHTTPURLResponse *response;
  69. NSData *data = [self queryAPI:@"api/login" withData:stringData andResponse:&response];
  70. if (data == nil) {
  71. return nil;
  72. } else {
  73. long code = [response statusCode];
  74. if (code == 200) {
  75. NSError *error;
  76. id object = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  77. if (error)
  78. return nil;
  79. if([object isKindOfClass:[NSDictionary class]]) {
  80. NSDictionary *results = object;
  81. NSDictionary *json = [results valueForKey:@"json"];
  82. if (json == nil)
  83. return nil;
  84. NSDictionary *data = [json valueForKey:@"data"];
  85. if (data == nil)
  86. return nil;
  87. return [data valueForKey:@"modhash"];
  88. } else {
  89. return nil;
  90. }
  91. } else {
  92. return nil;
  93. }
  94. }
  95. }
  96. -(NSArray *)convertJSONToItemArray:(NSData *)data ShowSubs:(Boolean)showSubs {
  97. NSError *error;
  98. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  99. NSDictionary *dat = [json valueForKey:@"data"];
  100. if (dat == nil)
  101. return nil;
  102. NSArray *children = [dat valueForKey:@"children"];
  103. if (children == nil)
  104. return nil;
  105. NSMutableArray *array = [NSMutableArray arrayWithCapacity:[children count]];
  106. for (NSUInteger i = 0; i < [children count]; i++) {
  107. NSDictionary *child = [children objectAtIndex:i];
  108. NSDictionary *current = [child valueForKey:@"data"];
  109. NSString *name = [current valueForKey:@"title"];
  110. NSString *link = [current valueForKey:@"url"];
  111. NSString *comments = nil;
  112. NSNumber *num = [current valueForKey:@"is_self"];
  113. BOOL isSelf = [num boolValue];
  114. if (!isSelf) {
  115. comments = [NSString stringWithFormat:@"http://www.reddit.com%@", [current valueForKey:@"permalink"]];
  116. }
  117. NSString *subreddit = [NSString stringWithFormat:subredditFormat, [current valueForKey:@"subreddit"]];
  118. NSInteger maxLen = maxTitleLength;
  119. if ([subreddit length] >= maxTitleLength)
  120. showSubs = FALSE;
  121. if (showSubs)
  122. maxLen -= [subreddit length];
  123. if ([name length] > maxLen)
  124. name = [NSString stringWithFormat:@"%@%@", [name substringToIndex:(maxLen - [replaceTextForTitle length])], replaceTextForTitle];
  125. if (showSubs)
  126. name = [NSString stringWithFormat:@"%@%@", name, subreddit];
  127. RedditItem *r = [RedditItem itemWithName:name Link:link Comments:comments Self:isSelf];
  128. NSString *fullName = [current valueForKey:@"title"];
  129. if (showSubs)
  130. fullName = [NSString stringWithFormat:@"%@%@", fullName, subreddit];
  131. [r setFullName:fullName];
  132. [array insertObject:r atIndex:i];
  133. if (i == ([children count] - 1)) {
  134. NSString *name = [NSString stringWithFormat:@"%@_%@", [child valueForKey:@"kind"], [current valueForKey:@"id"]];
  135. [array insertObject:name atIndex:i + 1];
  136. }
  137. }
  138. return array;
  139. }
  140. -(void)readFrontpage:(id)parent {
  141. NSHTTPURLResponse *response;
  142. NSString *after = ((AppDelegate *)parent).lastFullName;
  143. Boolean showSubreddits = ((AppDelegate *)parent).currentState.showSubreddit;
  144. NSString *url;
  145. if (after == nil)
  146. url = [NSString stringWithFormat:@"hot.json?limit=%ld", (long)length];
  147. else
  148. url = [NSString stringWithFormat:@"hot.json?limit=%ld&after=%@", (long)length, after];
  149. NSData *data = [self queryAPI:url withResponse:&response];
  150. if ((data == nil) || ([response statusCode] != 200)) {
  151. [parent performSelectorOnMainThread:@selector(reloadListHasFrontpageCallback:) withObject:nil waitUntilDone:false];
  152. } else {
  153. [parent performSelectorOnMainThread:@selector(reloadListHasFrontpageCallback:) withObject:[self convertJSONToItemArray:data ShowSubs:showSubreddits] waitUntilDone:false];
  154. }
  155. }
  156. -(void)readSubreddits:(id)parent {
  157. NSMutableString *subs = [NSMutableString stringWithString:@"r/"];
  158. for (NSUInteger i = 0; i < [subreddits count]; i++) {
  159. [subs appendString:[subreddits objectAtIndex:i]];
  160. if (i < ([subreddits count] - 1)) {
  161. [subs appendString:@"+"];
  162. }
  163. }
  164. NSString *after = ((AppDelegate *)parent).lastFullName;
  165. Boolean showSubreddits = ((AppDelegate *)parent).currentState.showSubreddit;
  166. NSString *url;
  167. if (after == nil)
  168. url = [NSString stringWithFormat:@"%@/hot.json?limit=%ld", subs, (long)length];
  169. else
  170. url = [NSString stringWithFormat:@"%@/hot.json?limit=%ld&after=%@", subs, (long)length, after];
  171. NSHTTPURLResponse *response;
  172. NSData *data = [self queryAPI:url withResponse:&response];
  173. if ((data == nil) || ([response statusCode] != 200)) {
  174. [parent performSelectorOnMainThread:@selector(reloadListHasSubredditsCallback:) withObject:nil waitUntilDone:false];
  175. } else {
  176. [parent performSelectorOnMainThread:@selector(reloadListHasSubredditsCallback:) withObject:[self convertJSONToItemArray:data ShowSubs:showSubreddits] waitUntilDone:false];
  177. }
  178. }
  179. -(void)isAuthenticatedNewModhash:(id)parent {
  180. NSHTTPURLResponse *response;
  181. NSData *dat = [self queryAPI:@"api/me.json" withResponse:&response];
  182. if ((dat != nil) && ([response statusCode] == 200)) {
  183. NSError *error;
  184. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:dat options:0 error:&error];
  185. NSDictionary *data = [json valueForKey:@"data"];
  186. if (data == nil) {
  187. NSLog(@"Not logged in!");
  188. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  189. return;
  190. }
  191. NSString *newHash = [data valueForKey:@"modhash"];
  192. if ((newHash == nil) || ([newHash isEqualToString:@""])) {
  193. NSLog(@"Did not receive modhash!");
  194. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  195. return;
  196. }
  197. if (![newHash isEqualToString:modhash]) {
  198. modhash = newHash;
  199. }
  200. [parent performSelectorOnMainThread:@selector(reloadListIsAuthenticatedCallback) withObject:nil waitUntilDone:false];
  201. return;
  202. }
  203. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  204. }
  205. -(NSData *)queryAPI:(NSString *)api withResponse:(NSHTTPURLResponse **)res {
  206. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self getAPIPoint:api]];
  207. [request setTimeoutInterval:5.0];
  208. [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
  209. [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
  210. [request setValue:[NSString stringWithFormat:@"%@/%@ by %@", appName, version, author] forHTTPHeaderField:@"User-Agent"];
  211. if ((modhash != nil) && (![modhash isEqualToString:@""]))
  212. [request addValue:modhash forHTTPHeaderField:@"X-Modhash"];
  213. [request setHTTPMethod:@"GET"];
  214. NSError *error = nil;
  215. NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:res error:&error];
  216. if (error)
  217. return nil;
  218. return data;
  219. }
  220. -(NSData *)queryAPI:(NSString *)api withData:(NSString *)string andResponse:(NSHTTPURLResponse **)res {
  221. NSData *requestBodyData = [string dataUsingEncoding:NSUTF8StringEncoding];
  222. NSString *requestBodyLength = [NSString stringWithFormat:@"%lu", (unsigned long)[requestBodyData length]];
  223. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self getAPIPoint:api]];
  224. [request setTimeoutInterval:5.0];
  225. [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
  226. [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
  227. [request setValue:requestBodyLength forHTTPHeaderField:@"Content-Length"];
  228. [request setValue:[NSString stringWithFormat:@"%@/%@ by %@", appName, version, author] forHTTPHeaderField:@"User-Agent"];
  229. if ((modhash != nil) && (![modhash isEqualToString:@""]))
  230. [request addValue:modhash forHTTPHeaderField:@"X-Modhash"];
  231. [request setHTTPMethod:@"POST"];
  232. [request setHTTPBody:requestBodyData];
  233. NSError *error = nil;
  234. NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:res error:&error];
  235. if (error)
  236. return nil;
  237. return data;
  238. }
  239. -(NSURL *)getAPIPoint:(NSString *)where {
  240. return [NSURL URLWithString:[NSString stringWithFormat:@"https://ssl.reddit.com/%@", where]];
  241. }
  242. -(NSString *)urlencode:(NSString *)string {
  243. NSMutableString *output = [NSMutableString string];
  244. const unsigned char *source = (const unsigned char *)[string UTF8String];
  245. long sourceLen = strlen((const char *)source);
  246. for (int i = 0; i < sourceLen; i++) {
  247. const unsigned char thisChar = source[i];
  248. if (thisChar == ' '){
  249. [output appendString:@"+"];
  250. } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
  251. (thisChar >= 'a' && thisChar <= 'z') ||
  252. (thisChar >= 'A' && thisChar <= 'Z') ||
  253. (thisChar >= '0' && thisChar <= '9')) {
  254. [output appendFormat:@"%c", thisChar];
  255. } else {
  256. [output appendFormat:@"%%%02X", thisChar];
  257. }
  258. }
  259. return output;
  260. }
  261. @end