Skip to content

Commit

Permalink
Merge pull request #568 from Piwigo/3.1.3
Browse files Browse the repository at this point in the history
Version 3.1.3
  • Loading branch information
EddyLB authored Feb 11, 2024
2 parents 2a92483 + 1715fa9 commit 475d1f8
Show file tree
Hide file tree
Showing 41 changed files with 570 additions and 366 deletions.
134 changes: 125 additions & 9 deletions piwigo.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

24 changes: 20 additions & 4 deletions piwigo/Album/AlbumSelector/SelectCategoryViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1054,12 +1054,23 @@ class SelectCategoryViewController: UIViewController, UITableViewDataSource, UIT
extension SelectCategoryViewController: NSFetchedResultsControllerDelegate {

func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
// Check that this update should be managed by this view controller
if view.window == nil || [recentAlbums, albums].contains(controller) == false ||
(wantedAction == .setAlbumThumbnail && controller == recentAlbums) {
return
}
// Begin the update
categoriesTableView.beginUpdates()
}

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {

// Check that this update should be managed by this view controller
if view.window == nil || [recentAlbums, albums].contains(controller) == false ||
(wantedAction == .setAlbumThumbnail && controller == recentAlbums) {
return
}

// Initialisation
var hasAlbumsInSection1 = false
if controller == albums, categoriesTableView.numberOfSections == 2 {
Expand All @@ -1071,32 +1082,37 @@ extension SelectCategoryViewController: NSFetchedResultsControllerDelegate {
case .insert:
guard var newIndexPath = newIndexPath else { return }
if hasAlbumsInSection1 { newIndexPath.section = 1 }
print("••> Insert category item at \(newIndexPath)")
debugPrint("••> Insert category item at \(newIndexPath)")
categoriesTableView?.insertRows(at: [newIndexPath], with: .automatic)
case .update:
guard var indexPath = indexPath else { return }
if hasAlbumsInSection1 { indexPath.section = 1 }
print("••> Update category item at \(indexPath)")
debugPrint("••> Update category item at \(indexPath)")
categoriesTableView?.reloadRows(at: [indexPath], with: .automatic)
case .move:
guard var indexPath = indexPath, var newIndexPath = newIndexPath else { return }
if hasAlbumsInSection1 {
indexPath.section = 1
newIndexPath.section = 1
}
print("••> Move category item from \(indexPath) to \(newIndexPath)")
debugPrint("••> Move category item from \(indexPath) to \(newIndexPath)")
categoriesTableView?.moveRow(at: indexPath, to: newIndexPath)
case .delete:
guard var indexPath = indexPath else { return }
if hasAlbumsInSection1 { indexPath.section = 1 }
print("••> Delete category item at \(indexPath)")
debugPrint("••> Delete category item at \(indexPath)")
categoriesTableView?.deleteRows(at: [indexPath], with: .automatic)
@unknown default:
debugPrint("SelectCategoryViewController: unknown NSFetchedResultsChangeType")
}
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
// Check that this update should be managed by this view controller
if view.window == nil || [recentAlbums, albums].contains(controller) == false ||
(wantedAction == .setAlbumThumbnail && controller == recentAlbums) {
return
}
// End updates
categoriesTableView.endUpdates()
}
Expand Down
26 changes: 17 additions & 9 deletions piwigo/Album/AlbumViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,12 @@ class AlbumViewController: UIViewController, UICollectionViewDelegate, UICollect
ClearCache.closeSession()
return User()
}
// User available ► Job done
if user.isFault {
// The user is not fired yet.
user.willAccessValue(forKey: nil)
user.didAccessValue(forKey: nil)
}
return user
}()

Expand Down Expand Up @@ -1580,9 +1586,11 @@ class AlbumViewController: UIViewController, UICollectionViewDelegate, UICollect

