|
20 | 20 | #include <objc/runtime.h>
|
21 | 21 | #include <objc/message.h>
|
22 | 22 | #include <objc/objc-exception.h>
|
| 23 | +#import <zlib.h> |
23 | 24 | #import <sys/qos.h>
|
24 | 25 | #import <BackgroundTasks/BackgroundTasks.h>
|
25 | 26 | #import <CommonCrypto/CommonDigest.h>
|
@@ -3303,4 +3304,67 @@ +(NSURLSession*) createEphemeralURLSession
|
3303 | 3304 | return [NSURLSession sessionWithConfiguration:sessionConfig];
|
3304 | 3305 | }
|
3305 | 3306 |
|
| 3307 | ++(NSURL* _Nullable) compressFileAtPath:(NSString*) path withLevel:(NSInteger) level |
| 3308 | +{ |
| 3309 | + uint8_t buffer[65536]; |
| 3310 | + |
| 3311 | + NSFileManager* fileManager = [NSFileManager defaultManager]; |
| 3312 | + NSString* filename = path.lastPathComponent; |
| 3313 | + NSString* gzipPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.gz", filename]]; |
| 3314 | + |
| 3315 | + DDLogInfo(@"Compressing file at '%@' into '%@'...", path, gzipPath); |
| 3316 | + |
| 3317 | + NSError* error = nil; |
| 3318 | + if([fileManager fileExistsAtPath:gzipPath]) |
| 3319 | + [fileManager removeItemAtPath:gzipPath error:&error]; |
| 3320 | + if(error != nil) |
| 3321 | + { |
| 3322 | + DDLogError(@"Could not delete old leftover gzip file at '%@': %@", gzipPath, error); |
| 3323 | + return nil; |
| 3324 | + } |
| 3325 | + |
| 3326 | + NSInputStream* input = [NSInputStream inputStreamWithFileAtPath:path]; |
| 3327 | + if(!input) |
| 3328 | + { |
| 3329 | + DDLogError(@"Could not open file to compress: %@", path); |
| 3330 | + return nil; |
| 3331 | + } |
| 3332 | + [input open]; |
| 3333 | + |
| 3334 | + FILE* outputFile = fopen([gzipPath fileSystemRepresentation], "wb"); |
| 3335 | + if(!outputFile) |
| 3336 | + { |
| 3337 | + DDLogError(@"Could not open gzip output file: %@", gzipPath); |
| 3338 | + [input close]; |
| 3339 | + return nil; |
| 3340 | + } |
| 3341 | + |
| 3342 | + gzFile gzOutput = gzdopen(fileno(outputFile), [NSString stringWithFormat:@"%ldwb", (long)level].UTF8String); |
| 3343 | + if(!gzOutput) |
| 3344 | + { |
| 3345 | + DDLogError(@"Could not create gzip stream for output file: %@", gzipPath); |
| 3346 | + fclose(outputFile); |
| 3347 | + [input close]; |
| 3348 | + return nil; |
| 3349 | + } |
| 3350 | + |
| 3351 | + NSInteger bytesRead; |
| 3352 | + while((bytesRead = [input read:buffer maxLength:sizeof(buffer)]) > 0) |
| 3353 | + { |
| 3354 | + if(gzwrite(gzOutput, buffer, (unsigned int)bytesRead) != bytesRead) |
| 3355 | + { |
| 3356 | + DDLogError(@"Failed to write gzip data to output file: %@", gzipPath); |
| 3357 | + gzclose(gzOutput); |
| 3358 | + [input close]; |
| 3359 | + return nil; |
| 3360 | + } |
| 3361 | + } |
| 3362 | + |
| 3363 | + gzclose(gzOutput); |
| 3364 | + [input close]; |
| 3365 | + |
| 3366 | + return [NSURL fileURLWithPath:gzipPath]; |
| 3367 | + |
| 3368 | +} |
| 3369 | + |
3306 | 3370 | @end
|
0 commit comments