-
Notifications
You must be signed in to change notification settings - Fork 240
/
SingleFileDownloader.m
376 lines (290 loc) · 11.6 KB
/
SingleFileDownloader.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
/*
* FilesDownloader
*
* Cocos2D-iPhone-Extensions v0.2.1
* https://github.com/cocos2d/cocos2d-iphone-extensions
*
* Copyright (c) 2010-2011 Stepan Generalov
* Copyright (c) 2011 Todd Lee
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#import "SingleFileDownloader.h"
#ifndef MYLOG
#ifdef DEBUG
#define MYLOG(...) NSLog(__VA_ARGS__)
#else
#define MYLOG(...) do {} while (0)
#endif
#endif
@interface SingleFileDownloader (Private)
+ (NSString *) destinationDirectoryPath;
+ (NSString *) tmpSuffix;
+ (NSFileHandle *) newFileWithName: (NSString *) newFilename;
+ (BOOL)checkTargetDirectory:(NSString *)targetPath;
@end
@interface SingleFileDownloader (NSURLConnectionDelegate)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
@end
@implementation SingleFileDownloader
+ (NSString *) tmpSuffix
{
return @".tmp";
}
+ (NSString *) tmpPathWithFilename: (NSString *) aFilename
{
return [NSString stringWithFormat:@"%@/%@%@", [self destinationDirectoryPath], aFilename, [self tmpSuffix]];
}
+ (NSString *) destinationDirectoryPath
{
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
#ifdef __MAC_OS_X_VERSION_MAX_ALLOWED
NSString *appBundleID = [[NSBundle mainBundle] bundleIdentifier];
path = [path stringByAppendingPathComponent:appBundleID];
#endif
return path;
}
+ (BOOL)checkTargetDirectory:(NSString *)targetPath
{
BOOL isDirectory = NO;
NSString *targetDirectory = [targetPath stringByDeletingLastPathComponent];
NSArray *pathComponents = [targetDirectory pathComponents];
NSString *currentTargetPath = @"";
for (int i = 0; i < [pathComponents count]; i++)
{
currentTargetPath = [currentTargetPath stringByAppendingPathComponent:[pathComponents objectAtIndex:i]];
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:currentTargetPath isDirectory:&isDirectory];
if (exists && isDirectory)
{
MYLOG(@"SingleFileDownloader#newFileWithName: %@ exists", currentTargetPath);
}
else
{
MYLOG(@"SingleFileDownloader#newFileWithName: %@ not exists! Creating...", currentTargetPath);
if ([[NSFileManager defaultManager] createDirectoryAtPath:currentTargetPath withIntermediateDirectories: YES attributes: nil error: NULL])
{
MYLOG(@"SingleFileDownloader#newFileWithName: SUCCESSFULL creating directory %@!", currentTargetPath);
}
else
{
MYLOG(@"SingleFileDownloader#newFileWithName: creating directory %@ FAILED!", currentTargetPath);
return FALSE;
}
}
}
return TRUE;
}
+ (NSFileHandle *) newFileWithName: (NSString *) newFilename
{
//creating caches directory if needed
NSString *cachesDirectoryPath = [self destinationDirectoryPath];
// creating target directory if needed
if (![self checkTargetDirectory:[cachesDirectoryPath stringByAppendingPathComponent:newFilename]])
{
return nil;
}
NSString * myFilePath = [self tmpPathWithFilename: newFilename];
if ( [ [NSFileManager defaultManager] createFileAtPath:myFilePath contents:nil attributes:nil] )
{
MYLOG(@"SingleFileDownloader#newFileWithName: %@ created OK!", myFilePath);
}
else
{
MYLOG(@"SingleFileDownloader#newFileWithName: %@ creation FAILED!", myFilePath);
return nil;
}
return [[NSFileHandle fileHandleForWritingAtPath: myFilePath] retain];
}
+ (id) fileDownloaderWithSourcePath: (NSString *) sourcePath targetFilename: (NSString *) aTargetFilename delegate: (id<SingleFileDownloaderDelegate>) aDelegate
{
return [ [ [self alloc] initWithSourcePath:sourcePath targetFilename: aTargetFilename delegate:aDelegate ] autorelease ];
}
- (id) initWithSourcePath: (NSString *) sourcePath targetFilename: (NSString *) aTargetFilename delegate: (id<SingleFileDownloaderDelegate>) aDelegate
{
if ( (self = [super init]) )
{
_connection = nil;
_filename = [ aTargetFilename retain];
_sourcePath = [ sourcePath retain];
_bytesReceived = 0;
_bytesTotal = 0;
_delegate = aDelegate;
_fileHandle = [[self class] newFileWithName: _filename];
}
return self;
}
- (void) dealloc
{
MYLOG(@"SingleFileDownloader#dealloc");
if ( _downloading )
[self cancelDownload];
[_connection release];
[_filename release];
[_sourcePath release];
[_fileHandle release];
[super dealloc];
}
- (void) startDownload
{
if ( [ [NSFileManager defaultManager] fileExistsAtPath: [self targetPath] ] )
{
MYLOG(@"SingleFileDownloader#startDownload file already downloaded and exist at %@", [self targetPath]);
[self cancelDownload];
NSDictionary *dict = [ [NSFileManager defaultManager] attributesOfItemAtPath: [self targetPath] error: NULL];
if (dict)
{
NSNumber *sizeOfFile = [dict valueForKey: NSFileSize];
_bytesTotal = _bytesReceived = [sizeOfFile intValue];
[_delegate downloadSizeUpdated];
}
else
MYLOG(@"SingleFileDownloader#startDownload exists, but no dict for attr!");
[ _delegate downloadFinished ];
return;
}
MYLOG(@"SingleFileDownloader#startDownload URL= %@", _sourcePath);
NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString: _sourcePath]
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: fileDownloaderDefaultTimeout];
_connection = [ [NSURLConnection connectionWithRequest: request delegate: self] retain];
NSString *err = nil;
if ( !_connection )
{
err = @"Can't open connection";
} else if ( !_fileHandle)
{
err = @"Can't create file";
}
if ( err )
{
MYLOG(@"SingleFileDownloader#startDownload download failed with error: %@!", err);
[_delegate downloadFailedWithError: err];
return;
}
_downloading = YES;
MYLOG(@"SingleFileDownloader#startDownload download started!");
}
- (void) cancelDownload
{
MYLOG(@"SingleFileDownloader#cancelDownload %@ download cancelled",_sourcePath);
_downloading = NO;
// close connection and file
if (_connection)
{
[_connection cancel];
[_connection release];
}
if ( _fileHandle )
[_fileHandle closeFile];
// delete tmp file
NSString *tmpPath = [NSString stringWithFormat:@"%@/%@%@", [[self class] destinationDirectoryPath], _filename, [[self class] tmpSuffix]];
[[NSFileManager defaultManager] removeItemAtPath: tmpPath error: NULL];
_connection = nil;
[_fileHandle release];
_fileHandle = nil;
//_bytesReceived = 0;
}
- (NSString *) targetPath
{
return [NSString stringWithFormat:@"%@/%@", [[self class] destinationDirectoryPath], _filename];
}
- (NSUInteger) contentDownloaded
{
return _bytesReceived;
}
- (NSUInteger) contentLength
{
return _bytesTotal;
}
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
_bytesReceived = 0;
_bytesTotal = [response expectedContentLength];
//test for free space
NSDictionary *fsAttributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[self targetPath] error: NULL];
unsigned long long freeSpace = [ [fsAttributes objectForKey:NSFileSystemFreeSize] unsignedLongLongValue ];
if ( freeSpace && ( freeSpace <= _bytesTotal ) )
{
MYLOG(@"Not Enough Space detected!");
NSString *err = @"Not enough space";
[_delegate downloadFailedWithError: err];
[self cancelDownload];
return;
}
[_delegate downloadSizeUpdated];
MYLOG(@"SingleFileDownloader#connection: %@ didReceiveResponse: %@", connection, response);
}
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{
MYLOG(@"SingleFileDownloader#connection: %@ willSendRequest: %@ redirectResponse: %@", connection, request, response );
if (response)
{
MYLOG(@"Redirect Detected!");
NSString *err = @"Unhandled redirect";
[_delegate downloadFailedWithError: err ];
[self cancelDownload];
return nil;
}
return request;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
_bytesReceived += [data length];
MYLOG(@"SingleFileDownloader#connection:%@ did receive data: [%d] Progress: %d/%d",
connection,
(int)[data length],
(int)_bytesReceived,
(int)_bytesTotal );
[_fileHandle seekToEndOfFile];
[_fileHandle writeData: data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error = nil;
[_fileHandle closeFile];
//rename ready file
NSString *tmpPath = [ [self class] tmpPathWithFilename: _filename ];
NSString *destPath = [self targetPath];
if ( ! [ [NSFileManager defaultManager] moveItemAtPath: tmpPath toPath: destPath error: &error] )
{
[self cancelDownload];
MYLOG(@"SingleFileDownloader#connectionDidFinishLoading FAILED: %@ Description: %@",
[error localizedFailureReason], [error localizedDescription] );
NSString *errString = [error localizedDescription];
[ _delegate downloadFailedWithError: errString ];
return;
}
[self cancelDownload];
[_delegate downloadFinished];
MYLOG(@"SingleFileDownloader#connectionDidFinishLoading: %@", connection );
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
MYLOG(@"SingleFileDownloader#connectionDidFailWithError: %@ Description: %@", [error localizedFailureReason], [error localizedDescription]);
[self cancelDownload];
//[_delegate downloadFailedWithError: [error localizedDescription] ];
[_delegate downloadFailedWithError: @"Connection Error" ];
}
@end