Skip to content
This repository was archived by the owner on Jan 20, 2021. It is now read-only.

Commit fd6021f

Browse files
Julian KahnertJulian Kahnert
authored andcommitted
- [+] Bug: nach dem ersten scan wird das Dokument nicht richtig angezeigt
- [+] Dokumenten name nicht immer lowercased - [+] Scan (& Share) quick Action
1 parent de1b28e commit fd6021f

File tree

19 files changed

+198
-91
lines changed

19 files changed

+198
-91
lines changed

AppClip/MainContentViewModel.swift

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,7 @@ final class MainContentViewModel: ObservableObject {
1818

1919
var sharingViewModel = PDFSharingViewModel()
2020
var scanViewModel = ScanTabViewModel(imageConverter: imageConverter,
21-
iapService: AppClipIAPService(),
22-
documentsFinishedHandler: {})
21+
iapService: AppClipIAPService())
2322
private var disposables = Set<AnyCancellable>()
2423

2524
init() {

ArchiveCore/Sources/ArchiveBackend/ArchiveStore.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -281,9 +281,9 @@ public final class ArchiveStore: ObservableObject, ArchiveStoreAPI, Log {
281281
// Do "--" and "__" exist in filename?
282282
guard url.lastPathComponent.contains("--"),
283283
url.lastPathComponent.contains("__"),
284-
!url.lastPathComponent.contains(Constants.documentDatePlaceholder),
285-
!url.lastPathComponent.contains(Constants.documentDescriptionPlaceholder),
286-
!url.lastPathComponent.contains(Constants.documentTagPlaceholder) else { return .untagged }
284+
!url.lastPathComponent.lowercased().contains(Constants.documentDatePlaceholder.lowercased()),
285+
!url.lastPathComponent.lowercased().contains(Constants.documentDescriptionPlaceholder.lowercased()),
286+
!url.lastPathComponent.lowercased().contains(Constants.documentTagPlaceholder.lowercased()) else { return .untagged }
287287

288288
return .tagged
289289
}

ArchiveCore/Sources/ArchiveBackend/Models/Document.swift

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -145,18 +145,19 @@ public final class Document: ObservableObject, Identifiable, Codable, Log {
145145
return "\(dateStr)--\(specification)__\(tagStr).pdf"
146146
}
147147

148+
/// This function updates the properties of the document.
149+
///
150+
/// Since it might run some time, this should not be run on the main thread.
148151
func updateProperties(with downloadStatus: FileChange.DownloadStatus, shouldParseDate: Bool) {
149-
if Thread.isMainThread {
150-
log.errorAndAssert("updateProperties() must not be called from the main thread.")
151-
}
152152
filename = (try? path.resourceValues(forKeys: [.localizedNameKey]).localizedName) ?? self.path.lastPathComponent
153153

154154
// parse the current filename and add finder file tags
155155
let parsedFilename = Document.parseFilename(self.filename)
156+
let placeholderTag = Constants.documentTagPlaceholder.lowercased()
156157
let tags = Set(parsedFilename.tagNames ?? []).union(path.fileTags)
157-
.filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && $0 != Constants.documentTagPlaceholder }
158+
.filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && $0.lowercased() != placeholderTag }
158159

