-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathThumbnailCacheManager.swift
220 lines (194 loc) · 10.5 KB
/
ThumbnailCacheManager.swift
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
//
// ThumbnailCacheManager.swift
// dslrbrowser
//
// Created by Andras Bekesi on 10/01/17.
// Copyright © 2017 Andras Bekesi. All rights reserved.
//
import Foundation
import Photos
import CoreData
open class ThumbnailCacheManager {
private var dc:DataController
private var thumbnails = [String : String]()
private var previews = [String : String]()
private var isRefreshRunning:Bool
open static let defaultManager:ThumbnailCacheManager = {
let instance = ThumbnailCacheManager()
return instance
}()
init() {
dc = DataController()
dc.waitUntilInitialized()
isRefreshRunning = false
refresh()
}
func getThumbnailKeyFor(cameraKey: String, title: String) -> String {
return ((cameraKey + title).data(using: .utf8)?.base64EncodedString())!
}
open func cleanUpDatabase() {
print("Cleaning up downloaded item database")
let photoEntityFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "PhotoEntity")
do {
let entities = try self.dc.managedObjectContext.fetch(photoEntityFetchRequest) as! [PhotoEntity]
print("Query download database map found ",entities.count, " entities")
for entity in entities {
let assets:PHFetchResult<PHAsset> = PHAsset.fetchAssets(withLocalIdentifiers: [entity.localIdentifier!], options: nil)
if (assets.count == 0) {
self.dc.managedObjectContext.delete(entity)
print("Removed ", entity.localIdentifier ?? "???")
}
}
try self.dc.managedObjectContext.save()
}
catch {
print("Error cleaning database", error)
}
print("Finished cleaning up downloaded item database")
}
open func refresh() {
if (!isRefreshRunning) {
isRefreshRunning = true
let backgroundQueue = DispatchQueue(label: "hu.bikeonet.dslrbrowser.photocollectionviewcontroller.thumbnailcache", qos: .background)
backgroundQueue.async {
//query downloaded image list from app's sqlite database
let photoEntityFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "PhotoEntity")
do {
let entities = try self.dc.managedObjectContext.fetch(photoEntityFetchRequest) as! [PhotoEntity]
print("Query download database map found ",entities.count, " entities")
var isDatabaseChanged:Bool = false
for entity in entities {
print("Refreshing thumbnail cache for entity ", entity)
//query Photos framework to check if image is still in photo roll
let assets:PHFetchResult<PHAsset> = PHAsset.fetchAssets(withLocalIdentifiers: [entity.localIdentifier!], options: nil)
if (assets.count > 0) {
print("Entity found in photo roll, generating thumbnail cache")
//check if a thumbnail is already cached in the filesystem
//and request a thumbnail image otherwise
self.checkThumbnailImage(entity: entity, asset: assets[0])
//check if a preview is already cached in the filesystem
//and request a preview image otherwise
self.checkPreviewImage(entity: entity, asset: assets[0])
}
else {
//remove deleted image from database
print("Entity not found in photo roll, cleaning up database entries")
let thumbnailKey = self.getThumbnailKeyFor(cameraKey: entity.cameraKey!, title: entity.title!)
if (self.thumbnails.keys.contains(thumbnailKey)) {
self.thumbnails.removeValue(forKey: thumbnailKey)
}
if (self.previews.keys.contains(thumbnailKey)) {
self.previews.removeValue(forKey: thumbnailKey)
}
self.dc.managedObjectContext.delete(entity)
CameraCollectionManager.removeFinishedDownloadFor(cameraKey: entity.cameraKey!, title: entity.title!)
isDatabaseChanged = true
}
}
if (isDatabaseChanged) {
try self.dc.managedObjectContext.save()
}
} catch {
print("Failed to fetch photos: \(error)")
}
print("ThumbnailCacheManager refresh() finished")
self.isRefreshRunning = false
}
}
}
func checkThumbnailImage(entity: PhotoEntity, asset: PHAsset) {
let filename:String = "dslrbrowser_phassetthumbnail_" + (entity.localIdentifier!.data(using: .utf8)?.base64EncodedString())! + ".png"
let cacheDirectory:URL = FileManager.default.urls(for: FileManager.SearchPathDirectory.cachesDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first!
let cacheFileName:URL = URL.init(fileURLWithPath: cacheDirectory.path + "/" + filename )
let thumbnailKey = self.getThumbnailKeyFor(cameraKey: entity.cameraKey!, title: entity.title!)
if ( FileManager.default.fileExists(atPath: cacheFileName.path) ) {
self.thumbnails[thumbnailKey] = cacheFileName.path
}
else {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
option.isSynchronous = true
option.resizeMode = PHImageRequestOptionsResizeMode.fast
option.isNetworkAccessAllowed = false
option.version = PHImageRequestOptionsVersion.current
manager.requestImage(for: asset, targetSize: CGSize(width: 80, height: 60), contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in
if (result != nil) {
UIGraphicsBeginImageContext((result?.size)!)
result?.draw(in: CGRect(x: 0, y: 0, width: (result?.size.width)!, height: (result?.size.height)!))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
let png = UIImagePNGRepresentation(newImage!)
if (png != nil) {
FileManager.default.createFile(atPath: cacheFileName.path, contents: png, attributes: nil)
}
UIGraphicsEndImageContext()
}
})
}
}
func checkPreviewImage(entity: PhotoEntity, asset: PHAsset) {
let filename:String = "dslrbrowser_phassetpreview_" + (entity.localIdentifier!.data(using: .utf8)?.base64EncodedString())! + ".png"
let cacheDirectory:URL = FileManager.default.urls(for: FileManager.SearchPathDirectory.cachesDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first!
let cacheFileName:URL = URL.init(fileURLWithPath: cacheDirectory.path + "/" + filename )
let thumbnailKey = self.getThumbnailKeyFor(cameraKey: entity.cameraKey!, title: entity.title!)
if ( FileManager.default.fileExists(atPath: cacheFileName.path) ) {
self.previews[thumbnailKey] = cacheFileName.path
}
else {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
option.isSynchronous = true
option.resizeMode = PHImageRequestOptionsResizeMode.fast
option.isNetworkAccessAllowed = false
option.version = PHImageRequestOptionsVersion.current
manager.requestImage(for: asset, targetSize: CGSize(width: 640, height: 480), contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in
if (result != nil) {
UIGraphicsBeginImageContext((result?.size)!)
result?.draw(in: CGRect(x: 0, y: 0, width: (result?.size.width)!, height: (result?.size.height)!))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
let png = UIImagePNGRepresentation(newImage!)
if (png != nil) {
FileManager.default.createFile(atPath: cacheFileName.path, contents: png, attributes: nil)
}
UIGraphicsEndImageContext()
}
})
}
}
open func isThumbnailAvailableFor(cameraKey: String, title: String) -> Bool {
let key = getThumbnailKeyFor(cameraKey: cameraKey, title: title)
return thumbnails.keys.contains(key)
}
open func isPreviewAvailableFor(cameraKey: String, title: String) -> Bool {
let key = getThumbnailKeyFor(cameraKey: cameraKey, title: title)
return previews.keys.contains(key)
}
open func getThumbnailImageFor(cameraKey: String, title: String) -> UIImage {
let key = getThumbnailKeyFor(cameraKey: cameraKey, title: title)
let path = thumbnails[key]
let data = FileManager.default.contents(atPath: path!)!
if (data.count > 0) {
return UIImage(data: data)!
}
return #imageLiteral(resourceName: "camera_wifi")
}
open func getPreviewImageFor(cameraKey: String, title: String) -> UIImage {
let key = getThumbnailKeyFor(cameraKey: cameraKey, title: title)
let path = previews[key]
let data = FileManager.default.contents(atPath: path!)!
if (data.count > 0) {
return UIImage(data: data)!
}
return #imageLiteral(resourceName: "camera_wifi")
}
open func generateThumbsFor(entity: PhotoEntity) {
let assets:PHFetchResult<PHAsset> = PHAsset.fetchAssets(withLocalIdentifiers: [entity.localIdentifier!], options: nil)
if (assets.count > 0) {
//check if a thumbnail is already cached in the filesystem
//and request a thumbnail image otherwise
self.checkThumbnailImage(entity: entity, asset: assets[0])
//check if a preview is already cached in the filesystem
//and request a preview image otherwise
self.checkPreviewImage(entity: entity, asset: assets[0])
}
}
}