-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnsplashImageCache.swift
More file actions
288 lines (262 loc) · 12.4 KB
/
UnsplashImageCache.swift
File metadata and controls
288 lines (262 loc) · 12.4 KB
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
//
// Created by Andres Canella on 7/27/18.
// Copyright (c) 2018 andres Canella. All rights reserved.
//
import Foundation
import RxSwift
import RealmSwift
public class UnsplashImageCache {
var debugLogging:Bool
var targetUnusedCount:Int
//subscribe to status for status feedback
public enum Status {
case error(description:String)
case requesting(path:String)
case requestAPISuccess
case requestImagesDone(succeeded:Int)
case skipFetchTargetUnseenReached
}
public let status = PublishSubject<Status>()
private let clientId:String
private let collections:[String]?
let serverPath = "https://api.unsplash.com/photos/random"
public init(clientId:String, collections:[String]? = nil, debugLogging:Bool = true, maxUnusedCount:Int = 10) {
self.clientId = clientId
self.collections = collections
self.debugLogging = debugLogging
self.targetUnusedCount = maxUnusedCount
}
deinit { log(message: "deinit") }
public func preCache(imageCount:Int = 3) {
//skip if unseen count target reached
let unseenCount = dbDownloadedUnseenCount()
log(message: "unseen count: \(unseenCount)")
if unseenCount >= self.targetUnusedCount {
log(message: "Unseen count target reached, skip.")
status.on(.next(.skipFetchTargetUnseenReached))
return
}
//pending results
var imageFetchSuccess = 0
//build path
var path = serverPath
path += "?client_id=\(clientId)"
path += "&count=\(imageCount)"
if collections != nil {
path += "&collections=\(collections!.joined(separator: ","))"
}
//request url
guard let url = URL(string: path) else { status.on(.next(.error(description: "Could not assemble request URL, with path: \(path)"))); return }
//request
status.on(.next(.requesting(path: path)))
var request = URLRequest(url: url)
request.httpMethod = "GET"
_ = URLSession.shared.rx
.response(request: request)
.observeOn(ConcurrentDispatchQueueScheduler(qos: .background))
//format
.flatMap { (response: URLResponse, data: Data) -> Observable<Data> in
if response is HTTPURLResponse {
self.status.on(.next(.requestAPISuccess))
return Observable.just(data)
} else {
return Observable.error(NSError(domain: "server response fail", code: -10, userInfo: nil))
}
}
.splitToElementData()
.filter({ (image, publisher) -> Bool in
//already logged
if let element = self.dbElement(id: image.id) {
self.log(message: "has Element: \(element)")
//pass filter if not downloaded,
return !element.downloaded
} else {
self.log(message: "does not have ElementId: \(image.id)")
//register new element
let element = UnsplashImageCacheElement()
element.id = image.id
element.fullImageUrlPath = image.urlPath
element.title = image.title
element.publisherUsername = publisher.username
element.publisherNameFirst = publisher.nameFirst
element.publisherNameLast = publisher.nameLast
element.publisherCustomPortfolioUrlPath = publisher.urlPath
element.seen = Date.distantPast
self.saveDb(element: element)
return true
}
})
//download
.flatMap { (image, publisher) -> Observable<(id:String, data:Data)> in
self.log(message: "Need to get asset: \(image.id)")
//image url
guard let url = URL(string: image.urlPath) else {
return Observable.error(NSError(domain: "Could not assemble image URL, with path: \(image.urlPath)", code: -10, userInfo: nil))
}
let request = URLRequest(url: url)
return URLSession.shared.rx
.response(request:request)
.map { (response: URLResponse, data: Data) -> (id:String, data:Data) in
return (id: image.id, data: data)
}
}
//save
.map { (id:String, data:Data) -> Void in
do {
try self.save(data: data, id: id)
//log downloaded
let element = self.dbElement(id: id)
let realm = try! Realm()
try! realm.write {
element?.downloaded = true
}
} catch {
self.status.on(.next(.error(description: "Could not save image, error: \(error)")))
}
}
.subscribe(onNext: {
self.log(message: "onNext")
//count succeeded
imageFetchSuccess += 1
}, onError: { error in
self.log(message: "onError: \(error)")
self.status.on(.next(.requestImagesDone(succeeded: imageFetchSuccess)))
}, onCompleted: {
self.log(message: "onComplected")
//finished fetch job
self.status.on(.next(.requestImagesDone(succeeded: imageFetchSuccess)))
})
}
public func randomElement() -> (image: UIImage, element:UnsplashImageCacheElement)? {
let elements = dbDownloadedElements()
if let unusedElement = elements.sorted(byKeyPath: "seen").first {
//log used
let realm = try! Realm()
try! realm.write {
unusedElement.seen = Date()
}
//get image
if let data = try? get(id: unusedElement.id), let image = UIImage(data: data) {
//return element with image
return (image:image, element:unusedElement)
}
}
return nil
}
public func debugListDbElements() {
self.log(message: "----elements----")
for element in dbElements() { self.log(message: "id: \(element.id), dl: \(element.downloaded), used: \(element.seen.description), url:\(element.fullImageUrlPath), username: \(element.publisherUsername ?? "nil"), nameFirst: \(element.publisherNameFirst ?? "nil"), nameLast: \(element.publisherNameLast ?? "nil"), title: \(element.title ?? "nil"), customPortfolio: \(element.publisherCustomPortfolioUrlPath ?? "nil")") }
self.log(message: "----------------")
}
private func cacheUrl() -> URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("ImageCache", isDirectory: true)
}
private func save(data:Data, id:String) throws {
//create directory if missing
var isDir = ObjCBool(true)
if !FileManager.default.fileExists(atPath: cacheUrl().path, isDirectory: &isDir) {
try FileManager.default.createDirectory(at: cacheUrl(), withIntermediateDirectories: false)
}
//save
let filename = cacheUrl().appendingPathComponent(id)
try data.write(to: filename)
}
private func get(id:String) throws -> Data {
let filename = cacheUrl().appendingPathComponent(id)
return try Data(contentsOf: filename)
}
private func saveDb(element:UnsplashImageCacheElement) {
let realm = try! Realm()
try! realm.write {
realm.add(element, update: true)
}
}
private func dbElements() -> Results<UnsplashImageCacheElement> {
let realm = try! Realm()
return realm.objects(UnsplashImageCacheElement.self)
}
private func dbDownloadedElements() -> Results<UnsplashImageCacheElement> {
return dbElements().filter("downloaded == true")
}
private func dbDownloadedUnseenCount() -> Int {
return dbDownloadedElements().filter("seen == %@", Date.distantPast).count
}
private func dbElement(id:String) -> UnsplashImageCacheElement? {
return dbElements().filter("id == '\(id)'").first
}
private func log(message:String) {
if debugLogging {
print("UIC: \(message)")
}
}
private func cropToBounds(image: UIImage, size: CGSize) -> UIImage? {
let rect = CGRect(x: (image.size.width - size.width) / 2, y: (image.size.height - size.height) / 2, width: size.width, height: size.height)
if let imageRef = image.cgImage?.cropping(to: rect) {
return UIImage(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation)
}
return nil
}
}
public extension ObservableType where E == Data {
public func splitToElementData() -> Observable<(image:(id:String, urlPath:String, title:String?), publisher:(username:String?, nameFirst:String?, nameLast:String?, urlPath:String?))> {
return Observable.create { observer in
return self.subscribe { event in
switch event {
case .next(let data):
guard let json = try? JSONSerialization.jsonObject(with: data, options:[]) as! Array<[String:Any]> else {
observer.on(.error(NSError(domain: "Split to elements, failed", code: -11, userInfo: nil)))
return
}
//iterate
for element in json {
guard let id = element["id"] as? String else { observer.on(.error(NSError(domain: "Split to elements, missing 'id' key", code: -11, userInfo: nil))); return }
guard let fullImageUrlPath = (element["urls"] as! [String:Any])["full"] as? String else { observer.on(.error(NSError(domain: "Split to elements, missing 'urls':'full' key", code: -11, userInfo: nil))); return }
let title = (element["location"] as? [String:Any])?["title"] as? String
let username = (element["user"] as? [String:Any])?["username"] as? String
let nameFirst = (element["user"] as? [String:Any])?["first_name"] as? String
let nameLast = (element["user"] as? [String:Any])?["last_name"] as? String
let portfolioUlrPath = (element["user"] as? [String:Any])?["portfolio_url"] as? String
observer.on(.next((
image:(
id:id,
urlPath:fullImageUrlPath,
title:title),
publisher:(
username:username,
nameFirst:nameFirst,
nameLast:nameLast,
urlPath:portfolioUlrPath
))))
}
case .error(let error):
observer.on(.error(error))
case .completed:
observer.on(.completed)
}
}
}
}
}
public class UnsplashImageCacheElement:Object {
@objc dynamic var id:String = ""
@objc dynamic var fullImageUrlPath:String = ""
@objc dynamic var title:String?
@objc dynamic var publisherUsername:String?
@objc dynamic var publisherNameFirst:String?
@objc dynamic var publisherNameLast:String?
@objc dynamic var publisherCustomPortfolioUrlPath:String?
@objc dynamic var downloaded = false
@objc dynamic var seen = Date.distantPast
public override static func primaryKey() -> String? {
return "id"
}
public func imageHumanUrl() -> URL? {
return URL(string: "https://unsplash.com/photos/\(id)")
}
public func publisherHumanUrl() -> URL? {
guard let hasPublisherId = publisherUsername else {
return nil
}
return URL(string: "https://unsplash.com/@\(hasPublisherId)")
}
}