RNFetchBlobReqBuilder.m
13.7 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
//
// RNFetchBlobReqBuilder.m
// RNFetchBlob
//
// Created by Ben Hsieh on 2016/7/9.
// Copyright © 2016年 wkh237. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "RNFetchBlobReqBuilder.h"
#import "RNFetchBlobNetwork.h"
#import "RNFetchBlobConst.h"
#import "RNFetchBlobFS.h"
#import "IOS7Polyfill.h"
#if __has_include(<React/RCTAssert.h>)
#import <React/RCTLog.h>
#else
#import "RCTLog.h"
#endif
@interface RNFetchBlobReqBuilder()
{
}
@end
@implementation RNFetchBlobReqBuilder
// Fetch blob data request
+(void) buildMultipartRequest:(NSDictionary *)options
taskId:(NSString *)taskId
method:(NSString *)method
url:(NSString *)url
headers:(NSDictionary *)headers
form:(NSArray *)form
onComplete:(void(^)(NSURLRequest * req, long bodyLength))onComplete
{
// NSString * encodedUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString * encodedUrl = url;
// send request
__block NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: encodedUrl]];
__block NSMutableDictionary *mheaders = [[NSMutableDictionary alloc] initWithDictionary:[RNFetchBlobNetwork normalizeHeaders:headers]];
NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
NSNumber * timeStampObj = [NSNumber numberWithDouble: timeStamp];
// generate boundary
__block NSString * boundary = [NSString stringWithFormat:@"RNFetchBlob%d", timeStampObj];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
__block NSMutableData * postData = [[NSMutableData alloc] init];
// combine multipart/form-data body
[[self class] buildFormBody:form boundary:boundary onComplete:^(NSData *formData, BOOL hasError) {
if(hasError)
{
onComplete(nil, nil);
}
else
{
if(formData != nil)
{
[postData appendData:formData];
// close form data
[postData appendData: [[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postData];
}
// set content-length
[mheaders setValue:[NSString stringWithFormat:@"%lu",[postData length]] forKey:@"Content-Length"];
[mheaders setValue:@"100-continue" forKey:@"Expect"];
// appaned boundary to content-type
[mheaders setValue:[NSString stringWithFormat:@"multipart/form-data; charset=utf-8; boundary=%@", boundary] forKey:@"content-type"];
[request setHTTPMethod: method];
[request setAllHTTPHeaderFields:mheaders];
onComplete(request, [formData length]);
}
}];
});
}
// Fetch blob data request
+(void) buildOctetRequest:(NSDictionary *)options
taskId:(NSString *)taskId
method:(NSString *)method
url:(NSString *)url
headers:(NSDictionary *)headers
body:(NSString *)body
onComplete:(void(^)(__weak NSURLRequest * req, long bodyLength))onComplete
{
// NSString * encodedUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString * encodedUrl = url;
// send request
__block NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL URLWithString: encodedUrl]];
__block NSMutableDictionary *mheaders = [[NSMutableDictionary alloc] initWithDictionary:[RNFetchBlobNetwork normalizeHeaders:headers]];
// move heavy task to another thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableData * blobData;
long size = -1;
// if method is POST, PUT or PATCH, convert data string format
if([[method lowercaseString] isEqualToString:@"post"] || [[method lowercaseString] isEqualToString:@"put"] || [[method lowercaseString] isEqualToString:@"patch"]) {
// generate octet-stream body
if(body != nil) {
__block NSString * cType = [[self class] getHeaderIgnoreCases:@"content-type" fromHeaders:mheaders];
__block NSString * transferEncoding = [[self class] getHeaderIgnoreCases:@"transfer-encoding" fromHeaders:mheaders];
// when headers does not contain a key named "content-type" (case ignored), use default content type
if(cType == nil)
{
[mheaders setValue:@"application/octet-stream" forKey:@"Content-Type"];
}
// when body is a string contains file path prefix, try load file from the path
if([body hasPrefix:FILE_PREFIX]) {
__block NSString * orgPath = [body substringFromIndex:[FILE_PREFIX length]];
orgPath = [RNFetchBlobFS getPathOfAsset:orgPath];
if([orgPath hasPrefix:AL_PREFIX])
{
[RNFetchBlobFS readFile:orgPath encoding:nil onComplete:^(NSData *content, NSString * err) {
if(err != nil)
{
onComplete(nil, nil);
}
else
{
[request setHTTPBody:content];
[request setHTTPMethod: method];
[request setAllHTTPHeaderFields:mheaders];
onComplete(request, [content length]);
}
}];
return;
}
size = [[[NSFileManager defaultManager] attributesOfItemAtPath:orgPath error:nil] fileSize];
if(transferEncoding != nil && [[transferEncoding lowercaseString] isEqualToString:@"chunked"])
{
[request setHTTPBodyStream: [NSInputStream inputStreamWithFileAtPath:orgPath ]];
}
else
{
__block NSData * bodyBytes = [NSData dataWithContentsOfFile:orgPath ];
[request setHTTPBody:bodyBytes];
}
}
// otherwise convert it as BASE64 data string
else {
__block NSString * cType = [[self class]getHeaderIgnoreCases:@"content-type" fromHeaders:mheaders];
// when content-type is application/octet* decode body string using BASE64 decoder
if([[cType lowercaseString] hasPrefix:@"application/octet"] || [[cType lowercaseString] RNFBContainsString:@";base64"])
{
__block NSString * ncType = [[cType stringByReplacingOccurrencesOfString:@";base64" withString:@""]stringByReplacingOccurrencesOfString:@";BASE64" withString:@""];
if([mheaders valueForKey:@"content-type"] != nil)
[mheaders setValue:ncType forKey:@"content-type"];
if([mheaders valueForKey:@"Content-Type"] != nil)
[mheaders setValue:ncType forKey:@"Content-Type"];
blobData = [[NSData alloc] initWithBase64EncodedString:body options:0];
[request setHTTPBody:blobData];
size = [blobData length];
}
// otherwise use the body as-is
else
{
size = [body length];
[request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]];
}
}
}
}
[request setHTTPMethod: method];
[request setAllHTTPHeaderFields:mheaders];
onComplete(request, size);
});
}
+(void) buildFormBody:(NSArray *)form boundary:(NSString *)boundary onComplete:(void(^)(NSData * formData, BOOL hasError))onComplete
{
__block NSMutableData * formData = [[NSMutableData alloc] init];
if(form == nil)
onComplete(nil, NO);
else
{
__block int i = 0;
__block int count = [form count];
// a recursive block that builds multipart body asynchornously
void __block (^getFieldData)(id field) = ^(id field)
{
NSString * name = [field valueForKey:@"name"];
__block NSString * content = [field valueForKey:@"data"];
NSString * contentType = [field valueForKey:@"type"];
// skip when the form field `name` or `data` is empty
if(content == nil || name == nil)
{
i++;
getFieldData([form objectAtIndex:i]);
RCTLogWarn(@"RNFetchBlob multipart request builder has found a field without `data` or `name` property, the field will be removed implicitly.");
return;
}
// field is a text field
if([field valueForKey:@"filename"] == nil || content == nil) {
contentType = contentType == nil ? @"text/plain" : contentType;
[formData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[formData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n", name] dataUsingEncoding:NSUTF8StringEncoding]];
[formData appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", contentType] dataUsingEncoding:NSUTF8StringEncoding]];
[formData appendData:[[NSString stringWithFormat:@"%@\r\n", content] dataUsingEncoding:NSUTF8StringEncoding]];
}
// field contains a file
else {
contentType = contentType == nil ? @"application/octet-stream" : contentType;
NSMutableData * blobData;
if(content != nil)
{
// append data from file asynchronously
if([content hasPrefix:FILE_PREFIX])
{
NSString * orgPath = [content substringFromIndex:[FILE_PREFIX length]];
orgPath = [RNFetchBlobFS getPathOfAsset:orgPath];
[RNFetchBlobFS readFile:orgPath encoding:nil onComplete:^(NSData *content, NSString * err) {
if(err != nil)
{
onComplete(formData, YES);
return;
}
NSString * filename = [field valueForKey:@"filename"];
[formData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[formData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name, filename] dataUsingEncoding:NSUTF8StringEncoding]];
[formData appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", contentType] dataUsingEncoding:NSUTF8StringEncoding]];
[formData appendData:content];
[formData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
i++;
if(i < count)
{
__block NSDictionary * nextField = [form objectAtIndex:i];
getFieldData(nextField);
}
else
{
onComplete(formData, NO);
getFieldData = nil;
}
}];
return ;
}
else
blobData = [[NSData alloc] initWithBase64EncodedString:content options:0];
}
NSString * filename = [field valueForKey:@"filename"];
[formData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[formData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name, filename] dataUsingEncoding:NSUTF8StringEncoding]];
[formData appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", contentType] dataUsingEncoding:NSUTF8StringEncoding]];
[formData appendData:blobData];
[formData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
blobData = nil;
}
i++;
if(i < count)
{
__block NSDictionary * nextField = [form objectAtIndex:i];
getFieldData(nextField);
}
else
{
onComplete(formData, NO);
getFieldData = nil;
}
};
__block NSDictionary * nextField = [form objectAtIndex:i];
getFieldData(nextField);
}
}
+(NSString *) getHeaderIgnoreCases:(NSString *)field fromHeaders:(NSMutableDictionary *) headers {
NSString * normalCase = [headers valueForKey:field];
NSString * ignoredCase = [headers valueForKey:[field lowercaseString]];
if( normalCase != nil)
return normalCase;
else
return ignoredCase;
}
@end