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.

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