-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWordPressApi.m
298 lines (268 loc) · 13.9 KB
/
WordPressApi.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
//
// WordPressApi.m
// WordPress
//
// Created by Jorge Bernal on 1/5/12.
// Copyright (c) 2012 WordPress. All rights reserved.
//
#import "WordPressApi.h"
#import "AFHTTPRequestOperation.h"
#import "AFXMLRPCClient.h"
#import "TouchXML.h"
#ifndef WPFLog
#define WPFLog(...) NSLog(__VA_ARGS__)
#endif
@interface WordPressApi ()
@property (readwrite, nonatomic, retain) NSURL *xmlrpc;
@property (readwrite, nonatomic, retain) NSString *username;
@property (readwrite, nonatomic, retain) NSString *password;
@property (readwrite, nonatomic, retain) AFXMLRPCClient *client;
+ (void)validateXMLRPCUrl:(NSURL *)url success:(void (^)())success failure:(void (^)(NSError *error))failure;
+ (void)logExtraInfo:(NSString *)format, ...;
@end
@implementation WordPressApi {
NSURL *_xmlrpc;
NSString *_username;
NSString *_password;
AFXMLRPCClient *_client;
}
@synthesize xmlrpc = _xmlrpc;
@synthesize username = _username;
@synthesize password = _password;
@synthesize client = _client;
+ (WordPressApi *)apiWithXMLRPCEndpoint:(NSURL *)xmlrpc username:(NSString *)username password:(NSString *)password {
return [[[self alloc] initWithXMLRPCEndpoint:xmlrpc username:username password:password] autorelease];
}
- (id)initWithXMLRPCEndpoint:(NSURL *)xmlrpc username:(NSString *)username password:(NSString *)password
{
self = [super init];
if (!self) {
return nil;
}
self.xmlrpc = xmlrpc;
self.username = username;
self.password = password;
self.client = [AFXMLRPCClient clientWithXMLRPCEndpoint:xmlrpc];
return self;
}
- (void)dealloc {
[_xmlrpc release];
[_username release];
[_password release];
[_client release];
[super dealloc];
}
#pragma mark - Authentication
- (void)authenticateWithSuccess:(void (^)())success failure:(void (^)(NSError *error))failure {
[self getBlogsWithSuccess:^(NSArray *blogs) {
if (success) {
success();
}
} failure:failure];
}
- (void)getBlogsWithSuccess:(void (^)(NSArray *blogs))success failure:(void (^)(NSError *error))failure {
[self.client callMethod:@"wp.getUsersBlogs"
parameters:[NSArray arrayWithObjects:self.username, self.password, nil]
success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
success(responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(error);
}
}];
}
#pragma mark - Helpers
+ (void)guessXMLRPCURLForSite:(NSString *)url
success:(void (^)(NSURL *xmlrpcURL))success
failure:(void (^)(NSError *error))failure {
__block NSURL *xmlrpcURL;
__block NSString *xmlrpc;
// ------------------------------------------------
// 0. Is an empty url? Sorry, no psychic powers yet
// ------------------------------------------------
if (url == nil || [url isEqualToString:@""]) {
NSError *error = [NSError errorWithDomain:@"org.wordpress.api" code:0 userInfo:[NSDictionary dictionaryWithObject:NSLocalizedString(@"Empty URL", @"") forKey:NSLocalizedDescriptionKey]];
[self logExtraInfo: [error localizedDescription] ];
return failure ? failure(error) : nil;
}
// ------------------------------------------------------------------------
// 1. Assume the given url is the home page and XML-RPC sits at /xmlrpc.php
// ------------------------------------------------------------------------
[self logExtraInfo: @"1. Assume the given url is the home page and XML-RPC sits at /xmlrpc.php" ];
if(![url hasPrefix:@"http"])
url = [NSString stringWithFormat:@"http://%@", url];
if ([url hasSuffix:@"xmlrpc.php"])
xmlrpc = url;
else
xmlrpc = [NSString stringWithFormat:@"%@/xmlrpc.php", url];
xmlrpcURL = [NSURL URLWithString:xmlrpc];
if (xmlrpcURL == nil) {
// Not a valid URL. Could be a bad protocol (htpp://), syntax error (http//), ...
// See https://github.com/koke/NSURL-Guess for extra help cleaning user typed URLs
NSError *error = [NSError errorWithDomain:@"org.wordpress.api" code:1 userInfo:[NSDictionary dictionaryWithObject:NSLocalizedString(@"Invalid URL", @"") forKey:NSLocalizedDescriptionKey]];
[self logExtraInfo: [error localizedDescription]];
return failure ? failure(error) : nil;
}
[self logExtraInfo: @"Trying the following URL: %@", xmlrpcURL ];
[self validateXMLRPCUrl:xmlrpcURL success:^{
if (success) {
success(xmlrpcURL);
}
} failure:^(NSError *error){
if ([error.domain isEqual:NSURLErrorDomain] && error.code == NSURLErrorUserCancelledAuthentication) {
[self logExtraInfo: [error localizedDescription]];
if (failure) {
failure(error);
}
return;
}
// -------------------------------------------
// 2. Try the given url as an XML-RPC endpoint
// -------------------------------------------
[self logExtraInfo:@"2. Try the given url as an XML-RPC endpoint"];
xmlrpcURL = [NSURL URLWithString:url];
[self logExtraInfo: @"Trying the following URL: %@", url];
[self validateXMLRPCUrl:xmlrpcURL success:^{
if (success) {
success(xmlrpcURL);
}
} failure:^(NSError *error){
[self logExtraInfo:[error localizedDescription]];
// ---------------------------------------------------
// 3. Fetch the original url and look for the RSD link
// ---------------------------------------------------
[self logExtraInfo:@"3. Fetch the original url and look for the RSD link by using RegExp"];
NSURLRequest *request = [NSURLRequest requestWithURL:xmlrpcURL];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error = NULL;
NSRegularExpression *rsdURLRegExp = [NSRegularExpression regularExpressionWithPattern:@"<link\\s+rel=\"EditURI\"\\s+type=\"application/rsd\\+xml\"\\s+title=\"RSD\"\\s+href=\"([^\"]*)\"[^/]*/>" options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *matches = [rsdURLRegExp matchesInString:operation.responseString options:0 range:NSMakeRange(0, [operation.responseString length])];
NSString *rsdURL = nil;
if ([matches count]) {
NSRange rsdURLRange = [[matches objectAtIndex:0] rangeAtIndex:1];
if(rsdURLRange.location != NSNotFound)
rsdURL = [operation.responseString substringWithRange:rsdURLRange];
}
if (rsdURL == nil) {
//the RSD link not found using RegExp, try to find it again on a "cleaned" HTML document
[self logExtraInfo:@"The RSD link not found using RegExp, on the following doc: %@", operation.responseString];
[self logExtraInfo:@"Try to find it again on a cleaned HTML document"];
NSError *htmlError;
CXMLDocument *rsdHTML = [[[CXMLDocument alloc] initWithXMLString:operation.responseString options:CXMLDocumentTidyXML error:&htmlError] autorelease];
if(!htmlError) {
NSString *cleanedHTML = [rsdHTML XMLStringWithOptions:CXMLDocumentTidyXML];
[self logExtraInfo:@"The cleaned doc: %@", cleanedHTML];
NSArray *matches = [rsdURLRegExp matchesInString:operation.responseString options:0 range:NSMakeRange(0, [cleanedHTML length])];
if ([matches count]) {
NSRange rsdURLRange = [[matches objectAtIndex:0] rangeAtIndex:1];
if (rsdURLRange.location != NSNotFound)
rsdURL = [cleanedHTML substringWithRange:rsdURLRange];
}
} else {
[self logExtraInfo:@"The cleaning function reported the following error: %@", [htmlError localizedDescription]];
}
}
if (rsdURL != nil) {
void (^parseBlock)(void) = ^() {
[self logExtraInfo:@"5. Parse the RSD document at the following URL: %@", rsdURL];
// -------------------------
// 5. Parse the RSD document
// -------------------------
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:rsdURL]];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *rsdError;
CXMLDocument *rsdXML = [[[CXMLDocument alloc] initWithXMLString:operation.responseString options:CXMLDocumentTidyXML error:&rsdError] autorelease];
if (!rsdError) {
@try {
CXMLElement *serviceXML = [[[rsdXML rootElement] children] objectAtIndex:1];
for(CXMLElement *api in [[[serviceXML elementsForName:@"apis"] objectAtIndex:0] elementsForName:@"api"]) {
if([[[api attributeForName:@"name"] stringValue] isEqualToString:@"WordPress"]) {
// Bingo! We found the WordPress XML-RPC element
xmlrpc = [[api attributeForName:@"apiLink"] stringValue];
xmlrpcURL = [NSURL URLWithString:xmlrpc];
[self logExtraInfo:@"Bingo! We found the WordPress XML-RPC element: %@", xmlrpcURL];
[self validateXMLRPCUrl:xmlrpcURL success:^{
if (success) success(xmlrpcURL);
} failure:^(NSError *error){
[self logExtraInfo: [error localizedDescription]];
if (failure) failure(error);
}];
}
}
}
@catch (NSException *exception) {
if (failure) failure(error);
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[self logExtraInfo: [error localizedDescription]];
if (failure) failure(error);
}];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
};
// ----------------------------------------------------------------------------
// 4. Try removing "?rsd" from the url, it should point to the XML-RPC endpoint
// ----------------------------------------------------------------------------
xmlrpc = [rsdURL stringByReplacingOccurrencesOfString:@"?rsd" withString:@""];
if (![xmlrpc isEqualToString:rsdURL]) {
xmlrpcURL = [NSURL URLWithString:xmlrpc];
[self validateXMLRPCUrl:xmlrpcURL success:^{
if (success) {
success(xmlrpcURL);
}
} failure:^(NSError *error){
parseBlock();
}];
} else {
parseBlock();
}
} else {
if (failure)
failure(error);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[self logExtraInfo:@"Can't fetch the original url: %@", [error localizedDescription]];
if (failure) failure(error);
}];
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];
}];
}];
}
#pragma mark - Private Methods
+ (void)validateXMLRPCUrl:(NSURL *)url success:(void (^)())success failure:(void (^)(NSError *error))failure {
AFXMLRPCClient *client = [AFXMLRPCClient clientWithXMLRPCEndpoint:url];
[client callMethod:@"system.listMethods"
parameters:[NSArray array]
success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
success();
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(error);
}
}];
}
+ (void)logExtraInfo:(NSString *)format, ... {
BOOL extraDebugIsActive = NO;
NSNumber *extra_debug = [[NSUserDefaults standardUserDefaults] objectForKey:@"extra_debug"];
if ([extra_debug boolValue]) {
extraDebugIsActive = YES;
}
#ifdef DEBUG
extraDebugIsActive = YES;
#endif
if( extraDebugIsActive == NO ) return;
va_list ap;
va_start(ap, format);
NSString *message = [[NSString alloc] initWithFormat:format arguments:ap];
WPFLog(@"[WordPressApi] < %@", message);
[message release];
}
@end