Vasilis

addition of getinbox2 again

/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
......@@ -137,8 +137,8 @@ typedef enum {
*/
/*!
@abstract Launching the Warply service.
@discussion This class method initialises the shared instance of WLAppService,
passes the launch options (if any) to managers in order to handle them and
@discussion This class method initialises the shared instance of WLAppService,
passes the launch options (if any) to managers in order to handle them and
launches the communication with Warply service using the provided unique app identification.
@param appUUID A string with the unique app identification.
@param launchOptions A dictionary with the application launch options. May be
......@@ -264,7 +264,7 @@ WL_VERSION_INTERFACE()
*/
/*!
@abstract Send an event.
@discussion This method sends an event. This event is stored into a local DB
@discussion This method sends an event. This event is stored into a local DB
and is sent over to Warply service when a threshold of stored events is exceeded or immediately if the priority parameter is YES
@param event A WLEvent object.
@param priority A BOOL value indicating if the event should be sent immediately or not.
......@@ -284,10 +284,8 @@ WL_VERSION_INTERFACE()
*/
- (BOOL)getInboxWithSuccessBlock:(void (^)(NSArray *list))success failureBlock:(void (^)(NSError *error))failure;
- (BOOL)getInbox2WithSuccessBlock:(void (^)(NSArray *list))success failureBlock:(void (^)(NSError *error))failure;
- (void)getProductsWithSuccessBlock:(NSString*)filter :(void(^)(NSMutableArray *params))success failureBlock:(void(^)(NSError *error))failure;
- (void)sendContactWithSuccessBlock:(NSString *)name andEmail:(NSString *)email andMsisdn:msisdn andMessage:message :(void(^)(NSMutableArray *params)) success failureBlock:(void(^)(NSError *error))failure;
......@@ -363,6 +361,7 @@ WL_VERSION_INTERFACE()
- (void) validateCouponWithSuccessBlock:(NSString*) coupon :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)loginCosmoteWithSuccessBlock:(NSString*)guid andAppUuid:(NSString*)appUuid andTicket:(NSString*)ticket :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
/*!
@abstract Get the full page add accordint to the display_type of a campaign.
@attributeblock successBlock This block is called when getInbox is sucessful and allOffers is empty or nil and returns an array with the available WLInboxItem items. Otherwise, the allOffers array is filtered.
......@@ -425,7 +424,7 @@ WL_VERSION_INTERFACE()
@return Returns YES if the app is registered with Warply and thus the success or failure block will definitely be called and NO otherwise. In the latter case, the call is queued and will be called as soon as / if the app registers with Warply.
@discussion This method gets the context for the specified path. The success block has a parameter of type
id as the type of the data returned value may differ in each case depending on the specified
path. The caller will probably want to use the return parameter and a timer to update the UI or do any other operation after a certain amount of time that the app remains unregistered and thus, cannot make the call.
path. The caller will probably want to use the return parameter and a timer to update the UI or do any other operation after a certain amount of time that the app remains unregistered and thus, cannot make the call.
*/
- (BOOL)getContextWithPath:(NSString *)path
successBlock:(void (^)(id contextResponse))successBlock
......@@ -441,7 +440,7 @@ WL_VERSION_INTERFACE()
@discussion This method post the context for the specified path. Make sure that
the path, you are trying to access, has write and not only read permissions. If
it has only read permsissions the post will fail with WLResultCodesReadOnly error
code. The caller will probably want to use the return parameter and a timer to update the UI or do any other operation after a certain amount of time that the app remains unregistered and thus, cannot make the call.
code. The caller will probably want to use the return parameter and a timer to update the UI or do any other operation after a certain amount of time that the app remains unregistered and thus, cannot make the call.
*/
- (BOOL)sendContext:(NSData*)context
successBlock:(void (^)(NSDictionary *contextResponse))successBlock
......@@ -449,11 +448,11 @@ WL_VERSION_INTERFACE()
/*!
@abstract Send all localy stored events to Warply service.
@discussion This method flags and sends all the locally stored events to Warply
service. This happend independent if number of locally stored event threshold
has be reached or not. The events are deleted from local DB only when the call is
sucesful. Otherwise, the events remain stored until either the threshold of stored
events is excited and they automatically send to Warply service or this method is
@discussion This method flags and sends all the locally stored events to Warply
service. This happend independent if number of locally stored event threshold
has be reached or not. The events are deleted from local DB only when the call is
sucesful. Otherwise, the events remain stored until either the threshold of stored
events is excited and they automatically send to Warply service or this method is
called again.
@attributeblock completionBlock This block is called when sendAllEvents is sucessful.
@attributeblock failureBlock This block is called when sendAllEvents fails and returns an error object with failure code and description.
......
......@@ -430,6 +430,29 @@ WL_VERSION_IMPLEMENTATION(WL_VERSION)
return [self isRegistrationValid];
}
- (BOOL)getInbox2WithSuccessBlock:(void (^)(NSArray *list))success failureBlock:(void (^)(NSError *error))failure
{
if (self.allOffers.count > 0) {
success(self.allOffers);
} else {
NSDictionary *postDictionary = @{@"offers": @{@"action": @"get_inbox"}};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:0 error:NULL];
[self sendContext:jsonData successBlock:^(NSDictionary *contextResponse) {
if (success) {
success([contextResponse valueForKey:@"MAPP_OFFER"]);
}
} failureBlock:^(NSError *error) {
if (failure) {
failure(error);
}
}];
}
return [self isRegistrationValid];
}
- (void)getProductsWithSuccessBlock:(NSString*)filter :(void(^)(NSMutableArray *params)) success failureBlock:(void(^)(NSError *error))failure
{
if (filter == nil) {
......@@ -556,6 +579,41 @@ WL_VERSION_IMPLEMENTATION(WL_VERSION)
}];
}
- (void)loginCosmoteWithSuccessBlock:(NSString*)guid andAppUuid:(NSString*)appUuid andTicket:(NSString*)ticket :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure
{
NSDictionary *postDictionary = @{@"guid": guid, @"app_uuid": appUuid, @"ticket": ticket };
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:0 error:NULL];
[self sendContextCosmote:jsonData successBlock:^(NSDictionary *contextResponse) {
if (success) {
NSString* clientId = [NSString alloc];
clientId = [contextResponse objectForKey:@"client_id"];
NSString* clientSecret = [NSString alloc];
clientSecret = [contextResponse objectForKey:@"client_secret"];
NSString* refreshToken = [NSString alloc];
refreshToken = [contextResponse objectForKey:@"refresh_token"];
NSString* accessToken = [NSString alloc];
accessToken = [contextResponse objectForKey:@"access_oken"];
[_db executeUpdate:@"DROP TABLE requestVariables"];
if ([_db tableExists:@"requestVariables"] == NO) {
[_db executeUpdate:@"CREATE TABLE requestVariables (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, client_id INTEGER, client_secret VARCHAR(255), access_token VARCHAR(255), refresh_token VARCHAR(255))"];
WL_FMDBLogError
[_db executeUpdate:@"INSERT INTO requestVariables (id, client_id, client_secret, refresh_token, access_token) VALUES (1, ?, ?, ?, ?)", clientId, clientSecret, refreshToken, accessToken];
} else {
[_db executeUpdate:@"UPDATE requestVariables SET client_id = ? , client_secret = ?, refresh_token = ?, access_token = ? WHERE id = 1", clientId, clientSecret, refreshToken, accessToken];
}
success(contextResponse);
}
} failureBlock:^(NSError *error) {
if (failure) {
failure(error);
}
NSLog(@"Error at fetching tags categories %@", error );
}];
}
- (void)loginWithSuccessBlock:(NSString*)id andPassword:(NSString*)password andLoginType:(NSString*)loginType :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure
{
NSString* webId = [NSString alloc];
......@@ -2199,6 +2257,34 @@ return appIsRegisteredWithWarply;
return appIsRegisteredWithWarply;
}
- (BOOL)sendContextCosmote:(NSData*)context
successBlock:(void (^)(NSDictionary *contextResponse))successBlock
failureBlock:(void (^)(NSError *error))failureBlock
{
BOOL appIsRegisteredWithWarply = [self isRegistrationValid];
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_WARPLY_ENABLED))
return appIsRegisteredWithWarply;
if (appIsRegisteredWithWarply == NO) {
[_pendingOperationsQueue setSuspended:YES];
[self registration];
}
NSString *path = nil;
NSInvocation *invocation = [self contextRequestInvocationWithTypeCosmote:WLContextRequestTypePost
data:context
path:path
successBlock:[successBlock copy]
failureBlock:[failureBlock copy]];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithInvocation:invocation];
[_pendingOperationsQueue addOperation:operation];
return appIsRegisteredWithWarply;
}
#pragma - Events
///////////////////////////////////////////////////////////////////////////////
- (void)addEvent:(WLEvent *)event priority:(BOOL)priority
......@@ -3726,6 +3812,29 @@ CGFloat DistanceBetweenTwoPoints(CGPoint point1,CGPoint point2)
return invocation;
}
- (NSInvocation *)contextRequestInvocationWithTypeCosmote:(WLContextRequestType)type
data:(NSData *)context
path:(NSString *)path
successBlock:(void (^)(NSDictionary *contextResponse))successBlock
failureBlock:(void (^)(NSError *error))failureBlock
{
void (^ successBlockCopy)(void) = [successBlock copy];
void (^ failureBlockCopy)(void) = [failureBlock copy];
NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(runContextRequestWithTypeCosmote:data:path:successBlock:failureBlock:)];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sgn];
[invocation setTarget:self];
[invocation setSelector:@selector(runContextRequestWithTypeCosmote:data:path:successBlock:failureBlock:)];
[invocation setArgument:&type atIndex:2];
[invocation setArgument:&context atIndex:3];
[invocation setArgument:&path atIndex:4];
[invocation setArgument:&successBlockCopy atIndex:5];
[invocation setArgument:&failureBlockCopy atIndex:6];
[invocation retainArguments];
return invocation;
}
- (void)runVerifyTicketRequestWithType:(WLContextRequestType)requestType
data:(NSData*)context
path:(NSString *)path
......@@ -3958,6 +4067,133 @@ CGFloat DistanceBetweenTwoPoints(CGPoint point1,CGPoint point2)
}
}
- (void)runContextRequestWithTypeCosmote:(WLContextRequestType)requestType
data:(NSData*)context
path:(NSString *)path
successBlock:(void (^)(id contextResponse))successBlock
failureBlock:(void (^)(NSError *error))failureBlock
{
//Create REQUEST
NSMutableString *urlString = [NSMutableString stringWithFormat:@"partners/gapp/verify"];
WLLOG(@"[WARP Trace] HTTP URL: %@", urlString);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:100];
NSDictionary *parameters;
if (context != nil) {
parameters = [NSJSONSerialization JSONObjectWithData:context options:NSJSONReadingAllowFragments error:NULL];
}
SuccessResponse successResponse = ^(NSURLSessionDataTask * _Nonnull task, id _Nullable JSON) {
if (JSON == nil) {
successBlock(@{@"status": @"0"});
}
else {
// NSData *responseData = [NSJSONSerialization dataWithJSONObject:JSON options:NSJSONWritingPrettyPrinted error:NULL];
// NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// WLLOG(@"[WARP Trace] HTTP %@ Response:%@", request.HTTPMethod, responseString);
WLLOG(@"************ WARP %@ CONTEXT ******************", request.HTTPMethod);
WLLOG(@"[WARP Trace] HTTP Web Id: %@", _webId);
WLLOG(@"[WARP Trace] HTTP API Key: %@", _apiKey);
WLLOG(@"[WARP Trace] HTTP %@ Request URL: %@", request.HTTPMethod, request.URL.absoluteString);
NSString *contextString = [[NSString alloc] initWithData:context encoding:NSUTF8StringEncoding];
WLLOG(@"[WARP Trace] HTTP %@ Request Body: %@", request.HTTPMethod, contextString);
WLLOG(@"*************************************************");
NSDictionary *contextResponse=[JSON valueForKey:@"context"];
if ([JSON objectForKey:@"status"]) {
int status = [[JSON valueForKey:@"status"] intValue];
if (status != WLResultCodesSuccess)
{
if ((status == WLResultCodesInvalidWebID) || (status == WLResultCodesDeviceRegistrationFailed))
{
self.webId = nil;
self.apiKey = nil;
[_pendingOperationsQueue setSuspended:YES];
}
NSString *errorDescrition = (status <= [WLResultCodesDescriptions count]) && status > 0 ? (WLResultCodesDescriptions[(status-1)]) : ([NSString stringWithFormat:@"Internal WARP Server error %d", status]);
NSDictionary *eDict = @{NSLocalizedDescriptionKey: errorDescrition};
NSError *error = [NSError errorWithDomain:WARP_ERROR_DOMAIN code:status userInfo:eDict];
if (failureBlock)
failureBlock(error);
return;
}
if (successBlock)
{
if ([path length]!=0)
{
successBlock([contextResponse valueForKey:path]);
return;
}
successBlock(contextResponse);
}
}else{
NSError *error = [NSError errorWithDomain:WARP_ERROR_DOMAIN code:1026 userInfo:@{NSLocalizedDescriptionKey: NSLocalizedString(@"Empty response", @"Warply")}];
if (failureBlock)
failureBlock(error);
}
}
};
FailureResponse faliureResponse = ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
WLLOG(@"************ WARP %@ CONTEXT ******************", request.HTTPMethod);
WLLOG(@"[WARP Trace] HTTP Web Id: %@", _webId);
WLLOG(@"[WARP Trace] HTTP API Key: %@", _apiKey);
WLLOG(@"[WARP Trace] HTTP %@ Request URL: %@", request.HTTPMethod, request.URL.absoluteString);
NSString *contextString = [[NSString alloc] initWithData:context encoding:NSUTF8StringEncoding];
WLLOG(@"[WARP Trace] HTTP %@ Request Body: %@", request.HTTPMethod, contextString);
WLLOG(@"[WARP Trace] Error: %@", [error description]);
WLLOG(@"*************************************************");
if (failureBlock)
failureBlock(error);
};
_httpClient.responseSerializer = [AFJSONResponseSerializer serializer];
_httpClient.requestSerializer = [AFJSONRequestSerializer serializer];
//Set HTTP Headers
time_t timestamp = (time_t) [[NSDate date] timeIntervalSince1970];
[_httpClient.requestSerializer setValue:_webId forHTTPHeaderField:@"loyalty-web-id"];
[_httpClient.requestSerializer setValue:[NSString stringWithFormat:@"%lu", timestamp] forHTTPHeaderField:@"loyalty-date"];
[_httpClient.requestSerializer setValue:[[NSString stringWithFormat:@"%@%lu", _apiKey, timestamp] SHA256Sum] forHTTPHeaderField:@"loyalty-signature"];
[_httpClient.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
[_httpClient.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[_httpClient.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"User-Agent"];
[_httpClient.requestSerializer setValue:[NSString stringWithFormat:@"ios:%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"]] forHTTPHeaderField:@"loyalty-bundle-id"];
[_httpClient.requestSerializer setValue:[[[UIDevice currentDevice] identifierForVendor] UUIDString] forHTTPHeaderField:@"unique-device-id"];
[_httpClient.requestSerializer setValue:@"apple" forHTTPHeaderField:@"vendor"];
[_httpClient.requestSerializer setValue:@"platform" forHTTPHeaderField:@"ios"];
[_httpClient.requestSerializer setValue:@"os_version" forHTTPHeaderField:[[UIDevice currentDevice] systemVersion]];
[_httpClient.requestSerializer setValue:@"mobile" forHTTPHeaderField:@"channel"];
if (requestType == WLContextRequestTypePost) {
// NSDictionary *parameters = [NSJSONSerialization JSONObjectWithData:context options:NSJSONReadingAllowFragments error:NULL];
[_httpClient POST:urlString parameters:parameters progress:nil success:successResponse failure:faliureResponse];
}
else {
[_httpClient GET:urlString parameters:parameters progress:nil success:successResponse failure:faliureResponse];
}
}
- (void)runContextRequestWithType2:(WLContextRequestType)requestType
data:(NSData*)context
path:(NSString *)path
......
......@@ -16,7 +16,6 @@
- (void) setToStage;
- (void) setLang:(NSString*) lang;
- (UIViewController *) openCoupons:(UIView*) parentView;
- (UIViewController *) openGifts;
- (void) applicationDidEnterBackground:(UIApplication *)application;
- (void) applicationWillEnterForeground:(UIApplication *)application;
- (void) applicationDidBecomeActive:(UIApplication *)application;
......@@ -60,6 +59,7 @@
- (NSDictionary*)getCouponSetsWithActive:(NSNumber*)active andVisible:(NSNumber*)visible andUuids:(NSArray*)uuids;
- (NSDictionary*)redeemCouponWithCoupon:(NSString*)coupon;
- (NSDictionary*)validateCouponWithCoupon:(NSString*)coupon;
- (NSDictionary*)loginCosmoteWithGuid:(NSString*)guid andAppUuid:(NSString*)appUuid andTicket:(NSString*)ticket;
@end
#endif /* MyApi_h */
......
......@@ -47,19 +47,11 @@ NSString *LANG;
}
- (UIViewController *) openCoupons:(UIView*) parentView{
UIViewController *couponsViewController = [CouponsViewInterface couponsViewController:parentView];
return couponsViewController;
}
- (UIViewController *) openGifts{
UIViewController *giftsViewController = [GiftsViewInterface giftsViewController];
// controller = [[UINavigationController alloc]initWithRootViewController:profileViewController];
// [window makeKeyAndVisible];
return giftsViewController;
}
//- (UIViewController *) openCoupons {
//// NSString* const frameworkBundleID = @"framework.warp.ly.WarplySDKFrameworkIOS";
//// NSBundle* bundle = [NSBundle bundleWithIdentifier:frameworkBundleID];
......@@ -1132,4 +1124,31 @@ NSString *LANG;
}
return resp;
}
- (NSDictionary*)loginCosmoteWithGuid:(NSString*)guid andAppUuid:(NSString*)appUuid andTicket:(NSString*)ticket {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] loginCosmoteWithSuccessBlock:guid andAppUuid:appUuid andTicket:ticket :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
@end
......