ServerAPI.m 14 KB
//
//  ServerAPI.m
//  LifeLog
//
//  Created by Nguyen Van Phong on 7/30/17.
//  Copyright © 2017 PhongNV. All rights reserved.
//

#import "ServerAPI.h"

NSString *const kServerAddress = @"http://clover.timesfun.jp:9001/";
NSString *const kUser = @"KEY_USER";
NSString *const kToken = @"KEY_TOKEN";

@implementation NSString (NSString_Extended)
- (NSString *)urlencode {
    NSMutableString *output = [NSMutableString string];
    const unsigned char *source = (const unsigned char *)[self UTF8String];
    int sourceLen = (int)strlen((const char *)source);
    for (int i = 0; i < sourceLen; ++i) {
        const unsigned char thisChar = source[i];
        if (thisChar == ' '){
            [output appendString:@"+"];
        } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
                   (thisChar >= 'a' && thisChar <= 'z') ||
                   (thisChar >= 'A' && thisChar <= 'Z') ||
                   (thisChar >= '0' && thisChar <= '9')) {
            [output appendFormat:@"%c", thisChar];
        } else {
            [output appendFormat:@"%%%02X", thisChar];
        }
    }
    return output;
}
@end

@implementation ServerAPI
static ServerAPI *_server = nil;

@synthesize timeOutInterval = _timeOutInterval;

+ (instancetype)server
{
    @synchronized(self) {
        if (_server == nil) {
            _server = [[ServerAPI alloc] init];
        }
    }
    return _server;
}

- (instancetype)init
{
    self = [super init];
    if (self != nil) {
        self.timeOutInterval = 150;
    }
    return self;
}

// Login
- (void)loginWithEmail:(NSString *)email Password:(NSString *)password CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion
{
    [self _request:[kServerAddress stringByAppendingFormat: @"login"] method:@"POST" paras:@{@"email":email, @"password": password} completion:^(NSData *data, NSError *error) {
        
        if (completion == NULL) {
            return ;
        }
        
        if (error == nil)
        {
            NSDictionary *dataResult =  [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error];
          
            int status = [dataResult[@"status"] intValue];
            if (status == 1) { // status = 1 success
                NSString *token = dataResult[@"result"][@"token"];
                NSDictionary *dictUser = dataResult[@"result"][@"user"];
                User *user = [[User alloc] init];
                user.user_id = [NSString stringWithFormat:@"%@",dictUser[@"id"]];
                user.username = [NSString stringWithFormat:@"%@",dictUser[@"username"]];
                user.full_name = [NSString stringWithFormat:@"%@",dictUser[@"full_name"]];
                user.nickname = [NSString stringWithFormat:@"%@",dictUser[@"nickname"]];
                user.email = [NSString stringWithFormat:@"%@",dictUser[@"email"]];
                user.password = [NSString stringWithFormat:@"%@",dictUser[@"password"]];
                user.birthday = [NSString stringWithFormat:@"%@",dictUser[@"birthday"]];
                user.address = [NSString stringWithFormat:@"%@",dictUser[@"address"]];
                user.gender = [[NSString stringWithFormat:@"%@",dictUser[@"gender"]] intValue];
                user.height = [[NSString stringWithFormat:@"%@",dictUser[@"height"]] floatValue];
                user.weight = [[NSString stringWithFormat:@"%@",dictUser[@"weight"]] floatValue];
                user.user_description = [NSString stringWithFormat:@"%@",dictUser[@"description"]];
                user.created_at = [NSString stringWithFormat:@"%@",dictUser[@"created_at"]];
                user.physical_activity = [NSString stringWithFormat:@"%@",dictUser[@"physical_activity"]];
                user.profile_image = [NSString stringWithFormat:@"%@",dictUser[@"profile_image"]];
                user.updated_at = [NSString stringWithFormat:@"%@",dictUser[@"updated_at"]];
                user.delete_flag = [[NSString stringWithFormat:@"%@",dictUser[@"delete_flag"]] intValue];
                user.fat_rate = [[NSString stringWithFormat:@"%@",dictUser[@"fat_rate"]] intValue];
                user.profiles_share = [[NSString stringWithFormat:@"%@",dictUser[@"profiles_share"]] intValue];
                user.remember_me = [[NSString stringWithFormat:@"%@",dictUser[@"remember_me"]] intValue];
                user.sound_notifications_share = [[NSString stringWithFormat:@"%@",dictUser[@"sound_notifications_share"]] intValue];
                user.spend_calo_in_day = [[NSString stringWithFormat:@"%@",dictUser[@"spend_calo_in_day"]] intValue];
                user.target = [[NSString stringWithFormat:@"%@",dictUser[@"target"]] intValue];
                completion(user, token, nil);
            }
            else { // status = 0 error
                NSString *message = dataResult[@"message"];
                NSError *loginFaild = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}];
                completion(nil, nil, loginFaild);
            }
        }
        else
        {
            completion(nil, nil, error);
        }
    }];
}

