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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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 = 60;
  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. [r setFullName:[current valueForKey:@"title"]];
  129. [array insertObject:r atIndex:i];
  130. if (i == ([children count] - 1)) {
  131. NSString *name = [NSString stringWithFormat:@"%@_%@", [child valueForKey:@"kind"], [current valueForKey:@"id"]];
  132. [array insertObject:name atIndex:i + 1];
  133. }
  134. }
  135. return array;
  136. }
  137. -(void)readFrontpage:(id)parent {
  138. NSHTTPURLResponse *response;
  139. NSString *after = ((AppDelegate *)parent).lastFullName;
  140. Boolean showSubreddits = ((AppDelegate *)parent).currentState.showSubreddit;
  141. NSString *url;
  142. if (after == nil)
  143. url = [NSString stringWithFormat:@"hot.json?limit=%ld", (long)length];
  144. else
  145. url = [NSString stringWithFormat:@"hot.json?limit=%ld&after=%@", (long)length, after];
  146. NSData *data = [self queryAPI:url withResponse:&response];
  147. if ((data == nil) || ([response statusCode] != 200)) {
  148. [parent performSelectorOnMainThread:@selector(reloadListHasFrontpageCallback:) withObject:nil waitUntilDone:false];
  149. } else {
  150. [parent performSelectorOnMainThread:@selector(reloadListHasFrontpageCallback:) withObject:[self convertJSONToItemArray:data ShowSubs:showSubreddits] waitUntilDone:false];
  151. }
  152. }
  153. -(void)readSubreddits:(id)parent {
  154. NSMutableString *subs = [NSMutableString stringWithString:@"r/"];
  155. for (NSUInteger i = 0; i < [subreddits count]; i++) {
  156. [subs appendString:[subreddits objectAtIndex:i]];
  157. if (i < ([subreddits count] - 1)) {
  158. [subs appendString:@"+"];
  159. }
  160. }
  161. NSString *after = ((AppDelegate *)parent).lastFullName;
  162. Boolean showSubreddits = ((AppDelegate *)parent).currentState.showSubreddit;
  163. NSString *url;
  164. if (after == nil)
  165. url = [NSString stringWithFormat:@"%@/hot.json?limit=%ld", subs, (long)length];
  166. else
  167. url = [NSString stringWithFormat:@"%@/hot.json?limit=%ld&after=%@", subs, (long)length, after];
  168. NSHTTPURLResponse *response;
  169. NSData *data = [self queryAPI:url withResponse:&response];
  170. if ((data == nil) || ([response statusCode] != 200)) {
  171. [parent performSelectorOnMainThread:@selector(reloadListHasSubredditsCallback:) withObject:nil waitUntilDone:false];
  172. } else {
  173. [parent performSelectorOnMainThread:@selector(reloadListHasSubredditsCallback:) withObject:[self convertJSONToItemArray:data ShowSubs:showSubreddits] waitUntilDone:false];
  174. }
  175. }
  176. -(void)isAuthenticatedNewModhash:(id)parent {
  177. NSHTTPURLResponse *response;
  178. NSData *data = [self queryAPI:@"api/me.json" withResponse:&response];
  179. if ((data != nil) && ([response statusCode] == 200)) {
  180. NSError *error;
  181. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  182. NSDictionary *data = [json valueForKey:@"data"];
  183. if (data == nil) {
  184. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  185. return;
  186. }
  187. NSString *newHash = [data valueForKey:@"modhash"];
  188. if ((newHash == nil) || ([newHash isEqualToString:@""])) {
  189. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  190. return;
  191. }
  192. if (![newHash isEqualToString:modhash]) {
  193. modhash = newHash;
  194. }
  195. [parent performSelectorOnMainThread:@selector(reloadListIsAuthenticatedCallback) withObject:nil waitUntilDone:false];
  196. return;
  197. }
  198. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  199. }
  200. -(NSData *)queryAPI:(NSString *)api withResponse:(NSHTTPURLResponse **)res {
  201. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self getAPIPoint:api]];
  202. [request setTimeoutInterval:5.0];
  203. [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
  204. [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
  205. [request setValue:[NSString stringWithFormat:@"%@/%@ by %@", appName, version, author] forHTTPHeaderField:@"User-Agent"];
  206. if ((modhash != nil) && (![modhash isEqualToString:@""]))
  207. [request addValue:modhash forHTTPHeaderField:@"X-Modhash"];
  208. [request setHTTPMethod:@"GET"];
  209. NSError *error = nil;
  210. NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:res error:&error];
  211. if (error)
  212. return nil;
  213. else
  214. return data;
  215. }
  216. -(NSData *)queryAPI:(NSString *)api withData:(NSString *)string andResponse:(NSHTTPURLResponse **)res {
  217. NSData *requestBodyData = [string dataUsingEncoding:NSUTF8StringEncoding];
  218. NSString *requestBodyLength = [NSString stringWithFormat:@"%lu", (unsigned long)[requestBodyData length]];
  219. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self getAPIPoint:api]];
  220. [request setTimeoutInterval:5.0];
  221. [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
  222. [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
  223. [request setValue:requestBodyLength forHTTPHeaderField:@"Content-Length"];
  224. [request setValue:[NSString stringWithFormat:@"%@/%@ by %@", appName, version, author] forHTTPHeaderField:@"User-Agent"];
  225. if ((modhash != nil) && (![modhash isEqualToString:@""]))
  226. [request addValue:modhash forHTTPHeaderField:@"X-Modhash"];
  227. [request setHTTPMethod:@"POST"];
  228. [request setHTTPBody:requestBodyData];
  229. NSError *error = nil;
  230. NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:res error:&error];
  231. if (error)
  232. return nil;
  233. else
  234. return data;
  235. }
  236. -(NSURL *)getAPIPoint:(NSString *)where {
  237. return [NSURL URLWithString:[NSString stringWithFormat:@"https://ssl.reddit.com/%@", where]];
  238. }
  239. -(NSString *)urlencode:(NSString *)string {
  240. NSMutableString *output = [NSMutableString string];
  241. const unsigned char *source = (const unsigned char *)[string UTF8String];
  242. long sourceLen = strlen((const char *)source);
  243. for (int i = 0; i < sourceLen; i++) {
  244. const unsigned char thisChar = source[i];
  245. if (thisChar == ' '){
  246. [output appendString:@"+"];
  247. } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
  248. (thisChar >= 'a' && thisChar <= 'z') ||
  249. (thisChar >= 'A' && thisChar <= 'Z') ||
  250. (thisChar >= '0' && thisChar <= '9')) {
  251. [output appendFormat:@"%c", thisChar];
  252. } else {
  253. [output appendFormat:@"%%%02X", thisChar];
  254. }
  255. }
  256. return output;
  257. }
  258. @end