PageRenderTime 48ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/WHAMBUSH/wbAPI.m

https://gitlab.com/urbanjunglestudio/whambush-ios
Objective C | 1155 lines | 895 code | 160 blank | 100 comment | 213 complexity | 40f1a9a509a3ff1f062844df24a3d064 MD5 | raw file
  1. //
  2. // wbAPI.m
  3. // WHAMBUSH
  4. //
  5. // Created by Jari Kalinainen on 8/26/13.
  6. // Copyright (c) 2013 Jari Kalinainen. All rights reserved.
  7. //
  8. #import "wbAPI.h"
  9. #import <sys/utsname.h>
  10. @implementation wbAPI
  11. @synthesize rootViewController;
  12. @synthesize uploadData;
  13. @synthesize currentViewController;
  14. @synthesize token;
  15. @synthesize pushToken;
  16. @synthesize vzaar_key;
  17. @synthesize vzaar_secret;
  18. //@synthesize guest_id;
  19. @synthesize num_active_missions;
  20. @synthesize num_incomplete_profile;
  21. @synthesize num_unread_activities;
  22. @synthesize uploading;
  23. //@synthesize GPUCamera;
  24. @synthesize iPhoneVersion;
  25. @synthesize is_guest;
  26. @synthesize portraitFrame;
  27. @synthesize landscapeFrame;
  28. @synthesize is_authenticated;
  29. @synthesize currentCountry;
  30. -(id) init
  31. {
  32. DPRINTCLASS;
  33. self = [super init];
  34. if (self) {
  35. uploading = NO;
  36. // if (waitView == nil) {
  37. // waitView = [[wbWaitView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width,[[UIScreen mainScreen] bounds].size.height)];
  38. // [waitView setHidden:YES];
  39. // [[[[UIApplication sharedApplication] delegate] window] addSubview:waitView];
  40. // }
  41. float width = [[UIScreen mainScreen] bounds].size.width;
  42. float height = [[UIScreen mainScreen] bounds].size.height;
  43. if (width < height) {
  44. portraitFrame = CGRectMake(0, 0, width, height);
  45. landscapeFrame = CGRectMake(0, 0, height, width);
  46. } else {
  47. landscapeFrame = CGRectMake(0, 0, width, height);
  48. portraitFrame = CGRectMake(0, 0, height, width);
  49. }
  50. firstTimeFail = NO;
  51. newUser = NO;
  52. }
  53. return self;
  54. }
  55. + (id)sharedAPI
  56. {
  57. static dispatch_once_t pred = 0;
  58. __strong static id _sharedObject = nil;
  59. dispatch_once(&pred, ^{
  60. _sharedObject = [[self alloc] init];
  61. });
  62. return _sharedObject;
  63. }
  64. -(NSString*)description
  65. {
  66. return [super description];
  67. }
  68. /////////////////////////
  69. -(float)statusBarHeight
  70. {
  71. //DNSLog(@"statusbar: %f",[UIApplication sharedApplication].statusBarFrame.size.height);
  72. float statusBarHeightLoc = [UIApplication sharedApplication].statusBarFrame.size.height;
  73. //DNSLog(@"statsbar : %f",statusBarHeightLoc);
  74. // [[wbFooter sharedFooter] setFixVal:0];
  75. if (statusBarHeightLoc > 20 || statusBarHeightLoc == NAN) {
  76. statusBarHeightLoc = 20;
  77. // [[wbFooter sharedFooter] setFixVal:20];
  78. }
  79. return statusBarHeightLoc;
  80. }
  81. -(float)footerBarHeight
  82. {
  83. float footerBarHeightLoc = 50.0;
  84. return footerBarHeightLoc;
  85. }
  86. -(float)headerBarHeight
  87. {
  88. // float headerY;
  89. // float logoY;
  90. // if ([self statusBarHeight] > 20) {
  91. // headerY = 20;
  92. // logoY = 0;
  93. // } else {
  94. // headerY = 0;
  95. // logoY = 10;
  96. // }
  97. float headBarHeightLoc = 50 + [self statusBarHeight];
  98. return headBarHeightLoc;
  99. }
  100. -(CGRect)headerBarRect
  101. {
  102. CGRect headerBarRectLoc = CGRectMake(0, 0, [[wbAPI sharedAPI] portraitFrame].size.width,[self headerBarHeight]);
  103. return headerBarRectLoc;
  104. }
  105. -(CGRect)footerBarRect
  106. {
  107. CGRect footerBarRectLoc = CGRectMake(0, [[wbAPI sharedAPI] portraitFrame].size.height-([self footerBarHeight]/*+[self statusBarHeight]-20*/), [[wbAPI sharedAPI] portraitFrame].size.width, [self footerBarHeight]);
  108. return footerBarRectLoc;
  109. }
  110. -(CGRect)contentRect
  111. {
  112. //CGRect headerBarRect = [self headerBarRect];
  113. CGRect footerBarRect = [self footerBarRect];
  114. CGRect contentRectLoc = CGRectMake(0, CGRectGetMaxY([self headerBarRect])/*[self headerBarHeight]*/, [[wbAPI sharedAPI] portraitFrame].size.width,CGRectGetMinY(footerBarRect)-[self headerBarHeight]/*-CGRectGetMaxY(headerBarRect)*/);
  115. return contentRectLoc;
  116. }
  117. /////////////////////////
  118. -(BOOL)checkIfNetworkAvailable
  119. {
  120. Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
  121. DCMSG(@"Check network");
  122. NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
  123. if (networkStatus == NotReachable) {
  124. DNSLog(@"There IS NO internet connection");
  125. [self showErrorWithTxt:NSLocalizedString(@"GENERAL_ERROR_NO_NETWORK", @"")];
  126. networkReachability = nil;
  127. kHIDEWAIT;
  128. return NO;
  129. } else {
  130. if ([self checkAPIReachability]) {
  131. if (networkStatus == ReachableViaWiFi) {
  132. page_size = 30;
  133. } else {
  134. page_size = 20;
  135. }
  136. networkReachability = nil;
  137. return YES;
  138. } else {
  139. [self showErrorWithTxt:NSLocalizedString(@"GENERAL_ERROR_NO_NETWORK", @"")];
  140. networkReachability = nil;
  141. return NO;
  142. }
  143. }
  144. }
  145. -(BOOL)checkAPIReachability {
  146. Reachability *apiReachability = [Reachability reachabilityWithHostname:kWHAMBUSHDOTNET];
  147. DCMSG(@"Check API");
  148. NetworkStatus apiStatus = [apiReachability currentReachabilityStatus];
  149. DCMSG(@"Check API, DONE");
  150. if (apiStatus == NotReachable) {
  151. apiReachability = nil;
  152. DCMSG(@"NO API?");
  153. return YES;
  154. } else {
  155. apiReachability = nil;
  156. return YES;
  157. }
  158. }
  159. -(NSURL*)urlWithEndpoint:(NSString*)endpoint
  160. {
  161. NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",kWHAMBUSHAPIURL,endpoint]];
  162. return url;
  163. }
  164. /////////////////////////////////////
  165. -(void)getJSONWithURL:(NSURL *)url response:(void (^)(id json))jsonResponse
  166. {
  167. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  168. manager.requestSerializer = [AFJSONRequestSerializer serializer];
  169. manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions: NSJSONReadingMutableContainers];
  170. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",nil];
  171. DCMSG(kWHAMBUSHTOKEN);
  172. DNSLog(@"-> %@",[url absoluteString]);
  173. DNSLog(@"-> %@",[url path]);
  174. //DNSLog(@"-> %@",[url pathComponents]);
  175. //DNSLog(@"-> %@",[url pathExtension]);
  176. if (kWHAMBUSHTOKEN != nil && is_authenticated) {
  177. NSAssert(kWHAMBUSHTOKEN != nil,@"");
  178. [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",kWHAMBUSHTOKEN] forHTTPHeaderField:@"Authorization"];
  179. }
  180. NSDictionary *parameters;
  181. if (!no_page){
  182. parameters = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld",(long)page_size],@"page_size", nil];
  183. } else {
  184. parameters = nil;
  185. }
  186. [manager GET:[url absoluteString] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
  187. DNSLog(@"Request: %@", operation.request);
  188. jsonResponse(responseObject);
  189. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  190. NSLog(@"1Error: %@", error);
  191. DNSLog(@"2Error: %@",operation.request);
  192. DNSLog(@"3Error: %@",operation.response);
  193. DNSLog(@"4Error: %@",operation.responseObject);
  194. DNSLog(@"5Error: %@",[operation.responseObject class]);
  195. if ([[operation.responseObject objectForKey:@"detail"] isEqualToString:@"TOKEN_ERROR_INACTIVE_USER"]) {
  196. [SSKeychain deletePasswordForService:kAPPNAME account:@"guest_id"];
  197. [self removeSettingWithKey:@"guest_id"];
  198. is_authenticated = NO;
  199. [self tryLogin];
  200. } else {
  201. NSArray *path = [[operation.request URL] pathComponents];
  202. NSString *pathString;
  203. if ([path count] > 3) {
  204. pathString = [NSString stringWithFormat:@"%@/%@",[path objectAtIndex:[path count]-2],[path objectAtIndex:[path count]-1]];
  205. } else {
  206. pathString = [NSString stringWithFormat:@"%@",[path lastObject]];
  207. }
  208. if ([operation.response statusCode] == 404) {
  209. [self performSelectorOnMainThread:@selector(showErrorWithTxt:) withObject:[NSString stringWithFormat:@"%@\nPath: %@",NSLocalizedString(@"GENERAL_ERROR_404",@""),pathString] waitUntilDone:NO];
  210. [kROOTVC performSelector:@selector(goHome:) withObject:nil];
  211. } else {
  212. NSString *errorTxt = [NSString stringWithFormat:@"%@\nCode: %ld %@",NSLocalizedString(@"GENERAL_ERROR_MAJOR",@""),(long)[operation.response statusCode],pathString];
  213. [self performSelectorOnMainThread:@selector(showErrorWithTxt:) withObject:errorTxt waitUntilDone:NO];
  214. }
  215. }
  216. }];
  217. }
  218. /////////////////////////////////////
  219. -(void)postJSONWithURL:(NSURL*)url paramenters:(NSDictionary*)parameters response:(void (^)(id json))jsonResponse errorResponse:(void (^)(id errorResponse))errorResponse
  220. {
  221. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  222. manager.requestSerializer = [AFJSONRequestSerializer serializer];
  223. manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions: NSJSONReadingMutableContainers];
  224. //DCMSG(kWHAMBUSHTOKEN);
  225. if (kWHAMBUSHTOKEN != nil && is_authenticated) {
  226. [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",kWHAMBUSHTOKEN] forHTTPHeaderField:@"Authorization"];
  227. }
  228. [manager POST:[url absoluteString] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
  229. DNSLog(@"Request: %@", operation.request);
  230. jsonResponse(responseObject);
  231. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  232. DNSLog(@"Error: %@",operation.responseObject);
  233. DNSLog(@"Operation request: %@",operation.request);
  234. DNSLog(@"Operation response: %@",operation.response);
  235. errorResponse(operation.responseObject);
  236. }];
  237. }
  238. /////////////////////////////////////
  239. -(void)deleteJSONWithURL:(NSURL*)url paramenters:(NSDictionary*)parameters response:(void (^)(id json))jsonResponse errorResponse:(void (^)(id errorResponse))errorResponse
  240. {
  241. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  242. manager.requestSerializer = [AFJSONRequestSerializer serializer];
  243. manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions: NSJSONReadingMutableContainers];
  244. if (kWHAMBUSHTOKEN != nil) {
  245. [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",kWHAMBUSHTOKEN] forHTTPHeaderField:@"Authorization"];
  246. }
  247. [manager DELETE:[url absoluteString] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
  248. DNSLog(@"Operation: %@",operation);
  249. DNSLog(@"Response: %@",responseObject);
  250. jsonResponse(responseObject);
  251. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  252. DNSLog(@"Error: %@",operation.responseObject);
  253. errorResponse(operation.responseObject);
  254. }];
  255. }
  256. /////////////////////////////////////
  257. -(void)putJSONWithURL:(NSURL*)url paramenters:(NSDictionary*)parameters response:(void (^)(id json))jsonResponse errorResponse:(void (^)(id errorResponse))errorResponse
  258. {
  259. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  260. manager.requestSerializer = [AFJSONRequestSerializer serializer];
  261. manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions: NSJSONReadingMutableContainers];
  262. if (kWHAMBUSHTOKEN != nil) {
  263. [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",kWHAMBUSHTOKEN] forHTTPHeaderField:@"Authorization"];
  264. }
  265. [manager PUT:[url absoluteString] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
  266. DNSLog(@"Operation: %@",operation);
  267. DNSLog(@"Response: %@",responseObject);
  268. jsonResponse(responseObject);
  269. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  270. DNSLog(@"Error: %@",operation.responseObject);
  271. errorResponse(operation.responseObject);
  272. }];
  273. }
  274. /////////////////////////////////////
  275. -(void)createUser:(NSDictionary *)userArray {
  276. [self postJSONWithURL:[self urlWithEndpoint:@"users/"] paramenters:userArray
  277. response:^(id data){
  278. NSString *guest_id = [self getSettingWithKey:@"guest_id"];
  279. [self saveLoginInfo:[NSDictionary dictionaryWithObjectsAndKeys:[userArray objectForKey:@"password1"],@"password",[userArray objectForKey:@"username"],@"username",guest_id,@"guest_id", nil]];
  280. [[wbLoginRegisterViewController sharedLRVC] closeAlert];
  281. newUser = TRUE;
  282. [[wbAPI sharedAPI] tryLogin];
  283. kHIDEWAIT;
  284. [self performSelectorOnMainThread:@selector(showNoteWithTxt:) withObject:[NSString stringWithFormat:NSLocalizedString(@"REGISTER_NEW_USER_INFO",@""),[userArray objectForKey:@"email"]] waitUntilDone:NO];
  285. }
  286. errorResponse:^(id data){
  287. kHIDEWAIT;
  288. if ([data objectForKey:@"username"] != nil) {
  289. [self performSelectorOnMainThread:@selector(showErrorWithTxt:) withObject:NSLocalizedString(@"REGISTER_ERROR_USERNAME",@"") waitUntilDone:NO];
  290. } else if ([data objectForKey:@"email"] != nil) {
  291. [self performSelectorOnMainThread:@selector( showErrorWithTxt:) withObject:NSLocalizedString(@"REGISTER_ERROR_EMAIL",@"") waitUntilDone:NO];
  292. } else if ([data objectForKey:@"promocode"] != nil) {
  293. newUserArray = userArray;
  294. [self performSelectorOnMainThread:@selector( askPromoCode:) withObject:NSLocalizedString(@"REGISTER_ERROR_PROMO_CODE",@"") waitUntilDone:NO];
  295. } else {
  296. [self performSelectorOnMainThread:@selector( showErrorWithTxt:) withObject:NSLocalizedString(@"GENERAL_ERROR_MAJOR",@"") waitUntilDone:NO];
  297. }
  298. }
  299. ];
  300. }
  301. -(void)getPhoneVersion
  302. {
  303. struct utsname systemInfo;
  304. uname(&systemInfo);
  305. NSString *idString;
  306. idString = [[NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@"iPhone" withString:@""];
  307. idString = [idString stringByReplacingOccurrencesOfString:@"," withString:@"."];
  308. NSInteger majorDeviceNumber = [idString floatValue];
  309. DNSLog(@"device version %@",idString);
  310. DNSLog(@"device version %ld",(long)majorDeviceNumber);
  311. iPhoneVersion = [NSNumber numberWithLong:majorDeviceNumber];
  312. }
  313. -(void)authenticate:(NSString *)username password:(NSString *)password guest_id:(NSString*)guestId
  314. {
  315. DCMSG(rootViewController);
  316. if([self checkIfNetworkAvailable]){
  317. struct utsname systemInfo;
  318. uname(&systemInfo);
  319. NSDictionary *loginArray = [NSDictionary dictionaryWithObjectsAndKeys:
  320. username,@"username",
  321. password,@"password",
  322. @"Apple",@"manufacturer",
  323. @"iOS",@"os",
  324. [UIDevice currentDevice].systemVersion,@"os_version",
  325. [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding],@"device",
  326. [[NSUserDefaults standardUserDefaults] objectForKey:@"version"],@"whambush_version",
  327. guestId,@"guest_id",
  328. nil];
  329. //DCMSG(loginArray);
  330. [self getPhoneVersion];
  331. [self postJSONWithURL:[self urlWithEndpoint:kAUTHENTICATE] paramenters:loginArray
  332. response:^(id data){
  333. DNSLog(@"data: %@",data);
  334. NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:
  335. password,@"password",
  336. username,@"username",
  337. [data objectForKey:@"token"],@"token",
  338. [[data objectForKey:@"settings"] objectForKey:@"vzaar_key"],@"vzaar_key",
  339. [[data objectForKey:@"settings"] objectForKey:@"vzaar_secret"],@"vzaar_secret",
  340. [NSString stringWithFormat:@"%@",[data objectForKey:@"guest_id"]] ,@"guest_id",
  341. nil];
  342. [self saveLoginInfo:info];
  343. is_authenticated = YES;
  344. [[wbData sharedData] performSelectorInBackground:@selector(getAllCountries) withObject:nil];
  345. DNSLog(@"%@",currentCountry);
  346. if (![self checkIfCountryExists] && [password length] < 3) {
  347. [kROOTVC performSelector:@selector(askCountry)];
  348. } else {
  349. [[wbData sharedData] createSupportMessage:loginArray];
  350. if ([data objectForKey:@"num_active_missions"] != nil) {
  351. num_active_missions = [NSString stringWithFormat:@"%@",[data objectForKey:@"num_active_missions"]];
  352. } else {
  353. num_active_missions = @"0";
  354. }
  355. if ([data objectForKey:@"incomplete"] != nil) {
  356. num_incomplete_profile = [NSString stringWithFormat:@"%@",[data objectForKey:@"incomplete"]];
  357. } else {
  358. num_incomplete_profile = @"0";
  359. }
  360. if ([data objectForKey:@"unread"] != nil) {
  361. num_unread_activities = [NSString stringWithFormat:@"%@",[data objectForKey:@"unread"]];
  362. } else {
  363. num_unread_activities = @"0";
  364. }
  365. [[wbData sharedData] setNum_of_unreadActivities:[NSNumber numberWithInteger:[num_unread_activities integerValue]]];
  366. if (pushToken != nil) {
  367. [self sendPushNotificationToken:pushToken];
  368. } else {
  369. if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
  370. {
  371. [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
  372. [[UIApplication sharedApplication] registerForRemoteNotifications];
  373. }
  374. else
  375. {
  376. [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
  377. (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
  378. }
  379. }
  380. if ([data objectForKey:@"user"] != nil) {
  381. is_guest = NO;
  382. [[wbUser sharedUser] performSelectorOnMainThread:@selector(setUserDetails:) withObject:[data objectForKey:@"user"] waitUntilDone:YES];
  383. //[[wbUser sharedUser] setUserDetails:[data objectForKey:@"user"]];
  384. //[[wbUser sharedUser] updateUserData];
  385. DMSG;
  386. //check if user is NEW
  387. if ([[[wbUser sharedUser] activation_state] isEqualToString:@"NEW"] && !newUser) {
  388. NSString *string = NSLocalizedString(@"GENERAL_WARNING_TITLE", @"");
  389. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:string
  390. message:[NSString stringWithFormat:NSLocalizedString(@"SETTINGS_EMAIL_NOT_ACTIVATED", @""),[[wbUser sharedUser] email]]
  391. delegate:self
  392. cancelButtonTitle:NSLocalizedString(@"SETTINGS_EMAIL_RESEND_ACTIVATION",@"")
  393. otherButtonTitles:NSLocalizedString(@"GENERAL_OK",@""),nil];
  394. [alert setTag:3];
  395. [alert show];
  396. }
  397. //[self saveCurrentCountry:[[wbUser sharedUser] countryDictionary]];
  398. [self saveSettingWithKey:@"country" andData:[[wbUser sharedUser] countryDictionary]];
  399. [self setCurrentCountry:[[wbUser sharedUser] countryDictionary]];
  400. } else {
  401. is_guest = YES;
  402. }
  403. [[wbData sharedData] performSelectorInBackground:@selector(getAllFeeds) withObject:nil];
  404. [[wbData sharedData] performSelectorInBackground:@selector(getAllMissionFeeds) withObject:nil];
  405. [[wbData sharedData] performSelectorInBackground:@selector(getAllActivity) withObject:nil];
  406. //[[wbData sharedData] performSelectorInBackground:@selector(getAllCountries) withObject:nil];
  407. // [[wbData sharedData] performSelectorInBackground:@selector(getTvChannels) withObject:nil];
  408. [[wbData sharedData] performSelectorOnMainThread:@selector(getTvChannels) withObject:nil waitUntilDone:NO];
  409. [rootViewController performSelector:@selector(loginOK)];
  410. [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"debugSetting"];
  411. }
  412. }
  413. errorResponse:^(id data){
  414. if ([data objectForKey:@"username"] != nil) {
  415. DMSG;
  416. [self showLoginErrorWithTxt:@"LOGIN_ERROR_WRONG_CREDENTIALS"];
  417. } else if ([data objectForKey:@"password"] != nil) {
  418. DMSG;
  419. [self showLoginErrorWithTxt:@"LOGIN_ERROR_WRONG_CREDENTIALS"];
  420. } else if ([data objectForKey:@"guest_id"] != nil) {
  421. DMSG;
  422. is_authenticated = NO;
  423. if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"debugSetting"] isEqualToString:kRESETGUESTID]) {
  424. [SSKeychain deletePasswordForService:kAPPNAME account:@"guest_id"];
  425. [self removeSettingWithKey:@"guest_id"];
  426. //guest_id = @"";
  427. [self tryLogin];
  428. } else {
  429. [self showErrorWithTxt:NSLocalizedString(@"GENERAL_ERROR_MAJOR",@"")];
  430. }
  431. } else if ([data objectForKey:@"non_field_errors"] != nil ) {
  432. DMSG;
  433. [self showLoginErrorWithTxt:[[data objectForKey:@"non_field_errors"] objectAtIndex:0]];
  434. } else {
  435. DMSG;
  436. [self logout];
  437. if (!firstTimeFail) {
  438. firstTimeFail = YES;
  439. [self tryLogin];
  440. } else {
  441. firstTimeFail = NO;
  442. [self showErrorWithTxt:NSLocalizedString(@"GENERAL_ERROR_MAJOR",@"")];
  443. }
  444. }
  445. DCMSG(data);
  446. }
  447. ];
  448. }
  449. }
  450. -(BOOL)checkIfCountryExists
  451. {
  452. if ([[self getSettingWithKey:@"country"] objectForKey:@"country"] != nil) {
  453. [self setCurrentCountry:[self getSettingWithKey:@"country"] ];
  454. DNSLog(@"%@",currentCountry);
  455. return YES;
  456. } else {
  457. return NO;
  458. }
  459. }
  460. //-(void)saveCurrentCountry:(NSDictionary*)country
  461. //{
  462. // NSString *error;
  463. // NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  464. // NSString *plistPath = [rootPath stringByAppendingPathComponent:@"settings.plist"];
  465. //
  466. // NSDictionary *plistDic;
  467. // if (country == nil) {
  468. // plistDic = @{@"guest_id":guest_id};
  469. // } else {
  470. // plistDic = @{@"country":country,@"guest_id":guest_id};
  471. // }
  472. // id plist = [NSPropertyListSerialization dataFromPropertyList:(id)plistDic format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
  473. // if(plist) {
  474. // [plist writeToFile:plistPath atomically:YES];
  475. // [[wbAPI sharedAPI] setCurrentCountry:country];
  476. // }
  477. //
  478. //}
  479. //
  480. -(id)getSettingWithKey:(NSString*)key
  481. {
  482. NSString *errorDesc = nil;
  483. NSPropertyListFormat format;
  484. NSString *plistPath;
  485. NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
  486. NSUserDomainMask, YES) objectAtIndex:0];
  487. plistPath = [rootPath stringByAppendingPathComponent:@"settings.plist"];
  488. if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
  489. plistPath = [[NSBundle mainBundle] pathForResource:@"settings" ofType:@"plist"];
  490. }
  491. NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
  492. NSDictionary *data = (NSDictionary *)[NSPropertyListSerialization
  493. propertyListFromData:plistXML
  494. mutabilityOption:NSPropertyListMutableContainersAndLeaves
  495. format:&format
  496. errorDescription:&errorDesc];
  497. if (!data) {
  498. NSLog(@"Error reading plist: %@, format: %lu", errorDesc, (unsigned long)format);
  499. }
  500. if (key != nil) {
  501. return [data objectForKey:key];
  502. } else {
  503. return data;
  504. }
  505. }
  506. -(void)saveSettingWithKey:(NSString*)key andData:(id)data
  507. {
  508. NSString *error;
  509. NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  510. NSString *plistPath = [rootPath stringByAppendingPathComponent:@"settings.plist"];
  511. NSDictionary *plistDic;
  512. NSMutableDictionary *settingsData = [[NSMutableDictionary alloc] initWithDictionary:[self getSettingWithKey:nil]];
  513. if (settingsData != nil) {
  514. //if ([settingsData objectForKey:key] != nil) {
  515. [settingsData setObject:data forKey:key];
  516. //}
  517. plistDic = settingsData;
  518. } else {
  519. plistDic = @{key:data};
  520. }
  521. id plist = [NSPropertyListSerialization dataFromPropertyList:(id)plistDic format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
  522. if(plist) {
  523. [plist writeToFile:plistPath atomically:YES];
  524. }
  525. }
  526. -(void)removeSettingWithKey:(NSString*)key
  527. {
  528. NSString *error;
  529. NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  530. NSString *plistPath = [rootPath stringByAppendingPathComponent:@"settings.plist"];
  531. NSMutableDictionary *settingsData = [[NSMutableDictionary alloc] initWithDictionary:[self getSettingWithKey:nil]];
  532. if (settingsData != nil) {
  533. if ([settingsData objectForKey:key] != nil) {
  534. [settingsData removeObjectForKey:key];
  535. NSDictionary *plistDic = settingsData;
  536. id plist = [NSPropertyListSerialization dataFromPropertyList:(id)plistDic format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
  537. if(plist) {
  538. [plist writeToFile:plistPath atomically:YES];
  539. }
  540. }
  541. }
  542. }
  543. -(void)showLoginErrorWithTxt:(NSString*)txt
  544. {
  545. DNSLog(@"%d %d",is_authenticated,is_guest);
  546. if ([txt isEqualToString:@"LOGIN_ERROR_WRONG_CREDENTIALS"]) {
  547. NSString *string = NSLocalizedString(@"GENERAL_ERROR_TITLE", @"");
  548. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:string
  549. message:NSLocalizedString(txt,@"")
  550. delegate:self
  551. cancelButtonTitle:NSLocalizedString(@"LOGIN_RESET_PASSWORD",@"")
  552. otherButtonTitles:NSLocalizedString(@"GENERAL_OK",@""),nil];
  553. [alert setTag:2];
  554. [alert show];
  555. if (!is_authenticated && !is_guest) {
  556. [self logout];
  557. [self tryLogin];
  558. }
  559. } else if ([txt isEqualToString:@"LOGIN_ERROR_INACTIVE_USER"]) {
  560. NSString *string = NSLocalizedString(@"GENERAL_ERROR_TITLE", @"");
  561. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:string
  562. message:NSLocalizedString(txt,@"")
  563. delegate:self
  564. cancelButtonTitle:NSLocalizedString(@"LOGIN_RESEND_ACTIVATION",@"")
  565. otherButtonTitles:NSLocalizedString(@"GENERAL_OK",@""),nil];
  566. [alert setTag:3];
  567. [alert show];
  568. if (!is_authenticated && !is_guest) {
  569. [self logout];
  570. [self tryLogin];
  571. }
  572. } else if ([txt isEqualToString:@"LOGIN_ERROR_BANNED_USER"]) {
  573. NSString *string = NSLocalizedString(@"GENERAL_ERROR_TITLE", @"");
  574. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:string
  575. message:NSLocalizedString(txt,@"")
  576. delegate:self
  577. cancelButtonTitle:NSLocalizedString(@"GENERAL_OK",@"")
  578. otherButtonTitles:nil];
  579. [alert setTag:4];
  580. [alert show];
  581. if (!is_authenticated && !is_guest) {
  582. [self logout];
  583. [self tryLogin];
  584. }
  585. }
  586. kHIDEWAIT;
  587. }
  588. -(void)tryLogin
  589. {
  590. // KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:kAPPNAME accessGroup:nil];
  591. // NSData *passData = [keychainItem objectForKey:(__bridge id)(kSecValueData)];
  592. // NSString *oldUsername = [keychainItem objectForKey:(__bridge id)(kSecAttrAccount)];
  593. // NSString *oldPassword = [[NSString alloc] initWithBytes:[passData bytes] length:[passData length] encoding:NSUTF8StringEncoding];
  594. // if (![oldPassword isEqualToString:@""]) {
  595. // [SSKeychain setPassword:oldUsername forService:kAPPNAME account:@"username"];
  596. // [SSKeychain setPassword:oldPassword forService:kAPPNAME account:@"password"];
  597. // [keychainItem resetKeychainItem];
  598. // }
  599. if([self checkIfNetworkAvailable]){
  600. NSString *username = [SSKeychain passwordForService:kAPPNAME account:@"username"];
  601. NSString *password = [SSKeychain passwordForService:kAPPNAME account:@"password"];
  602. //guest_id = [SSKeychain passwordForService:kAPPNAME account:@"guest_id"];
  603. NSString *guest_id = [SSKeychain passwordForService:kAPPNAME account:@"guest_id"];
  604. if (guest_id == nil || [guest_id isEqualToString:@"(null)"] || [guest_id isEqualToString:@""]) {
  605. guest_id = [self getSettingWithKey:@"guest_id"];
  606. } else {
  607. [self saveSettingWithKey:@"guest_id" andData:guest_id];
  608. }
  609. if (guest_id == nil || [guest_id isEqualToString:@"(null)"] || [guest_id isEqualToString:@""]) {
  610. guest_id = @"";
  611. }
  612. if(username != nil){
  613. [self authenticate:username password:password guest_id:guest_id];
  614. } else {
  615. [self authenticate:@"" password:@"" guest_id:guest_id];
  616. }
  617. }
  618. }
  619. -(void)saveLoginInfo:(NSDictionary *)info
  620. {
  621. //DCMSG(info);
  622. //clean wb keychain
  623. for (int i = 0; i < [[SSKeychain accountsForService:kAPPNAME] count]; i++) {
  624. (void)[SSKeychain deletePasswordForService:kAPPNAME account:[[[SSKeychain accountsForService:kAPPNAME] objectAtIndex:i] objectForKey:@"acct"]];
  625. }
  626. for (NSString* key in info) {
  627. if ([[info objectForKey:key] length] > 0) {
  628. [SSKeychain setPassword:[info objectForKey:key] forService:kAPPNAME account:key];
  629. }
  630. }
  631. token = [info objectForKey:@"token"];
  632. vzaar_key = [info objectForKey:@"vzaar_key"];
  633. vzaar_secret = [info objectForKey:@"vzaar_secret"];
  634. //guest_id = [info objectForKey:@"guest_id"];
  635. [self saveSettingWithKey:@"guest_id" andData:[info objectForKey:@"guest_id"]];
  636. }
  637. -(void)logout {
  638. DCMSG(@"Logout");
  639. [self removePushNotificationToken];
  640. //NSString *guest_id = [SSKeychain passwordForService:kAPPNAME account:@"guest_id"]; // save guest_id
  641. NSInteger count = [[SSKeychain accountsForService:kAPPNAME] count];
  642. NSArray *acct = [NSArray arrayWithArray:[SSKeychain accountsForService:kAPPNAME]];
  643. // clean keychain
  644. for (int i = 0; i < count; i++) {
  645. (void)[SSKeychain deletePasswordForService:kAPPNAME account:[[acct objectAtIndex:i] objectForKey:@"acct"]];
  646. }
  647. [SSKeychain setPassword:[self getSettingWithKey:@"guest_id"] forService:kAPPNAME account:@"guest_id"]; //restore guest_id
  648. [[wbData sharedData] clearData];
  649. [[wbUser sharedUser] flushUser];
  650. is_guest = YES;
  651. is_authenticated = NO;
  652. //DCMSG([SSKeychain accountsForService:kAPPNAME]);
  653. }
  654. //////////////////////////
  655. -(void)getDataWithEndpoint:(NSString*)endpoint delegate:(id)delegate
  656. {
  657. [self getDataWithURL:[NSString stringWithFormat:@"%@/%@",kWHAMBUSHAPIURL,endpoint] delegate:delegate];
  658. }
  659. -(void)getDataWithURL:(NSString*)urlStr delegate:(id)delegate
  660. {
  661. [self getDataWithURL:[NSURL URLWithString:urlStr] delegate:delegate selectorName:@"dataReady:"];
  662. }
  663. -(void)getDataWithURL:(NSURL*)url delegate:(id)delegate selectorName:(NSString*)selectorName
  664. {
  665. [self getJSONWithURL:url response:^(id data){
  666. [delegate performSelectorOnMainThread:NSSelectorFromString(selectorName) withObject:data waitUntilDone:NO];
  667. }];
  668. }
  669. //////////////////////////
  670. //////////////////////////
  671. -(void)showNoteWithTxt:(NSString*)noteTxt
  672. {
  673. NSString *string = NSLocalizedString(@"GENERAL_NOTE_TITLE", @"");
  674. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:string
  675. message:noteTxt
  676. delegate:nil
  677. cancelButtonTitle:NSLocalizedString(@"GENERAL_OK",@"")
  678. otherButtonTitles:nil];
  679. [alert show];
  680. kHIDEWAIT;
  681. }
  682. -(void)showErrorWithTxt:(NSString*)errorTxt
  683. {
  684. NSString *string = NSLocalizedString(@"GENERAL_ERROR_TITLE", @"");
  685. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:string
  686. message:errorTxt
  687. delegate:nil
  688. cancelButtonTitle:NSLocalizedString(@"GENERAL_OK",@"")
  689. otherButtonTitles:nil];
  690. [alert show];
  691. kHIDEWAIT;
  692. }
  693. -(void)askPromoCode:(NSString*)errorTxt
  694. {
  695. NSString *string = NSLocalizedString(@"GENERAL_ERROR_TITLE", @"");
  696. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:string
  697. message:errorTxt
  698. delegate:self
  699. cancelButtonTitle:NSLocalizedString(@"REGISTER_NOTIFY_WHEN_AVAILABLE",@"")
  700. otherButtonTitles:NSLocalizedString(@"GENERAL_OK",@""),nil];
  701. [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
  702. [alert setTag:1];
  703. [alert show];
  704. kHIDEWAIT;
  705. }
  706. -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  707. {
  708. if (alertView.tag == 1) { //askPromocode
  709. if (buttonIndex == 1) {
  710. NSMutableDictionary *new = [NSMutableDictionary dictionaryWithDictionary:newUserArray];
  711. [new setObject:[alertView textFieldAtIndex:0].text forKey:@"promocode"];
  712. DCMSG(new);
  713. DCMSG([alertView textFieldAtIndex:0].text);
  714. DCMSG(alertView);
  715. [self createUser:new];
  716. } else {
  717. NSDictionary *dataDic = [NSDictionary dictionaryWithObject:[newUserArray objectForKey:@"email"] forKey:@"email"];
  718. [self postJSONWithURL:[self urlWithEndpoint:@"subscribe/waitinglist/"] paramenters:dataDic response:^(id data){} errorResponse:^(id data){}];
  719. }
  720. }
  721. if (alertView.tag == 2) { //forgetPassword
  722. if (buttonIndex == 0) {
  723. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:NSLocalizedString(kRESETPASSWORDLINK,@"")]];
  724. }
  725. }
  726. if (alertView.tag == 3) { //inactive user
  727. if (buttonIndex == 0) {
  728. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:NSLocalizedString(kRESENDACTIVATIONLINK,@"")]];
  729. }
  730. }
  731. if (alertView.tag == 4) { //banned user
  732. // [[wbLoginRegisterViewController sharedLRVC] showLoginScreen];
  733. }
  734. }
  735. //////////////////////////
  736. -(void)setMissionData:(NSDictionary *)missionData
  737. {
  738. if(uploadData == nil){
  739. uploadData = [[NSMutableDictionary alloc]init];
  740. }
  741. if (missionData == nil) {
  742. [uploadData removeObjectForKey:@"missionData"];
  743. }else {
  744. [uploadData setObject:missionData forKey:@"missionData"];
  745. }
  746. DCMSG(uploadData);
  747. }
  748. //////////////////////////
  749. -(void)setVideoURL:(NSURL *)url
  750. {
  751. if(uploadData == nil){
  752. uploadData = [[NSMutableDictionary alloc]init];
  753. }
  754. AVAssetTrack *track = [[[AVURLAsset URLAssetWithURL:url options:nil] tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
  755. CGFloat videoAngleInDegree = atan2([track preferredTransform].b, [track preferredTransform].a)*180/M_PI;
  756. //DNSLog(@"width %f, height %f, angle %f",track.naturalSize.width,track.naturalSize.height,videoAngleInDegree);
  757. float uploadWidth;
  758. if (videoAngleInDegree == 90 || videoAngleInDegree == 270) {
  759. uploadWidth = ceilf(track.naturalSize.height/(track.naturalSize.width/(kVIDEOHEIGHT * 16.0/9.0)));
  760. if (uploadWidth > kVIDEOHEIGHT) {
  761. uploadWidth = kVIDEOHEIGHT;
  762. }
  763. } else {
  764. uploadWidth = track.naturalSize.width/(track.naturalSize.height/(float)kVIDEOHEIGHT);
  765. if (uploadWidth > ceilf((kVIDEOHEIGHT * 16.0/9.0))) {
  766. uploadWidth = ceilf((kVIDEOHEIGHT * 16.0/9.0));
  767. }
  768. }
  769. //DNSLog(@"upload width: %f : %f : %f : %f",uploadWidth,uploadWidth*(16.0/9.0),track.naturalSize.width,track.naturalSize.height);
  770. [uploadData setObject:[NSNumber numberWithInteger:uploadWidth] forKey:@"width"];
  771. [uploadData setObject:url forKey:@"url"];
  772. DCMSG(uploadData);
  773. track = nil;
  774. }
  775. -(void)clearUploadData
  776. {
  777. if(uploadData != nil){
  778. uploadData = nil;
  779. }
  780. }
  781. //////////////////////////
  782. -(void)finalizeUpload:(NSDictionary*)info vzaarId:(NSInteger)videoid missionId:(NSInteger)missionId delegate:(id)delegate
  783. {
  784. NSMutableDictionary *wbInfo = [[NSMutableDictionary alloc] initWithDictionary:info];
  785. [wbInfo setObject:[NSString stringWithFormat:@"%ld",(long)videoid] forKey:@"external_id"];
  786. if (missionId > 0) {
  787. [wbInfo setObject:[NSNumber numberWithInteger:missionId] forKey:@"mission_id"];
  788. }
  789. DCMSG(wbInfo);
  790. [self postJSONWithURL:[self urlWithEndpoint:kVIDEOAPI] paramenters:wbInfo response:^(id data){
  791. DCMSG(data);
  792. //update mission data
  793. if (missionId > 0) {
  794. wbMission *mission = [[wbData sharedData] getMissionWithId:[NSNumber numberWithInteger:missionId]];
  795. [mission updateMissionData];
  796. }
  797. [delegate performSelectorOnMainThread:@selector(uploadDone:) withObject:@YES waitUntilDone:NO];
  798. } errorResponse:^(id data){
  799. DCMSG(data);
  800. [delegate performSelectorOnMainThread:@selector(uploadDone:) withObject:@NO waitUntilDone:NO];
  801. }];
  802. }
  803. -(void)finalizeUpload:(NSDictionary*)info vzaarId:(NSInteger)videoid delegate:(id)delegate
  804. {
  805. [self finalizeUpload:info vzaarId:videoid missionId:-1 delegate:delegate];
  806. }
  807. //////////////////////////
  808. -(void)addComment:(NSString*)comment videoid:(NSInteger)videoid delegate:(id)delegate
  809. {
  810. NSDictionary *commentDic = [[NSDictionary alloc] initWithObjectsAndKeys:
  811. comment, @"comment", nil];
  812. DCMSG(commentDic);
  813. [self postJSONWithURL:[self urlWithEndpoint:[NSString stringWithFormat:@"%@video/%ld/",kCOMMENTAPI,(long)videoid]] paramenters:commentDic response:^(id data){
  814. DCMSG(data);
  815. [delegate performSelectorOnMainThread:@selector(refresh:) withObject:NULL waitUntilDone:YES];
  816. kHIDEWAIT
  817. } errorResponse:^(id data){
  818. DCMSG(data);
  819. kHIDEWAIT
  820. }];
  821. }
  822. //////////////////////////
  823. -(void)like:(BOOL)like videoid:(NSString*)videoid delegate:(id)delegate
  824. {
  825. NSDictionary *likeDic = [[NSDictionary alloc] initWithObjectsAndKeys:
  826. videoid, @"video_id", nil];
  827. DCMSG(likeDic);
  828. if(like){
  829. DMSG;
  830. [self postJSONWithURL:[self urlWithEndpoint:@"like/video/"] paramenters:likeDic response:^(id data){
  831. DCMSG(data);
  832. [delegate performSelector:@selector(likeDone:count:) withObject:[NSNumber numberWithInt:1] withObject:[NSNumber numberWithLong:[[data valueForKey:@"likes"] longValue]]];
  833. kHIDEWAIT
  834. } errorResponse:^(id data){
  835. DCMSG(data);
  836. [delegate performSelector:@selector(likeDone:count:) withObject:[NSNumber numberWithInt:1] withObject:[NSNumber numberWithLong:0]];
  837. kHIDEWAIT
  838. }];
  839. } else {
  840. [self postJSONWithURL:[self urlWithEndpoint:@"dislike/video/"] paramenters:likeDic response:^(id data){
  841. DCMSG(data);
  842. [delegate performSelector:@selector(likeDone:count:) withObject:[NSNumber numberWithInt:3] withObject:[NSNumber numberWithLong:[[data valueForKey:@"dislikes"] longValue]]];
  843. kHIDEWAIT
  844. } errorResponse:^(id data){
  845. DCMSG(data);
  846. [delegate performSelector:@selector(likeDone:count:) withObject:[NSNumber numberWithInt:3] withObject:[NSNumber numberWithLong:0]];
  847. kHIDEWAIT
  848. }];
  849. }
  850. }
  851. -(void)unlike:(BOOL)like videoid:(NSString*)videoid delegate:(id)delegate
  852. {
  853. NSDictionary *likeDic = [[NSDictionary alloc] initWithObjectsAndKeys:
  854. videoid, @"video_id", nil];
  855. DCMSG(likeDic);
  856. if(like){
  857. [self postJSONWithURL:[self urlWithEndpoint:@"unlike/video/"] paramenters:likeDic response:^(id data){
  858. DCMSG(data);
  859. [delegate performSelector:@selector(likeDone:count:) withObject:[NSNumber numberWithInt:2] withObject:[NSNumber numberWithLong:[[data valueForKey:@"likes"] longValue]]];
  860. kHIDEWAIT
  861. } errorResponse:^(id data){
  862. DCMSG(data);
  863. [delegate performSelector:@selector(likeDone:count:) withObject:[NSNumber numberWithInt:2] withObject:[NSNumber numberWithLong:0]];
  864. kHIDEWAIT
  865. }];
  866. } else {
  867. [self postJSONWithURL:[self urlWithEndpoint:@"undislike/video/"] paramenters:likeDic response:^(id data){
  868. DCMSG(data);
  869. [delegate performSelector:@selector(likeDone:count:) withObject:[NSNumber numberWithInt:4] withObject:[NSNumber numberWithLong:[[data valueForKey:@"dislikes"] longValue]]];
  870. kHIDEWAIT
  871. } errorResponse:^(id data){
  872. DCMSG(data);
  873. [delegate performSelector:@selector(likeDone:count:) withObject:[NSNumber numberWithInt:4] withObject:[NSNumber numberWithLong:0]];
  874. kHIDEWAIT
  875. }];
  876. }
  877. }
  878. //////////////////////////
  879. -(NSString*)beautifyTime:(NSString*)timeString
  880. {
  881. if (timeString == nil || [timeString isKindOfClass:[NSNull class]] || [timeString isEqualToString:@""]) {
  882. return @"";
  883. }
  884. NSDateFormatter* gmtDf = [[NSDateFormatter alloc] init];
  885. [gmtDf setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
  886. if ([timeString rangeOfString:@"."].location == NSNotFound) {
  887. [gmtDf setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
  888. } else {
  889. [gmtDf setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
  890. }
  891. NSDate* gmtDate = [gmtDf dateFromString:timeString];
  892. NSDateFormatter* locDf = [[NSDateFormatter alloc] init];
  893. [locDf setTimeZone:[NSTimeZone localTimeZone]];
  894. [locDf setDateFormat:@"dd.MM.yyyy HH:mm"];
  895. return [locDf stringFromDate:gmtDate];
  896. }
  897. -(NSString*)parsePostedTime:(NSString*)timeString
  898. {
  899. if (timeString == nil || [timeString isKindOfClass:[NSNull class]] || [timeString isEqualToString:@""]) {
  900. return @"";
  901. }
  902. //timeString = @"2013-10-30T17:26:00";
  903. //DCMSG(timeString);
  904. NSDateFormatter* gmtDf = [[NSDateFormatter alloc] init];
  905. [gmtDf setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
  906. if ([timeString rangeOfString:@"."].location == NSNotFound) {
  907. [gmtDf setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
  908. } else {
  909. [gmtDf setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
  910. }
  911. NSDate* gmtDate = [gmtDf dateFromString:timeString];
  912. NSDateFormatter* locDf = [[NSDateFormatter alloc] init];
  913. [locDf setTimeZone:[NSTimeZone localTimeZone]];
  914. [locDf setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
  915. NSDate *dateLoc = [locDf dateFromString:[locDf stringFromDate:gmtDate]];
  916. NSTimeInterval since = fabs([dateLoc timeIntervalSinceNow]);
  917. NSInteger days = (since/(3600 * 24));
  918. NSInteger weeks = (days/7);
  919. NSInteger hours = (since/3600);
  920. NSInteger minutes = (since/60);
  921. gmtDf = nil;
  922. gmtDate = nil;
  923. locDf = nil;
  924. dateLoc = nil;
  925. //NSLog(@"time: %@ = w: %d, d:%d, h:%d, m:%d",[locDf stringFromDate:gmtDate],weeks,days,hours,minutes);
  926. if (days > 6) {
  927. if (days < 14) {
  928. return NSLocalizedString(@"POSTED_WEEK_AGO",@"");
  929. } else {
  930. if (weeks > 4) {
  931. return NSLocalizedString(@"POSTED_LONG_TIME_AGO",@"");
  932. } else {
  933. return [NSString stringWithFormat:NSLocalizedString(@"POSTED_NRO_WEEKS_AGO",@""),(long)weeks];
  934. }
  935. }
  936. } else if (days > 0) {
  937. if (days == 1) {
  938. return NSLocalizedString(@"POSTED_DAY_AGO",@"");
  939. } else {
  940. return [NSString stringWithFormat:NSLocalizedString(@"POSTED_NRO_DAYS_AGO",@""),(long)days];
  941. }
  942. } else {
  943. if (hours < 1) {
  944. if (minutes < 1) {
  945. return NSLocalizedString(@"POSTED_JUST_NOW",@"");
  946. } else {
  947. return [NSString stringWithFormat:NSLocalizedString(@"POSTED_NRO_MINUTES_AGO",@""),(long)minutes];
  948. }
  949. } else if (hours == 1){
  950. return NSLocalizedString(@"POSTED_HOUR_AGO",@"");
  951. } else {
  952. return [NSString stringWithFormat:NSLocalizedString(@"POSTED_NRO_HOURS_AGO",@""),(long)hours];
  953. }
  954. }
  955. return NSLocalizedString(@"POSTED_SOMETIME",@"");
  956. }
  957. -(NSString*)parseMissionEndTime:(NSString*)timeString
  958. {
  959. if (timeString == nil || [timeString isKindOfClass:[NSNull class]] || [timeString isEqualToString:@""]) {
  960. return @"";
  961. }
  962. NSDateFormatter* gmtDf = [[NSDateFormatter alloc] init];
  963. [gmtDf setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
  964. [gmtDf setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
  965. NSDate* gmtDate = [gmtDf dateFromString:timeString];
  966. NSDateFormatter* locDf = [[NSDateFormatter alloc] init];
  967. [locDf setTimeZone:[NSTimeZone localTimeZone]];
  968. [locDf setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
  969. NSDate *dateLoc = [locDf dateFromString:[locDf stringFromDate:gmtDate]];
  970. NSTimeInterval since = fabs([dateLoc timeIntervalSinceNow]);
  971. gmtDf = nil;
  972. gmtDate = nil;
  973. locDf = nil;
  974. dateLoc = nil;
  975. NSInteger days = ceil(since/(3600 * 24));
  976. NSInteger hours = floor(since/3600);
  977. if (days > 6) {
  978. if (days < 14) {
  979. return NSLocalizedString(@"ENDS_AFTER_A_WEEK",@"");
  980. } else {
  981. NSInteger weeks = floor(days/7);
  982. if (weeks > 4) {
  983. return NSLocalizedString(@"ENDS_NOT_ANY_TIME_SOON",@"");
  984. } else {
  985. return [NSString stringWithFormat:NSLocalizedString(@"ENDS_AFTER_NRO_WEEKS",@""),(long)weeks];
  986. }
  987. }
  988. } else if (days > 0 && hours > 24) {
  989. if (days == 1) {
  990. return NSLocalizedString(@"ENDS_AFTER_A_DAY",@"");
  991. } else {
  992. return [NSString stringWithFormat:NSLocalizedString(@"ENDS_AFTER_NRO_DAYS",@""),(long)days];
  993. }
  994. } else {
  995. /