/WHAMBUSH/wbAPI.m
Objective C | 1155 lines | 895 code | 160 blank | 100 comment | 213 complexity | 40f1a9a509a3ff1f062844df24a3d064 MD5 | raw file
- //
- // wbAPI.m
- // WHAMBUSH
- //
- // Created by Jari Kalinainen on 8/26/13.
- // Copyright (c) 2013 Jari Kalinainen. All rights reserved.
- //
- #import "wbAPI.h"
- #import <sys/utsname.h>
- @implementation wbAPI
- @synthesize rootViewController;
- @synthesize uploadData;
- @synthesize currentViewController;
- @synthesize token;
- @synthesize pushToken;
- @synthesize vzaar_key;
- @synthesize vzaar_secret;
- //@synthesize guest_id;
- @synthesize num_active_missions;
- @synthesize num_incomplete_profile;
- @synthesize num_unread_activities;
- @synthesize uploading;
- //@synthesize GPUCamera;
- @synthesize iPhoneVersion;
- @synthesize is_guest;
- @synthesize portraitFrame;
- @synthesize landscapeFrame;
- @synthesize is_authenticated;
- @synthesize currentCountry;
- -(id) init
- {
- DPRINTCLASS;
- self = [super init];
- if (self) {
- uploading = NO;
- // if (waitView == nil) {
- // waitView = [[wbWaitView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width,[[UIScreen mainScreen] bounds].size.height)];
- // [waitView setHidden:YES];
- // [[[[UIApplication sharedApplication] delegate] window] addSubview:waitView];
- // }
- float width = [[UIScreen mainScreen] bounds].size.width;
- float height = [[UIScreen mainScreen] bounds].size.height;
-
- if (width < height) {
- portraitFrame = CGRectMake(0, 0, width, height);
- landscapeFrame = CGRectMake(0, 0, height, width);
- } else {
- landscapeFrame = CGRectMake(0, 0, width, height);
- portraitFrame = CGRectMake(0, 0, height, width);
- }
- firstTimeFail = NO;
- newUser = NO;
- }
- return self;
- }
- + (id)sharedAPI
- {
- static dispatch_once_t pred = 0;
- __strong static id _sharedObject = nil;
- dispatch_once(&pred, ^{
- _sharedObject = [[self alloc] init];
- });
- return _sharedObject;
- }
- -(NSString*)description
- {
- return [super description];
- }
- /////////////////////////
- -(float)statusBarHeight
- {
- //DNSLog(@"statusbar: %f",[UIApplication sharedApplication].statusBarFrame.size.height);
- float statusBarHeightLoc = [UIApplication sharedApplication].statusBarFrame.size.height;
- //DNSLog(@"statsbar : %f",statusBarHeightLoc);
- // [[wbFooter sharedFooter] setFixVal:0];
- if (statusBarHeightLoc > 20 || statusBarHeightLoc == NAN) {
- statusBarHeightLoc = 20;
- // [[wbFooter sharedFooter] setFixVal:20];
- }
- return statusBarHeightLoc;
- }
- -(float)footerBarHeight
- {
- float footerBarHeightLoc = 50.0;
- return footerBarHeightLoc;
- }
- -(float)headerBarHeight
- {
- // float headerY;
- // float logoY;
- // if ([self statusBarHeight] > 20) {
- // headerY = 20;
- // logoY = 0;
- // } else {
- // headerY = 0;
- // logoY = 10;
- // }
- float headBarHeightLoc = 50 + [self statusBarHeight];
- return headBarHeightLoc;
- }
- -(CGRect)headerBarRect
- {
- CGRect headerBarRectLoc = CGRectMake(0, 0, [[wbAPI sharedAPI] portraitFrame].size.width,[self headerBarHeight]);
-
- return headerBarRectLoc;
- }
- -(CGRect)footerBarRect
- {
- CGRect footerBarRectLoc = CGRectMake(0, [[wbAPI sharedAPI] portraitFrame].size.height-([self footerBarHeight]/*+[self statusBarHeight]-20*/), [[wbAPI sharedAPI] portraitFrame].size.width, [self footerBarHeight]);
-
- return footerBarRectLoc;
- }
- -(CGRect)contentRect
- {
- //CGRect headerBarRect = [self headerBarRect];
- CGRect footerBarRect = [self footerBarRect];
-
- CGRect contentRectLoc = CGRectMake(0, CGRectGetMaxY([self headerBarRect])/*[self headerBarHeight]*/, [[wbAPI sharedAPI] portraitFrame].size.width,CGRectGetMinY(footerBarRect)-[self headerBarHeight]/*-CGRectGetMaxY(headerBarRect)*/);
-
- return contentRectLoc;
- }
- /////////////////////////
- -(BOOL)checkIfNetworkAvailable
- {
- Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
- DCMSG(@"Check network");
- NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
- if (networkStatus == NotReachable) {
- DNSLog(@"There IS NO internet connection");
- [self showErrorWithTxt:NSLocalizedString(@"GENERAL_ERROR_NO_NETWORK", @"")];
- networkReachability = nil;
- kHIDEWAIT;
- return NO;
- } else {
- if ([self checkAPIReachability]) {
- if (networkStatus == ReachableViaWiFi) {
- page_size = 30;
- } else {
- page_size = 20;
- }
- networkReachability = nil;
- return YES;
- } else {
- [self showErrorWithTxt:NSLocalizedString(@"GENERAL_ERROR_NO_NETWORK", @"")];
- networkReachability = nil;
- return NO;
- }
- }
- }
- -(BOOL)checkAPIReachability {
- Reachability *apiReachability = [Reachability reachabilityWithHostname:kWHAMBUSHDOTNET];
- DCMSG(@"Check API");
- NetworkStatus apiStatus = [apiReachability currentReachabilityStatus];
- DCMSG(@"Check API, DONE");
- if (apiStatus == NotReachable) {
- apiReachability = nil;
- DCMSG(@"NO API?");
- return YES;
- } else {
- apiReachability = nil;
- return YES;
- }
-
- }
- -(NSURL*)urlWithEndpoint:(NSString*)endpoint
- {
- NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",kWHAMBUSHAPIURL,endpoint]];
- return url;
- }
- /////////////////////////////////////
- -(void)getJSONWithURL:(NSURL *)url response:(void (^)(id json))jsonResponse
- {
- AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
- manager.requestSerializer = [AFJSONRequestSerializer serializer];
- manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions: NSJSONReadingMutableContainers];
-
- manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",nil];
-
- DCMSG(kWHAMBUSHTOKEN);
- DNSLog(@"-> %@",[url absoluteString]);
- DNSLog(@"-> %@",[url path]);
- //DNSLog(@"-> %@",[url pathComponents]);
- //DNSLog(@"-> %@",[url pathExtension]);
-
- if (kWHAMBUSHTOKEN != nil && is_authenticated) {
- NSAssert(kWHAMBUSHTOKEN != nil,@"");
- [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",kWHAMBUSHTOKEN] forHTTPHeaderField:@"Authorization"];
- }
-
- NSDictionary *parameters;
- if (!no_page){
- parameters = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld",(long)page_size],@"page_size", nil];
- } else {
- parameters = nil;
- }
-
- [manager GET:[url absoluteString] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
- DNSLog(@"Request: %@", operation.request);
- jsonResponse(responseObject);
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
- NSLog(@"1Error: %@", error);
- DNSLog(@"2Error: %@",operation.request);
- DNSLog(@"3Error: %@",operation.response);
- DNSLog(@"4Error: %@",operation.responseObject);
- DNSLog(@"5Error: %@",[operation.responseObject class]);
- if ([[operation.responseObject objectForKey:@"detail"] isEqualToString:@"TOKEN_ERROR_INACTIVE_USER"]) {
- [SSKeychain deletePasswordForService:kAPPNAME account:@"guest_id"];
- [self removeSettingWithKey:@"guest_id"];
- is_authenticated = NO;
- [self tryLogin];
- } else {
- NSArray *path = [[operation.request URL] pathComponents];
- NSString *pathString;
- if ([path count] > 3) {
- pathString = [NSString stringWithFormat:@"%@/%@",[path objectAtIndex:[path count]-2],[path objectAtIndex:[path count]-1]];
- } else {
- pathString = [NSString stringWithFormat:@"%@",[path lastObject]];
- }
- if ([operation.response statusCode] == 404) {
- [self performSelectorOnMainThread:@selector(showErrorWithTxt:) withObject:[NSString stringWithFormat:@"%@\nPath: %@",NSLocalizedString(@"GENERAL_ERROR_404",@""),pathString] waitUntilDone:NO];
- [kROOTVC performSelector:@selector(goHome:) withObject:nil];
- } else {
- NSString *errorTxt = [NSString stringWithFormat:@"%@\nCode: %ld %@",NSLocalizedString(@"GENERAL_ERROR_MAJOR",@""),(long)[operation.response statusCode],pathString];
- [self performSelectorOnMainThread:@selector(showErrorWithTxt:) withObject:errorTxt waitUntilDone:NO];
- }
- }
- }];
- }
- /////////////////////////////////////
- -(void)postJSONWithURL:(NSURL*)url paramenters:(NSDictionary*)parameters response:(void (^)(id json))jsonResponse errorResponse:(void (^)(id errorResponse))errorResponse
- {
- AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
- manager.requestSerializer = [AFJSONRequestSerializer serializer];
- manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions: NSJSONReadingMutableContainers];
-
- //DCMSG(kWHAMBUSHTOKEN);
-
- if (kWHAMBUSHTOKEN != nil && is_authenticated) {
- [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",kWHAMBUSHTOKEN] forHTTPHeaderField:@"Authorization"];
- }
-
- [manager POST:[url absoluteString] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
- DNSLog(@"Request: %@", operation.request);
- jsonResponse(responseObject);
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
- DNSLog(@"Error: %@",operation.responseObject);
- DNSLog(@"Operation request: %@",operation.request);
- DNSLog(@"Operation response: %@",operation.response);
- errorResponse(operation.responseObject);
- }];
- }
- /////////////////////////////////////
- -(void)deleteJSONWithURL:(NSURL*)url paramenters:(NSDictionary*)parameters response:(void (^)(id json))jsonResponse errorResponse:(void (^)(id errorResponse))errorResponse
- {
- AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
- manager.requestSerializer = [AFJSONRequestSerializer serializer];
- manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions: NSJSONReadingMutableContainers];
-
- if (kWHAMBUSHTOKEN != nil) {
- [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",kWHAMBUSHTOKEN] forHTTPHeaderField:@"Authorization"];
- }
-
- [manager DELETE:[url absoluteString] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
- DNSLog(@"Operation: %@",operation);
- DNSLog(@"Response: %@",responseObject);
- jsonResponse(responseObject);
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
- DNSLog(@"Error: %@",operation.responseObject);
- errorResponse(operation.responseObject);
- }];
- }
- /////////////////////////////////////
- -(void)putJSONWithURL:(NSURL*)url paramenters:(NSDictionary*)parameters response:(void (^)(id json))jsonResponse errorResponse:(void (^)(id errorResponse))errorResponse
- {
- AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
- manager.requestSerializer = [AFJSONRequestSerializer serializer];
- manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions: NSJSONReadingMutableContainers];
-
- if (kWHAMBUSHTOKEN != nil) {
- [manager.requestSerializer setValue:[NSString stringWithFormat:@"Token %@",kWHAMBUSHTOKEN] forHTTPHeaderField:@"Authorization"];
- }
-
- [manager PUT:[url absoluteString] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
- DNSLog(@"Operation: %@",operation);
- DNSLog(@"Response: %@",responseObject);
- jsonResponse(responseObject);
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
- DNSLog(@"Error: %@",operation.responseObject);
- errorResponse(operation.responseObject);
- }];
- }
- /////////////////////////////////////
- -(void)createUser:(NSDictionary *)userArray {
- [self postJSONWithURL:[self urlWithEndpoint:@"users/"] paramenters:userArray
- response:^(id data){
- NSString *guest_id = [self getSettingWithKey:@"guest_id"];
- [self saveLoginInfo:[NSDictionary dictionaryWithObjectsAndKeys:[userArray objectForKey:@"password1"],@"password",[userArray objectForKey:@"username"],@"username",guest_id,@"guest_id", nil]];
- [[wbLoginRegisterViewController sharedLRVC] closeAlert];
- newUser = TRUE;
- [[wbAPI sharedAPI] tryLogin];
- kHIDEWAIT;
- [self performSelectorOnMainThread:@selector(showNoteWithTxt:) withObject:[NSString stringWithFormat:NSLocalizedString(@"REGISTER_NEW_USER_INFO",@""),[userArray objectForKey:@"email"]] waitUntilDone:NO];
- }
- errorResponse:^(id data){
- kHIDEWAIT;
- if ([data objectForKey:@"username"] != nil) {
- [self performSelectorOnMainThread:@selector(showErrorWithTxt:) withObject:NSLocalizedString(@"REGISTER_ERROR_USERNAME",@"") waitUntilDone:NO];
- } else if ([data objectForKey:@"email"] != nil) {
- [self performSelectorOnMainThread:@selector( showErrorWithTxt:) withObject:NSLocalizedString(@"REGISTER_ERROR_EMAIL",@"") waitUntilDone:NO];
- } else if ([data objectForKey:@"promocode"] != nil) {
- newUserArray = userArray;
- [self performSelectorOnMainThread:@selector( askPromoCode:) withObject:NSLocalizedString(@"REGISTER_ERROR_PROMO_CODE",@"") waitUntilDone:NO];
- } else {
- [self performSelectorOnMainThread:@selector( showErrorWithTxt:) withObject:NSLocalizedString(@"GENERAL_ERROR_MAJOR",@"") waitUntilDone:NO];
- }
- }
- ];
-
- }
- -(void)getPhoneVersion
- {
- struct utsname systemInfo;
- uname(&systemInfo);
- NSString *idString;
- idString = [[NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@"iPhone" withString:@""];
- idString = [idString stringByReplacingOccurrencesOfString:@"," withString:@"."];
- NSInteger majorDeviceNumber = [idString floatValue];
-
- DNSLog(@"device version %@",idString);
- DNSLog(@"device version %ld",(long)majorDeviceNumber);
-
- iPhoneVersion = [NSNumber numberWithLong:majorDeviceNumber];
-
- }
- -(void)authenticate:(NSString *)username password:(NSString *)password guest_id:(NSString*)guestId
- {
- DCMSG(rootViewController);
- if([self checkIfNetworkAvailable]){
- struct utsname systemInfo;
- uname(&systemInfo);
- NSDictionary *loginArray = [NSDictionary dictionaryWithObjectsAndKeys:
- username,@"username",
- password,@"password",
- @"Apple",@"manufacturer",
- @"iOS",@"os",
- [UIDevice currentDevice].systemVersion,@"os_version",
- [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding],@"device",
- [[NSUserDefaults standardUserDefaults] objectForKey:@"version"],@"whambush_version",
- guestId,@"guest_id",
- nil];
-
- //DCMSG(loginArray);
-
- [self getPhoneVersion];
-
- [self postJSONWithURL:[self urlWithEndpoint:kAUTHENTICATE] paramenters:loginArray
- response:^(id data){
-
- DNSLog(@"data: %@",data);
- NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:
- password,@"password",
- username,@"username",
- [data objectForKey:@"token"],@"token",
- [[data objectForKey:@"settings"] objectForKey:@"vzaar_key"],@"vzaar_key",
- [[data objectForKey:@"settings"] objectForKey:@"vzaar_secret"],@"vzaar_secret",
- [NSString stringWithFormat:@"%@",[data objectForKey:@"guest_id"]] ,@"guest_id",
- nil];
- [self saveLoginInfo:info];
-
- is_authenticated = YES;
-
- [[wbData sharedData] performSelectorInBackground:@selector(getAllCountries) withObject:nil];
- DNSLog(@"%@",currentCountry);
- if (![self checkIfCountryExists] && [password length] < 3) {
- [kROOTVC performSelector:@selector(askCountry)];
- } else {
- [[wbData sharedData] createSupportMessage:loginArray];
-
- if ([data objectForKey:@"num_active_missions"] != nil) {
- num_active_missions = [NSString stringWithFormat:@"%@",[data objectForKey:@"num_active_missions"]];
- } else {
- num_active_missions = @"0";
- }
-
- if ([data objectForKey:@"incomplete"] != nil) {
- num_incomplete_profile = [NSString stringWithFormat:@"%@",[data objectForKey:@"incomplete"]];
- } else {
- num_incomplete_profile = @"0";
- }
-
- if ([data objectForKey:@"unread"] != nil) {
- num_unread_activities = [NSString stringWithFormat:@"%@",[data objectForKey:@"unread"]];
- } else {
- num_unread_activities = @"0";
- }
- [[wbData sharedData] setNum_of_unreadActivities:[NSNumber numberWithInteger:[num_unread_activities integerValue]]];
-
-
- if (pushToken != nil) {
- [self sendPushNotificationToken:pushToken];
- } else {
- if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
- {
- [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
- [[UIApplication sharedApplication] registerForRemoteNotifications];
- }
- else
- {
- [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
- (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
- }
- }
-
- if ([data objectForKey:@"user"] != nil) {
-
- is_guest = NO;
-
- [[wbUser sharedUser] performSelectorOnMainThread:@selector(setUserDetails:) withObject:[data objectForKey:@"user"] waitUntilDone:YES];
- //[[wbUser sharedUser] setUserDetails:[data objectForKey:@"user"]];
- //[[wbUser sharedUser] updateUserData];
- DMSG;
-
- //check if user is NEW
- if ([[[wbUser sharedUser] activation_state] isEqualToString:@"NEW"] && !newUser) {
- NSString *string = NSLocalizedString(@"GENERAL_WARNING_TITLE", @"");
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:string
- message:[NSString stringWithFormat:NSLocalizedString(@"SETTINGS_EMAIL_NOT_ACTIVATED", @""),[[wbUser sharedUser] email]]
- delegate:self
- cancelButtonTitle:NSLocalizedString(@"SETTINGS_EMAIL_RESEND_ACTIVATION",@"")
- otherButtonTitles:NSLocalizedString(@"GENERAL_OK",@""),nil];
- [alert setTag:3];
- [alert show];
- }
-
- //[self saveCurrentCountry:[[wbUser sharedUser] countryDictionary]];
- [self saveSettingWithKey:@"country" andData:[[wbUser sharedUser] countryDictionary]];
- [self setCurrentCountry:[[wbUser sharedUser] countryDictionary]];
- } else {
- is_guest = YES;
- }
- [[wbData sharedData] performSelectorInBackground:@selector(getAllFeeds) withObject:nil];
- [[wbData sharedData] performSelectorInBackground:@selector(getAllMissionFeeds) withObject:nil];
- [[wbData sharedData] performSelectorInBackground:@selector(getAllActivity) withObject:nil];
- //[[wbData sharedData] performSelectorInBackground:@selector(getAllCountries) withObject:nil];
- // [[wbData sharedData] performSelectorInBackground:@selector(getTvChannels) withObject:nil];
- [[wbData sharedData] performSelectorOnMainThread:@selector(getTvChannels) withObject:nil waitUntilDone:NO];
-
- [rootViewController performSelector:@selector(loginOK)];
-
- [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"debugSetting"];
-
- }
-
- }
- errorResponse:^(id data){
- if ([data objectForKey:@"username"] != nil) {
- DMSG;
- [self showLoginErrorWithTxt:@"LOGIN_ERROR_WRONG_CREDENTIALS"];
- } else if ([data objectForKey:@"password"] != nil) {
- DMSG;
- [self showLoginErrorWithTxt:@"LOGIN_ERROR_WRONG_CREDENTIALS"];
- } else if ([data objectForKey:@"guest_id"] != nil) {
- DMSG;
- is_authenticated = NO;
- if ([[[NSUserDefaults standardUserDefaults] stringForKey:@"debugSetting"] isEqualToString:kRESETGUESTID]) {
- [SSKeychain deletePasswordForService:kAPPNAME account:@"guest_id"];
- [self removeSettingWithKey:@"guest_id"];
- //guest_id = @"";
- [self tryLogin];
- } else {
- [self showErrorWithTxt:NSLocalizedString(@"GENERAL_ERROR_MAJOR",@"")];
- }
- } else if ([data objectForKey:@"non_field_errors"] != nil ) {
- DMSG;
- [self showLoginErrorWithTxt:[[data objectForKey:@"non_field_errors"] objectAtIndex:0]];
- } else {
- DMSG;
- [self logout];
- if (!firstTimeFail) {
- firstTimeFail = YES;
- [self tryLogin];
- } else {
- firstTimeFail = NO;
- [self showErrorWithTxt:NSLocalizedString(@"GENERAL_ERROR_MAJOR",@"")];
- }
- }
- DCMSG(data);
- }
- ];
- }
- }
- -(BOOL)checkIfCountryExists
- {
-
- if ([[self getSettingWithKey:@"country"] objectForKey:@"country"] != nil) {
- [self setCurrentCountry:[self getSettingWithKey:@"country"] ];
- DNSLog(@"%@",currentCountry);
- return YES;
- } else {
- return NO;
- }
- }
- //-(void)saveCurrentCountry:(NSDictionary*)country
- //{
- // NSString *error;
- // NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
- // NSString *plistPath = [rootPath stringByAppendingPathComponent:@"settings.plist"];
- //
- // NSDictionary *plistDic;
- // if (country == nil) {
- // plistDic = @{@"guest_id":guest_id};
- // } else {
- // plistDic = @{@"country":country,@"guest_id":guest_id};
- // }
- // id plist = [NSPropertyListSerialization dataFromPropertyList:(id)plistDic format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
- // if(plist) {
- // [plist writeToFile:plistPath atomically:YES];
- // [[wbAPI sharedAPI] setCurrentCountry:country];
- // }
- //
- //}
- //
- -(id)getSettingWithKey:(NSString*)key
- {
- NSString *errorDesc = nil;
- NSPropertyListFormat format;
- NSString *plistPath;
- NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
- NSUserDomainMask, YES) objectAtIndex:0];
- plistPath = [rootPath stringByAppendingPathComponent:@"settings.plist"];
- if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
- plistPath = [[NSBundle mainBundle] pathForResource:@"settings" ofType:@"plist"];
- }
- NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
- NSDictionary *data = (NSDictionary *)[NSPropertyListSerialization
- propertyListFromData:plistXML
- mutabilityOption:NSPropertyListMutableContainersAndLeaves
- format:&format
- errorDescription:&errorDesc];
- if (!data) {
- NSLog(@"Error reading plist: %@, format: %lu", errorDesc, (unsigned long)format);
- }
-
- if (key != nil) {
- return [data objectForKey:key];
- } else {
- return data;
- }
- }
- -(void)saveSettingWithKey:(NSString*)key andData:(id)data
- {
- NSString *error;
- NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
- NSString *plistPath = [rootPath stringByAppendingPathComponent:@"settings.plist"];
- NSDictionary *plistDic;
-
- NSMutableDictionary *settingsData = [[NSMutableDictionary alloc] initWithDictionary:[self getSettingWithKey:nil]];
- if (settingsData != nil) {
- //if ([settingsData objectForKey:key] != nil) {
- [settingsData setObject:data forKey:key];
- //}
- plistDic = settingsData;
- } else {
- plistDic = @{key:data};
- }
- id plist = [NSPropertyListSerialization dataFromPropertyList:(id)plistDic format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
- if(plist) {
- [plist writeToFile:plistPath atomically:YES];
- }
- }
- -(void)removeSettingWithKey:(NSString*)key
- {
- NSString *error;
- NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
- NSString *plistPath = [rootPath stringByAppendingPathComponent:@"settings.plist"];
-
- NSMutableDictionary *settingsData = [[NSMutableDictionary alloc] initWithDictionary:[self getSettingWithKey:nil]];
- if (settingsData != nil) {
- if ([settingsData objectForKey:key] != nil) {
- [settingsData removeObjectForKey:key];
- NSDictionary *plistDic = settingsData;
- id plist = [NSPropertyListSerialization dataFromPropertyList:(id)plistDic format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
- if(plist) {
- [plist writeToFile:plistPath atomically:YES];
- }
- }
- }
- }
- -(void)showLoginErrorWithTxt:(NSString*)txt
- {
- DNSLog(@"%d %d",is_authenticated,is_guest);
- if ([txt isEqualToString:@"LOGIN_ERROR_WRONG_CREDENTIALS"]) {
- NSString *string = NSLocalizedString(@"GENERAL_ERROR_TITLE", @"");
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:string
- message:NSLocalizedString(txt,@"")
- delegate:self
- cancelButtonTitle:NSLocalizedString(@"LOGIN_RESET_PASSWORD",@"")
- otherButtonTitles:NSLocalizedString(@"GENERAL_OK",@""),nil];
- [alert setTag:2];
- [alert show];
- if (!is_authenticated && !is_guest) {
- [self logout];
- [self tryLogin];
- }
- } else if ([txt isEqualToString:@"LOGIN_ERROR_INACTIVE_USER"]) {
- NSString *string = NSLocalizedString(@"GENERAL_ERROR_TITLE", @"");
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:string
- message:NSLocalizedString(txt,@"")
- delegate:self
- cancelButtonTitle:NSLocalizedString(@"LOGIN_RESEND_ACTIVATION",@"")
- otherButtonTitles:NSLocalizedString(@"GENERAL_OK",@""),nil];
- [alert setTag:3];
- [alert show];
- if (!is_authenticated && !is_guest) {
- [self logout];
- [self tryLogin];
- }
- } else if ([txt isEqualToString:@"LOGIN_ERROR_BANNED_USER"]) {
- NSString *string = NSLocalizedString(@"GENERAL_ERROR_TITLE", @"");
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:string
- message:NSLocalizedString(txt,@"")
- delegate:self
- cancelButtonTitle:NSLocalizedString(@"GENERAL_OK",@"")
- otherButtonTitles:nil];
- [alert setTag:4];
- [alert show];
- if (!is_authenticated && !is_guest) {
- [self logout];
- [self tryLogin];
- }
- }
- kHIDEWAIT;
- }
- -(void)tryLogin
- {
- // KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:kAPPNAME accessGroup:nil];
- // NSData *passData = [keychainItem objectForKey:(__bridge id)(kSecValueData)];
- // NSString *oldUsername = [keychainItem objectForKey:(__bridge id)(kSecAttrAccount)];
- // NSString *oldPassword = [[NSString alloc] initWithBytes:[passData bytes] length:[passData length] encoding:NSUTF8StringEncoding];
- // if (![oldPassword isEqualToString:@""]) {
- // [SSKeychain setPassword:oldUsername forService:kAPPNAME account:@"username"];
- // [SSKeychain setPassword:oldPassword forService:kAPPNAME account:@"password"];
- // [keychainItem resetKeychainItem];
- // }
-
-
- if([self checkIfNetworkAvailable]){
- NSString *username = [SSKeychain passwordForService:kAPPNAME account:@"username"];
- NSString *password = [SSKeychain passwordForService:kAPPNAME account:@"password"];
- //guest_id = [SSKeychain passwordForService:kAPPNAME account:@"guest_id"];
- NSString *guest_id = [SSKeychain passwordForService:kAPPNAME account:@"guest_id"];
- if (guest_id == nil || [guest_id isEqualToString:@"(null)"] || [guest_id isEqualToString:@""]) {
- guest_id = [self getSettingWithKey:@"guest_id"];
- } else {
- [self saveSettingWithKey:@"guest_id" andData:guest_id];
- }
- if (guest_id == nil || [guest_id isEqualToString:@"(null)"] || [guest_id isEqualToString:@""]) {
- guest_id = @"";
- }
-
-
- if(username != nil){
- [self authenticate:username password:password guest_id:guest_id];
- } else {
- [self authenticate:@"" password:@"" guest_id:guest_id];
- }
- }
- }
- -(void)saveLoginInfo:(NSDictionary *)info
- {
- //DCMSG(info);
-
- //clean wb keychain
- for (int i = 0; i < [[SSKeychain accountsForService:kAPPNAME] count]; i++) {
- (void)[SSKeychain deletePasswordForService:kAPPNAME account:[[[SSKeychain accountsForService:kAPPNAME] objectAtIndex:i] objectForKey:@"acct"]];
- }
-
- for (NSString* key in info) {
- if ([[info objectForKey:key] length] > 0) {
- [SSKeychain setPassword:[info objectForKey:key] forService:kAPPNAME account:key];
- }
- }
- token = [info objectForKey:@"token"];
- vzaar_key = [info objectForKey:@"vzaar_key"];
- vzaar_secret = [info objectForKey:@"vzaar_secret"];
- //guest_id = [info objectForKey:@"guest_id"];
- [self saveSettingWithKey:@"guest_id" andData:[info objectForKey:@"guest_id"]];
- }
- -(void)logout {
-
- DCMSG(@"Logout");
- [self removePushNotificationToken];
- //NSString *guest_id = [SSKeychain passwordForService:kAPPNAME account:@"guest_id"]; // save guest_id
-
- NSInteger count = [[SSKeychain accountsForService:kAPPNAME] count];
- NSArray *acct = [NSArray arrayWithArray:[SSKeychain accountsForService:kAPPNAME]];
-
- // clean keychain
- for (int i = 0; i < count; i++) {
- (void)[SSKeychain deletePasswordForService:kAPPNAME account:[[acct objectAtIndex:i] objectForKey:@"acct"]];
- }
-
- [SSKeychain setPassword:[self getSettingWithKey:@"guest_id"] forService:kAPPNAME account:@"guest_id"]; //restore guest_id
-
- [[wbData sharedData] clearData];
- [[wbUser sharedUser] flushUser];
- is_guest = YES;
- is_authenticated = NO;
- //DCMSG([SSKeychain accountsForService:kAPPNAME]);
- }
- //////////////////////////
- -(void)getDataWithEndpoint:(NSString*)endpoint delegate:(id)delegate
- {
- [self getDataWithURL:[NSString stringWithFormat:@"%@/%@",kWHAMBUSHAPIURL,endpoint] delegate:delegate];
- }
- -(void)getDataWithURL:(NSString*)urlStr delegate:(id)delegate
- {
- [self getDataWithURL:[NSURL URLWithString:urlStr] delegate:delegate selectorName:@"dataReady:"];
- }
- -(void)getDataWithURL:(NSURL*)url delegate:(id)delegate selectorName:(NSString*)selectorName
- {
-
- [self getJSONWithURL:url response:^(id data){
- [delegate performSelectorOnMainThread:NSSelectorFromString(selectorName) withObject:data waitUntilDone:NO];
- }];
- }
- //////////////////////////
- //////////////////////////
- -(void)showNoteWithTxt:(NSString*)noteTxt
- {
- NSString *string = NSLocalizedString(@"GENERAL_NOTE_TITLE", @"");
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:string
- message:noteTxt
- delegate:nil
- cancelButtonTitle:NSLocalizedString(@"GENERAL_OK",@"")
- otherButtonTitles:nil];
- [alert show];
- kHIDEWAIT;
- }
- -(void)showErrorWithTxt:(NSString*)errorTxt
- {
- NSString *string = NSLocalizedString(@"GENERAL_ERROR_TITLE", @"");
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:string
- message:errorTxt
- delegate:nil
- cancelButtonTitle:NSLocalizedString(@"GENERAL_OK",@"")
- otherButtonTitles:nil];
- [alert show];
- kHIDEWAIT;
- }
- -(void)askPromoCode:(NSString*)errorTxt
- {
- NSString *string = NSLocalizedString(@"GENERAL_ERROR_TITLE", @"");
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:string
- message:errorTxt
- delegate:self
- cancelButtonTitle:NSLocalizedString(@"REGISTER_NOTIFY_WHEN_AVAILABLE",@"")
- otherButtonTitles:NSLocalizedString(@"GENERAL_OK",@""),nil];
- [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
- [alert setTag:1];
- [alert show];
- kHIDEWAIT;
- }
- -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
- {
- if (alertView.tag == 1) { //askPromocode
- if (buttonIndex == 1) {
- NSMutableDictionary *new = [NSMutableDictionary dictionaryWithDictionary:newUserArray];
- [new setObject:[alertView textFieldAtIndex:0].text forKey:@"promocode"];
- DCMSG(new);
- DCMSG([alertView textFieldAtIndex:0].text);
- DCMSG(alertView);
- [self createUser:new];
- } else {
- NSDictionary *dataDic = [NSDictionary dictionaryWithObject:[newUserArray objectForKey:@"email"] forKey:@"email"];
- [self postJSONWithURL:[self urlWithEndpoint:@"subscribe/waitinglist/"] paramenters:dataDic response:^(id data){} errorResponse:^(id data){}];
- }
- }
- if (alertView.tag == 2) { //forgetPassword
- if (buttonIndex == 0) {
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:NSLocalizedString(kRESETPASSWORDLINK,@"")]];
- }
- }
- if (alertView.tag == 3) { //inactive user
- if (buttonIndex == 0) {
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:NSLocalizedString(kRESENDACTIVATIONLINK,@"")]];
- }
- }
- if (alertView.tag == 4) { //banned user
- // [[wbLoginRegisterViewController sharedLRVC] showLoginScreen];
- }
- }
- //////////////////////////
- -(void)setMissionData:(NSDictionary *)missionData
- {
- if(uploadData == nil){
- uploadData = [[NSMutableDictionary alloc]init];
- }
- if (missionData == nil) {
- [uploadData removeObjectForKey:@"missionData"];
- }else {
- [uploadData setObject:missionData forKey:@"missionData"];
- }
- DCMSG(uploadData);
- }
- //////////////////////////
- -(void)setVideoURL:(NSURL *)url
- {
- if(uploadData == nil){
- uploadData = [[NSMutableDictionary alloc]init];
- }
-
- AVAssetTrack *track = [[[AVURLAsset URLAssetWithURL:url options:nil] tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
- CGFloat videoAngleInDegree = atan2([track preferredTransform].b, [track preferredTransform].a)*180/M_PI;
- //DNSLog(@"width %f, height %f, angle %f",track.naturalSize.width,track.naturalSize.height,videoAngleInDegree);
-
- float uploadWidth;
-
- if (videoAngleInDegree == 90 || videoAngleInDegree == 270) {
- uploadWidth = ceilf(track.naturalSize.height/(track.naturalSize.width/(kVIDEOHEIGHT * 16.0/9.0)));
- if (uploadWidth > kVIDEOHEIGHT) {
- uploadWidth = kVIDEOHEIGHT;
- }
- } else {
- uploadWidth = track.naturalSize.width/(track.naturalSize.height/(float)kVIDEOHEIGHT);
- if (uploadWidth > ceilf((kVIDEOHEIGHT * 16.0/9.0))) {
- uploadWidth = ceilf((kVIDEOHEIGHT * 16.0/9.0));
- }
- }
-
- //DNSLog(@"upload width: %f : %f : %f : %f",uploadWidth,uploadWidth*(16.0/9.0),track.naturalSize.width,track.naturalSize.height);
-
- [uploadData setObject:[NSNumber numberWithInteger:uploadWidth] forKey:@"width"];
-
- [uploadData setObject:url forKey:@"url"];
- DCMSG(uploadData);
-
- track = nil;
- }
- -(void)clearUploadData
- {
- if(uploadData != nil){
- uploadData = nil;
- }
- }
- //////////////////////////
- -(void)finalizeUpload:(NSDictionary*)info vzaarId:(NSInteger)videoid missionId:(NSInteger)missionId delegate:(id)delegate
- {
- NSMutableDictionary *wbInfo = [[NSMutableDictionary alloc] initWithDictionary:info];
- [wbInfo setObject:[NSString stringWithFormat:@"%ld",(long)videoid] forKey:@"external_id"];
-
- if (missionId > 0) {
- [wbInfo setObject:[NSNumber numberWithInteger:missionId] forKey:@"mission_id"];
- }
- DCMSG(wbInfo);
-
- [self postJSONWithURL:[self urlWithEndpoint:kVIDEOAPI] paramenters:wbInfo response:^(id data){
- DCMSG(data);
-
- //update mission data
- if (missionId > 0) {
- wbMission *mission = [[wbData sharedData] getMissionWithId:[NSNumber numberWithInteger:missionId]];
- [mission updateMissionData];
- }
- [delegate performSelectorOnMainThread:@selector(uploadDone:) withObject:@YES waitUntilDone:NO];
- } errorResponse:^(id data){
- DCMSG(data);
- [delegate performSelectorOnMainThread:@selector(uploadDone:) withObject:@NO waitUntilDone:NO];
- }];
-
- }
- -(void)finalizeUpload:(NSDictionary*)info vzaarId:(NSInteger)videoid delegate:(id)delegate
- {
- [self finalizeUpload:info vzaarId:videoid missionId:-1 delegate:delegate];
- }
- //////////////////////////
- -(void)addComment:(NSString*)comment videoid:(NSInteger)videoid delegate:(id)delegate
- {
- NSDictionary *commentDic = [[NSDictionary alloc] initWithObjectsAndKeys:
- comment, @"comment", nil];
-
- DCMSG(commentDic);
-
- [self postJSONWithURL:[self urlWithEndpoint:[NSString stringWithFormat:@"%@video/%ld/",kCOMMENTAPI,(long)videoid]] paramenters:commentDic response:^(id data){
- DCMSG(data);
- [delegate performSelectorOnMainThread:@selector(refresh:) withObject:NULL waitUntilDone:YES];
- kHIDEWAIT
- } errorResponse:^(id data){
- DCMSG(data);
- kHIDEWAIT
- }];
-
- }
- //////////////////////////
- -(void)like:(BOOL)like videoid:(NSString*)videoid delegate:(id)delegate
- {
- NSDictionary *likeDic = [[NSDictionary alloc] initWithObjectsAndKeys:
- videoid, @"video_id", nil];
- DCMSG(likeDic);
- if(like){
- DMSG;
- [self postJSONWithURL:[self urlWithEndpoint:@"like/video/"] paramenters:likeDic response:^(id data){
- DCMSG(data);
- [delegate performSelector:@selector(likeDone:count:) withObject:[NSNumber numberWithInt:1] withObject:[NSNumber numberWithLong:[[data valueForKey:@"likes"] longValue]]];
- kHIDEWAIT
- } errorResponse:^(id data){
- DCMSG(data);
- [delegate performSelector:@selector(likeDone:count:) withObject:[NSNumber numberWithInt:1] withObject:[NSNumber numberWithLong:0]];
- kHIDEWAIT
- }];
- } else {
- [self postJSONWithURL:[self urlWithEndpoint:@"dislike/video/"] paramenters:likeDic response:^(id data){
- DCMSG(data);
- [delegate performSelector:@selector(likeDone:count:) withObject:[NSNumber numberWithInt:3] withObject:[NSNumber numberWithLong:[[data valueForKey:@"dislikes"] longValue]]];
- kHIDEWAIT
- } errorResponse:^(id data){
- DCMSG(data);
- [delegate performSelector:@selector(likeDone:count:) withObject:[NSNumber numberWithInt:3] withObject:[NSNumber numberWithLong:0]];
- kHIDEWAIT
- }];
- }
- }
- -(void)unlike:(BOOL)like videoid:(NSString*)videoid delegate:(id)delegate
- {
- NSDictionary *likeDic = [[NSDictionary alloc] initWithObjectsAndKeys:
- videoid, @"video_id", nil];
- DCMSG(likeDic);
- if(like){
- [self postJSONWithURL:[self urlWithEndpoint:@"unlike/video/"] paramenters:likeDic response:^(id data){
- DCMSG(data);
- [delegate performSelector:@selector(likeDone:count:) withObject:[NSNumber numberWithInt:2] withObject:[NSNumber numberWithLong:[[data valueForKey:@"likes"] longValue]]];
- kHIDEWAIT
- } errorResponse:^(id data){
- DCMSG(data);
- [delegate performSelector:@selector(likeDone:count:) withObject:[NSNumber numberWithInt:2] withObject:[NSNumber numberWithLong:0]];
- kHIDEWAIT
- }];
-
- } else {
- [self postJSONWithURL:[self urlWithEndpoint:@"undislike/video/"] paramenters:likeDic response:^(id data){
- DCMSG(data);
- [delegate performSelector:@selector(likeDone:count:) withObject:[NSNumber numberWithInt:4] withObject:[NSNumber numberWithLong:[[data valueForKey:@"dislikes"] longValue]]];
- kHIDEWAIT
- } errorResponse:^(id data){
- DCMSG(data);
- [delegate performSelector:@selector(likeDone:count:) withObject:[NSNumber numberWithInt:4] withObject:[NSNumber numberWithLong:0]];
- kHIDEWAIT
- }];
- }
- }
- //////////////////////////
- -(NSString*)beautifyTime:(NSString*)timeString
- {
- if (timeString == nil || [timeString isKindOfClass:[NSNull class]] || [timeString isEqualToString:@""]) {
- return @"";
- }
- NSDateFormatter* gmtDf = [[NSDateFormatter alloc] init];
- [gmtDf setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
- if ([timeString rangeOfString:@"."].location == NSNotFound) {
- [gmtDf setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
- } else {
- [gmtDf setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
- }
- NSDate* gmtDate = [gmtDf dateFromString:timeString];
- NSDateFormatter* locDf = [[NSDateFormatter alloc] init];
- [locDf setTimeZone:[NSTimeZone localTimeZone]];
- [locDf setDateFormat:@"dd.MM.yyyy HH:mm"];
-
- return [locDf stringFromDate:gmtDate];
-
- }
- -(NSString*)parsePostedTime:(NSString*)timeString
- {
- if (timeString == nil || [timeString isKindOfClass:[NSNull class]] || [timeString isEqualToString:@""]) {
- return @"";
- }
- //timeString = @"2013-10-30T17:26:00";
- //DCMSG(timeString);
- NSDateFormatter* gmtDf = [[NSDateFormatter alloc] init];
- [gmtDf setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
- if ([timeString rangeOfString:@"."].location == NSNotFound) {
- [gmtDf setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
- } else {
- [gmtDf setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
- }
- NSDate* gmtDate = [gmtDf dateFromString:timeString];
-
- NSDateFormatter* locDf = [[NSDateFormatter alloc] init];
- [locDf setTimeZone:[NSTimeZone localTimeZone]];
- [locDf setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
- NSDate *dateLoc = [locDf dateFromString:[locDf stringFromDate:gmtDate]];
- NSTimeInterval since = fabs([dateLoc timeIntervalSinceNow]);
-
- NSInteger days = (since/(3600 * 24));
- NSInteger weeks = (days/7);
- NSInteger hours = (since/3600);
- NSInteger minutes = (since/60);
-
- gmtDf = nil;
- gmtDate = nil;
- locDf = nil;
- dateLoc = nil;
-
- //NSLog(@"time: %@ = w: %d, d:%d, h:%d, m:%d",[locDf stringFromDate:gmtDate],weeks,days,hours,minutes);
-
- if (days > 6) {
- if (days < 14) {
- return NSLocalizedString(@"POSTED_WEEK_AGO",@"");
- } else {
- if (weeks > 4) {
- return NSLocalizedString(@"POSTED_LONG_TIME_AGO",@"");
- } else {
- return [NSString stringWithFormat:NSLocalizedString(@"POSTED_NRO_WEEKS_AGO",@""),(long)weeks];
- }
- }
- } else if (days > 0) {
- if (days == 1) {
- return NSLocalizedString(@"POSTED_DAY_AGO",@"");
- } else {
- return [NSString stringWithFormat:NSLocalizedString(@"POSTED_NRO_DAYS_AGO",@""),(long)days];
- }
- } else {
- if (hours < 1) {
- if (minutes < 1) {
- return NSLocalizedString(@"POSTED_JUST_NOW",@"");
- } else {
- return [NSString stringWithFormat:NSLocalizedString(@"POSTED_NRO_MINUTES_AGO",@""),(long)minutes];
- }
- } else if (hours == 1){
- return NSLocalizedString(@"POSTED_HOUR_AGO",@"");
- } else {
- return [NSString stringWithFormat:NSLocalizedString(@"POSTED_NRO_HOURS_AGO",@""),(long)hours];
- }
- }
-
-
- return NSLocalizedString(@"POSTED_SOMETIME",@"");
- }
- -(NSString*)parseMissionEndTime:(NSString*)timeString
- {
- if (timeString == nil || [timeString isKindOfClass:[NSNull class]] || [timeString isEqualToString:@""]) {
- return @"";
- }
- NSDateFormatter* gmtDf = [[NSDateFormatter alloc] init];
- [gmtDf setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
- [gmtDf setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
- NSDate* gmtDate = [gmtDf dateFromString:timeString];
-
- NSDateFormatter* locDf = [[NSDateFormatter alloc] init];
- [locDf setTimeZone:[NSTimeZone localTimeZone]];
- [locDf setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
- NSDate *dateLoc = [locDf dateFromString:[locDf stringFromDate:gmtDate]];
-
- NSTimeInterval since = fabs([dateLoc timeIntervalSinceNow]);
- gmtDf = nil;
- gmtDate = nil;
- locDf = nil;
- dateLoc = nil;
-
- NSInteger days = ceil(since/(3600 * 24));
- NSInteger hours = floor(since/3600);
- if (days > 6) {
- if (days < 14) {
- return NSLocalizedString(@"ENDS_AFTER_A_WEEK",@"");
- } else {
- NSInteger weeks = floor(days/7);
- if (weeks > 4) {
- return NSLocalizedString(@"ENDS_NOT_ANY_TIME_SOON",@"");
- } else {
- return [NSString stringWithFormat:NSLocalizedString(@"ENDS_AFTER_NRO_WEEKS",@""),(long)weeks];
- }
- }
- } else if (days > 0 && hours > 24) {
- if (days == 1) {
- return NSLocalizedString(@"ENDS_AFTER_A_DAY",@"");
- } else {
- return [NSString stringWithFormat:NSLocalizedString(@"ENDS_AFTER_NRO_DAYS",@""),(long)days];
- }
- } else {
- /