Skip to content

Commit

Permalink
Merge pull request #394 from Piwigo/v2.5.1
Browse files Browse the repository at this point in the history
v2.5.1
  • Loading branch information
EddyLB authored Sep 10, 2020
2 parents 2661add + 3139450 commit afefe0f
Show file tree
Hide file tree
Showing 53 changed files with 531 additions and 324 deletions.
4 changes: 2 additions & 2 deletions piwigo.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -2222,7 +2222,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 2.5;
MARKETING_VERSION = 2.5.1;
OTHER_LDFLAGS = (
"$(inherited)",
"-all_load",
Expand Down Expand Up @@ -2285,7 +2285,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 2.5;
MARKETING_VERSION = 2.5.1;
OTHER_LDFLAGS = (
"$(inherited)",
"-all_load",
Expand Down
10 changes: 6 additions & 4 deletions piwigo/Albums/AlbumImagesViewController.m
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@
#import "SAMKeychain.h"
#import "SearchImagesViewController.h"

#ifndef DEBUG_LIFECYCLE
#define DEBUG_LIFECYCLE
#endif
//#ifndef DEBUG_LIFECYCLE
//#define DEBUG_LIFECYCLE
//#endif

CGFloat const kRadius = 25.0;
CGFloat const kDeg2Rad = 3.141592654 / 180.0;
Expand Down Expand Up @@ -1260,7 +1260,9 @@ -(void)getCategoryData:(NSNotification *)notification
inRecursiveMode:[Model sharedInstance].loadAllCategoryInfo
OnCompletion:^(NSURLSessionTask *task, NSArray *albums) {
self.isCachedAtInit = YES;
[self.imagesCollection reloadData];
if (albums != nil) {
[self.imagesCollection reloadData];
}

// Hide loading HUD
[self hideHUD];
Expand Down
7 changes: 5 additions & 2 deletions piwigo/Albums/Services/AlbumData.m
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ -(void)loadMoreImagesOnCompletion:(void (^)(void))completion
if (downloadedImageDataCount >= totalImageCount)
{
NSLog(@"loadMoreImagesOnCompletion: we have all image data");
self.images = [[CategoriesData sharedInstance] getCategoryById:self.categoryId].imageList;
// We have all the image data, just manually sort it (uploaded images are appended to cache)
self.images = [CategoryImageSort sortImages:[[CategoriesData sharedInstance] getCategoryById:self.categoryId].imageList for:[Model sharedInstance].defaultSort];
if(completion)
{
completion();
Expand All @@ -91,7 +92,8 @@ -(void)loadMoreImagesOnCompletion:(void (^)(void))completion
{
return;
}
self.images = [[CategoriesData sharedInstance] getCategoryById:self.categoryId].imageList;
// We have all the image data, just manually sort it (uploaded images are appended to cache)
self.images = [CategoryImageSort sortImages:[[CategoriesData sharedInstance] getCategoryById:self.categoryId].imageList for:[Model sharedInstance].defaultSort];
if(completion)
{
completion();
Expand Down Expand Up @@ -164,6 +166,7 @@ -(void)updateSortString
break;

case kPiwigoSortManual: // Manual order
case kPiwigoSortRandom: // Random order
// Empty string
break;

Expand Down
3 changes: 2 additions & 1 deletion piwigo/Data Cache/ClearCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class ClearCache: NSObject {
CategoriesData.sharedInstance().clearCache()

// URL requests
URLCache.shared.removeAllCachedResponses()
Model.sharedInstance()?.imageCache.removeAllCachedResponses()
Model.sharedInstance()?.thumbnailCache.removeAllImages()
}
}
9 changes: 7 additions & 2 deletions piwigo/Data Cache/Tags Data/TagsProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,16 @@ class TagsProvider {
*/
private func importTags(from tagPropertiesArray: [TagProperties]) throws {

guard !tagPropertiesArray.isEmpty else { return }

// Create a private queue context.
let taskContext = DataController.getPrivateContext()

// We shall perform at least one import in case where
// the user did delete all tags or untag all photos
guard !tagPropertiesArray.isEmpty else {
_ = importOneBatch([TagProperties](), taskContext: taskContext)
return
}

// Process records in batches to avoid a high memory footprint.
let batchSize = 256
let count = tagPropertiesArray.count
Expand Down
2 changes: 1 addition & 1 deletion piwigo/Data Cache/Uploads Data/Upload.swift
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ extension Upload {
func getUploadProperties(with state: kPiwigoUploadState, error: String?) -> UploadProperties {
return UploadProperties.init(localIdentifier: self.localIdentifier,
serverPath: self.serverPath, category: Int(self.category),
// Upload request date is now and state is waiting
// Upload request date, state and error
requestDate: self.requestDate, requestState: state, requestError: error,
// Photo creation date and filename
creationDate: self.creationDate, fileName: self.fileName,
Expand Down
38 changes: 27 additions & 11 deletions piwigo/Data Cache/Uploads Data/UploadsProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -259,13 +259,16 @@ class UploadsProvider: NSObject {

// MARK: - Delete Uploads
/**
Delete a batch of upload requests from the Core Data store on the main queue,
Delete a batch of upload requests from the Core Data store on a private queue,
processing the record in batches to avoid a high memory footprint.
*/
func delete(uploadRequests: [Upload]) {

guard !uploadRequests.isEmpty else { return }

// Create a private queue context.
let taskContext = DataController.getPrivateContext()

// Process records in batches to avoid a high memory footprint.
let batchSize = 256
let count = uploadRequests.count
Expand All @@ -285,8 +288,8 @@ class UploadsProvider: NSObject {
let uploadsBatch = Array(uploadRequests[range])

// Stop the entire deletion if any batch is unsuccessful.
if !deleteOneBatch(uploadsBatch) {
return
if !deleteOneBatch(uploadsBatch, taskContext: taskContext) {
break
}
}

Expand All @@ -311,20 +314,19 @@ class UploadsProvider: NSObject {
}

/**
Delete one batch of uploads on the main queue. After saving,
Delete one batch of uploads on a private queue. After saving,
resets the context to clean up the cache and lower the memory footprint.
NSManagedObjectContext.performAndWait doesn't rethrow so this function
catches throws within the closure and uses a return value to indicate
whether the import is successful.
*/
private func deleteOneBatch(_ uploadsBatch: [Upload]) -> Bool {
private func deleteOneBatch(_ uploadsBatch: [Upload], taskContext: NSManagedObjectContext) -> Bool {
// Check current queue
print("•••>> deleteOneBatch()", queueName())

var success = false
// taskContext.performAndWait
managedObjectContext.performAndWait {
taskContext.performAndWait {

// Loop over uploads to delete
for upload in uploadsBatch {
Expand All @@ -334,20 +336,34 @@ class UploadsProvider: NSObject {
UploadManager.shared.deleteFilesInUploadsDirectory(with: filenamePrefix)

// Retrieve object in main context
let uploadToDelete = managedObjectContext.object(with: upload.objectID)
let uploadToDelete = taskContext.object(with: upload.objectID)

// Delete upload record
managedObjectContext.delete(uploadToDelete)
taskContext.delete(uploadToDelete)
}

// Save all insertions and deletions from the context to the store.
if managedObjectContext.hasChanges {
if taskContext.hasChanges {
do {
try managedObjectContext.save()
try taskContext.save()

// Performs a task in the main queue and wait until this tasks finishes
DispatchQueue.main.async {
self.managedObjectContext.performAndWait {
do {
// Saves the data from the child to the main context to be stored properly
try self.managedObjectContext.save()
} catch {
fatalError("Failure to save context: \(error)")
}
}
}
}
catch {
fatalError("Failure to save context: \(error)")
}
// Reset the taskContext to free the cache and lower the memory footprint.
taskContext.reset()
}

success = true
Expand Down
2 changes: 1 addition & 1 deletion piwigo/Image/Details/ImageDetailViewController.m
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ -(instancetype)initWithCategoryId:(NSInteger)categoryId atImageIndex:(NSInteger)
// Progress bar
self.progressBar = [UIProgressView new];
self.progressBar.translatesAutoresizingMaskIntoConstraints = NO;
[self.progressBar setProgress:0.0 animated:NO];
self.progressBar.hidden = NO;
[self.view addSubview:self.progressBar];
[self.view addConstraints:[NSLayoutConstraint constraintFillWidth:self.progressBar]];
Expand Down Expand Up @@ -1287,7 +1288,6 @@ -(void)downloadProgress:(CGFloat)progress
{
[self.progressBar setProgress:progress animated:YES];
self.progressBar.hidden = (progress == 1) ? YES : NO;
// NSLog(@"==> setProgress:%.2f", progress);
}


Expand Down
12 changes: 9 additions & 3 deletions piwigo/Image/Details/ImagePreviewViewController.m
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,11 @@ -(void)setImageScrollViewWithImageData:(PiwigoImageData*)imageData
// Display "play" button if video
self.scrollView.playImage.hidden = !(imageData.isVideo);

// Thumbnail image may be used as placeholder image
// Thumbnail image should be available in cache
NSString *thumbnailStr = [imageData getURLFromImageSizeType:(kPiwigoImageSize)[Model sharedInstance].defaultThumbnailSize];
NSURL *thumbnailURL = [NSURL URLWithString:thumbnailStr];
UIImageView *thumb = [UIImageView new];
thumb.image = [UIImage imageWithData:[[[Model sharedInstance].imageCache cachedResponseForRequest:[NSURLRequest requestWithURL:thumbnailURL]] data]];
thumb.image = [[Model sharedInstance].thumbnailCache imageforRequest:[NSURLRequest requestWithURL:thumbnailURL] withAdditionalIdentifier:nil];
self.scrollView.imageView.image = thumb.image ? thumb.image : [UIImage imageNamed:@"placeholderImage"];

// Previewed image
Expand All @@ -107,6 +107,7 @@ -(void)setImageScrollViewWithImageData:(PiwigoImageData*)imageData
progress:^(NSProgress * _Nonnull progress) {
dispatch_async(dispatch_get_main_queue(),
^(void){
// Update progress bar
if([weakSelf.imagePreviewDelegate respondsToSelector:@selector(downloadProgress:)])
{
[weakSelf.imagePreviewDelegate downloadProgress:progress.fractionCompleted];
Expand All @@ -116,11 +117,16 @@ -(void)setImageScrollViewWithImageData:(PiwigoImageData*)imageData
success:^(NSURLSessionTask *task, UIImage *image) {
if (image != nil) {
weakSelf.scrollView.imageView.image = image;
// Update progress bar
if([weakSelf.imagePreviewDelegate respondsToSelector:@selector(downloadProgress:)])
{
[weakSelf.imagePreviewDelegate downloadProgress:1.0];
}
weakSelf.imageLoaded = YES; // Hide progress bar
// Hide progress bar
weakSelf.imageLoaded = YES;
// Store image in cache
NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:task.response data:UIImageJPEGRepresentation(image, 0.9)];
[[Model sharedInstance].imageCache storeCachedResponse:cachedResponse forDataTask:weakSelf.downloadTask];
}
else { // Keep thumbnail or placeholder if image could not be loaded
#if defined(DEBUG)
Expand Down
32 changes: 23 additions & 9 deletions piwigo/Image/ImageService.m
Original file line number Diff line number Diff line change
Expand Up @@ -493,15 +493,25 @@ +(NSURLSessionTask*)getFavoritesOnPage:(NSInteger)page
success:^(NSURLSessionTask *task, id responseObject) {

if([[responseObject objectForKey:@"stat"] isEqualToString:@"ok"]) {
// Store number of images in cache
NSInteger nberImages = [[[[responseObject objectForKey:@"result"] objectForKey:@"paging"] objectForKey:@"count"] integerValue];
[[CategoriesData sharedInstance] getCategoryById:kPiwigoFavoritesCategoryId].numberOfImages = nberImages;
[[CategoriesData sharedInstance] getCategoryById:kPiwigoFavoritesCategoryId].totalNumberOfImages = nberImages;

// Parse images
NSArray *searchedImages = [ImageService parseAlbumImagesJSON:[responseObject objectForKey:@"result"] forCategoryId:kPiwigoFavoritesCategoryId];
if(completion) {
completion(task, searchedImages);
// Check the presence of favorite images
if ([[responseObject objectForKey:@"result"] isKindOfClass:[NSDictionary class]]) {
// Store number of images in cache
NSInteger nberImages = [[[[responseObject objectForKey:@"result"] objectForKey:@"paging"] objectForKey:@"count"] integerValue];
[[CategoriesData sharedInstance] getCategoryById:kPiwigoFavoritesCategoryId].numberOfImages = nberImages;
[[CategoriesData sharedInstance] getCategoryById:kPiwigoFavoritesCategoryId].totalNumberOfImages = nberImages;

// Parse images
NSArray *searchedImages = [ImageService parseAlbumImagesJSON:[responseObject objectForKey:@"result"] forCategoryId:kPiwigoFavoritesCategoryId];
if(completion) {
completion(task, searchedImages);
}
} else {
// No favorite image in the server database
[[CategoriesData sharedInstance] getCategoryById:kPiwigoFavoritesCategoryId].numberOfImages = 0;
[[CategoriesData sharedInstance] getCategoryById:kPiwigoFavoritesCategoryId].totalNumberOfImages = 0;
if(completion) {
completion(task, [NSArray new]);
}
}
}
else
Expand Down Expand Up @@ -835,6 +845,10 @@ +(PiwigoImageData*)parseBasicImageInfoJSON:(NSDictionary*)imageJson

// Object "file"
imageData.fileName = [NetworkHandler UTF8EncodedStringFromString:[imageJson objectForKey:@"file"]];
if ([imageData.fileName length] == 0) {
// Filename should never be empty. Just in case…
imageData.fileName = @"PiwigoImage.jpg";
}
NSString *fileExt = [[imageData.fileName pathExtension] uppercaseString];
if([fileExt isEqualToString:@"MP4"] || [fileExt isEqualToString:@"M4V"] ||
[fileExt isEqualToString:@"OGG"] || [fileExt isEqualToString:@"OGV"] ||
Expand Down
Loading

0 comments on commit afefe0f

Please sign in to comment.