159-
DispatchQueue.main.sync {
160+
let workItem = DispatchWorkItem {
160161
self.downloadStatus = downloadStatus
161162

162163
// set the date
@@ -173,6 +174,12 @@ public final class Document: ObservableObject, Identifiable, Codable, Log {
173174
self.tags = tags
174175
}
175176

177+
if Thread.isMainThread {
178+
workItem.perform()
179+
} else {
180+
DispatchQueue.main.sync(execute: workItem)
181+
}
182+
176183
guard downloadStatus == .local,
177184
shouldParseDate else { return }
178185
self.parseContent()

ArchiveCore/Sources/ArchiveBackend/PathManager/PathManager.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ public final class PathManager: Log {
8080
public func getArchiveUrl() throws -> URL {
8181
let archiveURL: URL
8282
if UserDefaults.standard.isInDemoMode {
83-
archiveURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
83+
archiveURL = fileManager.temporaryDirectory
8484
} else {
8585
archiveURL = try archivePathType.getArchiveUrl()
8686
}

ArchiveCore/Sources/ArchiveSharedConstants/Tab.swift

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,17 @@ public enum Tab: String, CaseIterable, Identifiable, Hashable, Equatable {
1515
#endif
1616

1717
public var id: String { rawValue }
18-
public var name: String { rawValue.capitalized }
18+
public var name: String {
19+
if self == .scan {
20+
#if os(macOS)
21+
return "Import"
22+
#else
23+
return "Scan"
24+
#endif
25+
} else {
26+
return rawValue.capitalized
27+
}
28+
}
1929
public var iconName: String {
2030
switch self {
2131
case .scan:

ArchiveCore/Sources/ArchiveViews/MainNavigationViewModel.swift

Lines changed: 67 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
// Created by Julian Kahnert on 30.10.19.
66
// Copyright © 2019 Julian Kahnert. All rights reserved.
77
//
8-
// swiftlint:disable function_body_length
8+
// swiftlint:disable function_body_length type_body_length
99

1010
import ArchiveBackend
1111
import Combine
@@ -32,36 +32,20 @@ public final class MainNavigationViewModel: ObservableObject, Log {
3232
@Published var showTutorial = !UserDefaults.appGroup.tutorialShown
3333
@Published var sheetType: SheetType?
3434

35-
public let imageConverter = ImageConverter(getDocumentDestination: getDocumentDestination)
36-
37-
lazy var scanViewModel = ScanTabViewModel(imageConverter: imageConverter, iapService: Self.iapService, documentsFinishedHandler: Self.scanFinished)
35+
public let imageConverter: ImageConverter
36+
var scanViewModel: ScanTabViewModel
3837
let tagViewModel = TagTabViewModel()
3938
let archiveViewModel = ArchiveViewModel()
40-
public private(set) lazy var moreViewModel = MoreTabViewModel(iapService: Self.iapService, archiveStore: Self.archiveStore)
39+
public let moreViewModel = MoreTabViewModel(iapService: MainNavigationViewModel.iapService, archiveStore: MainNavigationViewModel.archiveStore)
4140

4241
let iapViewModel = IAPViewModel(iapService: iapService)
4342

4443
private var disposables = Set<AnyCancellable>()
4544

46-
@ViewBuilder
47-
func getView(for sheetType: SheetType) -> some View {
48-
switch sheetType {
49-
case .iapView:
50-
IAPView(viewModel: iapViewModel)
51-
#if canImport(MessageUI)
52-
case .supportView:
53-
SupportMailView(subject: Self.mailSubject,
54-
recipients: Self.mailRecipients,
55-
errorHandler: { NotificationCenter.default.postAlert($0) })
56-
#endif
57-
#if !os(macOS)
58-
case .activityView(let items):
59-
AppActivityView(activityItems: items)
60-
#endif
61-
}
62-
}
63-
6445
public init() {
46+
imageConverter = ImageConverter(getDocumentDestination: Self.getDocumentDestination)
47+
scanViewModel = ScanTabViewModel(imageConverter: imageConverter, iapService: Self.iapService)
48+
6549
NotificationCenter.default.alertPublisher()
6650
.receive(on: DispatchQueue.main)
6751
.assign(to: &$alertDataModel)
@@ -176,18 +160,39 @@ public final class MainNavigationViewModel: ObservableObject, Log {
176160
}
177161
}
178162

179-
#if !os(macOS)
180163
imageConverter.$processedDocumentUrl
181-
.compactMap { [weak self] url in
182-
guard let url = url,
183-
self?.scanViewModel.shareDocumentAfterScan ?? false else { return nil }
184-
185-
// show share sheet
186-
return .activityView(items: [url])
164+
.compactMap { $0 }
165+
.sink { [weak self] url in
166+
#if os(macOS)
167+
Self.showFirstDocumentFinishedDialogIfNeeded()
168+
#else
169+
if let self = self,
170+
self.scanViewModel.shareDocumentAfterScan {
171+
self.showShareDialog(with: url)
172+
} else {
173+
Self.showFirstDocumentFinishedDialogIfNeeded()
174+
}
175+
#endif
187176
}
188-
.assign(to: &$sheetType)
177+
.store(in: &disposables)
178+
}
189179

180+
@ViewBuilder
181+
func getView(for sheetType: SheetType) -> some View {
182+
switch sheetType {
183+
case .iapView:
184+
IAPView(viewModel: iapViewModel)
185+
#if canImport(MessageUI)
186+
case .supportView:
187+
SupportMailView(subject: Self.mailSubject,
188+
recipients: Self.mailRecipients,
189+
errorHandler: { NotificationCenter.default.postAlert($0) })
190+
#endif
191+
#if !os(macOS)
192+
case .activityView(let items):
193+
AppActivityView(activityItems: items)
190194
#endif
195+
}
191196
}
192197

193198
func handleTempFilesIfNeeded(_ scenePhase: ScenePhase) {
@@ -279,6 +284,16 @@ public final class MainNavigationViewModel: ObservableObject, Log {
279284
action: showSupport))
280285
}
281286

287+
#if !os(macOS)
288+
public func showScan(shareAfterScan: Bool) {
289+
withAnimation {
290+
currentTab = .scan
291+
scanViewModel.shareDocumentAfterScan = shareAfterScan
292+
scanViewModel.startScanning()
293+
}
294+
}
295+
#endif
296+
282297
// MARK: - Delegate Functions
283298

284299
private static func getDocumentDestination() -> URL? {
@@ -290,18 +305,9 @@ public final class MainNavigationViewModel: ObservableObject, Log {
290305
}
291306
}
292307

293-
// private func documentProcessingCompletionHandler(_ url: URL) {
294-
// guard scanViewModel.shareDocumentAfterScan else { return }
295-
//
296-
// #if !os(macOS)
297-
// // show share sheet
298-
// sheetType = .activityView(items: [url])
299-
// #endif
300-
// }
301-
302308
// MARK: - Helper Functions
303309

304-
private static func scanFinished() {
310+
private static func showFirstDocumentFinishedDialogIfNeeded() {
305311
guard !UserDefaults.appGroup.firstDocumentScanAlertPresented else { return }
306312
UserDefaults.appGroup.firstDocumentScanAlertPresented = true
307313

@@ -321,11 +327,29 @@ public final class MainNavigationViewModel: ObservableObject, Log {
321327
try imageConverter.handle(url)
322328
} catch {
323329
log.error("Unable to handle file.", metadata: ["filetype": "\(url.pathExtension)", "error": "\(error)"])
324-
// try? FileManager.default.removeItem(at: url)
330+
try? FileManager.default.removeItem(at: url)
325331

326332
NotificationCenter.default.postAlert(error)
327333
}
328334
}
335+
336+
#if !os(macOS)
337+
private func showShareDialog(with url: URL) {
338+
let formatter = DateFormatter()
339+
formatter.locale = .autoupdatingCurrent
340+
formatter.setLocalizedDateFormatFromTemplate("dd-MM-yyyy jmmssa")
341+
let dateString = formatter.string(from: Date()).replacingOccurrences(of: ":", with: ".").replacingOccurrences(of: ",", with: "")
342+
let filename = "PDF Archiver \(dateString).pdf"
343+
let destination = FileManager.default.temporaryDirectory.appendingPathComponent(filename)
344+
do {
345+
try FileManager.default.copyItem(at: url, to: destination)
346+
347+
self.sheetType = .activityView(items: [destination])
348+
} catch {
349+
NotificationCenter.default.postAlert(error)
350+
}
351+
}
352+
#endif
329353
}
330354

331355
extension MainNavigationViewModel {
@@ -377,7 +401,7 @@ extension MainNavigationViewModel {
377401
service.recipients = Self.mailRecipients
378402
service.subject = Self.mailSubject
379403

380-
let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("Diagnostics-Report.html")
404+
let url = FileManager.default.temporaryDirectory.appendingPathComponent("Diagnostics-Report.html")
381405

382406
// remove previous report
383407
try? FileManager.default.removeItem(at: url)

ArchiveCore/Sources/ArchiveViews/ScanTab/ScanTabView.swift

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -133,10 +133,7 @@ struct ScanTabView_Previews: PreviewProvider {
133133

134134
static var previews: some View {
135135
// swiftlint:disable:next trailing_closure
136-
ScanTabView(viewModel: ScanTabViewModel(imageConverter: ImageConverter(), iapService: MockIAPService(), documentsFinishedHandler: {
137-
print("Scan completed!")
138-
139-
}))
136+
ScanTabView(viewModel: ScanTabViewModel(imageConverter: ImageConverter(), iapService: MockIAPService()))
140137
.frame(maxWidth: .infinity)
141138
.padding()
142139
}

ArchiveCore/Sources/ArchiveViews/ScanTab/ScanTabViewModel.swift

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,13 @@ public final class ScanTabViewModel: ObservableObject, DropDelegate, Log {
3636

3737
private let imageConverter: ImageConverterAPI
3838
private let iapService: IAPServiceAPI
39-
private let documentsFinishedHandler: () -> Void
4039

4140
private var lastProgressValue: CGFloat?
4241
private var disposables = Set<AnyCancellable>()
4342

44-
public init(imageConverter: ImageConverterAPI, iapService: IAPServiceAPI, documentsFinishedHandler: @escaping () -> Void) {
43+
public init(imageConverter: ImageConverterAPI, iapService: IAPServiceAPI) {
4544
self.imageConverter = imageConverter
4645
self.iapService = iapService
47-
self.documentsFinishedHandler = documentsFinishedHandler
4846

4947
// show the processing indicator, if documents are currently processed
5048
if imageConverter.totalDocumentCount.value != 0 {
@@ -59,11 +57,6 @@ public final class ScanTabViewModel: ObservableObject, DropDelegate, Log {
5957
guard let self = self else { return }
6058
let documentProgress = notification.object as? Float
6159
self.updateProcessingIndicator(with: documentProgress)
62-
63-
guard documentProgress == nil else { return }
64-
65-
// there might be a better way for this inout workaround
66-
self.documentsFinishedHandler()
6760
}
6861
.store(in: &disposables)
6962
}

ArchiveCore/Sources/ArchiveViews/TagTab/TagTabViewModel.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ final class TagTabViewModel: ObservableObject, Log {
225225
guard let document = currentDocument else { return }
226226

227227
document.date = date
228-
document.specification = specification.slugified(withSeparator: "-")
228+
document.specification = specification.slugified(withSeparator: "-").lowercased()
229229
document.tags = Set(documentTags.map { $0.slugified(withSeparator: "") })
230230

231231
DispatchQueue.global(qos: .userInitiated).async {

ArchiveCore/Tests/ArchiveBackendTests/DeepDirectoryWatcherTests.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ final class DeepDirectoryWatcherTests: XCTestCase {
1616

1717
override func setUpWithError() throws {
1818
try super.setUpWithError()
19-
tempDir = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent(UUID().uuidString)
19+
tempDir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
2020

2121
guard let tempDir = tempDir else {
2222
XCTFail("TempDir could not be created.")

ArchiveCore/Tests/ArchiveBackendTests/DocumentTests.swift

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
//
77

88
@testable import ArchiveBackend
9+
import ArchiveSharedConstants
910
import XCTest
1011

1112
final class DocumentTests: XCTestCase {
@@ -231,7 +232,6 @@ final class DocumentTests: XCTestCase {
231232
func testComparableWithSameUUID() {
232233

233234
// setup
234-
_ = UUID()
235235
let document1 = Document(path: URL(fileURLWithPath: "~/Downloads/2018-05-12--example-description__tag1_tag2.pdf"), taggingStatus: .tagged, downloadStatus: defaultDownloadStatus, byteSize: defaultSize)
236236
let document2 = Document(path: URL(fileURLWithPath: "~/Downloads/2018-05-12--example-description__tag1_tag2.pdf"), taggingStatus: .tagged, downloadStatus: defaultDownloadStatus, byteSize: defaultSize)
237237

@@ -366,6 +366,18 @@ final class DocumentTests: XCTestCase {
366366
XCTAssertNil(tagNames)
367367
}
368368

369+
func testPlaceholder() {
370+
371+
// setup
372+
let document = Document(path: URL(fileURLWithPath: "~/Downloads/2018-05-12--\(Constants.documentDescriptionPlaceholder)__\(Constants.documentTagPlaceholder).pdf"), taggingStatus: .untagged, downloadStatus: defaultDownloadStatus, byteSize: defaultSize)
373+
374+
document.updateProperties(with: .local, shouldParseDate: false)
375+
376+
// assert - placeholders must not be in the tags or specification
377+
XCTAssertEqual(document.tags, [])
378+
XCTAssertEqual(document.specification, "")
379+
}
380+
369381
// func testDocumentRenamingPath() {
370382
//
371383
// // setup

ArchiveCore/Tests/ArchiveBackendTests/PDFProcessingTests.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import PDFKit
1212
import XCTest
1313

1414
final class PDFProcessingTests: XCTestCase {
15-
private static let tempFolder = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent(UUID().uuidString)
15+
private static let tempFolder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
1616
private static let referenceDocument = PDFDocument(url: Bundle.billPDFUrl)!
1717

1818
private let queue: OperationQueue = {

ArchiveCore/Tests/ArchiveBackendTests/PathManagerTests.swift

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import PDFKit
1212
import XCTest
1313

1414
final class PathManagerTests: XCTestCase {
15-
static let tempFolder = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent(UUID().uuidString)
15+
static let tempFolder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
1616

1717
override func setUpWithError() throws {
1818
try super.setUpWithError()
@@ -27,6 +27,7 @@ final class PathManagerTests: XCTestCase {
2727
#if os(macOS)
2828
func testArchiveChangeMacOS() throws {
2929
let currentArchiveFolder = Self.tempFolder.appendingPathComponent("CurrentArchive")
30+
XCTAssertNoThrow(try FileManager.default.createDirectory(at: currentArchiveFolder, withIntermediateDirectories: true, attributes: nil))
3031
UserDefaults.appGroup.archivePathType = .local(currentArchiveFolder)
3132

3233
let archiveUrl = try PathManager.shared.getArchiveUrl()

ArchiveCore/Tests/ArchiveSharedConstantsTests/FileManagerMoveTests.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ final class FileManagerMoveTests: XCTestCase {
4646

4747
override func setUpWithError() throws {
4848
try super.setUpWithError()
49-
tempDir = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent(UUID().uuidString)
49+
tempDir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
5050

5151
let url = try XCTUnwrap(tempDir)
5252

0 commit comments

Comments
 (0)