Repository navigation
Expand file tree
/
Copy pathDBRequest.m
More file actions
executable file
·321 lines (259 loc) · 10.7 KB
/
Copy pathDBRequest.m
File metadata and controls
executable file
·321 lines (259 loc) · 10.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
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
//
// DBRestRequest.m
// DropboxSDK
//
// Created by Brian Smith on 4/9/10.
// Copyright 2010 Dropbox, Inc. All rights reserved.
//
#import "DBRequest.h"
#import "DBLog.h"
#import "DBError.h"
#import "JSON.h"
id<DBNetworkRequestDelegate> dbNetworkRequestDelegate = nil;
@interface DBRequest ()
- (void)setError:(NSError *)error;
@property (nonatomic, retain) NSFileManager *fileManager;
@end
@implementation DBRequest
+ (void)setNetworkRequestDelegate:(id<DBNetworkRequestDelegate>)delegate {
dbNetworkRequestDelegate = delegate;
}
- (id)initWithURLRequest:(NSURLRequest*)aRequest andInformTarget:(id)aTarget selector:(SEL)aSelector {
if ((self = [super init])) {
request = [aRequest retain];
target = aTarget;
selector = aSelector;
fileManager = [NSFileManager new];
urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[dbNetworkRequestDelegate networkRequestStarted];
}
return self;
}
- (void) dealloc {
[urlConnection cancel];
[request release];
[urlConnection release];
[fileHandle release];
[fileManager release];
[userInfo release];
[sourcePath release];
[response release];
[xDropboxMetadataJSON release];
[resultFilename release];
[tempFilename release];
[resultData release];
[error release];
[super dealloc];
}
@synthesize failureSelector;
@synthesize fileManager;
@synthesize downloadProgressSelector;
@synthesize uploadProgressSelector;
@synthesize userInfo;
@synthesize sourcePath;
@synthesize request;
@synthesize response;
@synthesize xDropboxMetadataJSON;
@synthesize downloadProgress;
@synthesize uploadProgress;
@synthesize resultData;
@synthesize resultFilename;
@synthesize error;
- (NSString*)resultString {
return [[[NSString alloc]
initWithData:resultData encoding:NSUTF8StringEncoding]
autorelease];
}
- (NSObject*)resultJSON {
return [[self resultString] JSONValue];
}
- (NSInteger)statusCode {
return [response statusCode];
}
- (long long)responseBodySize {
// Use the content-length header, if available.
long long contentLength = [[[response allHeaderFields] objectForKey:@"Content-Length"] longLongValue];
if (contentLength > 0) return contentLength;
// Fall back on the bytes field in the metadata x-header, if available.
if (xDropboxMetadataJSON != nil) {
id bytes = [xDropboxMetadataJSON objectForKey:@"bytes"];
if (bytes != nil) {
return [bytes longLongValue];
}
}
return 0;
}
- (void)cancel {
[urlConnection cancel];
target = nil;
if (tempFilename) {
[fileHandle closeFile];
NSError* rmError;
if (![fileManager removeItemAtPath:tempFilename error:&rmError]) {
DBLogError(@"DBRequest#cancel Error removing temp file: %@", rmError);
}
}
[dbNetworkRequestDelegate networkRequestStopped];
}
- (id)parseResponseAsType:(Class)cls {
if (error) return nil;
NSObject *res = [self resultJSON];
if (![res isKindOfClass:cls]) {
[self setError:[NSError errorWithDomain:DBErrorDomain code:DBErrorInvalidResponse userInfo:userInfo]];
return nil;
}
return res;
}
#pragma mark NSURLConnection delegate methods
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)aResponse {
response = [(NSHTTPURLResponse*)aResponse retain];
// Parse out the x-response-metadata as JSON.
xDropboxMetadataJSON = [[[[response allHeaderFields] objectForKey:@"X-Dropbox-Metadata"] JSONValue] retain];
if (resultFilename && [self statusCode] == 200) {
// Create the file here so it's created in case it's zero length
// File is downloaded into a temporary file and then moved over when completed successfully
NSString* filename = [[NSProcessInfo processInfo] globallyUniqueString];
tempFilename = [[NSTemporaryDirectory() stringByAppendingPathComponent:filename] retain];
BOOL success = [fileManager createFileAtPath:tempFilename contents:nil attributes:nil];
if (!success) {
DBLogError(@"DBRequest#connection:didReceiveData: Error creating temp file: (%d) %s",
errno, strerror(errno));
}
fileHandle = [[NSFileHandle fileHandleForWritingAtPath:tempFilename] retain];
}
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
if (resultFilename && [self statusCode] == 200) {
@try {
[fileHandle writeData:data];
} @catch (NSException* e) {
// In case we run out of disk space
[urlConnection cancel];
[fileHandle closeFile];
[fileManager removeItemAtPath:tempFilename error:nil];
[self setError:[NSError errorWithDomain:DBErrorDomain code:DBErrorInsufficientDiskSpace userInfo:userInfo]];
SEL sel = failureSelector ? failureSelector : selector;
[target performSelector:sel withObject:self];
[dbNetworkRequestDelegate networkRequestStopped];
return;
}
} else {
if (resultData == nil) {
resultData = [NSMutableData new];
}
[resultData appendData:data];
}
bytesDownloaded += [data length];
long long responseBodySize = [self responseBodySize];
if (responseBodySize > 0) {
downloadProgress = (CGFloat)bytesDownloaded / (CGFloat)responseBodySize;
if (downloadProgressSelector) {
[target performSelector:downloadProgressSelector withObject:self];
}
}
}
- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
[fileHandle closeFile];
[fileHandle release];
fileHandle = nil;
if (self.statusCode != 200) {
NSMutableDictionary* errorUserInfo = [NSMutableDictionary dictionaryWithDictionary:userInfo];
// To get error userInfo, first try and make sense of the response as JSON, if that
// fails then send back the string as an error message
NSString* resultString = [self resultString];
if ([resultString length] > 0) {
@try {
DBJsonParser *jsonParser = [DBJsonParser new];
NSObject* resultJSON = [jsonParser objectWithString:resultString];
[jsonParser release];
if ([resultJSON isKindOfClass:[NSDictionary class]]) {
[errorUserInfo addEntriesFromDictionary:(NSDictionary*)resultJSON];
}
} @catch (NSException* e) {
[errorUserInfo setObject:resultString forKey:@"errorMessage"];
}
}
[self setError:[NSError errorWithDomain:DBErrorDomain code:self.statusCode userInfo:errorUserInfo]];
} else if (tempFilename) {
NSError* moveError;
// Check that the file size is the same as the Content-Length
NSDictionary* fileAttrs = [fileManager attributesOfItemAtPath:tempFilename error:&moveError];
if (!fileAttrs) {
DBLogError(@"DBRequest#connectionDidFinishLoading: error getting file attrs: %@", moveError);
[fileManager removeItemAtPath:tempFilename error:nil];
[self setError:[NSError errorWithDomain:moveError.domain code:moveError.code userInfo:self.userInfo]];
} else if ([self responseBodySize] != 0 && [self responseBodySize] != [fileAttrs fileSize]) {
// This happens in iOS 4.0 when the network connection changes while loading
[fileManager removeItemAtPath:tempFilename error:nil];
[self setError:[NSError errorWithDomain:DBErrorDomain code:DBErrorGenericError userInfo:self.userInfo]];
} else {
// Everything's OK, move temp file over to desired file
[fileManager removeItemAtPath:resultFilename error:nil];
BOOL success = [fileManager moveItemAtPath:tempFilename toPath:resultFilename error:&moveError];
if (!success) {
DBLogError(@"DBRequest#connectionDidFinishLoading: error moving temp file to desired location: %@",
[moveError localizedDescription]);
[self setError:[NSError errorWithDomain:moveError.domain code:moveError.code userInfo:self.userInfo]];
}
}
[tempFilename release];
tempFilename = nil;
}
SEL sel = (error && failureSelector) ? failureSelector : selector;
[target performSelector:sel withObject:self];
[dbNetworkRequestDelegate networkRequestStopped];
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)anError {
[fileHandle closeFile];
[self setError:[NSError errorWithDomain:anError.domain code:anError.code userInfo:self.userInfo]];
bytesDownloaded = 0;
downloadProgress = 0;
uploadProgress = 0;
if (tempFilename) {
NSError* removeError;
BOOL success = [fileManager removeItemAtPath:tempFilename error:&removeError];
if (!success) {
DBLogError(@"DBRequest#connection:didFailWithError: error removing temporary file: %@",
[removeError localizedDescription]);
}
[tempFilename release];
tempFilename = nil;
}
SEL sel = failureSelector ? failureSelector : selector;
[target performSelector:sel withObject:self];
[dbNetworkRequestDelegate networkRequestStopped];
}
- (void)connection:(NSURLConnection*)connection didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
uploadProgress = (CGFloat)totalBytesWritten / (CGFloat)totalBytesExpectedToWrite;
if (uploadProgressSelector) {
[target performSelector:uploadProgressSelector withObject:self];
}
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)response {
return nil;
}
- (NSInputStream *)connection:(NSURLConnection *)connection needNewBodyStream:(NSURLRequest *)req {
if (!sourcePath) {
DBLogWarning(@"DropboxSDK: need new body stream, but none available");
return nil;
}
return [NSInputStream inputStreamWithFileAtPath:sourcePath];
}
#pragma mark private methods
- (void)setError:(NSError *)theError {
if (theError == error) return;
[error release];
error = [theError retain];
NSString *errorStr = [error.userInfo objectForKey:@"error"];
if (!errorStr) {
errorStr = [error description];
}
if (!([error.domain isEqual:DBErrorDomain] && error.code == 304)) {
// Log errors unless they're 304's
DBLogWarning(@"DropboxSDK: error making request to %@ - (%ld) %@",
[[request URL] path], (long)error.code, errorStr);
}
}
@end