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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. //
  2. // Reddit.m
  3. // RedditBar
  4. //
  5. // Created by Thomas Buck on 01.12.13.
  6. // Copyright (c) 2013 xythobuz. All rights reserved.
  7. //
  8. #import "Reddit.h"
  9. #import "AppDelegate.h"
  10. @implementation Reddit
  11. NSString *version = @"1.0.0";
  12. NSString *author = @"xythobuz";
  13. NSString *appName = @"RedditBar";
  14. NSInteger maxTitleLength = 50;
  15. NSString *replaceTextForTitle = @"...";
  16. @synthesize username, modhash, password, length, subreddits;
  17. -(id)initWithUsername:(NSString *)name Modhash:(NSString *)hash Length:(NSInteger)leng {
  18. self = [super init];
  19. if (self) {
  20. username = name;
  21. modhash = hash;
  22. password = nil;
  23. length = leng;
  24. }
  25. return self;
  26. }
  27. -(id)initWithUsername:(NSString *)name Password:(NSString *)pass {
  28. self = [super init];
  29. if (self) {
  30. username = name;
  31. modhash = nil;
  32. password = pass;
  33. }
  34. return self;
  35. }
  36. -(NSString *)queryModhash {
  37. NSMutableString *stringData = [NSMutableString stringWithString:@"api_type=json"];
  38. [stringData appendFormat:@"&user=%@", [self urlencode: username]];
  39. [stringData appendFormat:@"&passwd=%@", [self urlencode: password]];
  40. [stringData appendString:@"&rem=True"];
  41. NSHTTPURLResponse *response;
  42. NSData *data = [self queryAPI:@"api/login" withData:stringData andResponse:&response];
  43. if (data == nil) {
  44. return nil;
  45. } else {
  46. long code = [response statusCode];
  47. if (code == 200) {
  48. NSError *error;
  49. id object = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  50. if (error)
  51. return nil;
  52. if([object isKindOfClass:[NSDictionary class]]) {
  53. NSDictionary *results = object;
  54. NSDictionary *json = [results valueForKey:@"json"];
  55. if (json == nil)
  56. return nil;
  57. NSDictionary *data = [json valueForKey:@"data"];
  58. if (data == nil)
  59. return nil;
  60. return [data valueForKey:@"modhash"];
  61. } else {
  62. return nil;
  63. }
  64. } else {
  65. return nil;
  66. }
  67. }
  68. }
  69. -(NSArray *)convertJSONToItemArray:(NSData *)data {
  70. NSError *error;
  71. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  72. NSDictionary *dat = [json valueForKey:@"data"];
  73. if (dat == nil)
  74. return nil;
  75. NSArray *children = [dat valueForKey:@"children"];
  76. if (children == nil)
  77. return nil;
  78. NSMutableArray *array = [NSMutableArray arrayWithCapacity:[children count]];
  79. for (NSUInteger i = 0; i < [children count]; i++) {
  80. NSDictionary *child = [children objectAtIndex:i];
  81. NSDictionary *current = [child valueForKey:@"data"];
  82. NSString *name = [current valueForKey:@"title"];
  83. NSString *link = [current valueForKey:@"url"];
  84. NSString *comments = nil;
  85. NSNumber *num = [current valueForKey:@"is_self"];
  86. BOOL isSelf = [num boolValue];
  87. if (!isSelf) {
  88. comments = [NSString stringWithFormat:@"http://www.reddit.com%@", [current valueForKey:@"permalink"]];
  89. }
  90. if ([name length] > maxTitleLength) {
  91. name = [NSString stringWithFormat:@"%@%@", [name substringToIndex:(maxTitleLength - [replaceTextForTitle length])], replaceTextForTitle];
  92. }
  93. RedditItem *r = [RedditItem itemWithName:name Link:link Comments:comments Self:isSelf];
  94. [array insertObject:r atIndex:i];
  95. }
  96. return array;
  97. }
  98. -(void)readFrontpage:(id)parent {
  99. NSHTTPURLResponse *response;
  100. NSString *url = [NSString stringWithFormat:@"hot.json?limit=%ld", (long)length];
  101. NSData *data = [self queryAPI:url withResponse:&response];
  102. if ((data == nil) || ([response statusCode] != 200)) {
  103. [parent performSelectorOnMainThread:@selector(reloadListHasFrontpageCallback:) withObject:nil waitUntilDone:false];
  104. } else {
  105. [parent performSelectorOnMainThread:@selector(reloadListHasFrontpageCallback:) withObject:[self convertJSONToItemArray:data] waitUntilDone:false];
  106. }
  107. }
  108. -(void)readSubreddits:(id)parent {
  109. // TODO read subreddits (as multireddit?)
  110. // TODO if implemented, enable checkbox in prefs
  111. }
  112. -(void)isAuthenticatedNewModhash:(id)parent {
  113. NSHTTPURLResponse *response;
  114. NSData *data = [self queryAPI:@"api/me.json" withResponse:&response];
  115. if ((data != nil) && ([response statusCode] == 200)) {
  116. NSError *error;
  117. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  118. NSDictionary *data = [json valueForKey:@"data"];
  119. if (data == nil) {
  120. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  121. return;
  122. }
  123. NSString *newHash = [data valueForKey:@"modhash"];
  124. if ((newHash == nil) || ([newHash isEqualToString:@""])) {
  125. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  126. return;
  127. }
  128. if (![newHash isEqualToString:modhash]) {
  129. modhash = newHash;
  130. }
  131. [parent performSelectorOnMainThread:@selector(reloadListIsAuthenticatedCallback) withObject:nil waitUntilDone:false];
  132. return;
  133. }
  134. [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
  135. }
  136. -(NSData *)queryAPI:(NSString *)api withResponse:(NSHTTPURLResponse **)res {
  137. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self getAPIPoint:api]];
  138. [request setTimeoutInterval:5.0];
  139. [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
  140. [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
  141. [request setValue:[NSString stringWithFormat:@"%@/%@ by %@", appName, version, author] forHTTPHeaderField:@"User-Agent"];
  142. if ((modhash != nil) && (![modhash isEqualToString:@""]))
  143. [request addValue:modhash forHTTPHeaderField:@"X-Modhash"];
  144. [request setHTTPMethod:@"GET"];
  145. NSError *error = nil;
  146. NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:res error:&error];
  147. if (error)
  148. return nil;
  149. else
  150. return data;
  151. }
  152. -(NSData *)queryAPI:(NSString *)api withData:(NSString *)string andResponse:(NSHTTPURLResponse **)res {
  153. NSData *requestBodyData = [string dataUsingEncoding:NSUTF8StringEncoding];
  154. NSString *requestBodyLength = [NSString stringWithFormat:@"%lu", (unsigned long)[requestBodyData length]];
  155. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self getAPIPoint:api]];
  156. [request setTimeoutInterval:5.0];
  157. [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
  158. [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
  159. [request setValue:requestBodyLength forHTTPHeaderField:@"Content-Length"];
  160. [request setValue:[NSString stringWithFormat:@"%@/%@ by %@", appName, version, author] forHTTPHeaderField:@"User-Agent"];
  161. if ((modhash != nil) && (![modhash isEqualToString:@""]))
  162. [request addValue:modhash forHTTPHeaderField:@"X-Modhash"];
  163. [request setHTTPMethod:@"POST"];
  164. [request setHTTPBody:requestBodyData];
  165. NSError *error = nil;
  166. NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:res error:&error];
  167. if (error)
  168. return nil;
  169. else
  170. return data;
  171. }
  172. -(NSURL *)getAPIPoint:(NSString *)where {
  173. return [NSURL URLWithString:[NSString stringWithFormat:@"https://ssl.reddit.com/%@", where]];
  174. }
  175. -(NSString *)urlencode:(NSString *)string {
  176. NSMutableString *output = [NSMutableString string];
  177. const unsigned char *source = (const unsigned char *)[string UTF8String];
  178. long sourceLen = strlen((const char *)source);
  179. for (int i = 0; i < sourceLen; i++) {
  180. const unsigned char thisChar = source[i];
  181. if (thisChar == ' '){
  182. [output appendString:@"+"];
  183. } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
  184. (thisChar >= 'a' && thisChar <= 'z') ||
  185. (thisChar >= 'A' && thisChar <= 'Z') ||
  186. (thisChar >= '0' && thisChar <= '9')) {
  187. [output appendFormat:@"%c", thisChar];
  188. } else {
  189. [output appendFormat:@"%%%02X", thisChar];
  190. }
  191. }
  192. return output;
  193. }
  194. @end