// Register
- (void)registerUserWithParams:(NSDictionary *)params CompletionHandler: (void (^)(User *, NSString *, NSError *)) completion {
    [self _request:[kServerAddress stringByAppendingFormat: @"register"] method:@"POST" paras:params completion:^(NSData *data, NSError *error) {
        
        if (completion == NULL) {
            return ;
        }
        
        if (error == nil)
        {
            NSDictionary *dataResult =  [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error];
            
            int status = [dataResult[@"status"] intValue];
            if (status == 1) { // status = 1 success
                NSString *token = dataResult[@"result"][@"token"];
                NSDictionary *dictUser = dataResult[@"result"][@"user"];
                User *user = [[User alloc] init];
                user.user_id = [NSString stringWithFormat:@"%@",dictUser[@"id"]];
                user.username = [NSString stringWithFormat:@"%@",dictUser[@"username"]];
                user.full_name = [NSString stringWithFormat:@"%@",dictUser[@"full_name"]];
                user.nickname = [NSString stringWithFormat:@"%@",dictUser[@"nickname"]];
                user.email = [NSString stringWithFormat:@"%@",dictUser[@"email"]];
                user.password = [NSString stringWithFormat:@"%@",dictUser[@"password"]];
                user.birthday = [NSString stringWithFormat:@"%@",dictUser[@"birthday"]];
                user.address = [NSString stringWithFormat:@"%@",dictUser[@"address"]];
                user.gender = [[NSString stringWithFormat:@"%@",dictUser[@"gender"]] intValue];
                user.height = [[NSString stringWithFormat:@"%@",dictUser[@"height"]] floatValue];
                user.weight = [[NSString stringWithFormat:@"%@",dictUser[@"weight"]] floatValue];
                user.user_description = [NSString stringWithFormat:@"%@",dictUser[@"description"]];
                user.created_at = [NSString stringWithFormat:@"%@",dictUser[@"created_at"]];
                user.physical_activity = [NSString stringWithFormat:@"%@",dictUser[@"physical_activity"]];
                user.profile_image = [NSString stringWithFormat:@"%@",dictUser[@"profile_image"]];
                user.updated_at = [NSString stringWithFormat:@"%@",dictUser[@"updated_at"]];
                user.delete_flag = [[NSString stringWithFormat:@"%@",dictUser[@"delete_flag"]] intValue];
                user.fat_rate = [[NSString stringWithFormat:@"%@",dictUser[@"fat_rate"]] intValue];
                user.profiles_share = [[NSString stringWithFormat:@"%@",dictUser[@"profiles_share"]] intValue];
                user.remember_me = [[NSString stringWithFormat:@"%@",dictUser[@"remember_me"]] intValue];
                user.sound_notifications_share = [[NSString stringWithFormat:@"%@",dictUser[@"sound_notifications_share"]] intValue];
                user.spend_calo_in_day = [[NSString stringWithFormat:@"%@",dictUser[@"spend_calo_in_day"]] intValue];
                user.target = [[NSString stringWithFormat:@"%@",dictUser[@"target"]] intValue];
                completion(user, token, nil);
            }
            else { // status = 0 error
                NSString *message = dataResult[@"message"];
                NSError *loginFaild = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}];
                completion(nil, nil, loginFaild);
            }
        }
        else
        {
            completion(nil, nil, error);
        }
    }];
}

