-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRSNetflixEngine.m
423 lines (326 loc) · 17.3 KB
/
RSNetflixEngine.m
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
//
// RSNetflixEngine.m
// RSNetflixEngine
//
// Created by Rizwan on 5/29/11.
// Copyright 2011 Rizwan Sattar. All rights reserved.
//
#import "RSNetflixEngine.h"
@interface RSNetflixEngine (PrivateMethods)
// Marking requests as active
- (void) addRequest:(RSNetflixAPIRequest *)request;
- (void) removeRequest:(RSNetflixAPIRequest *)request;
// Delegate methods
- (BOOL) isValidDelegateForSelector:(SEL)selector;
@end
@implementation RSNetflixEngine
@synthesize delegate;
@synthesize apiContext;
- (void)dealloc
{
[apiContext release];
[activeURLConnections release];
[super dealloc];
}
- (id)initWithAPIContext:(RSNetflixAPIContext *)inAPIContext
{
if ((self = [super init])) {
self.apiContext = inAPIContext;
activeURLConnections = [[NSMutableArray array] retain];
}
return self;
}
#pragma mark - Delegate convenience methods
- (void)notifyDelegateOfRequestSuccess:(NSString *)requestIdentifier response:(NSDictionary *)response
{
// Notify our engine delegate
if([self isValidDelegateForSelector:@selector(netflixEngine:requestSucceeded:withResponse:)]) {
[delegate netflixEngine:self requestSucceeded:requestIdentifier withResponse:response];
}
}
- (void)notifyDelegateOfRequestFailure:(NSString *)requestIdentifier withError:(NSError *)error
{
// Notify our engine delegate
if([self isValidDelegateForSelector:@selector(netflixEngine:requestFailed:withError:)]) {
[delegate netflixEngine:self requestFailed:requestIdentifier withError:error];
}
}
#pragma mark - OAuth tokens (for getting the user's permission to access their info)
- (NSString *)requestOAuthToken
{
return [self requestOAuthTokenWithSuccessBlock:nil errorBlock:nil];
}
- (NSString *)requestOAuthTokenWithSuccessBlock:(void (^)(NSString *))successBlock errorBlock:(void (^)(NSError *))errorBlock
{
/* Typical response:
2011-11-06 16:13:36.519 RSNetflixEngine[52813:10103] NetflixAPIRequestDelegate didCompleteWithResponse:
{
"application_name" = "Movies on Netflix";
"login_url" = "https://api-user.netflix.com/oauth/login?oauth_token=5edcjztdexd8em6czp2tydc4";
"oauth_token" = 5edcjztdexd8em6czp2tydc4;
"oauth_token_secret" = N4YDE4mPFSGF;
}
*/
RSNetflixAPIRequest *request = [[[RSNetflixAPIRequest alloc] initWithAPIContext:apiContext] autorelease];
// Even though we're using blocks, we still make ourselves a delegate of this request, so that
// we have a singular place we can account for active requests
request.delegate = self;
[self addRequest:request];
return [request callAPIMethod:RSNetflixMethodRequestToken
arguments:nil
isSigned:YES
httpMethod:RSNetflixAPIHttpMethodGet
withSuccessBlock:^(NSDictionary *response) {
NSLog(@"OAuthTokenRequest completed in RSNetflixEngine!");
if([response objectForKey:@"status"] == nil) {
// Update our API Context with the oAuthRequestToken and oAuthRequestTokenSecret
apiContext.oAuthRequestToken = [response objectForKey:@"oauth_token"];
apiContext.oAuthRequestTokenSecret = [response objectForKey:@"oauth_token_secret"];
apiContext.oAuthLoginUrlFragment = [NSURL URLWithString:[response objectForKey:@"login_url"]];
NSString *completeLoginUrlString = [apiContext constructUserLoginUrlString];
// Now request specific
if([self isValidDelegateForSelector:@selector(netflixEngine:oAuthTokenRequestSucceededWithLoginUrlString:forRequestId:)]) {
[delegate netflixEngine:self oAuthTokenRequestSucceededWithLoginUrlString:completeLoginUrlString forRequestId:request.identifier];
}
if(successBlock) {
successBlock(completeLoginUrlString);
}
} else {
/* Could receive a response like:
{
status = {
message = "Internal Error";
"status_code" = 500;
};
}
*/
NSInteger statusCode = [[response valueForKeyPath:@"status.status_code"] intValue];
NSString *message = [response valueForKeyPath:@"status.message"];
NSLog(@"Server responded with statusCode: %d '%@'",statusCode,message);
}
}
errorBlock:^(NSError *error) {
NSLog(@"OAuthTokenRequest failed in RSNetflixEngine!");
if(errorBlock) {
errorBlock(error);
}
}];
}
#pragma mark - Accessing OAuth Token Secret
- (NSString *)accessOAuthToken
{
return [self accessOAuthTokenWithSuccessBlock:nil errorBlock:nil];
}
- (NSString *)accessOAuthTokenWithSuccessBlock:(void (^)(void))successBlock errorBlock:(void (^)(NSError *))errorBlock
{
RSNetflixAPIRequest *request = [[[RSNetflixAPIRequest alloc] initWithAPIContext:apiContext] autorelease];
// Even though we're using blocks, we still make ourselves a delegate of this request, so that
// we have a singular place we can account for active requests
request.delegate = self;
[self addRequest:request];
return [request callAPIMethod:RSNetflixMethodAccessToken
arguments:nil
isSigned:YES
httpMethod:RSNetflixAPIHttpMethodGet
withSuccessBlock:^(NSDictionary *response) {
NSLog(@"OAuthAccesssTokenRequest completed in RSNetflixEngine with response: \n%@", response);
if([response objectForKey:@"error"] == nil) {
// we got no error!
/*
{
"oauth_token" = AUTHORIZED_TOKEN;
"oauth_token_secret" = AUTHORIZED_TOKEN_SECRET;
"user_id" = USER_ID_WHO_AUTHORIZED_US;
}
*/
// Update our API Context with the oAuthRequestToken and oAuthRequestTokenSecret
apiContext.oAuthAccessToken = [response objectForKey:@"oauth_token"];
apiContext.oAuthAccessTokenSecret = [response objectForKey:@"oauth_token_secret"];
apiContext.userId = [response objectForKey:@"user_id"];
// Now we can clear our request token/secret, because they are useless
apiContext.oAuthRequestToken = @"";
apiContext.oAuthRequestTokenSecret = @"";
// Now request specific
if([self isValidDelegateForSelector:@selector(netflixEngine:oAuthTokenAccessSucceededForRequestId:)]) {
[delegate netflixEngine:self oAuthTokenAccessSucceededForRequestId:request.identifier];
}
if(successBlock) {
successBlock();
}
} else {
NSLog(@"Got a error response from the server: %@",response);
}
}
errorBlock:^(NSError *error) {
NSLog(@"OAuthTokenRequest failed in RSNetflixEngine!");
if(errorBlock) {
errorBlock(error);
}
}];
}
#pragma mark - User methods
- (NSString *)retrieveUserInformationForUserId:(NSString *)userId
{
return [self retrieveUserInformationForUserId:userId withSuccessBlock:nil errorBlock:nil];
}
- (NSString *)retrieveUserInformationForUserId:(NSString *)userId withSuccessBlock:(void (^)(NSDictionary *))successBlock errorBlock:(void (^)(NSError *))errorBlock
{
RSNetflixAPIRequest *request = [[[RSNetflixAPIRequest alloc] initWithAPIContext:apiContext] autorelease];
// Even though we're using blocks, we still make ourselves a delegate of this request, so that
// we have a singular place we can account for active requests
request.delegate = self;
[self addRequest:request];
return [request callAPIMethod:[NSString stringWithFormat:@"users/%@",userId]
arguments:nil
isSigned:YES
httpMethod:RSNetflixAPIHttpMethodGet
withSuccessBlock:^(NSDictionary *response) {
NSLog(@"retrieveUserInformationForUserId completed in RSNetflixEngine with response: \n%@", response);
if([response objectForKey:@"error"] == nil) {
// we got no error!
// Now request specific
if([self isValidDelegateForSelector:@selector(netflixEngine:userInformationRetrieved:forRequestId:)]) {
[delegate netflixEngine:self userInformationRetrieved:response forRequestId:request.identifier];
}
if(successBlock) {
successBlock(response);
}
} else {
NSLog(@"Got a error response from the server: %@",response);
}
}
errorBlock:^(NSError *error) {
NSLog(@"retrieveUserInformationForUserId failed in RSNetflixEngine!");
if(errorBlock) {
errorBlock(error);
}
}];
}
- (NSString *)retrieveQueuesForUserId:(NSString *)userId withSuccessBlock:(void (^)(NSDictionary *))successBlock errorBlock:(void (^)(NSError *))errorBlock
{
RSNetflixAPIRequest *request = [[[RSNetflixAPIRequest alloc] initWithAPIContext:apiContext] autorelease];
// Even though we're using blocks, we still make ourselves a delegate of this request, so that
// we have a singular place we can account for active requests
request.delegate = self;
[self addRequest:request];
/*
return [request callAPIURLString:@"http://api.netflix.com/catalog/titles/movies/70052691" isSigned:YES httpMethod:RSNetflixAPIHttpMethodGet withSuccessBlock:successBlock errorBlock:errorBlock];
*/
return [request callAPIMethod:[NSString stringWithFormat:@"users/%@/queues/disc/available",userId]
arguments:nil
isSigned:YES
httpMethod:RSNetflixAPIHttpMethodGet
withSuccessBlock:^(NSDictionary *response) {
NSLog(@"retrieveQueuesForUserId completed in RSNetflixEngine with response: \n%@", response);
if([response objectForKey:@"error"] == nil) {
// we got no error!
// Now request specific
if([self isValidDelegateForSelector:@selector(netflixEngine:userInformationRetrieved:forRequestId:)]) {
[delegate netflixEngine:self userInformationRetrieved:response forRequestId:request.identifier];
}
if(successBlock) {
successBlock(response);
}
} else {
NSLog(@"Got a error response from the server: %@",response);
}
}
errorBlock:^(NSError *error) {
NSLog(@"retrieveUserInformationForUserId failed in RSNetflixEngine!");
if(errorBlock) {
errorBlock(error);
}
}];
}
#pragma mark -
#pragma mark Catalog methods
- (NSString *)searchForTitlesMatchingTerm:(NSString*)term
{
return [self searchForTitlesMatchingTerm:term withMaxResults:-1 andPageOffset:0];
}
- (NSString *)searchForTitlesMatchingTerm:(NSString*)term withMaxResults:(NSInteger)maxResults andPageOffset:(NSInteger)pageOffset
{
return [self searchForTitlesMatchingTerm:term withMaxResults:maxResults andPageOffset:pageOffset withSuccessBlock:nil errorBlock:nil];
}
- (NSString *)searchForTitlesMatchingTerm:(NSString*)term withMaxResults:(NSInteger)maxResults andPageOffset:(NSInteger)pageOffset withSuccessBlock:(void (^)(NSDictionary *))successBlock errorBlock:(void (^)(NSError *))errorBlock
{
if(maxResults < 0)
{
maxResults = 25;
}
if(pageOffset < 0)
{
pageOffset = 0;
}
RSNetflixAPIRequest *request = [[[RSNetflixAPIRequest alloc] initWithAPIContext:apiContext] autorelease];
request.delegate = self;
NSDictionary *arguments = [NSDictionary dictionaryWithObjectsAndKeys:
[[NSNumber numberWithInteger:maxResults] stringValue],@"max_results",
term,@"term",
[[NSNumber numberWithInteger:pageOffset] stringValue],@"start_index",
nil];
[self addRequest:request];
return [request callAPIMethod:RSNetflixMethodSearchCatalogTitles
arguments:arguments
isSigned:YES
httpMethod:RSNetflixAPIHttpMethodGet
withSuccessBlock:^(NSDictionary *response) {
if([self isValidDelegateForSelector:@selector(netflixEngine:titleSearchForTerm:returnedWithResponse:forRequestId:)]) {
[delegate netflixEngine:self titleSearchForTerm:term returnedWithResponse:response forRequestId:request.identifier];
}
if(successBlock) {
successBlock(response);
}
}
errorBlock:^(NSError *error) {
if(errorBlock) {
errorBlock(error);
}
}];
}
#pragma mark -
#pragma mark API Request delegate
- (void)netflixAPIRequest:(RSNetflixAPIRequest *)inRequest didCompleteWithResponse:(NSDictionary *)inResponseDictionary
{
[self removeRequest:inRequest];
[self notifyDelegateOfRequestSuccess:inRequest.identifier response:inResponseDictionary];
}
- (void)netflixAPIRequest:(RSNetflixAPIRequest *)inRequest didFailWithError:(NSError *)inError
{
[self removeRequest:inRequest];
[self notifyDelegateOfRequestFailure:inRequest.identifier withError:inError];
}
#pragma mark Request Management
// Marking requests as active
- (void) addRequest:(RSNetflixAPIRequest *)request
{
[activeURLConnections addObject:request];
}
- (void) removeRequest:(RSNetflixAPIRequest *)request
{
if([activeURLConnections containsObject:request]) {
[activeURLConnections removeObject:request];
}
}
#pragma mark Delegate methods
// Inspired (lifted) by https://github.com/mattgemmell/MGTwitterEngine
- (BOOL) isValidDelegateForSelector:(SEL)selector
{
return ((delegate != nil) && [delegate respondsToSelector:selector]);
}
#pragma mark -
#pragma Constant Declarations
// Declaring REST method names as constants
NSString * const RSNetflixMethodRequestToken = @"oauth/request_token";
NSString * const RSNetflixMethodAccessToken = @"oauth/access_token";
NSString * const RSNetflixMethodSearchCatalogTitles = @"catalog/titles";
NSString * const RSNetflixMethodAutocompleteCatalogTitles = @"catalog/titles/autocomplete";
NSString * const RSNetflixMethodRetrieveAllCatalogTitles = @"catalog/titles/index";
NSString * const RSNetflixMethodTitleIdTemplate = @"catalog/titles/movies/%@"; // titleId
NSString * const RSNetflixMethodSeriesIdTemplate = @"catalog/titles/series/%@"; // seriesId
NSString * const RSNetflixMethodSeasonIdTemplate = @"catalog/titles/series/%@/seasons/%@"; // seriesId, seasonId
NSString * const RSNetflixMethodProgramIdTemplate = @"catalog/titles/programs/%@"; // programId
NSString * const RSNetflixMethodTitleSimilarsTemplate = @"catalog/titles/%@/%@/similars"; // type, titleId
NSString * const RSNetflixMethodSearchPeople = @"catalog/people";
NSString * const RSNetflixMethodPersonIdTemplate = @"catalog/people/%@"; // personId
@end