aka RedditBar, Mac OS X menu bar reddit client
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Reddit.m 15KB

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