-
Notifications
You must be signed in to change notification settings - Fork 33
/
AppDelegate.swift
334 lines (272 loc) · 14.5 KB
/
AppDelegate.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
//
// AppDelegate.swift
// Zotero
//
// Created by Michal Rentka on 03/02/2019.
// Copyright © 2019 Corporation for Digital Scholarship. All rights reserved.
//
import UIKit
import CocoaLumberjackSwift
import RealmSwift
import SwiftUI
import PSPDFKit
import PSPDFKitUI
protocol SceneActivityCounter: AnyObject {
func sceneWillEnterForeground()
func sceneDidEnterBackground()
}
final class AppDelegate: UIResponder {
var controllers: Controllers!
private var foregroundSceneCount = 0
// MARK: - Migration
private func migratePdfSettings() {
let rawScrollDirection = UserDefaults.standard.value(forKey: "PdfReader.ScrollDirection") as? UInt
let rawPageTransition = UserDefaults.standard.value(forKey: "PdfReader.PageTransition") as? UInt
guard rawScrollDirection != nil || rawPageTransition != nil else { return }
var settings = Defaults.shared.pdfSettings
settings.direction = rawScrollDirection.flatMap({ ScrollDirection(rawValue: $0) }) ?? settings.direction
settings.transition = rawPageTransition.flatMap({ PageTransition(rawValue: $0) }) ?? settings.transition
Defaults.shared.pdfSettings = settings
UserDefaults.standard.removeObject(forKey: "PdfReader.ScrollDirection")
UserDefaults.standard.removeObject(forKey: "PdfReader.PageTransition")
}
private func migrateActiveColor() {
guard let activeColorHex = UserDefaults.zotero.object(forKey: "PDFReaderState.activeColor") as? String else { return }
Defaults.shared.highlightColorHex = activeColorHex
Defaults.shared.noteColorHex = activeColorHex
Defaults.shared.squareColorHex = activeColorHex
Defaults.shared.inkColorHex = activeColorHex
UserDefaults.zotero.removeObject(forKey: "PDFReaderState.activeColor")
}
private func migrateItemsSortType() {
guard let sortTypeData = UserDefaults.standard.data(forKey: "ItemsSortType"),
let unarchived = try? PropertyListDecoder().decode(ItemsSortType.self, from: sortTypeData) else { return }
Defaults.shared.itemsSortType = unarchived
UserDefaults.standard.removeObject(forKey: "ItemsSortType")
}
/// This migration was created to move from "old" file structure (before build 120) to "new" one, where items are stored with their proper filenames.
/// In `DidMigrateFileStructure` all downloaded items were moved. Items which were up for upload were forgotten, so `DidMigrateFileStructure2` was added to migrate also these items.
/// TODO: - Remove after beta
private func migrateFileStructure(queue: DispatchQueue) {
let didMigrateFileStructure = UserDefaults.standard.bool(forKey: "DidMigrateFileStructure")
let didMigrateFileStructure2 = UserDefaults.standard.bool(forKey: "DidMigrateFileStructure2")
guard !didMigrateFileStructure || !didMigrateFileStructure2 else { return }
guard let dbStorage = self.controllers.userControllers?.dbStorage else {
// If user is logget out, no need to migrate, DB is empty and files should be gone.
UserDefaults.standard.setValue(true, forKey: "DidMigrateFileStructure")
UserDefaults.standard.setValue(true, forKey: "DidMigrateFileStructure2")
return
}
// Migrate file structure
if !didMigrateFileStructure && !didMigrateFileStructure2 {
if let items = try? self.readAttachmentTypes(for: ReadAllDownloadedAndForUploadItemsDbRequest(), dbStorage: dbStorage, queue: queue) {
self.migrateFileStructure(for: items)
}
UserDefaults.standard.setValue(true, forKey: "DidMigrateFileStructure")
UserDefaults.standard.setValue(true, forKey: "DidMigrateFileStructure2")
} else if !didMigrateFileStructure {
if let items = try? self.readAttachmentTypes(for: ReadAllDownloadedItemsDbRequest(), dbStorage: dbStorage, queue: queue) {
self.migrateFileStructure(for: items)
}
UserDefaults.standard.setValue(true, forKey: "DidMigrateFileStructure")
} else if !didMigrateFileStructure2 {
if let items = try? self.readAttachmentTypes(for: ReadAllItemsForUploadDbRequest(), dbStorage: dbStorage, queue: queue) {
self.migrateFileStructure(for: items)
}
UserDefaults.standard.setValue(true, forKey: "DidMigrateFileStructure2")
}
NotificationCenter.default.post(name: .forceReloadItems, object: nil)
}
private func readAttachmentTypes<Request: DbResponseRequest>(for request: Request, dbStorage: DbStorage, queue: DispatchQueue) throws -> [(String, LibraryIdentifier, Attachment.Kind)] where Request.Response == Results<RItem> {
var types: [(String, LibraryIdentifier, Attachment.Kind)] = []
try dbStorage.perform(on: queue, with: { coordinator in
let items = try coordinator.perform(request: request)
types = items.compactMap({ item -> (String, LibraryIdentifier, Attachment.Kind)? in
guard let type = AttachmentCreator.attachmentType(for: item, options: .light, fileStorage: nil, urlDetector: nil), let libraryId = item.libraryId else { return nil }
return (item.key, libraryId, type)
})
coordinator.invalidate()
})
return types
}
private func migrateFileStructure(for items: [(String, LibraryIdentifier, Attachment.Kind)]) {
for (key, libraryId, type) in items {
switch type {
case .url: break
case .file(_, _, _, let linkType) where (linkType == .embeddedImage || linkType == .linkedFile): break // Embedded images and linked files don't need to be checked.
case .file(let filename, let contentType, _, let linkType):
// Snapshots were stored based on new structure, no need to do anything.
guard linkType != .importedUrl || contentType != "text/html" else { continue }
let filenameParts = filename.split(separator: ".")
let oldFile: File
if filenameParts.count > 1, let ext = filenameParts.last.flatMap(String.init) {
oldFile = FileData(rootPath: Files.appGroupPath, relativeComponents: ["downloads", libraryId.folderName], name: key, ext: ext)
} else {
oldFile = FileData(rootPath: Files.appGroupPath, relativeComponents: ["downloads", libraryId.folderName], name: key, contentType: contentType)
}
let newFile = Files.attachmentFile(in: libraryId, key: key, filename: filename, contentType: contentType)
try? self.controllers.fileStorage.move(from: oldFile, to: newFile)
}
}
}
private func removeFinishedUploadFiles(queue: DispatchQueue) {
let didDeleteFiles = UserDefaults.standard.bool(forKey: "DidDeleteFinishedUploadFiles")
guard !didDeleteFiles && self.controllers.fileStorage.has(Files.uploads),
let userControllers = self.controllers.userControllers else { return }
do {
let contents: [File] = try self.controllers.fileStorage.contentsOfDirectory(at: Files.uploads)
guard !contents.isEmpty else { return }
let backgroundUploads = userControllers.backgroundUploadObserver.context.uploads
let webDavEnabled = userControllers.webDavController.sessionStorage.isEnabled
var keysForUpload: Set<String> = []
var filesToDelete: [File] = []
if webDavEnabled {
let forUploadResults = try userControllers.dbStorage.perform(request: ReadAllItemsForUploadDbRequest(), on: queue)
keysForUpload = Set(forUploadResults.map({ $0.key }))
forUploadResults.first?.realm?.invalidate()
}
for file in contents {
if file.name.isEmpty && file.mimeType.isEmpty {
// Background Zotero upload
if !webDavEnabled && backgroundUploads.contains(where: { $0.fileUrl.lastPathComponent == file.relativeComponents.last }) {
// If file is being uploaded in background, don't delete
continue
}
filesToDelete.append(file)
continue
}
if file.ext == "zip" && !file.name.isEmpty {
// Background/foreground WebDAV upload
if webDavEnabled && (backgroundUploads.contains(where: { $0.fileUrl.deletingPathExtension().lastPathComponent == file.name }) || keysForUpload.contains(file.name)) {
// If file is being uploaded in background or queued to upload during sync, don't delete
continue
}
filesToDelete.append(file)
}
}
for file in filesToDelete {
try? self.controllers.fileStorage.remove(file)
}
UserDefaults.standard.setValue(true, forKey: "DidDeleteFinishedUploadFiles")
} catch let error {
DDLogError("AppDelegate: can't remove finished uploads - \(error)")
}
}
private func updateCreatorSummaryFormat(queue: DispatchQueue) {
guard !UserDefaults.standard.bool(forKey: "DidUpdateCreatorSummaryFormat") else { return }
guard let dbStorage = self.controllers.userControllers?.dbStorage else {
// User logged out, don't need to update
UserDefaults.standard.set(true, forKey: "DidUpdateCreatorSummaryFormat")
return
}
do {
try dbStorage.perform(request: UpdateCreatorSummaryFormatDbRequest(), on: queue)
UserDefaults.standard.set(true, forKey: "DidUpdateCreatorSummaryFormat")
} catch let error {
DDLogError("AppDelegate: can't update creator summary format - \(error)")
}
}
// MARK: - Setups
private func setupLogs() {
#if DEBUG
// Enable console logs only for debug mode
let logger = DDOSLogger.sharedInstance
logger.logFormatter = DebugLogFormatter(targetName: "Zotero")
DDLog.add(logger)
dynamicLogLevel = .debug
#else
// Change to .info to enable server logging
// Change to .warning/.error to disable server logging
dynamicLogLevel = .info
#endif
}
private func setupAppearance() {
// Navigation bars
let appearance = UINavigationBarAppearance()
appearance.configureWithDefaultBackground()
UINavigationBar.appearance().scrollEdgeAppearance = appearance
UINavigationBar.appearance().tintColor = Asset.Colors.zoteroBlue.color
// Toolbars
UIToolbar.appearance().tintColor = Asset.Colors.zoteroBlue.color
// Buttons
UIButton.appearance().tintColor = Asset.Colors.zoteroBlue.color
// Search bar
UISearchBar.appearance().tintColor = Asset.Colors.zoteroBlue.color
}
private func setupExportDefaults() {
if UserDefaults.standard.string(forKey: "QuickCopyLocaleId") != nil {
// Value is already assigned, no need to do anything else.
return
}
guard let localeIds = try? ExportLocaleReader.loadIds() else { return }
let defaultLocale = localeIds.first(where: { $0.contains(Locale.current.identifier) }) ?? "en-US"
UserDefaults.standard.setValue(defaultLocale, forKey: "QuickCopyLocaleId")
UserDefaults.standard.setValue(defaultLocale, forKey: "ExportLocaleId")
}
}
extension AppDelegate: SceneActivityCounter {
func sceneDidEnterBackground() {
self.foregroundSceneCount -= 1
if self.foregroundSceneCount == 0 {
self.applicationDidEnterBackground(UIApplication.shared)
}
}
func sceneWillEnterForeground() {
if self.foregroundSceneCount == 0 {
self.applicationWillEnterForeground(UIApplication.shared)
}
self.foregroundSceneCount += 1
}
}
extension AppDelegate: UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if let key = Licenses.shared.pspdfkitKey {
PSPDFKit.SDK.setLicenseKey(key)
}
PSPDFKit.SDK.shared.styleManager.setLastUsedValue(AnnotationsConfig.imageAnnotationLineWidth,
forProperty: "lineWidth",
forKey: PSPDFKit.Annotation.ToolVariantID(tool: .square))
self.setupLogs()
self.controllers = Controllers()
self.setupAppearance()
self.setupExportDefaults()
self.migrateActiveColor()
self.migratePdfSettings()
self.migrateItemsSortType()
let queue = DispatchQueue(label: "org.zotero.AppDelegateMigration", qos: .userInitiated)
queue.async {
self.migrateFileStructure(queue: queue)
self.removeFinishedUploadFiles(queue: queue)
self.updateCreatorSummaryFormat(queue: queue)
}
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
self.controllers.didEnterBackground()
}
func applicationWillEnterForeground(_ application: UIApplication) {
self.controllers.willEnterForeground()
NotificationCenter.default.post(name: .willEnterForeground, object: nil)
}
func applicationWillTerminate(_ application: UIApplication) {
self.controllers.willTerminate()
}
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
guard let userControllers = self.controllers.userControllers else {
completionHandler()
return
}
userControllers.backgroundUploadObserver.handleEventsForBackgroundURLSession(with: identifier, completionHandler: completionHandler)
}
func application(_ application: UIApplication, shouldSaveSecureApplicationState coder: NSCoder) -> Bool {
return true
}
func application(_ application: UIApplication, shouldRestoreSecureApplicationState coder: NSCoder) -> Bool {
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession,
options: UIScene.ConnectionOptions) -> UISceneConfiguration {
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
}