// MARK: - UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let navBarHeight = Float(navigationController?.navigationBar.frame.origin.y ?? 0.0) + Float(navigationController?.navigationBar.frame.size.height ?? 0.0)
let navBarYpos = navigationController?.navigationBar.frame.origin.y ?? 0.0
let navBarThickness = navigationController?.navigationBar.frame.size.height ?? 0.0
let navBarHeight = navBarYpos + navBarThickness
// NSLog(@"==>> %f", scrollView.contentOffset.y + navBarHeight);
if roundf(Float(scrollView.contentOffset.y) + navBarHeight) > 1 ||
if round(scrollView.contentOffset.y + navBarHeight) > 1 ||
(categoryId != AlbumVars.shared.defaultCategory) {
// Show navigation bar border
if #available(iOS 13.0, *) {
Expand Down Expand Up @@ -1636,13 +1644,13 @@ extension AlbumViewController: NSFetchedResultsControllerDelegate {
selectedImageIds.remove(image.pwgID)
}
updateOperations.append( BlockOperation { [weak self] in
print("••> Delete item of album #\(fetchDelegate.categoryId) at \(indexPath)")
debugPrint("••> Delete item of album #\(fetchDelegate.categoryId) at \(indexPath)")
self?.imagesCollection?.deleteItems(at: [indexPath])
})
// Disable menu if this is the last deleted image
if albumData.nbImages == 0 {
updateOperations.append( BlockOperation { [weak self] in
print("••> Last removed image ► disable menu")
debugPrint("••> Last removed image ► disable menu")
self?.isSelect = false
self?.updateButtonsInPreviewMode()
})
Expand All @@ -1652,7 +1660,7 @@ extension AlbumViewController: NSFetchedResultsControllerDelegate {
if let image = anObject as? Image {
let cellIndexPath = IndexPath(item: indexPath.item, section: 1)
updateOperations.append( BlockOperation { [weak self] in
print("••> Update image at \(cellIndexPath) of album #\(fetchDelegate.categoryId)")
debugPrint("••> Update image at \(cellIndexPath) of album #\(fetchDelegate.categoryId)")
if let cell = self?.imagesCollection?.cellForItem(at: cellIndexPath) as? ImageCollectionViewCell {
// Re-configure image cell
cell.config(with: image, inCategoryId: fetchDelegate.categoryId)
Expand All @@ -1665,7 +1673,7 @@ extension AlbumViewController: NSFetchedResultsControllerDelegate {
})
} else if let album = anObject as? Album {
updateOperations.append( BlockOperation { [weak self] in
print("••> Update album at \(indexPath) of album #\(fetchDelegate.categoryId)")
debugPrint("••> Update album at \(indexPath) of album #\(fetchDelegate.categoryId)")
if let cell = self?.imagesCollection?.cellForItem(at: indexPath) as? AlbumCollectionViewCell {
// Re-configure album cell
cell.albumData = album
Expand All @@ -1676,13 +1684,13 @@ extension AlbumViewController: NSFetchedResultsControllerDelegate {
guard var newIndexPath = newIndexPath else { return }
if anObject is Image { newIndexPath.section = 1 }
updateOperations.append( BlockOperation { [weak self] in
print("••> Insert item of album #\(fetchDelegate.categoryId) at \(newIndexPath)")
debugPrint("••> Insert item of album #\(fetchDelegate.categoryId) at \(newIndexPath)")
self?.imagesCollection?.insertItems(at: [newIndexPath])
})
// Enable menu if this is the first added image
if albumData.nbImages == 1 {
updateOperations.append( BlockOperation { [weak self] in
print("••> First added image ► enable menu")
debugPrint("••> First added image ► enable menu")
self?.updateButtonsInPreviewMode()
})
}
Expand All @@ -1695,7 +1703,7 @@ extension AlbumViewController: NSFetchedResultsControllerDelegate {
newIndexPath.section = 1
}
updateOperations.append( BlockOperation { [weak self] in
print("••> Move item of album #\(fetchDelegate.categoryId) from \(indexPath) to \(newIndexPath)")
debugPrint("••> Move item of album #\(fetchDelegate.categoryId) from \(indexPath) to \(newIndexPath)")
self?.imagesCollection?.moveItem(at: indexPath, to: newIndexPath)
})
default:
Expand Down
7 changes: 4 additions & 3 deletions piwigo/Album/Extensions/AlbumViewController+Search.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,15 @@ extension AlbumViewController: UISearchControllerDelegate

// Initialise albumData
albumData = albumProvider.getAlbum(ofUser: user, withId: categoryId)!
self.resetSearchAlbum(withQuery: "")
resetSearchAlbum(withQuery: "")

// Update albums
fetchAlbumsRequest.predicate = albumPredicate.withSubstitutionVariables(["catId" : categoryId])
let substitute: [String : Any] = ["catId" : categoryId]
fetchAlbumsRequest.predicate = albumPredicate.withSubstitutionVariables(substitute)
try? albums.performFetch()

// Update images
fetchImagesRequest.predicate = imagePredicate.withSubstitutionVariables(["catId" : categoryId])
fetchImagesRequest.predicate = imagePredicate.withSubstitutionVariables(substitute)
try? images.performFetch()

// Reload collection
Expand Down
2 changes: 1 addition & 1 deletion piwigo/Album/Extensions/AlbumViewController+Select.swift
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ extension AlbumViewController
// Will interpret touches only in horizontal direction
if let gPR = gestureRecognizer as? UIPanGestureRecognizer {
let translation = gPR.translation(in: imagesCollection)
if abs(Float(translation.x)) > abs(Float(translation.y)) {
if abs(translation.x) > abs(translation.y) {
return true
}
}
Expand Down
4 changes: 2 additions & 2 deletions piwigo/Image/Download/ImageDownload.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class ImageDownload {

// MARK: - Initialization
init(imageID: Int64, ofSize imageSize: pwgImageSize, atURL imageURL: URL,
fromServer serverID: String, fileSize: Int64 = NSURLSessionTransferSizeUnknown,
fromServer serverID: String, fileSize: Int64 = .zero,
placeHolder: UIImage, progress: ((Float) -> Void)? = nil,
completion: @escaping (URL) -> Void, failure: @escaping (Error) -> Void) {

Expand All @@ -37,7 +37,7 @@ class ImageDownload {

// Store file size and handlers
self.imageURL = imageURL
self.fileSize = fileSize == Int64.zero ? NSURLSessionTransferSizeUnknown : fileSize
self.fileSize = fileSize
self.placeHolder = placeHolder
self.progressHandler = progress
self.completionHandler = completion
Expand Down
39 changes: 20 additions & 19 deletions piwigo/Image/Download/ImageSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ class ImageSession: NSObject {

// MARK: - Asynchronous Methods
func getImage(withID imageID: Int64?, ofSize imageSize: pwgImageSize, atURL imageURL: URL?,
fromServer serverID: String?, fileSize: Int64 = NSURLSessionTransferSizeUnknown,
fromServer serverID: String?, fileSize: Int64 = .zero,
placeHolder: UIImage, progress: ((Float) -> Void)? = nil,
completion: @escaping (URL) -> Void, failure: @escaping (Error) -> Void) {
// Check arguments
Expand All @@ -106,10 +106,9 @@ class ImageSession: NSObject {
progress: progress, completion: completion, failure: failure)

// Do we already have this image or video in cache?
if download.fileURL.fileSize != 0 {
if download.fileURL.fileSize > 0 {
// We do have an image in cache, but is this the image or expected video?
if imageSize == .fullRes,
[NSURLSessionTransferSizeUnknown, 0].contains(fileSize) == false {
if imageSize == .fullRes {
let cachedFileSize = download.fileURL.fileSize
let diff = abs((Double(cachedFileSize) - Double(fileSize)) / Double(fileSize))
// print("••> Image \(download.fileURL.lastPathComponent) of \(cachedFileSize) bytes (\((diff * 1000).rounded(.awayFromZero)/10)%) retrieved from cache.")
Expand All @@ -118,6 +117,7 @@ class ImageSession: NSObject {
return
}
} else {
// debugPrint("••> return cached image \(String(describing: download.fileURL.lastPathComponent)) i.e., downloaded from \(imageURL)")
completion(download.fileURL)
return
}
Expand All @@ -126,17 +126,18 @@ class ImageSession: NSObject {
// Download this image in the background thread
downloadQueue.async {
guard let download = self.activeDownloads[imageURL] else {
// print("••> Launch download: \(imageURL.lastPathComponent)")
// debugPrint("••> Launch download of image: \(imageURL)")
download.task = self.dataSession.downloadTask(with: request)
download.task?.countOfBytesClientExpectsToSend = Int64((request.allHTTPHeaderFields ?? [:]).count)
download.task?.countOfBytesClientExpectsToReceive = download.fileSize
let expectedSize: Int64 = fileSize == .zero ? NSURLSessionTransferSizeUnknown : fileSize
download.task?.countOfBytesClientExpectsToReceive = expectedSize
download.task?.resume()
self.activeDownloads[imageURL] = download
return
}

// Resume download
// print("••> Resume download: \(imageURL)")
// debugPrint("••> Resume download of image: \(imageURL)")
download.progressHandler = progress
if let progressHandler = download.progressHandler {
progressHandler(download.progress)
Expand All @@ -163,7 +164,7 @@ class ImageSession: NSObject {

// Cancel the download request
download.task?.cancel(byProducingResumeData: { imageData in
// print("••> Pause download: \(imageURL.lastPathComponent)")
// debugPrint("••> Pause download: \(imageURL)")
download.resumeData = imageData
})
}
Expand All @@ -175,7 +176,7 @@ class ImageSession: NSObject {
}

// Cancel the download request
// print("••> Cancel download: \(imageURL.lastPathComponent)")
// debugPrint("••> Cancel download: \(imageURL)")
download.task?.cancel()
activeDownloads[imageURL] = nil
}
Expand All @@ -186,13 +187,13 @@ class ImageSession: NSObject {
extension ImageSession: URLSessionDelegate {

func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
// print(" > The data session has been invalidated")
// debugPrint(" > The data session has been invalidated")
activeDownloads = [ : ]
}

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
// print(" > Session-level authentication request from the remote server.")
// debugPrint(" > Session-level authentication request from the remote server.")

// Get protection space for current domain
let protectionSpace = challenge.protectionSpace
Expand Down Expand Up @@ -246,7 +247,7 @@ extension ImageSession: URLSessionDelegate {
extension ImageSession: URLSessionTaskDelegate {

func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print(" > Task-level authentication request from the remote server")
// debugPrint(" > Task-level authentication request from the remote server")

// Check authentication method
let authMethod = challenge.protectionSpace.authenticationMethod
Expand Down Expand Up @@ -287,7 +288,7 @@ extension ImageSession: URLSessionTaskDelegate {
}
} else {
// Return cached image with completionHandler
// print("••> Did complete task #\(task.taskIdentifier)")
// debugPrint("••> Did complete task #\(task.taskIdentifier)")
if let completion = download.completionHandler,
let fileURL = download.fileURL {
completion(fileURL)
Expand All @@ -306,8 +307,8 @@ extension ImageSession: URLSessionDownloadDelegate {
didWriteData bytesWritten: Int64, totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
// Retrieve the original URL of this task
// print("••> Progress task #\(downloadTask.taskIdentifier) -> \(String(describing: downloadTask.currentRequest?.url))")
// print(" amongst \(activeDownloads.count) active downloads.")
// debugPrint("••> Progress task #\(downloadTask.taskIdentifier) -> \(String(describing: downloadTask.currentRequest?.url))")
// debugPrint(" amongst \(activeDownloads.count) active downloads.")
guard let imageURL = downloadTask.originalRequest?.url ?? downloadTask.currentRequest?.url,
let download = activeDownloads[imageURL] else {
return
Expand All @@ -316,15 +317,15 @@ extension ImageSession: URLSessionDownloadDelegate {
// Update progress bar if any
if let progressHandler = download.progressHandler {
download.progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
// print("••> Progress task #\(downloadTask.taskIdentifier) -> \(download.progress)")
// debugPrint("••> Progress task #\(downloadTask.taskIdentifier) -> \(download.progress)")
progressHandler(download.progress)
}
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
// Retrieve the URL of this task
print("••> Task #\(downloadTask.taskIdentifier) did finish downloading.")
// debugPrint("••> Task #\(downloadTask.taskIdentifier) did finish downloading.")
guard let imageURL = downloadTask.originalRequest?.url ?? downloadTask.currentRequest?.url,
let download = activeDownloads[imageURL],
let fileURL = download.fileURL else {
Expand All @@ -336,7 +337,7 @@ extension ImageSession: URLSessionDownloadDelegate {
let fm = FileManager.default
let dirURL = fileURL.deletingLastPathComponent()
if fm.fileExists(atPath: dirURL.path) == false {
print("••> Create directory \(dirURL.path)")
// debugPrint("••> Create directory \(dirURL.path)")
try fm.createDirectory(at: dirURL, withIntermediateDirectories: true,
attributes: nil)
}
Expand All @@ -346,7 +347,7 @@ extension ImageSession: URLSessionDownloadDelegate {

// Store image
try fm.copyItem(at: location, to: fileURL)
print("••> Image \(fileURL.lastPathComponent) stored in cache")
// debugPrint("••> Image \(fileURL.lastPathComponent) stored in cache (downloaded at \(String(describing: download.imageURL)))")
} catch {
// Return error with failureHandler
if let failure = download.failureHandler {
Expand Down
Loading

0 comments on commit 475d1f8

Please sign in to comment.