- (void)forgetPass:(NSString *)email CompletionHandler:(void (^)(NSError *)) completion {
    [self _request:[kServerAddress stringByAppendingFormat: @"forgetPass"] method:@"POST" paras:@{@"email":email} completion:^(NSData *data, NSError *error) {
    
        if (completion == NULL) {
            return ;
        }
    
        if (error == nil)
        {
            NSDictionary *dataResult =  [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error];
      
            int status = [dataResult[@"status"] intValue];
            if (status == 1) { // status = 1 success
                completion(nil);
            }
            else { // status = 0 error
                NSString *message = dataResult[@"message"];
                NSError *forgetPass = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}];
                completion(forgetPass);
            }
        }
        else
        {
            completion(error);
        }
    }];
}
- (void)confirmForgetPass:(NSString *)email withConfirm:(NSString *)confirm CompletionHandler:(void (^)(NSError *)) completion {
    [self _request:[kServerAddress stringByAppendingFormat: @"forgetPass/confirm"] method:@"POST" paras:@{@"email":email, @"code_confirm": confirm} completion:^(NSData *data, NSError *error) {
    
        if (completion == NULL) {
            return ;
        }
    
        if (error == nil)
        {
            NSDictionary *dataResult =  [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error];
      
            int status = [dataResult[@"status"] intValue];
            if (status == 1) { // status = 1 success
                completion(nil);
            }
            else { // status = 0 error
                NSString *message = dataResult[@"message"];
                NSError *confirmForgetPass = [NSError errorWithDomain:@"LifeLog_Domain" code:-1 userInfo:@{@"message":message}];
                completion(confirmForgetPass);
            }
        }
        else
        {
            completion(error);
        }
  }];
}

- (void)uploadImage:(NSString *)token andImageData:(NSData *)data CompletionHandler:(void (^)(NSString *, NSError *)) completion {
    NSDictionary *dict = nil;
    NSString *base64Encoded = [data base64EncodedStringWithOptions:0];
    if (token != nil) {
        dict = @{@"token":token, @"img": base64Encoded};
    }
    else {
        dict = @{@"img": base64Encoded};
    }
    [self _request:[kServerAddress stringByAppendingFormat: @"upload-image"] method:@"POST" paras:dict completion:^(NSData *data, NSError *error) {
      
        if (completion == NULL) {
            return ;
        }
    
        if (error == nil)
        {
            NSDictionary *dataResult =  [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingAllowFragments error: &error];
            NSString *image_profile = [NSString stringWithFormat:@"%@", dataResult[@"message"]];
            completion(image_profile, nil);
        }
        else
        {
            completion(nil, error);
        }
  }];
}

#pragma mark - Private Function
- (NSData *) _encodeDictionary: (NSDictionary *) dictionary
{
    NSMutableArray *parts = [[NSMutableArray alloc] init];
    for (id key in dictionary)
    {
        NSString *encodedValue = [[dictionary[key] description] urlencode];
        NSString *encodedKey = [[key description] urlencode];//[[key description] stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
        NSString *part = [NSString stringWithFormat: @"%@=%@", encodedKey, encodedValue];
        [parts addObject:part];
    }
    NSString *encodedDictionary = [parts componentsJoinedByString:@"&"];
    return [encodedDictionary dataUsingEncoding: NSUTF8StringEncoding];
}

- (void) _request:(NSString *)address method:(NSString *)method paras:(NSDictionary *)paras completion:(void (^)(NSData *data, NSError *error))completion
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:address]];
    request.HTTPMethod = method;
    [request setValue: @"application/json" forHTTPHeaderField: @"Accept"];
    [request setValue: @"application/json" forHTTPHeaderField: @"Content-Type"];
    [request setTimeoutInterval:self.timeOutInterval];
    
    if (paras != nil)
    {
        NSData *encodedData = [self _encodeDictionary: paras];
        [request setValue: [NSString stringWithFormat: @"%lu", (unsigned long) encodedData.length] forHTTPHeaderField: @"Content-Length"];
        [request setValue: @"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField: @"Content-Type"];
        [request setHTTPBody: encodedData];
    }
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                            completionHandler:
                                  ^(NSData *data, NSURLResponse *response, NSError *error) {
                                      if (completion == NULL) {
                                          return ;
                                      }
                                      if (error == nil)
                                      {
                                          completion(data, nil);
                                      }
                                      else
                                      {
                                          completion(nil, error);
                                      }
                                  }];
    
    [task resume];
}

@end