-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMisoApiClient.m
More file actions
489 lines (396 loc) · 15.9 KB
/
MisoApiClient.m
File metadata and controls
489 lines (396 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//
// MisoApiClient.m
// MisoApiProject
//
// Created by Chris Lavender on 12/9/11.
// Copyright (c) 2011 Miso Media. All rights reserved.
//
// Server Information
// ---------- Production Server
//#define miso_current_server @"Production Server"
//#define miso_api_url @"https://music.misomedia.com/api"
//#define miso_device_login_api_url @"https://music.misomedia.com/api/account/login.json?api_key=%@&version=%@"
// ----------- Dev server
#define miso_current_server @"Dev Server"
#define miso_api_url @"http://dev.misomedia.com/api"
#define miso_device_login_api_url @"http://dev.misomedia.com/api/account/login.json?api_key=%@&version=%@"
// ----------- Staging server
//#define miso_current_server @"Staging Server"
//#define miso_api_url @"http://staging.misomedia.com/api"
//#define miso_device_login_api_url @"http://staging.misomedia.com/api/account/login.json?api_key=%@&version=%@"
#import "MisoApiClient.h"
#import "MisoApiAccountClient.h"
#import "MisoApiAdvertisementsClient.h"
#import "MisoApiArrangementsClient.h"
#import "MisoApiArtistsClient.h"
#import "MisoApiComposersClient.h"
#import "MisoApiInstrumentsClient.h"
#import "MisoApiInstrumentBrandsClient.h"
#import "MisoApiInstrumentSeriesClient.h"
#import "MisoApiPartsClient.h"
#import "MisoApiSongsClient.h"
#import "MisoApiBooksClient.h"
//#import "SBJson.h" //for < iOS 5
#import "Reachability.h"
// CL: the error handler should be set externally.
// But putting here for now.
#import "ErrorHandler.h"
#define _LogRequestParams_ 0
static NSString *misoBaseUrl = miso_api_url;
static const NSString *MisoApiErrorKey = @"MisoApiError"; // for retrieving miso api errors from NSError objects
@interface MisoApiClient()
{
__block MisoApiClient *blockMisoApiClient;
}
- (BOOL)checkApiErrorCode:(id)incomingData error:(NSError **)anError;
- (void)sendRequestUsingNSURLConnectionWithURLRequest:(NSURLRequest *)request andCallback:(void (^)(id))handler;
// parser is only for < iOS 5
//@property (nonatomic, strong) SBJsonParser *jsonParser;
@property (nonatomic, strong) NSOperationQueue *opQueue;
@property (nonatomic, strong, readonly) NSDictionary *userAuthData;
@end
@implementation MisoApiClient
@synthesize api_key = _api_key;
@synthesize version = _version;
@synthesize user_id = _user_id;
@synthesize auth_token = _auth_token;
@synthesize userAuthData = _userAuthData;
@synthesize opQueue = _opQueue;
//@synthesize jsonParser = _jsonParser;
@synthesize errorHandler = _errorHandler;
@synthesize accountClient = _accountClient;
@synthesize advertisementsClient = _advertisementsClient;
@synthesize arrangementsClient = _arrangementsClient;
@synthesize artistsClient = _artistsClient;
@synthesize composersClient = _composersClient;
@synthesize instrumentsClient = _instrumentsClient;
@synthesize instrumentBrandsClient = _instrumentBrandsClient;
@synthesize instrumentSeriesClient = _instrumentSeriesClient;
@synthesize partsClient = _partsClient;
@synthesize songsClient = _songsClient;
@synthesize booksClient = _booksClient;
static MisoApiClient *apiClient;
+ (MisoApiClient *) apiClient
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
apiClient = [[MisoApiClient alloc] init];
apiClient->blockMisoApiClient = apiClient;
});
return apiClient;
}
- (void)dealloc
{
[_userAuthData release];
// [_jsonParser release];
[_opQueue release];
[_errorHandler release];
[_accountClient release];
[_advertisementsClient release];
[_arrangementsClient release];
[_artistsClient release];
[_composersClient release];
[_instrumentsClient release];
[_instrumentBrandsClient release];
[_instrumentSeriesClient release];
[_partsClient release];
[_songsClient release];
[super dealloc];
}
#pragma mark- MisoApiErrorChecking
- (BOOL)checkApiErrorCode:(id)incomingData error:(NSError **)anError
{
BOOL result = NO;
if ([incomingData isKindOfClass:[NSDictionary class]])
{
// CL: It's a dictionary so check for an error code
NSDictionary *responseDict = incomingData;
NSNumber *apiErrorCode = [responseDict objectForKey:@"code"];
if(apiErrorCode && anError != NULL)
{
int error = [apiErrorCode intValue];
// JH: handle errors outside of the bounds of plist
if (error > 0 && error <= 31)[self.errorHandler handleError:apiErrorCode];
NSString *description = [incomingData objectForKey:@"error"];
// Make and return custom domain error.
NSArray *objArray = [NSArray arrayWithObjects:description, incomingData, nil];
NSArray *keyArray = [NSArray arrayWithObjects:NSLocalizedDescriptionKey, MisoApiErrorKey , nil];
NSDictionary *userDict = [NSDictionary dictionaryWithObjects:objArray forKeys:keyArray];
*anError = [[[NSError alloc] initWithDomain:@"Miso API Error" code:[apiErrorCode intValue] userInfo:userDict] autorelease];
result = YES;
}
}
return result;
}
#pragma mark- Send Request Methods
- (void)sendRequestUsingNSURLConnectionWithURLRequest:(NSURLRequest *)request andCallback:(void (^)(id))handler
{
__block __typeof__(self)blockSelf = self;
// CL: build a block to be run asynchronously
void (^handleResponse)(NSURLResponse *, NSData *, NSError *) = ^(NSURLResponse *response, NSData *data, NSError *error) {
id results = nil;
// CL: http errors would be caught here.
if (error) {
NSLog(@"[%@ %@] HTTP error: %@", NSStringFromClass([blockSelf class]), NSStringFromSelector(_cmd), error.localizedDescription);
results = error;
}
else {
// CL: parse the JSON
if (data) {
results = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
}
else {
results = nil;
}
// CL: json errors would be caught here.
if (error) {
NSLog(@"[%@ %@] JSON error: %@", NSStringFromClass([blockSelf class]), NSStringFromSelector(_cmd), error.localizedDescription);
results = error;
}
// CL: Check for an Miso API errors.
else if ([blockSelf checkApiErrorCode:results error:&error]) {
//CL: if there's an error make the NSError object the result.
if (error) results = error;
}
}
// If no errors send result to the completion block
handler(results);
};
[NSURLConnection sendAsynchronousRequest:request
queue:self.opQueue
completionHandler:handleResponse];
}
#pragma mark- MisoApiClientProtocol Method Implementations
- (void)requestWithPath:(NSString *)path
method:(NSString *)method
getParams:(NSDictionary *)getParams
postParams:(NSDictionary *)postParams
andCallback:(void (^)(id))handler
{
NSMutableDictionary *combinedParams = [NSMutableDictionary dictionaryWithObjectsAndKeys:
self.api_key, @"api_key",
self.version, @"version",
self.user_id, @"user_id",
self.auth_token, @"auth_token",
nil];
[combinedParams addEntriesFromDictionary:getParams];
NSString *pathString;
if (method) pathString = [NSString stringWithFormat:@"/%@/%@.json?",path,method];
else pathString = [NSString stringWithFormat:@"/%@.json?",path];
NSString *paramString = [combinedParams urlEncodedString];
// build the complete url using stringWithFormat:"
NSString *urlString = [NSString stringWithFormat:@"%@%@%@", misoBaseUrl, pathString, paramString];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request;
if (postParams)
{
NSString *post = [postParams urlEncodedString];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
#if _LogRequestParams_
NSLog(@"Post Params: %@", post);
#endif
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:url];
[postRequest setHTTPMethod:@"POST"];
[postRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
[postRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[postRequest setHTTPBody:postData];
request = postRequest;
}
else
{
request = [NSURLRequest requestWithURL:url];
}
#if _LogRequestParams_
NSLog(@"Path: %@", path);
NSLog(@"Method: %@", method);
NSLog(@"Combined Params: %@", combinedParams);
NSLog(@"Url String: %@", urlString);
#endif
// CL: Since we currently have two different request options (pre/post iOS 5) check for Reachability HERE!
if ([[self class] internetIsReachable])
{
if ([[NSURLConnection class] respondsToSelector:@selector(sendAsynchronousRequest:queue:completionHandler:)])
{
[self sendRequestUsingNSURLConnectionWithURLRequest:request andCallback:handler];
}
}
}
#pragma mark- Setter/Getter Overrides
// CL: the below errorHandler overrides is here temporarily
// should be set externally.
- (id)errorHandler
{
if (!_errorHandler) {
_errorHandler = [[ErrorHandler alloc]init];
}
return _errorHandler;
}
- (NSString *)api_key
{
if (!_api_key) {
_api_key = [[NSString alloc]initWithString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"MisoApiKey"]];
}
return _api_key;
}
- (NSString *)version
{
if (!_version) {
_version = [[NSString alloc] initWithString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"]];
}
return _version;
}
- (NSOperationQueue *)opQueue
{
if (!_opQueue) {
_opQueue = [[NSOperationQueue alloc] init];
}
return _opQueue;
}
- (MisoApiAccountClient *)accountClient
{
if (!_accountClient) {
_accountClient = [[MisoApiAccountClient alloc]init];
_accountClient.delegate = self;
}
return _accountClient;
}
- (MisoApiAdvertisementsClient *)advertisementsClient
{
if (!_advertisementsClient) {
_advertisementsClient = [[MisoApiAdvertisementsClient alloc]init];
_advertisementsClient.delegate = self;
}
return _advertisementsClient;
}
- (MisoApiArrangementsClient *)arrangementsClient
{
if (!_arrangementsClient) {
_arrangementsClient = [[MisoApiArrangementsClient alloc]init];
_arrangementsClient.delegate = self;
}
return _arrangementsClient;
}
- (MisoApiArtistsClient *)artistsClient
{
if (!_artistsClient) {
_artistsClient = [[MisoApiArtistsClient alloc]init];
_artistsClient.delegate = self;
}
return _artistsClient;
}
- (MisoApiComposersClient *)composersClient
{
if (!_composersClient) {
_composersClient = [[MisoApiComposersClient alloc]init];
_composersClient.delegate = self;
}
return _composersClient;
}
- (MisoApiInstrumentsClient *)instrumentsClient
{
if (!_instrumentsClient) {
_instrumentsClient = [[MisoApiInstrumentsClient alloc]init];
_instrumentsClient.delegate = self;
}
return _instrumentsClient;
}
- (MisoApiInstrumentBrandsClient *)instrumentBrandsClient
{
if (!_instrumentBrandsClient) {
_instrumentBrandsClient = [[MisoApiInstrumentBrandsClient alloc]init];
_instrumentBrandsClient.delegate = self;
}
return _instrumentBrandsClient;
}
- (MisoApiInstrumentSeriesClient *)instrumentSeriesClient
{
if (!_instrumentSeriesClient) {
_instrumentSeriesClient = [[MisoApiInstrumentSeriesClient alloc]init];
_instrumentSeriesClient.delegate = self;
}
return _instrumentSeriesClient;
}
- (MisoApiPartsClient *)partsClient
{
if (!_partsClient) {
_partsClient = [[MisoApiPartsClient alloc]init];
_partsClient.delegate = self;
}
return _partsClient;
}
- (MisoApiSongsClient *)songsClient
{
if (!_songsClient) {
_songsClient = [[MisoApiSongsClient alloc]init];
_songsClient.delegate = self;
}
return _songsClient;
}
- (MisoApiBooksClient *)booksClient
{
if (!_booksClient) {
_booksClient = [[MisoApiBooksClient alloc]init];
_booksClient.delegate = self;
}
return _booksClient;
}
#pragma mark- Reachability Methods
+ (BOOL)internetIsReachable
{
BOOL result = YES;
Reachability *r = [Reachability reachabilityWithHostName:@"google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if(internetStatus == NotReachable)
{
// CL: maybe this should be changed to send a message to a VC?
UIAlertView *Alert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection"
message:@"You do not seem to have internet connectivity at this time. Please connect to the internet to use this feature."
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles: nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"LogOutFromShop" object:nil];
[Alert show];
[Alert release];
result = NO;
}
return result;
}
@end
#pragma mark- NSDictionary API Specific Category Implementation
// helper function: get the string form of any object
static NSString *toString(id object) {
return [NSString stringWithFormat: @"%@", object];
}
// helper function: get the url encoded string form of any object
static NSString *urlEncode(id object) {
NSString *string = nil;
// CL: if the Dictionary item is an Array of other objects
// than we need to pull them out and prep them.
// otherwise, the memory addresses are sent rather than the values
if ([object isKindOfClass:[NSArray class]]) string = [object componentsJoinedByString:@","];
else string = toString(object);
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)string,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8);
return [encodedString autorelease];
}
@implementation NSDictionary (UrlEncoding)
-(NSString *)urlEncodedString
{
NSMutableArray *parts = [NSMutableArray array];
//NSArray* sortedKeys = [self keysSortedByValueUsingSelector:@selector(caseInsensitiveCompare:)];
for (id key in self)
{
id value = [self objectForKey:key];
NSString *part = [NSString stringWithFormat: @"%@=%@", urlEncode(key), urlEncode(value)];
[parts addObject: part];
}
[parts sortUsingSelector:@selector(caseInsensitiveCompare:)];
return [parts componentsJoinedByString: @"&"];
}
@end