-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMRScalingImageCache.m
384 lines (295 loc) · 12 KB
/
MRScalingImageCache.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
377
378
379
380
381
382
383
384
//
// MRScalingImageCache.m
//
// Created by Michael Rhodes on 10/03/2012.
//
// Copyright (c) 2012, Michael Rhodes
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include <CommonCrypto/CommonDigest.h>
#import "MRScalingImageCache.h"
#import "UIImage+Resize.h"
@implementation ScaleInfo
@synthesize width;
@synthesize height;
@synthesize quality;
@synthesize mode;
@end
@interface MRScalingImageCache (Private)
-(UIImage *)_processImage:(UIImage *)original
width:(float)width
height:(float)height
quality:(CGInterpolationQuality)quality
mode:(UIViewContentMode)mode;
@end
@implementation MRScalingImageCache
@synthesize scales = _scales;
@synthesize storePath = _storePath;
-(id)initWithStorePath:(NSString *)path
{
self = [super init];
if (self != nil) {
_storePath = [path copy];
}
return self;
}
-(NSMutableDictionary *)scales
{
if (_scales == nil) {
_scales = [[NSMutableDictionary alloc] init];
}
return _scales;
}
-(void)addScale:(ScaleInfo *)scaleInfo forName:(NSString *)name
{
[self.scales setObject:scaleInfo forKey:name];
}
-(NSString*)sha1:(NSString*)input
{
const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:input.length];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(data.bytes, (CC_LONG)data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
return output;
}
-(void)downloadImageToCacheForURL:(NSString *)url
{
[self _downloadImageToCacheForURL:url];
}
-(NSString *)_downloadPathForURL:(NSString *)url
{
NSString *storePath = self.storePath;
// Hash the URL to get our filename
NSString *hashed_url = [self sha1:url];
NSString *hashed_filename = [NSString stringWithFormat:@"%@.png", hashed_url];
// Check for the filename in the cache
NSString *cached_file_path = [storePath stringByAppendingPathComponent:hashed_filename];
return cached_file_path;
}
-(NSString *)_downloadPathForURL:(NSString *)url forScale:(NSString *)name
{
NSString *storePath = self.storePath;
// Hash the URL to get our filename
NSString *hashed_url = [self sha1:url];
NSString *scale_factor = [[UIScreen mainScreen] scale] == 2.f ? @"@2x" : @""; // we handle creating retina scaled images
NSString *hashed_filename = [NSString stringWithFormat:@"%@_%@%@.png", hashed_url, name, scale_factor];
// Check for the filename in the cache
NSString *cached_file_path = [storePath stringByAppendingPathComponent:hashed_filename];
return cached_file_path;
}
/**
Make a synchronous request with NSURLSession
*/
-(NSData*)makeRequest:(NSURL*)url
{
dispatch_semaphore_t latch = dispatch_semaphore_create(0);
__block NSData *responseData;
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:url
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
if (error) {
NSLog(@"Error searching TMDb: %@", error);
} else {
responseData = data;
}
dispatch_semaphore_signal(latch);
}] resume];
dispatch_semaphore_wait(latch, dispatch_walltime(DISPATCH_TIME_NOW, 60 * NSEC_PER_SEC));
return responseData;
}
-(NSString *)_downloadImageToCacheForURL:(NSString *)url
{
// Will download a file to the cache if not present
// and return the path to the downloaded image.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *storePath = self.storePath;
NSError *error;
// Create the storage folder if it doesn't exist
if (![fileManager fileExistsAtPath:storePath]) {
[fileManager createDirectoryAtPath:storePath
withIntermediateDirectories:YES
attributes:nil
error:&error];
}
NSString *cached_file_path = [self _downloadPathForURL:url];
BOOL available = [fileManager fileExistsAtPath:cached_file_path];
// If not in cache, download
if (!available) {
//NSLog(@"Image not in cache; downloading...");
// Get an image from the URL below
NSData *responseData = [self makeRequest:[NSURL URLWithString:url]];
// In certain error states it is possible for response data to be nil.
// In this scenario, we assume that we should not cache the image to
// ensure we try again in the future.
if (responseData) {
UIImage *image = [[UIImage alloc] initWithData:responseData];
//NSLog(@"%f,%f",image.size.width,image.size.height);
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data1 writeToFile:cached_file_path atomically:YES];
}
}
else {
//NSLog(@"Image found in cache");
}
return cached_file_path;
}
-(UIImage *)imageForURL:(NSString *)url
{
NSString *cached_file_path = [self _downloadImageToCacheForURL:url];
return [UIImage imageWithContentsOfFile:cached_file_path];
}
-(UIImage *)imageFromCacheForURL:(NSString *)url
{
NSString *cached_file_path = [self _downloadPathForURL:url];
return [self _imageFromCacheForPath:cached_file_path];
}
-(UIImage *)_imageFromCacheForPath:(NSString *)path
{
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL available = [fileManager fileExistsAtPath:path];
if (available) {
UIImage *image = [UIImage imageWithContentsOfFile:path];
//NSLog(@"%@: %f", path, image.scale);
return image;
} else {
return nil;
}
}
-(UIImage *)imageForURL:(NSString *)url
scale:(NSString *)name
{
ScaleInfo *si = [self.scales objectForKey:name];
if (si == nil) {
NSString *reason = [NSString stringWithFormat:@"Could not find ScaleInfo for %@", name];
@throw [NSException exceptionWithName:NSInvalidArgumentException
reason:reason
userInfo:nil];
}
NSString *scaledPath = [self _downloadPathForURL:url forScale:name];
UIImage *cached_scaled = [self _imageFromCacheForPath:scaledPath];
if (cached_scaled != nil) {
//NSLog(@"Read scale %@ from %@", name, scaledPath);
return cached_scaled;
}
UIImage *original = [self imageForURL:url];
if (original == nil) return nil;
UIImage *processed = [self _processImage:original
width:si.width
height:si.height
quality:si.quality
mode:si.mode];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(processed)];
[data1 writeToFile:scaledPath atomically:YES];
//NSLog(@"Wrote scale %@ to path %@", name, scaledPath);
return processed;
}
-(UIImage *)imageFromCacheForURL:(NSString *)url
scale:(NSString *)name
{
ScaleInfo *si = [self.scales objectForKey:name];
if (si == nil) {
NSString *reason = [NSString stringWithFormat:@"Could not find ScaleInfo for %@", name];
@throw [NSException exceptionWithName:NSInvalidArgumentException
reason:reason
userInfo:nil];
}
NSString *scaledPath = [self _downloadPathForURL:url forScale:name];
UIImage *cached_scaled = [self _imageFromCacheForPath:scaledPath];
if (cached_scaled != nil) {
//NSLog(@"Read scale %@ from %@", name, scaledPath);
return cached_scaled;
}
UIImage *original = [self imageFromCacheForURL:url];
if (original == nil) return nil;
UIImage *processed = [self _processImage:original
width:si.width
height:si.height
quality:si.quality
mode:si.mode];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(processed)];
[data1 writeToFile:scaledPath atomically:YES];
//NSLog(@"Wrote scale %@ to path %@", name, scaledPath);
return processed;
}
-(UIImage *)_processImage:(UIImage *)original
width:(float)width
height:(float)height
quality:(CGInterpolationQuality)quality
mode:(UIViewContentMode)mode
{
float oh = original.size.height;
float ow = original.size.width;
height = height * [[UIScreen mainScreen] scale];
width = width * [[UIScreen mainScreen] scale];
float nh,nw;
if (oh < ow) {
float sf = height / oh;
nh = height;
nw = ow * sf;
} else {
float sf = width / ow;
nh = oh * sf;
nw = width;
}
//NSLog(@"%f, %f, %f, %f", nw,nh,crop_left,crop_top);
CGSize size = CGSizeMake(nw, nh);
UIImage *resized = [original resizedImage:size
interpolationQuality:quality];
CGRect bounds = CGRectMake((nw - width) / 2,
(nh - height) / 2,
width,
height);
UIImage *cropped = [resized croppedImage:bounds];
return cropped;
}
-(void)cleanUpWithKeepList:(NSSet *)keep_urls
{
//NSLog(@"ThumbnailCache cleanup");
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *storePath = self.storePath;
NSMutableSet *keep_hashes = [[NSMutableSet alloc] init];
for (NSString *url in keep_urls) {
[keep_hashes addObject:[self sha1:url]];
}
NSArray *fileList = [fileManager contentsOfDirectoryAtPath:storePath error:nil];
NSMutableArray *to_delete = [NSMutableArray array];
for (NSString *name in fileList){
//NSLog(@"File: %@", name);
NSString *hash_prefix = [name substringToIndex:CC_SHA1_DIGEST_LENGTH*2];
//NSLog(@"Prefix: %@", hash_prefix);
if (![keep_hashes containsObject:hash_prefix]) {
[to_delete addObject:name];
}
}
for (NSString *name in to_delete) {
NSLog(@"MRScalingImageCache clean up: deleting %@", name);
[fileManager removeItemAtPath:[storePath stringByAppendingPathComponent:name] error:nil];
}
}
@end