ASIWebPageRequest.m
8.82 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
//
// ASIWebPageRequest.m
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 29/06/2010.
// Copyright 2010 All-Seeing Interactive. All rights reserved.
//
// EXPERIMENTAL PROOF OF CONCEPT - DO NOT USE
#import "ASIWebPageRequest.h"
#import "ASINetworkQueue.h"
static xmlChar *xpathExpr = (xmlChar *)"//link[@rel = \"stylesheet\"]/@href|//script/@src|//img/@src";
@interface ASIWebPageRequest ()
- (void)readResourceURLs;
- (void)updateResourceURLs;
- (void)cleanUp;
@property (retain, nonatomic) ASINetworkQueue *externalResourceQueue;
@property (retain, nonatomic) NSMutableDictionary *resourceList;
@end
@implementation ASIWebPageRequest
- (void)markAsFinished
{
}
- (void)requestFinished
{
NSString *responseHTML = [self responseString];
if (!responseHTML) {
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:100 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to read HTML string from response",NSLocalizedDescriptionKey,nil]]];
return;
}
NSError *err = nil;
responseHTML = [ASIWebPageRequest XHTMLForString:[self responseString] error:&err];
if (err) {
[self failWithError:err];
return;
} else if (!responseHTML) {
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to convert response string to XHTML",NSLocalizedDescriptionKey,nil]]];
return;
}
xmlInitParser();
// Strip the namespace, because it makes the xpath query a pain
responseHTML = [responseHTML stringByReplacingOccurrencesOfString:@" xmlns=\"http://www.w3.org/1999/xhtml\"" withString:@""];
NSData *data = [responseHTML dataUsingEncoding:NSUTF8StringEncoding];
/* Load XML document */
doc = xmlParseMemory([data bytes], [data length]);
if (doc == NULL) {
xmlFreeDoc(doc);
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Error: unable to parse reponse XML",NSLocalizedDescriptionKey,nil]]];
return;
}
[self setResourceList:[NSMutableDictionary dictionary]];
// Populate the list of URLS to download
[self readResourceURLs];
// Create a new request for every item in the queue
[[self externalResourceQueue] cancelAllOperations];
[self setExternalResourceQueue:[ASINetworkQueue queue]];
[[self externalResourceQueue] setDelegate:self];
[[self externalResourceQueue] setQueueDidFinishSelector:@selector(finishedFetchingExternalResources:)];
[[self externalResourceQueue] setRequestDidFinishSelector:@selector(externalResourceFetchSucceeded:)];
[[self externalResourceQueue] setRequestDidFailSelector:@selector(externalResourceFetchFailed:)];
[[self externalResourceQueue] setDownloadProgressDelegate:[self downloadProgressDelegate]];
[[self externalResourceQueue] setUploadProgressDelegate:[self uploadProgressDelegate]];
for (NSString *theURL in [[self resourceList] keyEnumerator]) {
ASIHTTPRequest *externalResourceRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:theURL]];
[externalResourceRequest setRequestHeaders:[self requestHeaders]];
[[self externalResourceQueue] addOperation:externalResourceRequest];
}
[[self externalResourceQueue] go];
}
- (void)externalResourceFetchSucceeded:(ASIHTTPRequest *)externalResourceRequest
{
NSMutableDictionary *requestResponse = [NSMutableDictionary dictionary];
NSString *contentType = [[externalResourceRequest responseHeaders] objectForKey:@"Content-Type"];
if (!contentType) {
contentType = @"application/octet-stream";
}
[requestResponse setObject:contentType forKey:@"ContentType"];
[requestResponse setObject:[externalResourceRequest responseData] forKey:@"Data"];
[[self resourceList] setObject:requestResponse forKey:[[externalResourceRequest originalURL] absoluteString]];
}
- (void)externalResourceFetchFailed:(ASIHTTPRequest *)externalResourceRequest
{
[self failWithError:[externalResourceRequest error]];
}
- (void)finishedFetchingExternalResources:(ASINetworkQueue *)queue
{
if (![self error]) {
[self updateResourceURLs];
}
[self cleanUp];
[super requestFinished];
[(id)super markAsFinished];
}
- (void)cleanUp
{
xmlDocDump(stdout, doc);
xmlFreeDoc(doc);
xmlCleanupParser();
}
- (void)readResourceURLs
{
/* Create xpath evaluation context */
xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
if(xpathCtx == NULL) {
xmlFreeDoc(doc);
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Error: unable to create new XPath context",NSLocalizedDescriptionKey,nil]]];
return;
}
/* Evaluate xpath expression */
xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression(xpathExpr, xpathCtx);
if(xpathObj == NULL) {
xmlXPathFreeContext(xpathCtx);
xmlFreeDoc(doc);
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Error: unable to evaluate XPath expression!",NSLocalizedDescriptionKey,nil]]];
return;
}
xmlNodeSetPtr nodes = xpathObj->nodesetval;
int size = (nodes) ? nodes->nodeNr : 0;
int i;
for(i = size - 1; i >= 0; i--) {
assert(nodes->nodeTab[i]);
//NSLog(@"%s",xmlNodeGetContent(nodes->nodeTab[i]));
NSString *theURL = [[NSURL URLWithString:[NSString stringWithCString:(char *)xmlNodeGetContent(nodes->nodeTab[i]) encoding:NSUTF8StringEncoding] relativeToURL:[self url]] absoluteString];
//NSLog(@"%@",theURL);
[resourceList setObject:@"" forKey:theURL];
if (nodes->nodeTab[i]->type != XML_NAMESPACE_DECL) {
nodes->nodeTab[i] = NULL;
}
}
xmlXPathFreeObject(xpathObj);
xmlXPathFreeContext(xpathCtx);
}
- (void)updateResourceURLs
{
/* Create xpath evaluation context */
xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
if(xpathCtx == NULL) {
xmlFreeDoc(doc);
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Error: unable to create new XPath context",NSLocalizedDescriptionKey,nil]]];
return;
}
/* Evaluate xpath expression */
xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression(xpathExpr, xpathCtx);
if(xpathObj == NULL) {
xmlXPathFreeContext(xpathCtx);
xmlFreeDoc(doc);
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:101 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Error: unable to evaluate XPath expression!",NSLocalizedDescriptionKey,nil]]];
return;
}
xmlNodeSetPtr nodes = xpathObj->nodesetval;
int size = (nodes) ? nodes->nodeNr : 0;
int i;
for(i = size - 1; i >= 0; i--) {
assert(nodes->nodeTab[i]);
NSString *theURL = [[NSURL URLWithString:[NSString stringWithCString:(char *)xmlNodeGetContent(nodes->nodeTab[i]) encoding:NSUTF8StringEncoding] relativeToURL:[self url]] absoluteString];
NSData *data = [[resourceList objectForKey:theURL] objectForKey:@"Data"];
NSString *contentType = [[resourceList objectForKey:theURL] objectForKey:@"ContentType"];
if (data && contentType) {
NSString *newData = [NSString stringWithFormat:@"data:%@;base64,",contentType];
newData = [newData stringByAppendingString:[ASIHTTPRequest base64forData:data]];
xmlNodeSetContent(nodes->nodeTab[i], (xmlChar *)[newData cStringUsingEncoding:NSUTF8StringEncoding]);
}
if (nodes->nodeTab[i]->type != XML_NAMESPACE_DECL) {
nodes->nodeTab[i] = NULL;
}
}
xmlXPathFreeObject(xpathObj);
xmlXPathFreeContext(xpathCtx);
}
+ (NSString *)XHTMLForString:(NSString *)inputHTML error:(NSError **)error
{
const char* input = [inputHTML cStringUsingEncoding:NSUTF8StringEncoding];
TidyBuffer output = {0,0,0,0};
TidyBuffer errbuf = {0,0,0,0};
int rc = -1;
Bool ok;
TidyDoc tdoc = tidyCreate();
ok = tidyOptSetBool(tdoc, TidyXhtmlOut, yes);
if (ok) {
rc = tidySetErrorBuffer(tdoc, &errbuf);
}
if (rc >= 0) {
rc = (tidyOptSetBool(tdoc, TidyXmlDecl, yes) ? rc : -1 );
rc = (tidyOptSetValue(tdoc, TidyCharEncoding, "utf8") ? rc : -1 );
}
if (rc >= 0) {
rc = tidyParseString(tdoc, input);
}
if (rc >= 0) {
rc = tidyCleanAndRepair(tdoc);
}
if (rc >= 0) {
rc = tidyRunDiagnostics(tdoc);
}
if (rc > 1) {
rc = (tidyOptSetBool(tdoc, TidyForceOutput, yes) ? rc : -1 );
}
if (rc >= 0) {
rc = tidySaveBuffer(tdoc, &output);
}
if (rc < 0) {
*error = [NSError errorWithDomain:NetworkRequestErrorDomain code:102 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to tidy HTML with error code %d",rc],NSLocalizedDescriptionKey,nil]];
return nil;
}
NSString *xhtml = [[[NSString alloc] initWithBytes:output.bp length:output.size encoding:NSUTF8StringEncoding] autorelease];
tidyBufFree(&output);
tidyBufFree(&errbuf);
tidyRelease(tdoc);
return xhtml;
}
@synthesize externalResourceQueue;
@synthesize resourceList;
@end