aka RedditBar, Mac OS X menu bar reddit client
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Reddit.m 13KB

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