-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTPPAnnotations.swift
401 lines (338 loc) · 15.6 KB
/
TPPAnnotations.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
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
import UIKit
import R2Shared
protocol AnnotationsManager {
func postListeningPosition(forBook bookID: String, selectorValue: String, completion: ((_ serverID: String?) -> Void)?)
func postAudiobookBookmark(forBook bookID: String, selectorValue: String) async throws -> String?
func getServerBookmarks(forBook bookID:String?,
atURL annotationURL:URL?,
motivation: TPPBookmarkSpec.Motivation,
completion: @escaping (_ bookmarks: [Bookmark]?) -> ())
func deleteBookmark(annotationId: String, completionHandler: @escaping (_ success: Bool) -> ())
}
@objcMembers final class TPPAnnotationsWrapper: NSObject, AnnotationsManager {
func postListeningPosition(forBook bookID: String, selectorValue: String, completion: ((String?) -> Void)?) {
TPPAnnotations.postListeningPosition(forBook: bookID, selectorValue: selectorValue, completion: completion)
}
func postAudiobookBookmark(forBook bookID: String, selectorValue: String) async throws -> String? {
try await TPPAnnotations.postAudiobookBookmark(forBook: bookID, selectorValue: selectorValue)
}
func getServerBookmarks(forBook bookID: String?, atURL annotationURL: URL?, motivation: TPPBookmarkSpec.Motivation = .bookmark, completion: @escaping ([Bookmark]?) -> ()) {
TPPAnnotations.getServerBookmarks(forBook: bookID, atURL: annotationURL, motivation: motivation, completion: completion)
}
func deleteBookmark(annotationId: String, completionHandler: @escaping (Bool) -> ()) {
TPPAnnotations.deleteBookmark(annotationId: annotationId, completionHandler: completionHandler)
}
}
@objcMembers final class TPPAnnotations: NSObject {
// MARK: - Reading Position
/// Reads the current reading position from the server, parses the response
/// and returns the result to the `completionHandler`.
class func syncReadingPosition(ofBook bookID: String?, toURL url:URL?,
completion: @escaping (_ readPos: Bookmark?) -> ()) {
guard syncIsPossibleAndPermitted() else {
Log.debug(#file, "Account does not support sync or sync is disabled.")
completion(nil)
return
}
TPPAnnotations.getServerBookmarks(forBook: bookID, atURL: url, motivation: .readingProgress) { bookmarks in
completion(bookmarks?.first)
}
}
class func postListeningPosition(forBook bookID: String, selectorValue: String, completion: ((_ serverID: String?) -> Void)? = nil) {
postReadingPosition(forBook: bookID, selectorValue: selectorValue, motivation: .readingProgress, completion: completion)
}
class func postAudiobookBookmark(forBook bookID: String, selectorValue: String) async throws -> String? {
return try await withCheckedThrowingContinuation { continuation in
postReadingPosition(forBook: bookID, selectorValue: selectorValue, motivation: .bookmark) { serverID in
if let serverID = serverID {
continuation.resume(returning: serverID)
} else {
continuation.resume(throwing: NSError(domain: "Error posting bookmark", code: 1, userInfo: nil))
}
}
}
}
class func postReadingPosition(forBook bookID: String, selectorValue: String, motivation: TPPBookmarkSpec.Motivation, completion: ((_ serverID: String?) -> Void)? = nil) {
guard syncIsPossibleAndPermitted() else {
Log.debug(#file, "Account does not support sync or sync is disabled.")
completion?(nil)
return
}
guard let annotationsURL = TPPAnnotations.annotationsURL else {
Log.error(#file, "Annotations URL was nil while updating reading position")
completion?(nil)
return
}
// Format bookmark for submission to server according to spec
let bookmark = TPPBookmarkSpec(time: NSDate(),
device: TPPUserAccount.sharedAccount().deviceID ?? "",
motivation: motivation,
bookID: bookID,
selectorValue: selectorValue)
let parameters = bookmark.dictionaryForJSONSerialization()
postAnnotation(forBook: bookID, withAnnotationURL: annotationsURL, withParameters: parameters, queueOffline: true) { (success, id) in
guard success else {
TPPErrorLogger.logError(withCode: .apiCall,
summary: "Error posting annotation",
metadata: [
"bookID": bookID,
"annotationID": id ?? "N/A",
"annotationURL": annotationsURL])
completion?(nil)
return
}
Log.debug(#file, "Successfully saved Reading Position to server: \(selectorValue)")
completion?(id)
}
}
class func postBookmark(_ page: TPPPDFPage, forBookID bookID: String, completion: @escaping (_ serverID: String?) -> Void) {
guard syncIsPossibleAndPermitted() else {
Log.debug(#file, "Account does not support sync or sync is disabled.")
completion(nil)
return
}
guard let annotationsURL = TPPAnnotations.annotationsURL else {
Log.error(#file, "Annotations URL was nil while posting bookmark")
return
}
guard let selectorValue = page.bookmarkSelector else {
Log.error(#file, "Bookmark selectorValue was nil while posting bookmark")
return
}
let spec = TPPBookmarkSpec(
time: NSDate(),
device: TPPUserAccount.sharedAccount().deviceID ?? "",
motivation: .bookmark,
bookID: bookID,
selectorValue: selectorValue
)
let parameters = spec.dictionaryForJSONSerialization()
postAnnotation(forBook: bookID, withAnnotationURL: annotationsURL, withParameters: parameters, queueOffline: false) { (success, id) in
completion(id)
}
}
class func postBookmark(_ bookmark: TPPReadiumBookmark,
forBookID bookID: String,
completion: @escaping (_ serverID: String?) -> ())
{
guard syncIsPossibleAndPermitted() else {
Log.debug(#file, "Account does not support sync or sync is disabled.")
completion(nil)
return
}
guard let annotationsURL = TPPAnnotations.annotationsURL else {
Log.error(#file, "Annotations URL was nil while posting bookmark")
return
}
let spec = TPPBookmarkSpec(
id: UUID().uuidString,
time: (bookmark.time.dateFromISO8601 as NSDate? ?? NSDate()),
device: bookmark.device ?? "",
motivation: .bookmark,
bookID: bookID,
selectorValue: bookmark.location
)
let parameters = spec.dictionaryForJSONSerialization()
postAnnotation(forBook: bookID, withAnnotationURL: annotationsURL, withParameters: parameters, queueOffline: false) { (success, id) in
completion(id)
}
}
/// Serializes the `parameters` into JSON and POSTs them to the server.
class func postAnnotation(forBook bookID: String,
withAnnotationURL url: URL,
withParameters parameters: [String: Any],
timeout: TimeInterval = TPPDefaultRequestTimeout,
queueOffline: Bool,
_ completionHandler: @escaping (_ success: Bool, _ annotationID: String?) -> ()) {
guard let jsonData = try? JSONSerialization.data(withJSONObject: parameters, options: [.prettyPrinted]) else {
Log.error(#file, "Network request abandoned. Could not create JSON from given parameters.")
completionHandler(false, nil)
return
}
var request = TPPNetworkExecutor.shared.request(for: url)
request.httpMethod = "POST"
request.httpBody = jsonData
request.timeoutInterval = timeout
let task = TPPNetworkExecutor.shared.POST(request) { (data, response, error) in
if let error = error as NSError? {
Log.error(#file, "Annotation POST error (nsCode: \(error.code) Description: \(error.localizedDescription))")
if (NetworkQueue.StatusCodes.contains(error.code)) && (queueOffline == true) {
self.addToOfflineQueue(bookID, url, parameters)
}
completionHandler(false, nil)
return
}
guard let statusCode = (response as? HTTPURLResponse)?.statusCode else {
Log.error(#file, "Annotation POST error: No response received from server")
completionHandler(false, nil)
return
}
if statusCode == 200 {
Log.debug(#file, "Annotation POST: Success 200.")
let serverAnnotationID = annotationID(fromNetworkData: data)
completionHandler(true, serverAnnotationID)
} else {
Log.error(#file, "Annotation POST: Response Error. Status Code: \(statusCode)")
completionHandler(false, nil)
}
}
task?.resume()
}
private class func annotationID(fromNetworkData data: Data?) -> String? {
guard let data = data else {
Log.error(#file, "No Annotation ID saved: No data received from server.")
return nil
}
guard let json = try? JSONSerialization.jsonObject(with: data, options: []) as! [String:Any] else {
Log.error(#file, "No Annotation ID saved: JSON could not be created from data.")
return nil
}
if let annotationID = json[TPPBookmarkSpec.Id.key] as? String {
return annotationID
} else {
Log.error(#file, "No Annotation ID saved: Key/Value not found in JSON response.")
return nil
}
}
// MARK: - Bookmarks
// Completion handler will return a nil parameter if there are any failures with
// the network request, deserialization, or sync permission is not allowed.
class func getServerBookmarks(forBook bookID:String?,
atURL annotationURL:URL?,
motivation: TPPBookmarkSpec.Motivation = .bookmark,
completion: @escaping (_ bookmarks: [Bookmark]?) -> ()) {
guard syncIsPossibleAndPermitted() else {
Log.debug(#file, "Account does not support sync or sync is disabled.")
completion(nil)
return
}
guard let bookID = bookID, let annotationURL = annotationURL else {
Log.error(#file, "Required parameter was nil.")
completion(nil)
return
}
let dataTask = TPPNetworkExecutor.shared.GET(annotationURL) { (data, response, error) in
if let error = error as NSError? {
Log.error(#file, "Request Error Code: \(error.code). Description: \(error.localizedDescription)")
completion(nil)
return
}
guard let data = data,
let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []),
let json = jsonObject as? [String: Any] else {
Log.error(#file, "Response from annotation server could not be serialized.")
completion(nil)
return
}
guard let first = json["first"] as? [String: Any],
let items = first["items"] as? [[String: Any]] else {
Log.error(#file, "Missing required key from Annotations response, or no items exist.")
completion(nil)
return
}
let bookmarks = items.compactMap {
TPPBookmarkFactory.make(fromServerAnnotation: $0,
annotationType: motivation,
bookID: bookID)
}
completion(bookmarks)
}
dataTask?.resume()
}
class func deleteBookmarks(_ bookmarks: [TPPReadiumBookmark]) {
for localBookmark in bookmarks {
if let annotationID = localBookmark.annotationId {
deleteBookmark(annotationId: annotationID) { success in
if success {
Log.debug(#file, "Server bookmark deleted: \(annotationID)")
} else {
Log.error(#file, "Bookmark not deleted from server. Moving on: \(annotationID)")
}
}
}
}
}
class func deleteBookmark(annotationId: String,
completionHandler: @escaping (_ success: Bool) -> ()) {
if !syncIsPossibleAndPermitted() {
Log.debug(#file, "Account does not support sync or sync is disabled.")
completionHandler(true)
return
}
guard let url = URL(string: annotationId) else {
Log.error(#file, "Invalid URL from Annotation ID")
completionHandler(false)
return
}
var request = TPPNetworkExecutor.shared.request(for: url)
request.timeoutInterval = TPPDefaultRequestTimeout
let task = TPPNetworkExecutor.shared.DELETE(request) { (data, response, error) in
let response = response as? HTTPURLResponse
if response?.statusCode == 200 {
Log.info(#file, "200: DELETE bookmark success")
completionHandler(true)
} else if let code = response?.statusCode {
Log.error(#file, "DELETE bookmark failed with server response code: \(code)")
completionHandler(false)
} else {
guard let error = error as NSError? else { return }
Log.error(#file, "DELETE bookmark Request Failed with Error Code: \(error.code). Description: \(error.localizedDescription)")
completionHandler(false)
}
}
task?.resume()
}
// Method is called when the SyncManager is syncing bookmarks
// If an existing local bookmark is missing an annotationID, assume it still needs to be uploaded.
class func uploadLocalBookmarks(_ bookmarks: [TPPReadiumBookmark],
forBook bookID: String,
completion: @escaping ([TPPReadiumBookmark], [TPPReadiumBookmark])->()) {
if !syncIsPossibleAndPermitted() {
Log.debug(#file, "Account does not support sync or sync is disabled.")
return
}
Log.debug(#file, "Begin task of uploading local bookmarks, count: \(bookmarks.count).")
let uploadGroup = DispatchGroup()
var bookmarksFailedToUpdate = [TPPReadiumBookmark]()
var bookmarksUpdated = [TPPReadiumBookmark]()
for localBookmark in bookmarks {
if localBookmark.annotationId == nil {
uploadGroup.enter()
postBookmark(localBookmark, forBookID: bookID) { serverID in
if let ID = serverID {
localBookmark.annotationId = ID
bookmarksUpdated.append(localBookmark)
} else {
Log.error(#file, "Local Bookmark not uploaded: \(localBookmark)")
bookmarksFailedToUpdate.append(localBookmark)
}
uploadGroup.leave()
}
}
}
uploadGroup.notify(queue: DispatchQueue.main) {
Log.debug(#file, "Finished task of uploading local bookmarks.")
completion(bookmarksUpdated, bookmarksFailedToUpdate)
}
}
// MARK: -
/// Annotation-syncing is possible only if the given `account` is signed-in
/// and if the currently selected library supports it.
class func syncIsPossible(_ account: TPPUserAccount) -> Bool {
let library = AccountsManager.shared.currentAccount
return account.hasCredentials() && library?.details?.supportsSimplyESync == true
}
class func syncIsPossibleAndPermitted() -> Bool {
let acct = AccountsManager.shared.currentAccount
return syncIsPossible(TPPUserAccount.sharedAccount()) && acct?.details?.syncPermissionGranted == true
}
static var annotationsURL: URL? {
return TPPConfiguration.mainFeedURL()?.appendingPathComponent("annotations/")
}
private class func addToOfflineQueue(_ bookID: String?, _ url: URL, _ parameters: [String:Any]) {
let libraryID = AccountsManager.shared.currentAccount?.uuid ?? ""
let parameterData = try? JSONSerialization.data(withJSONObject: parameters, options: [.prettyPrinted])
let headers = TPPNetworkExecutor.shared.request(for: url).allHTTPHeaderFields
NetworkQueue.shared().addRequest(libraryID, bookID, url, .POST, parameterData, headers)
}
}