aka RedditBar, Mac OS X menu bar reddit client
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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