From ee69d23b5d19ead265202a8652f5f275df8559e7 Mon Sep 17 00:00:00 2001 From: TSI-amrutwaghmare <96108296+TSI-amrutwaghmare@users.noreply.github.com> Date: Tue, 21 Nov 2023 14:34:02 +0530 Subject: [PATCH 1/3] NMC 1988 - Scan customisation changes --- Tests/NextcloudUnitTests/ScanTests.swift | 111 ++ .../NCCreateFormUploadScanDocument.swift | 1273 +++++++++++++++++ .../Scan document/NCDocumentCamera.swift | 61 +- .../NMC Views/FileNameInputTextField.swift | 66 + .../NMC Views/FileNameInputTextField.xib | 81 ++ .../NMC Views/JPGImageSaveSwitchView.swift | 43 + .../NMC Views/JPGImageSaveSwitchView.xib | 63 + .../NMC Views/PNGImageSaveSwitchView.swift | 43 + .../NMC Views/PNGImageSaveSwitchView.xib | 63 + .../NMC Views/PasswordInputField.swift | 72 + .../NMC Views/PasswordInputField.xib | 70 + .../NMC Views/PdfWithOcrSwitchView.swift | 42 + .../NMC Views/PdfWithOcrSwitchView.xib | 74 + .../NMC Views/PdfWithoutOcrSwitchView.swift | 43 + .../NMC Views/PdfWithoutOcrSwitchView.xib | 74 + .../NMC Views/ScanDocumentPathView.swift | 33 + .../NMC Views/ScanDocumentPathView.xib | 74 + .../NMC Views/SetPDFPasswordSwitchView.swift | 52 + .../NMC Views/SetPDFPasswordSwitchView.xib | 78 + .../NMC Views/TextFileWithOcrSwitchView.swift | 40 + .../NMC Views/TextFileWithOcrSwitchView.xib | 63 + 21 files changed, 2514 insertions(+), 5 deletions(-) create mode 100644 Tests/NextcloudUnitTests/ScanTests.swift create mode 100644 iOSClient/Scan document/NCCreateFormUploadScanDocument.swift create mode 100644 iOSClient/Scan document/NMC Views/FileNameInputTextField.swift create mode 100644 iOSClient/Scan document/NMC Views/FileNameInputTextField.xib create mode 100644 iOSClient/Scan document/NMC Views/JPGImageSaveSwitchView.swift create mode 100644 iOSClient/Scan document/NMC Views/JPGImageSaveSwitchView.xib create mode 100644 iOSClient/Scan document/NMC Views/PNGImageSaveSwitchView.swift create mode 100644 iOSClient/Scan document/NMC Views/PNGImageSaveSwitchView.xib create mode 100644 iOSClient/Scan document/NMC Views/PasswordInputField.swift create mode 100644 iOSClient/Scan document/NMC Views/PasswordInputField.xib create mode 100644 iOSClient/Scan document/NMC Views/PdfWithOcrSwitchView.swift create mode 100644 iOSClient/Scan document/NMC Views/PdfWithOcrSwitchView.xib create mode 100644 iOSClient/Scan document/NMC Views/PdfWithoutOcrSwitchView.swift create mode 100644 iOSClient/Scan document/NMC Views/PdfWithoutOcrSwitchView.xib create mode 100644 iOSClient/Scan document/NMC Views/ScanDocumentPathView.swift create mode 100644 iOSClient/Scan document/NMC Views/ScanDocumentPathView.xib create mode 100644 iOSClient/Scan document/NMC Views/SetPDFPasswordSwitchView.swift create mode 100644 iOSClient/Scan document/NMC Views/SetPDFPasswordSwitchView.xib create mode 100644 iOSClient/Scan document/NMC Views/TextFileWithOcrSwitchView.swift create mode 100644 iOSClient/Scan document/NMC Views/TextFileWithOcrSwitchView.xib diff --git a/Tests/NextcloudUnitTests/ScanTests.swift b/Tests/NextcloudUnitTests/ScanTests.swift new file mode 100644 index 0000000000..750fc86d01 --- /dev/null +++ b/Tests/NextcloudUnitTests/ScanTests.swift @@ -0,0 +1,111 @@ +// +// ScanTests.swift +// NextcloudTests +// +// Created by A200020526 on 18/05/23. +// Copyright © 2023 Marino Faggiana. All rights reserved. +// + +@testable import Nextcloud +import XCTest +import XLForm + +final class ScanTests: XCTestCase { + + var viewController: NCCreateFormUploadScanDocument? + override func setUpWithError() throws { + // Put setup code here. This method is called before the invocation of each test method in the class. + viewController = NCCreateFormUploadScanDocument() + } + override func tearDownWithError() throws { + // Put teardown code here. This method is called after the invocation of each test method in the class. + viewController = nil + } + func testExample() throws { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. + // Any test you write for XCTest can be annotated as throws and async. + // Mark your test throws to produce an unexpected failure when your test encounters an uncaught error. + // Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards. + } + func testPerformanceExample() throws { + // This is an example of a performance test case. + self.measure { + // Put the code you want to measure the time of here. + } + } + public func testImageColor() { + // Create a test color + let testColor = UIColor.red + // Create a test image + let testImage = UIImage(named: "activityTypeInfo") // Replace "your_image_name" with the name of your test image + // Call the imageColor function with the test color + let resultImage = testImage?.imageColor(testColor) + // Assert that the result image is not nil + XCTAssertNotNil(resultImage, "Result image should not be nil") + // Assert that the result image has the same size as the test image + XCTAssertEqual(resultImage?.size, testImage?.size, "Result image should have the same size as the test image") + } + func testIsAtleastOneFiletypeSelected() { + // Set up the initial switch states + viewController?.isPDFWithOCRSwitchOn = false + viewController?.isPDFWithoutOCRSwitchOn = false + viewController?.isTextFileSwitchOn = false + viewController?.isPNGFormatSwitchOn = false + viewController?.isJPGFormatSwitchOn = false + + // Call the function under test + let result1 = viewController?.isAtleastOneFiletypeSelected() ?? false + + // Assert the initial result + XCTAssertFalse(result1, "None of the file types are selected initially") + + // Update switch states + viewController?.isPDFWithOCRSwitchOn = true + + // Call the function under test again + let result2 = viewController?.isAtleastOneFiletypeSelected() ?? false + + // Assert the updated result + XCTAssertTrue(result2, "At least one file type is selected") + } + + func testBestFittingFont() { + // Set up the initial values + let text = "Hello, World!" + let bounds = CGRect(x: 0, y: 0, width: 200, height: 100) + let fontDescriptor = UIFontDescriptor(name: "Helvetica", size: 20) + let fontColor = UIColor.black + + // Call the function under test + let attributes = viewController?.bestFittingFont(for: text, in: bounds, fontDescriptor: fontDescriptor, fontColor: fontColor) + + // Assert the results + XCTAssertNotNil(attributes?[NSAttributedString.Key.font], "Font attribute should not be nil") + XCTAssertNotNil(attributes?[NSAttributedString.Key.foregroundColor], "Font color attribute should not be nil") + XCTAssertNotNil(attributes?[NSAttributedString.Key.kern], "Kern attribute should not be nil") + + XCTAssertEqual(attributes?[NSAttributedString.Key.foregroundColor] as? UIColor, fontColor, "Font color should match the input value") + + let font = attributes?[NSAttributedString.Key.font] as? UIFont + XCTAssertNotNil(font, "Font should not be nil") + XCTAssertEqual(font?.fontName, fontDescriptor.fontAttributes[.name] as? String, "Font name should match the input value") + } + + func testChangeCompressionImage() { + // Set up the initial values + guard let image = UIImage(named: "activityTypeInfo") else { + return + } + + // Call the function under test + let compressedImage = viewController?.changeCompressionImage(image) + + // Assert the results + XCTAssertNotNil(compressedImage, "Compressed image should not be nil") + if let width = compressedImage?.size.width, let height = compressedImage?.size.height { + XCTAssertTrue(width <= 841.8, "Compressed image width should be less than or equal to the base width") + XCTAssertTrue(height <= 595.2, "Compressed image height should be less than or equal to the base height") + } + } +} diff --git a/iOSClient/Scan document/NCCreateFormUploadScanDocument.swift b/iOSClient/Scan document/NCCreateFormUploadScanDocument.swift new file mode 100644 index 0000000000..60e8b8cd0d --- /dev/null +++ b/iOSClient/Scan document/NCCreateFormUploadScanDocument.swift @@ -0,0 +1,1273 @@ +// +// NCCreateFormUploadScanDocument.swift +// Nextcloud +// +// Created by Marino Faggiana on 14/11/2018. +// Copyright © 2018 Marino Faggiana. All rights reserved. +// +// Author Marino Faggiana +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . +// + +import UIKit +import NextcloudKit +import Vision +import VisionKit +import Photos +import XLForm + +class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NCCreateFormUploadConflictDelegate { + + let appDelegate = UIApplication.shared.delegate as? AppDelegate + + enum TypeQuality { + case low + case medium + case high + } + var quality: TypeQuality = .medium + + var editorId = "" + var serverUrl = "" + var titleServerUrl = "" + var arrayImages: [UIImage] = [] + var fileName = CCUtility.createFileNameDate("scan", extension: "pdf") + var password: String = "" + var fileType = "PDF" + var isPDFWithOCRSwitchOn = false + var isPDFWithoutOCRSwitchOn = false + var isSetpasswordEnable = false + + var isTextFileSwitchOn = false + var isPNGFormatSwitchOn = false + var isJPGFormatSwitchOn = false + var isOCRActivatedFileConflicts = false + + + var cellBackgoundColor = NCBrandColor.shared.secondarySystemGroupedBackground + + // MARK: - View Life Cycle + + convenience init(serverUrl: String, arrayImages: [UIImage]) { + + self.init() + + if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate?.urlBase ?? "", userId: appDelegate?.userId ?? "") { + titleServerUrl = "/" + } else { + titleServerUrl = (serverUrl as NSString).lastPathComponent + } + + self.serverUrl = serverUrl + self.arrayImages = arrayImages + } + + // MARK: - View Life Cycle + + override func viewDidLoad() { + + super.viewDidLoad() + + self.title = NSLocalizedString("_save_settings_", comment: "") + + let saveButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save)) + + self.navigationItem.rightBarButtonItem = saveButton + let cancelButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(cancel)) + self.navigationItem.leftBarButtonItem = cancelButton + self.navigationItem.rightBarButtonItem?.tintColor = NCBrandColor.shared.brand + self.navigationItem.leftBarButtonItem?.tintColor = NCBrandColor.shared.brand + + self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none + + changeTheming() + + initializeForm() + + let value = CCUtility.getTextRecognitionStatus() + setTextRecognition(newValue: value) + NotificationCenter.default.addObserver(self, selector: #selector(appTerminateNotify), name: UIApplication.willTerminateNotification, object: nil) + } + + override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { + super.traitCollectionDidChange(previousTraitCollection) + + changeTheming() + } + + override func viewWillDisappear(_ animated: Bool) { + NotificationCenter.default.removeObserver(self) + showDeleteAlert() + } + + @objc func appTerminateNotify() { + showDeleteAlert() + } + // MARK: - Theming + + @objc func changeTheming() { + + view.backgroundColor = NCBrandColor.shared.secondarySystemGroupedBackground + tableView.backgroundColor = NCBrandColor.shared.secondarySystemGroupedBackground + cellBackgoundColor = NCBrandColor.shared.secondarySystemGroupedBackground + tableView.reloadData() + } + + // MARK: XLForm + + func initializeForm() { + + let form: XLFormDescriptor = XLFormDescriptor() as XLFormDescriptor + form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow + + var section: XLFormSectionDescriptor + var row: XLFormRowDescriptor + + // Section: Destination Folder + + section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: "")) + form.addFormSection(section) + + XLFormViewController.cellClassesForRowDescriptorTypes()["NMCScamFileNameCustomInputField"] = FileNameInputTextField.self + row = XLFormRowDescriptor(tag: "fileName", rowType: "NMCScamFileNameCustomInputField", title: NSLocalizedString("_filename_", comment: "")) + row.cellClass = FileNameInputTextField.self + row.cellConfig["fileNameInputTextField.placeholder"] = self.fileName + + row.cellConfig["fileNameInputTextField.textAlignment"] = NSTextAlignment.left.rawValue + row.cellConfig["fileNameInputTextField.font"] = UIFont.systemFont(ofSize: 15.0) + row.cellConfig["fileNameInputTextField.textColor"] = NCBrandColor.shared.label + + + section.addFormRow(row) + //FileName custom view END + + section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_location_", comment: "")) + form.addFormSection(section) + + //Scan documnet folder path + XLFormViewController.cellClassesForRowDescriptorTypes()["NMCScanFolderPathCustomCell"] = ScanDocumentPathView.self + row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: "NMCScanFolderPathCustomCell", title: self.titleServerUrl) + row.action.formSelector = #selector(changeDestinationFolder(_:)) + row.cellConfig["backgroundColor"] = cellBackgoundColor + row.cellConfig["folderImage.image"] = UIImage(named: "folder")?.imageColor(NCBrandColor.shared.customer) + row.cellConfig["photoLabel.textAlignment"] = NSTextAlignment.left.rawValue + row.cellConfig["photoLabel.font"] = UIFont.systemFont(ofSize: 15.0) + row.cellConfig["photoLabel.textColor"] = NCBrandColor.shared.label + if(self.titleServerUrl == "/"){ + row.cellConfig["photoLabel.text"] = NSLocalizedString("_prefix_upload_path_", comment: "") + }else{ + row.cellConfig["photoLabel.text"] = self.titleServerUrl + } + row.cellConfig["textLabel.text"] = "" + + section.addFormRow(row) + // END of Scan documnet folder path + + + section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_with_text_recognition_", comment: "")) + form.addFormSection(section) + + // Save with Text Recognition PDF + XLFormViewController.cellClassesForRowDescriptorTypes()["NMCPdfWithOCRSwitchCell"] = PdfWithOcrSwitchView.self + row = XLFormRowDescriptor(tag: "PDFWithOCRSwitch", rowType: "NMCPdfWithOCRSwitchCell", title: self.titleServerUrl) + row.cellConfig["cellLabel.text"] = NSLocalizedString("_pdf_with_ocr_", comment: "") + row.cellConfig["switchControl.onTintColor"] = NCBrandColor.shared.brand + row.cellConfig["cellLabel.font"] = UIFont.systemFont(ofSize: 15.0) + row.cellConfig["cellLabel.textColor"] = NCBrandColor.shared.label + + section.addFormRow(row) + // END of Save with Text Recognition PDF + + //Save with Text Recognition text file + XLFormViewController.cellClassesForRowDescriptorTypes()["NMCTextFileWithOCRSwitchCell"] = TextFileWithOcrSwitchView.self + row = XLFormRowDescriptor(tag: "TextFileWithOCRSwitch", rowType: "NMCTextFileWithOCRSwitchCell", title: self.titleServerUrl) + row.cellConfig["cellLabel.text"] = NSLocalizedString("_text_file_ocr_", comment: "") + row.cellConfig["switchControl.onTintColor"] = NCBrandColor.shared.brand + row.cellConfig["cellLabel.font"] = UIFont.systemFont(ofSize: 15.0) + row.cellConfig["cellLabel.textColor"] = NCBrandColor.shared.label + + section.addFormRow(row) + //END of Save with Text Recognition text file + + section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_without_text_recognition_", comment: "")) + form.addFormSection(section) + + // PDF without text recongnition + XLFormViewController.cellClassesForRowDescriptorTypes()["NMCPDFWithoutOCRSwitchCell"] = PdfWithoutOcrSwitchView.self + row = XLFormRowDescriptor(tag: "PDFWithoutOCRSwitch", rowType: "NMCPDFWithoutOCRSwitchCell", title: self.titleServerUrl) + row.cellConfig["cellLabel.text"] = NSLocalizedString("_pdf_", comment: "") + row.cellConfig["switchControl.onTintColor"] = NCBrandColor.shared.brand + row.cellConfig["cellLabel.font"] = UIFont.systemFont(ofSize: 15.0) + row.cellConfig["cellLabel.textColor"] = NCBrandColor.shared.label + + section.addFormRow(row) + // END of PDF without text recongnition + + // JPG without text recongnition + + XLFormViewController.cellClassesForRowDescriptorTypes()["NMCJPGWithoutOCRSwitchCell"] = JPGImageSaveSwitchView.self + row = XLFormRowDescriptor(tag: "JPGWithoutOCRSwitch", rowType: "NMCJPGWithoutOCRSwitchCell", title: self.titleServerUrl) + row.cellConfig["cellLabel.text"] = NSLocalizedString("_jpg_", comment: "") + row.cellConfig["switchControl.onTintColor"] = NCBrandColor.shared.brand + row.cellConfig["cellLabel.font"] = UIFont.systemFont(ofSize: 15.0) + row.cellConfig["cellLabel.textColor"] = NCBrandColor.shared.label + + section.addFormRow(row) + // END JPG without text recongnition + + // PNG without text recongnition + XLFormViewController.cellClassesForRowDescriptorTypes()["NMCPNGWithoutOCRSwitchCell"] = PNGImageSaveSwitchView.self + row = XLFormRowDescriptor(tag: "PNGWithoutOCRSwitch", rowType: "NMCPNGWithoutOCRSwitchCell", title: self.titleServerUrl) + row.cellConfig["cellLabel.text"] = NSLocalizedString("_png_", comment: "") + row.cellConfig["switchControl.onTintColor"] = NCBrandColor.shared.brand + row.cellConfig["cellLabel.font"] = UIFont.systemFont(ofSize: 15.0) + row.cellConfig["cellLabel.textColor"] = NCBrandColor.shared.label + + section.addFormRow(row) + // END without text recongnition + + // PDF password section + section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_pdf_password_", comment: "")) + form.addFormSection(section) + // END of PDF password + + // Set PDF password switch + XLFormViewController.cellClassesForRowDescriptorTypes()["NMCSetPDFPasswordSwitchCell"] = SetPDFPasswordSwitchView.self + row = XLFormRowDescriptor(tag: "PDFSetPasswordSwitch", rowType: "NMCSetPDFPasswordSwitchCell", title: self.titleServerUrl) + row.cellConfig["cellLabel.text"] = NSLocalizedString("_set_password_", comment: "") + row.cellConfig["switchControl.onTintColor"] = NCBrandColor.shared.brand + row.cellConfig["cellLabel.font"] = UIFont.systemFont(ofSize: 15.0) + row.cellConfig["cellLabel.textColor"] = NCBrandColor.shared.label + + section.addFormRow(row) + // END of set PDF password switch + + // enter password input field + XLFormViewController.cellClassesForRowDescriptorTypes()["NMCSetPasswordCustomInputField"] = PasswordInputField.self + row = XLFormRowDescriptor(tag: "SetPasswordInputField", rowType: "NMCSetPasswordCustomInputField", title: NSLocalizedString("_filename_", comment: "")) + row.cellClass = PasswordInputField.self + row.cellConfig["fileNameInputTextField.placeholder"] = NSLocalizedString("_password_", comment: "") + + row.cellConfig["fileNameInputTextField.textAlignment"] = NSTextAlignment.left.rawValue + row.cellConfig["fileNameInputTextField.font"] = UIFont.systemFont(ofSize: 15.0) + row.cellConfig["fileNameInputTextField.textColor"] = NCBrandColor.shared.label + row.cellConfig["backgroundColor"] = NCBrandColor.shared.secondarySystemGroupedBackground + row.hidden = 1 + + + section.addFormRow(row) + + // Section: Password + + section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_pdf_password_", comment: "")) + // form.addFormSection(section) + + row = XLFormRowDescriptor(tag: "password", rowType: XLFormRowDescriptorTypePassword, title: NSLocalizedString("_password_", comment: "")) + row.cellConfig["backgroundColor"] = NCBrandColor.shared.backgroundForm + + row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0) + row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label + + row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue + row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0) + row.cellConfig["textField.textColor"] = NCBrandColor.shared.label + + self.form = form + } + + override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) { + + super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue) + + if formRow.tag == "textRecognition" { + + } + + if formRow.tag == "fileName" { + + self.form.delegate = nil + + let fileNameNew = newValue as? String + + if fileNameNew != nil { + self.fileName = CCUtility.removeForbiddenCharactersServer(fileNameNew) + } else { + self.fileName = "" + } + + formRow.value = self.fileName + + self.updateFormRow(formRow) + + self.form.delegate = self + } + + if formRow.tag == "password" { + let stringPassword = newValue as? String + if stringPassword != nil { + password = stringPassword! + } else { + password = "" + } + } + + if formRow.tag == "filetype" { + fileType = newValue as? String ?? "" + + let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")! + let rowPassword : XLFormRowDescriptor = self.form.formRow(withTag: "password")! + rowFileName.value = createFileName(rowFileName.value as? String) + + self.updateFormRow(rowFileName) + + // rowPassword + if fileType == "JPG" || fileType == "TXT" { + rowPassword.value = "" + password = "" + rowPassword.disabled = true + } else { + rowPassword.disabled = false + } + + self.updateFormRow(rowPassword) + } + + if formRow.tag == "PDFSetPasswordSwitch"{ + + isSetpasswordEnable = (formRow.value! as AnyObject).boolValue + let setPasswordInputField : XLFormRowDescriptor = self.form.formRow(withTag: "SetPasswordInputField")! + if (formRow.value! as AnyObject).boolValue == true { + setPasswordInputField.hidden = 0 + }else { + setPasswordInputField.hidden = 1 + } + } + + if formRow.tag == "PDFWithOCRSwitch"{ + //TODO + print("In PDF with OCR: value for without OCR \(isPDFWithoutOCRSwitchOn)") + isPDFWithOCRSwitchOn = (formRow.value! as AnyObject).boolValue + if (!isPDFWithoutOCRSwitchOn){ + if (formRow.value! as AnyObject).boolValue == true { + let setPasswordSwitchOption : XLFormRowDescriptor = self.form.formRow(withTag: "PDFSetPasswordSwitch")! + setPasswordSwitchOption.cellConfig["cellLabel.textColor"] = NCBrandColor.shared.label//isEnabled + setPasswordSwitchOption.value = "enable_switch" + + self.tableView.reloadData() + }else{ + let setPasswordSwitchOption : XLFormRowDescriptor = self.form.formRow(withTag: "PDFSetPasswordSwitch")! + setPasswordSwitchOption.cellConfig["cellLabel.textColor"] = NCBrandColor.shared.graySoft + setPasswordSwitchOption.disabled = true + setPasswordSwitchOption.value = "disable_switch" + self.tableView.reloadData() + + } + } + + } + + if formRow.tag == "PDFWithoutOCRSwitch"{ + print("In PDF without OCR: value for with OCR \(isPDFWithOCRSwitchOn)") + + isPDFWithoutOCRSwitchOn = (formRow.value! as AnyObject).boolValue + if(!isPDFWithOCRSwitchOn){ + if (formRow.value! as AnyObject).boolValue == true { + let setPasswordSwitchOption : XLFormRowDescriptor = self.form.formRow(withTag: "PDFSetPasswordSwitch")! + setPasswordSwitchOption.cellConfig["cellLabel.textColor"] = NCBrandColor.shared.label//isEnabled + setPasswordSwitchOption.value = "enable_switch" + + self.tableView.reloadData() + }else{ + let setPasswordSwitchOption : XLFormRowDescriptor = self.form.formRow(withTag: "PDFSetPasswordSwitch")! + setPasswordSwitchOption.cellConfig["cellLabel.textColor"] = NCBrandColor.shared.graySoft + setPasswordSwitchOption.disabled = true + setPasswordSwitchOption.value = "disable_switch" + self.tableView.reloadData() + + } + } + + } + + if formRow.tag == "SetPasswordInputField" { + let stringPassword = newValue as? String + if stringPassword != nil { + password = stringPassword! + } else { + password = "" + } + } + + if formRow.tag == "TextFileWithOCRSwitch" { + isTextFileSwitchOn = (formRow.value! as AnyObject).boolValue + self.setTextRecognition(newValue: newValue as? Bool ?? false) + } + if formRow.tag == "JPGWithoutOCRSwitch" { + isJPGFormatSwitchOn = (formRow.value! as AnyObject).boolValue + } + if formRow.tag == "PNGWithoutOCRSwitch" { + isPNGFormatSwitchOn = (formRow.value! as AnyObject).boolValue + } + + + } + + + override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { + return 4 + } + func setTextRecognition(newValue: Bool) { + + let rowFileName: XLFormRowDescriptor = self.form.formRow(withTag: "fileName")! + + self.form.delegate = nil + fileType = "PDF" + rowFileName.value = createFileName(rowFileName.value as? String) + self.updateFormRow(rowFileName) + self.tableView.reloadData() + + CCUtility.setTextRecognitionStatus(newValue) + + self.form.delegate = self + } + + func createFileName(_ fileName: String?) -> String { + + var name: String = "" + var newFileName: String = "" + + if fileName == nil || fileName == "" { + name = CCUtility.createFileNameDate("scan", extension: "pdf") ?? "scan.pdf" + } else { + name = fileName! + } + + let ext = (name as NSString).pathExtension.uppercased() + + if ext == "" { + newFileName = name + "." + fileType.lowercased() + } else { + newFileName = (name as NSString).deletingPathExtension + "." + fileType.lowercased() + } + + return newFileName + } + + // MARK: - Action + + func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], indexPath: [IndexPath], overwrite: Bool, copy: Bool, move: Bool) { + + if serverUrl != nil { + + self.serverUrl = serverUrl! + + if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate?.urlBase ?? "", userId: appDelegate?.userId ?? "") { + self.titleServerUrl = "/" + } else { + self.titleServerUrl = (serverUrl! as NSString).lastPathComponent + } + + // Update + let row : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")! + row.title = self.titleServerUrl + row.cellConfig["photoLabel.text"] = self.titleServerUrl + self.updateFormRow(row) + } + } + + func startProcessForSaving(){ + + let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")! + guard let name = rowFileName.value else { + return + } + if name as? String == "" { + return + } + + let ext = (name as? NSString)?.pathExtension.uppercased() + var fileNameSave = "" + + if ext == "" { + fileNameSave = (name as? String ?? "") + "." + fileType.lowercased() + } else { + fileNameSave = ((name as? NSString)?.deletingPathExtension ?? "") + "." + fileType.lowercased() + } + + + NCActivityIndicator.shared.startActivity(backgroundView: self.view, style: .medium) + + saveImages(fileNameSave: fileNameSave,fileType: "jpg",metadataConflict: nil,completion: { (success) -> Void in + print("jpg line of code executed") + if success { // this will be equal to whatever value is set in this method call + print("true") + saveImages(fileNameSave: fileNameSave,fileType: "png",metadataConflict: nil,completion: { (success) -> Void in + print("png line of code executed") + if success { + if(isPDFWithOCRSwitchOn){ + savePDF(ocrSwitchOn: true,completion: {(success) -> Void in + if success{ + if(isPDFWithoutOCRSwitchOn){ + savePDF(ocrSwitchOn: false, completion: {(success) -> Void in + if success{ + //Save Text File + if(isTextFileSwitchOn){ + saveTxtFile(completion: {(success) -> Void in + if success{ + //DELETE Files + showDeleteAlert() + NCActivityIndicator.shared.stop() + } + }) + }else{ + //DELETE files + showDeleteAlert() + NCActivityIndicator.shared.stop() + } + } + }) + }else{ + //Save Text File + if(isTextFileSwitchOn){ + saveTxtFile(completion: {(success) -> Void in + if success{ + //DELETE Files + showDeleteAlert() + NCActivityIndicator.shared.stop() + } + }) + }else{ + //DELETE files + showDeleteAlert() + NCActivityIndicator.shared.stop() + } + } + } + }) + }else { + if(isPDFWithoutOCRSwitchOn){ + savePDF(ocrSwitchOn: false, completion: {(success) -> Void in + if success{ + //Save Text File + if(isTextFileSwitchOn){ + saveTxtFile(completion: {(success) -> Void in + if success{ + //DELETE Files + showDeleteAlert() + NCActivityIndicator.shared.stop() + } + }) + }else{ + //DELETE files + showDeleteAlert() + NCActivityIndicator.shared.stop() + } + } + }) + }else{ + //Save Text File + if(isTextFileSwitchOn){ + saveTxtFile(completion: {(success) -> Void in + if success{ + //DELETE Files + showDeleteAlert() + NCActivityIndicator.shared.stop() + } + }) + }else{ + //DELETE files + showDeleteAlert() + NCActivityIndicator.shared.stop() + } + } + } + } + }) + } + }) + } + + + @objc func save() { + let password = (getPasswordFromField() ?? "").trimmingCharacters(in: .whitespaces) + self.password = password + + if(isSetpasswordEnable && password == ""){ + showAlert() + return + } + + if(!isAtleastOneFiletypeSelected()){ + + let alertController = UIAlertController(title: "", message: NSLocalizedString("_no_file_type_selection_error_", comment: ""), preferredStyle: .alert) + let alertWindow = UIWindow(frame: UIScreen.main.bounds) + alertWindow.windowLevel = UIWindow.Level.alert + alertWindow.rootViewController = UIViewController() + alertWindow.makeKeyAndVisible() + let actionOk = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default) { (action:UIAlertAction) in + alertController.dismiss(animated: true, completion: nil) + } + + alertController.addAction(actionOk) + self.present(alertController, animated: true) + }else { + // Request delete all image scanned + let alertController = UIAlertController(title: "", message: NSLocalizedString("_saved_info_alert_", comment: ""), preferredStyle: .alert) + let alertWindow = UIWindow(frame: UIScreen.main.bounds) + alertWindow.windowLevel = UIWindow.Level.alert + alertWindow.rootViewController = UIViewController() + alertWindow.makeKeyAndVisible() + let actionOk = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default) { (action:UIAlertAction) in + self.startProcessForSaving() + alertController.dismiss(animated: true, completion: nil) + } + + alertController.addAction(actionOk) + self.present(alertController, animated: true) + } + + } + + func showAlert(){ + // Request delete all image scanned + let alertController = UIAlertController(title: "", message: NSLocalizedString("_no_password_warn_", comment: ""), preferredStyle: .alert) + let alertWindow = UIWindow(frame: UIScreen.main.bounds) + alertWindow.windowLevel = UIWindow.Level.alert + alertWindow.rootViewController = UIViewController() + alertWindow.makeKeyAndVisible() + let actionOk = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default) { (action:UIAlertAction) in + alertController.dismiss(animated: true, completion: nil) + } + + alertController.addAction(actionOk) + //alertWindow.addSubview(alertController) + self.present(alertController, animated: true) + //alertWindow.rootViewController?.present(alertController, animated: true, completion: nil) + + } + + func showAlertForInfo(){ + // Request delete all image scanned + let alertController = UIAlertController(title: "", message: NSLocalizedString("_saved_info_alert_", comment: ""), preferredStyle: .alert) + let alertWindow = UIWindow(frame: UIScreen.main.bounds) + alertWindow.windowLevel = UIWindow.Level.alert + alertWindow.rootViewController = UIViewController() + alertWindow.makeKeyAndVisible() + let actionOk = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default) { (action:UIAlertAction) in + alertController.dismiss(animated: true, completion: nil) + } + + alertController.addAction(actionOk) + //alertWindow.addSubview(alertController) + self.present(alertController, animated: true) + } + func saveTxtFile(completion: (Bool) -> ()){ + + let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")! + guard var name = rowFileName.value else { + return + } + if name as? String == "" { + return + } + + for count in 0.. ()){ + + let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")! + guard var name = rowFileName.value else { + return + } + if name as? String == "" { + return + } + + if (ocrSwitchOn){ + name = name as? String + } + + let ext = (name as? NSString)?.pathExtension.uppercased() + var fileNameSave = "" + + if (ext == "") { + if (ocrSwitchOn){ + fileNameSave = (name as? String ?? "") + "_OCR" + "." + "pdf" + }else{ + fileNameSave = (name as? String ?? "") + "." + "pdf" + } + } else { + if(ocrSwitchOn){ + fileNameSave = ((name as? NSString)?.deletingPathExtension ?? "") + "_OCR" + "." + fileType.lowercased() + + }else{ + fileNameSave = ((name as? NSString)?.deletingPathExtension ?? "") + "." + fileType.lowercased() + } + } + + + let metadataForUpload = NCManageDatabase.shared.createMetadata(account: appDelegate?.account ?? "", user: appDelegate?.user ?? "", userId: appDelegate?.userId ?? "", fileName: fileNameSave, fileNameView: fileNameSave, ocId: UUID().uuidString, serverUrl: serverUrl, urlBase: appDelegate?.urlBase ?? "", url: "", contentType: "", isLivePhoto: false) + + metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground + metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile + metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload + + NCActivityIndicator.shared.startActivity(backgroundView: self.view, style: .medium) + DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { + self.isPDFWithOCRSwitchOn = ocrSwitchOn + self.dismissAndUpload(metadataForUpload, fileType: "PDF") + } + + completion(true) + } + + fileprivate func showDeleteAlert() { + + let path = CCUtility.getDirectoryScan()! + + do { + let filePaths = try FileManager.default.contentsOfDirectory(atPath: path) + for filePath in filePaths { + try FileManager.default.removeItem(atPath: path + "/" + filePath) + } + } catch let error as NSError { + print("Error: \(error.debugDescription)") + } + + self.dismiss(animated: true, completion: nil) + } + + func saveImages(fileNameSave: String, fileType: String, metadataConflict: tableMetadata?, completion: (Bool) -> ()) { + + if(!isJPGFormatSwitchOn && fileType == "jpg"){ + completion(true) + return + }else if(!isPNGFormatSwitchOn && fileType == "png"){ + completion(true) + return + } + else { + let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")! + guard var name = rowFileName.value else { + return + } + if name as? String == "" { + return + } + + for count in 0.. 0 { + NCActivityIndicator.shared.startActivity(backgroundView: self.view, style: .medium) + + DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { + // if let metadata = metadatas![0] as? tableMetadata{ + if (metadatas![0].fileExtension == "jpg"){ + //TODO for jpg + self.dismissAndUpload(metadatas![0],fileType: "JPG") + NCActivityIndicator.shared.stop() + + }else if(metadatas![0].fileExtension == "png") { + //TODO for png + self.dismissAndUpload(metadatas![0],fileType: "PNG") + NCActivityIndicator.shared.stop() + + + }else if(metadatas![0].fileExtension == "pdf"){ + //TODO for pdf + self.isOCRActivatedFileConflicts = metadatas![0].fileName.contains("_OCR") + self.dismissAndUpload(metadatas![0],fileType: "PDF") + NCActivityIndicator.shared.stop() + + }else if(metadatas![0].fileExtension == "txt"){ + //TODO for txt + self.dismissAndUpload(metadatas![0],fileType: "TXT") + NCActivityIndicator.shared.stop() + + } + } + } + } + + func dismissAndUpload(_ metadata: tableMetadata, fileType: String?) { + + guard let fileNameGenerateExport = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else { + NCActivityIndicator.shared.stop() + + let error = NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_") + NCContentPresenter.shared.showError(error: error) + return + } + let fileUrl = URL(fileURLWithPath: fileNameGenerateExport) + + // Text Recognition TXT + // if fileType == "TXT" && self.form.formRow(withTag: "textRecognition")!.value as! Int == 1 { + if fileType == "TXT" { + + var textFile = "" + for image in self.arrayImages { + + let requestHandler = VNImageRequestHandler(cgImage: image.cgImage!, options: [:]) + + let request = VNRecognizeTextRequest { request, _ in + guard let observations = request.results as? [VNRecognizedTextObservation] else { + NCActivityIndicator.shared.stop() + return + } + for observation in observations { + guard let textLine = observation.topCandidates(1).first else { + continue + } + + textFile += textLine.string + textFile += "\n" + } + } + + request.recognitionLevel = .accurate + request.usesLanguageCorrection = true + try? requestHandler.perform([request]) + } + + do { + + try textFile.write(to: fileUrl, atomically: true, encoding: .utf8) + } catch { + NCActivityIndicator.shared.stop() + let error = NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_") + NCContentPresenter.shared.showError(error: error) + return + } + } + + if fileType == "PDF" { + + let pdfData = NSMutableData() + + if !password.isEmpty { + for char in password.unicodeScalars { + if !char.isASCII { + NCActivityIndicator.shared.stop() + let error = NKError(errorCode: NCGlobal.shared.errorForbidden, errorDescription: "_password_ascii_") + NCContentPresenter.shared.showError(error: error) + return + } + } + let info: [AnyHashable: Any] = [kCGPDFContextUserPassword as String: password, kCGPDFContextOwnerPassword as String: password] + UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, info) + } else { + UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil) + } + var fontColor = UIColor.clear +#if targetEnvironment(simulator) + fontColor = UIColor.red +#endif + + for var image in self.arrayImages { + + image = changeCompressionImage(image) + + let bounds = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height) + + //self.form.formRow(withTag: "textRecognition")!.value as! Int == 1 + if isPDFWithOCRSwitchOn { + + UIGraphicsBeginPDFPageWithInfo(bounds, nil) + image.draw(in: bounds) + + let requestHandler = VNImageRequestHandler(cgImage: image.cgImage!, options: [:]) + + let request = VNRecognizeTextRequest { request, _ in + guard let observations = request.results as? [VNRecognizedTextObservation] else { + NCActivityIndicator.shared.stop() + return + } + for observation in observations { + guard let textLine = observation.topCandidates(1).first else { + continue + } + + var t: CGAffineTransform = CGAffineTransform.identity + t = t.scaledBy(x: image.size.width, y: -image.size.height) + t = t.translatedBy(x: 0, y: -1) + let rect = observation.boundingBox.applying(t) + let text = textLine.string + + let font = UIFont.systemFont(ofSize: rect.size.height, weight: .regular) + let attributes = self.bestFittingFont(for: text, in: rect, fontDescriptor: font.fontDescriptor, fontColor: fontColor) + + text.draw(with: rect, options: .usesLineFragmentOrigin, attributes: attributes, context: nil) + } + } + + request.recognitionLevel = .accurate + request.usesLanguageCorrection = true + try? requestHandler.perform([request]) + + } else { + + UIGraphicsBeginPDFPageWithInfo(bounds, nil) + image.draw(in: bounds) + } + } + + UIGraphicsEndPDFContext() + + do { + try pdfData.write(to: fileUrl, options: .atomic) + } catch { + print("error catched") + } + } + + if fileType == "JPG" { + + //let image = changeCompressionImage(self.arrayImages[0]) + + for image in self.arrayImages { + // let image = changeCompressionImage(self.arrayImages[0]) + guard let data = image.jpegData(compressionQuality: CGFloat(0.5)) else { + NCActivityIndicator.shared.stop() + NCContentPresenter.shared.messageNotification("_error_", error: NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_"), delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info) + return + } + + do { + try data.write(to: fileUrl, options: .atomic) + } catch { + NCActivityIndicator.shared.stop() + NCContentPresenter.shared.messageNotification("_error_", error: NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_"), delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info) + return + } + } + + + } + + if fileType == "PNG" { + + //let image = changeCompressionImage(self.arrayImages[0]) + + for image in self.arrayImages { + // let image = changeCompressionImage(self.arrayImages[0]) + guard let data = image.jpegData(compressionQuality: CGFloat(0.5)) else { + NCActivityIndicator.shared.stop() + NCContentPresenter.shared.messageNotification("_error_", error: NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_"), delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info) + return + } + + do { + try data.write(to: NSURL.fileURL(withPath: fileNameGenerateExport), options: .atomic) + } catch { + NCActivityIndicator.shared.stop() + NCContentPresenter.shared.messageNotification("_error_", error: NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_"), delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info) + return + } + } + } + + metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNameGenerateExport) + + NCActivityIndicator.shared.stop() + + NCNetworkingProcessUpload.shared.createProcessUploads(metadatas: [metadata], completion: { _ in }) + + // Request delete all image scanned + let alertController = UIAlertController(title: "", message: NSLocalizedString("_delete_all_scanned_images_", comment: ""), preferredStyle: .alert) + + let actionYes = UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (_: UIAlertAction) in + + let path = CCUtility.getDirectoryScan()! + + do { + let filePaths = try FileManager.default.contentsOfDirectory(atPath: path) + for filePath in filePaths { + try FileManager.default.removeItem(atPath: path + "/" + filePath) + } + } catch let error as NSError { + print("Error: \(error.debugDescription)") + } + + self.dismiss(animated: true, completion: nil) + } + + let actionNo = UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (_: UIAlertAction) in + self.dismiss(animated: true, completion: nil) + } + + alertController.addAction(actionYes) + alertController.addAction(actionNo) + self.present(alertController, animated: true, completion: nil) + } + + + @objc func cancel() { + + self.dismiss(animated: true, completion: nil) + } + + @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) { + + self.deselectFormRow(sender) + let storyboard = UIStoryboard(name: "NCSelect", bundle: nil) + if let navigationController = storyboard.instantiateInitialViewController() as? UINavigationController { + let viewController = navigationController.topViewController as? NCSelect + viewController?.delegate = self + viewController?.typeOfCommandView = .selectCreateFolder + viewController?.includeDirectoryE2EEncryption = true + self.present(navigationController, animated: true, completion: nil) + } + + } + + func changeCompressionImage(_ image: UIImage) -> UIImage { + + var compressionQuality: CGFloat = 0.5 + var baseHeight: Float = 595.2 // A4 + var baseWidth: Float = 841.8 // A4 + + switch quality { + case .low: + baseHeight *= 1 + baseWidth *= 1 + compressionQuality = 0.3 + case .medium: + baseHeight *= 2 + baseWidth *= 2 + compressionQuality = 0.6 + case .high: + baseHeight *= 4 + baseWidth *= 4 + compressionQuality = 0.9 + } + + var newHeight = Float(image.size.height) + var newWidth = Float(image.size.width) + var imgRatio: Float = newWidth / newHeight + let baseRatio: Float = baseWidth / baseHeight + + if newHeight > baseHeight || newWidth > baseWidth { + if imgRatio < baseRatio { + imgRatio = baseHeight / newHeight + newWidth = imgRatio * newWidth + newHeight = baseHeight + } else if imgRatio > baseRatio { + imgRatio = baseWidth / newWidth + newHeight = imgRatio * newHeight + newWidth = baseWidth + } else { + newHeight = baseHeight + newWidth = baseWidth + } + } + + let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(newWidth), height: CGFloat(newHeight)) + UIGraphicsBeginImageContext(rect.size) + image.draw(in: rect) + let img = UIGraphicsGetImageFromCurrentImageContext() + let imageData = img?.jpegData(compressionQuality: CGFloat(compressionQuality)) + UIGraphicsEndImageContext() + return UIImage(data: imageData!) ?? image + } + + func bestFittingFont(for text: String, in bounds: CGRect, fontDescriptor: UIFontDescriptor, fontColor: UIColor) -> [NSAttributedString.Key: Any] { + + let constrainingDimension = min(bounds.width, bounds.height) + let properBounds = CGRect(origin: .zero, size: bounds.size) + var attributes: [NSAttributedString.Key: Any] = [:] + + let infiniteBounds = CGSize(width: CGFloat.infinity, height: CGFloat.infinity) + var bestFontSize: CGFloat = constrainingDimension + + // Search font (H) + for fontSize in stride(from: bestFontSize, through: 0, by: -1) { + let newFont = UIFont(descriptor: fontDescriptor, size: fontSize) + attributes[.font] = newFont + + let currentFrame = text.boundingRect(with: infiniteBounds, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil) + + if properBounds.contains(currentFrame) { + bestFontSize = fontSize + break + } + } + + // Search kern (W) + let font = UIFont(descriptor: fontDescriptor, size: bestFontSize) + attributes = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: fontColor, NSAttributedString.Key.kern: 0] as [NSAttributedString.Key: Any] + for kern in stride(from: 0, through: 100, by: 0.1) { + let attributesTmp = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: fontColor, NSAttributedString.Key.kern: kern] as [NSAttributedString.Key: Any] + let size = text.size(withAttributes: attributesTmp).width + if size <= bounds.width { + attributes = attributesTmp + } else { + break + } + } + + return attributes + } + + func isAtleastOneFiletypeSelected() -> Bool{ + if(isPDFWithOCRSwitchOn + || isPDFWithoutOCRSwitchOn + || isTextFileSwitchOn + || isPNGFormatSwitchOn + || isJPGFormatSwitchOn){ + + return true + }else{ + return false + } + } + + func getPasswordFromField() -> String? { + if let setPasswordInputField : XLFormRowDescriptor = self.form.formRow(withTag: "SetPasswordInputField") { + var password = "" + if let indexPath = self.form.indexPath(ofFormRow: setPasswordInputField) { + let cell = tableView.cellForRow(at: indexPath) as? PasswordInputField + password = cell?.fileNameInputTextField.text ?? "" + } + return password + } + return nil + } +} + diff --git a/iOSClient/Scan document/NCDocumentCamera.swift b/iOSClient/Scan document/NCDocumentCamera.swift index b42cf3dd67..7dc5e773d9 100644 --- a/iOSClient/Scan document/NCDocumentCamera.swift +++ b/iOSClient/Scan document/NCDocumentCamera.swift @@ -32,6 +32,7 @@ class NCDocumentCamera: NSObject, VNDocumentCameraViewControllerDelegate { var viewController: UIViewController? let utilityFileSystem = NCUtilityFileSystem() + let appDelegate = UIApplication.shared.delegate as? AppDelegate func openScannerDocument(viewController: UIViewController) { @@ -66,11 +67,7 @@ class NCDocumentCamera: NSObject, VNDocumentCameraViewControllerDelegate { if let viewController = self.viewController as? NCScan { viewController.loadImage() } else { - let storyboard = UIStoryboard(name: "NCScan", bundle: nil) - let controller = storyboard.instantiateInitialViewController()! - - controller.modalPresentationStyle = UIModalPresentationStyle.pageSheet - self.viewController?.present(controller, animated: true, completion: nil) + self.reDirectToSave() } } } @@ -78,4 +75,58 @@ class NCDocumentCamera: NSObject, VNDocumentCameraViewControllerDelegate { func documentCameraViewControllerDidCancel(_ controller: VNDocumentCameraViewController) { controller.dismiss(animated: true, completion: nil) } + + func reDirectToSave(){ + var itemsSource: [String] = [] + + //Data Source for collectionViewDestination + var imagesDestination: [UIImage] = [] + var itemsDestination: [String] = [] + + do { + let atPath = CCUtility.getDirectoryScan()! + let directoryContents = try FileManager.default.contentsOfDirectory(atPath: atPath) + for fileName in directoryContents { + if fileName.first != "." { + itemsSource.append(fileName) + } + } + } catch { + print(error.localizedDescription) + } + + itemsSource = itemsSource.sorted() + + for fileName in itemsSource { + + if !itemsDestination.contains(fileName) { + + let fileNamePathAt = CCUtility.getDirectoryScan() + "/" + fileName + + guard let data = try? Data(contentsOf: URL(fileURLWithPath: fileNamePathAt)) else { return } + guard let image = UIImage(data: data) else { return } + + imagesDestination.append(image) + itemsDestination.append(fileName) + } + } + + if imagesDestination.count > 0 { + + var images: [UIImage] = [] + var serverUrl = appDelegate?.activeServerUrl ?? "" + + for image in imagesDestination { + images.append(image) + } + + let formViewController = NCCreateFormUploadScanDocument.init(serverUrl: serverUrl, arrayImages: images) + + formViewController.modalPresentationStyle = UIModalPresentationStyle.pageSheet + + let navigationController = UINavigationController(rootViewController: formViewController) + + self.viewController?.present(navigationController, animated: true, completion: nil) + } + } } diff --git a/iOSClient/Scan document/NMC Views/FileNameInputTextField.swift b/iOSClient/Scan document/NMC Views/FileNameInputTextField.swift new file mode 100644 index 0000000000..b074dcd2b8 --- /dev/null +++ b/iOSClient/Scan document/NMC Views/FileNameInputTextField.swift @@ -0,0 +1,66 @@ +// +// FileNameInputTextField.swift +// Nextcloud +// +// Created by Sumit on 03/06/21. +// Copyright © 2021 Marino Faggiana. All rights reserved. +// + +import Foundation + +class FileNameInputTextField: XLFormBaseCell,UITextFieldDelegate { + + @IBOutlet weak var fileNameInputTextField: UITextField! + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + + fileNameInputTextField.delegate = self + } + + override func setSelected(_ selected: Bool, animated: Bool) { + super.setSelected(selected, animated: animated) + + // Configure the view for the selected state + } + + override func configure() { + super.configure() + } + + override func update() { + super.update() + } + + func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { + + if fileNameInputTextField == textField { + if let rowDescriptor = rowDescriptor, let text = self.fileNameInputTextField.text { + + if (text + " ").isEmpty == false { + rowDescriptor.value = self.fileNameInputTextField.text! + string + } else { + rowDescriptor.value = nil + } + } + } + + self.formViewController().textField(textField, shouldChangeCharactersIn: range, replacementString: string) + + return true + } + + func textFieldShouldReturn(_ textField: UITextField) -> Bool { + self.formViewController()?.textFieldShouldReturn(fileNameInputTextField) + return true + } + + func textFieldShouldClear(_ textField: UITextField) -> Bool { + self.formViewController()?.textFieldShouldClear(fileNameInputTextField) + return true + } + + override class func formDescriptorCellHeight(for rowDescriptor: XLFormRowDescriptor!) -> CGFloat { + return 45 + } +} diff --git a/iOSClient/Scan document/NMC Views/FileNameInputTextField.xib b/iOSClient/Scan document/NMC Views/FileNameInputTextField.xib new file mode 100644 index 0000000000..173862a3ae --- /dev/null +++ b/iOSClient/Scan document/NMC Views/FileNameInputTextField.xib @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/iOSClient/Scan document/NMC Views/JPGImageSaveSwitchView.swift b/iOSClient/Scan document/NMC Views/JPGImageSaveSwitchView.swift new file mode 100644 index 0000000000..c3b94d8916 --- /dev/null +++ b/iOSClient/Scan document/NMC Views/JPGImageSaveSwitchView.swift @@ -0,0 +1,43 @@ +// +// JPGmageSaveSwitchView.swift +// Nextcloud +// +// Created by Sumit on 04/06/21. +// Copyright © 2021 Marino Faggiana. All rights reserved. +// + +import Foundation + + +class JPGImageSaveSwitchView: XLFormBaseCell{ + @IBOutlet weak var cellLabel: UILabel! + @IBOutlet weak var switchControl: UISwitch! + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + self.selectionStyle = .none + switchControl.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged) + + } + + override func configure() { + super.configure() + } + + override func update() { + super.update() + } + + @objc func switchChanged(mySwitch: UISwitch) { + let value = mySwitch.isOn + // Do something + + if value { + //on + self.rowDescriptor.value = value + }else{ + self.rowDescriptor.value = value + } + } +} diff --git a/iOSClient/Scan document/NMC Views/JPGImageSaveSwitchView.xib b/iOSClient/Scan document/NMC Views/JPGImageSaveSwitchView.xib new file mode 100644 index 0000000000..8658100453 --- /dev/null +++ b/iOSClient/Scan document/NMC Views/JPGImageSaveSwitchView.xib @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/iOSClient/Scan document/NMC Views/PNGImageSaveSwitchView.swift b/iOSClient/Scan document/NMC Views/PNGImageSaveSwitchView.swift new file mode 100644 index 0000000000..371b562706 --- /dev/null +++ b/iOSClient/Scan document/NMC Views/PNGImageSaveSwitchView.swift @@ -0,0 +1,43 @@ +// +// PNGImageSaveSwitchView.swift +// Nextcloud +// +// Created by Sumit on 09/06/21. +// Copyright © 2021 Marino Faggiana. All rights reserved. +// + +import Foundation + + +class PNGImageSaveSwitchView: XLFormBaseCell{ + @IBOutlet weak var cellLabel: UILabel! + @IBOutlet weak var switchControl: UISwitch! + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + self.selectionStyle = .none + switchControl.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged) + + } + + override func configure() { + super.configure() + } + + override func update() { + super.update() + } + + @objc func switchChanged(mySwitch: UISwitch) { + let value = mySwitch.isOn + // Do something + + if value { + //on + self.rowDescriptor.value = value + }else{ + self.rowDescriptor.value = value + } + } +} diff --git a/iOSClient/Scan document/NMC Views/PNGImageSaveSwitchView.xib b/iOSClient/Scan document/NMC Views/PNGImageSaveSwitchView.xib new file mode 100644 index 0000000000..d3c7312316 --- /dev/null +++ b/iOSClient/Scan document/NMC Views/PNGImageSaveSwitchView.xib @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/iOSClient/Scan document/NMC Views/PasswordInputField.swift b/iOSClient/Scan document/NMC Views/PasswordInputField.swift new file mode 100644 index 0000000000..6f7a9609c7 --- /dev/null +++ b/iOSClient/Scan document/NMC Views/PasswordInputField.swift @@ -0,0 +1,72 @@ +// +// PasswordInputField.swift +// Nextcloud +// +// Created by Sumit on 10/06/21. +// Copyright © 2021 Marino Faggiana. All rights reserved. +// + +import Foundation + +class PasswordInputField: XLFormBaseCell,UITextFieldDelegate { + + @IBOutlet weak var fileNameInputTextField: UITextField! + @IBOutlet weak var separatorBottom: UIView! + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + fileNameInputTextField.isSecureTextEntry = true + fileNameInputTextField.delegate = self + separatorBottom.backgroundColor = NCBrandColor.shared.systemGray4 + self.selectionStyle = .none + } + + override func setSelected(_ selected: Bool, animated: Bool) { + super.setSelected(selected, animated: animated) + + // Configure the view for the selected state + } + + override func configure() { + super.configure() + // fileNameInputTextField.isEnabled = false + + } + + override func update() { + super.update() + } + + func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { + + if fileNameInputTextField == textField { + if let rowDescriptor = rowDescriptor, let text = self.fileNameInputTextField.text { + + if (text + " ").isEmpty == false { + rowDescriptor.value = self.fileNameInputTextField.text! + string + } else { + rowDescriptor.value = nil + } + } + } + + self.formViewController().textField(textField, shouldChangeCharactersIn: range, replacementString: string) + + return true + } + + func textFieldShouldReturn(_ textField: UITextField) -> Bool { + self.formViewController()?.textFieldShouldReturn(fileNameInputTextField) + return true + } + + func textFieldShouldClear(_ textField: UITextField) -> Bool { + self.formViewController()?.textFieldShouldClear(fileNameInputTextField) + return true + } + + override class func formDescriptorCellHeight(for rowDescriptor: XLFormRowDescriptor!) -> CGFloat { + return 45 + } +} diff --git a/iOSClient/Scan document/NMC Views/PasswordInputField.xib b/iOSClient/Scan document/NMC Views/PasswordInputField.xib new file mode 100644 index 0000000000..26914e0760 --- /dev/null +++ b/iOSClient/Scan document/NMC Views/PasswordInputField.xib @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/iOSClient/Scan document/NMC Views/PdfWithOcrSwitchView.swift b/iOSClient/Scan document/NMC Views/PdfWithOcrSwitchView.swift new file mode 100644 index 0000000000..140d68ca67 --- /dev/null +++ b/iOSClient/Scan document/NMC Views/PdfWithOcrSwitchView.swift @@ -0,0 +1,42 @@ +// +// PdfWithOcrSwitchView.swift +// Nextcloud +// +// Created by Sumit on 04/06/21. +// Copyright © 2021 Marino Faggiana. All rights reserved. +// + +import Foundation + +class PdfWithOcrSwitchView: XLFormBaseCell{ + @IBOutlet weak var cellLabel: UILabel! + @IBOutlet weak var switchControl: UISwitch! + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + self.selectionStyle = .none + switchControl.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged) + + } + + override func configure() { + super.configure() + } + + override func update() { + super.update() + } + + @objc func switchChanged(mySwitch: UISwitch) { + let value = mySwitch.isOn + // Do something + + if value { + //on + self.rowDescriptor.value = value + }else{ + self.rowDescriptor.value = value + } + } +} diff --git a/iOSClient/Scan document/NMC Views/PdfWithOcrSwitchView.xib b/iOSClient/Scan document/NMC Views/PdfWithOcrSwitchView.xib new file mode 100644 index 0000000000..06cdcae9b6 --- /dev/null +++ b/iOSClient/Scan document/NMC Views/PdfWithOcrSwitchView.xib @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/iOSClient/Scan document/NMC Views/PdfWithoutOcrSwitchView.swift b/iOSClient/Scan document/NMC Views/PdfWithoutOcrSwitchView.swift new file mode 100644 index 0000000000..8065abe710 --- /dev/null +++ b/iOSClient/Scan document/NMC Views/PdfWithoutOcrSwitchView.swift @@ -0,0 +1,43 @@ +// +// PdfWithoutOcrSwitchView.swift +// Nextcloud +// +// Created by Sumit on 04/06/21. +// Copyright © 2021 Marino Faggiana. All rights reserved. +// + +import Foundation + + +class PdfWithoutOcrSwitchView: XLFormBaseCell{ + @IBOutlet weak var cellLabel: UILabel! + @IBOutlet weak var switchControl: UISwitch! + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + self.selectionStyle = .none + switchControl.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged) + + } + + override func configure() { + super.configure() + } + + override func update() { + super.update() + } + + @objc func switchChanged(mySwitch: UISwitch) { + let value = mySwitch.isOn + // Do something + + if value { + //on + self.rowDescriptor.value = value + }else{ + self.rowDescriptor.value = value + } + } +} diff --git a/iOSClient/Scan document/NMC Views/PdfWithoutOcrSwitchView.xib b/iOSClient/Scan document/NMC Views/PdfWithoutOcrSwitchView.xib new file mode 100644 index 0000000000..46ebf565f7 --- /dev/null +++ b/iOSClient/Scan document/NMC Views/PdfWithoutOcrSwitchView.xib @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/iOSClient/Scan document/NMC Views/ScanDocumentPathView.swift b/iOSClient/Scan document/NMC Views/ScanDocumentPathView.swift new file mode 100644 index 0000000000..8c3b1bec19 --- /dev/null +++ b/iOSClient/Scan document/NMC Views/ScanDocumentPathView.swift @@ -0,0 +1,33 @@ +// +// ScanDocumentPathView.swift +// Nextcloud +// +// Created by Sumit on 03/06/21. +// Copyright © 2021 Marino Faggiana. All rights reserved. +// + +import Foundation + +class ScanDocumentPathView: XLFormButtonCell{ + + @IBOutlet weak var photoLabel: UILabel! + @IBOutlet weak var folderImage: UIImageView! + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + + + } + + override func configure() { + super.configure() + + + } + + override func update() { + super.update() + } + +} diff --git a/iOSClient/Scan document/NMC Views/ScanDocumentPathView.xib b/iOSClient/Scan document/NMC Views/ScanDocumentPathView.xib new file mode 100644 index 0000000000..fa30321541 --- /dev/null +++ b/iOSClient/Scan document/NMC Views/ScanDocumentPathView.xib @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/iOSClient/Scan document/NMC Views/SetPDFPasswordSwitchView.swift b/iOSClient/Scan document/NMC Views/SetPDFPasswordSwitchView.swift new file mode 100644 index 0000000000..f5c46486ed --- /dev/null +++ b/iOSClient/Scan document/NMC Views/SetPDFPasswordSwitchView.swift @@ -0,0 +1,52 @@ +// +// SetPDFPasswordSwitchView.swift +// Nextcloud +// +// Created by Sumit on 10/06/21. +// Copyright © 2021 Marino Faggiana. All rights reserved. +// + +import Foundation + +class SetPDFPasswordSwitchView: XLFormBaseCell{ + @IBOutlet weak var cellLabel: UILabel! + @IBOutlet weak var switchControl: UISwitch! + + override func awakeFromNib() { + super.awakeFromNib() + // Initialization code + self.selectionStyle = .none + switchControl.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged) + + } + + override func configure() { + super.configure() + self.switchControl.isEnabled = false + } + + override func update() { + super.update() + + if let rowValue = rowDescriptor.value as? String { + if (rowValue == "disable_switch"){ + self.switchControl.isEnabled = false + self.switchControl.isOn = false + }else if(rowValue == "enable_switch"){ + self.switchControl.isEnabled = true + } + } + } + + @objc func switchChanged(mySwitch: UISwitch) { + let value = mySwitch.isOn + // Do something + + if value { + //on + self.rowDescriptor.value = value + }else{ + self.rowDescriptor.value = value + } + } +} diff --git a/iOSClient/Scan document/NMC Views/SetPDFPasswordSwitchView.xib b/iOSClient/Scan document/NMC Views/SetPDFPasswordSwitchView.xib new file mode 100644 index 0000000000..e0ddc1ca1a --- /dev/null +++ b/iOSClient/Scan document/NMC Views/SetPDFPasswordSwitchView.xib @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/iOSClient/Scan document/NMC Views/TextFileWithOcrSwitchView.swift b/iOSClient/Scan document/NMC Views/TextFileWithOcrSwitchView.swift new file mode 100644 index 0000000000..3d6efba15b --- /dev/null +++ b/iOSClient/Scan document/NMC Views/TextFileWithOcrSwitchView.swift @@ -0,0 +1,40 @@ +// +// TextFileWithOcrSwitchView.swift +// Nextcloud +// +// Created by Sumit on 04/06/21. +// Copyright © 2021 Marino Faggiana. All rights reserved. +// + +import Foundation + +class TextFileWithOcrSwitchView: XLFormBaseCell{ + @IBOutlet weak var switchControl: UISwitch! + @IBOutlet weak var cellLabel: UILabel! + + override func awakeFromNib() { + super.awakeFromNib() + self.selectionStyle = .none + switchControl.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged) + } + + override func configure() { + super.configure() + + } + + override func update() { + super.update() + } + + @objc func switchChanged(mySwitch: UISwitch) { + let value = mySwitch.isOn + if value { + //on + self.rowDescriptor.value = value + }else{ + self.rowDescriptor.value = value + } + } + +} diff --git a/iOSClient/Scan document/NMC Views/TextFileWithOcrSwitchView.xib b/iOSClient/Scan document/NMC Views/TextFileWithOcrSwitchView.xib new file mode 100644 index 0000000000..5f0ff73601 --- /dev/null +++ b/iOSClient/Scan document/NMC Views/TextFileWithOcrSwitchView.xib @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 3185e1c1e4c9532432368b7f69890b1cf01d8875 Mon Sep 17 00:00:00 2001 From: TSI-amrutwaghmare <96108296+TSI-amrutwaghmare@users.noreply.github.com> Date: Fri, 1 Dec 2023 13:34:04 +0530 Subject: [PATCH 2/3] NMC 1988 - Merging changes after Nextcloud release 4.9.2 --- .../NCCreateFormUploadScanDocument.swift | 58 ++++++++----------- .../Scan document/NCDocumentCamera.swift | 4 +- 2 files changed, 27 insertions(+), 35 deletions(-) diff --git a/iOSClient/Scan document/NCCreateFormUploadScanDocument.swift b/iOSClient/Scan document/NCCreateFormUploadScanDocument.swift index 60e8b8cd0d..071d2a49d1 100644 --- a/iOSClient/Scan document/NCCreateFormUploadScanDocument.swift +++ b/iOSClient/Scan document/NCCreateFormUploadScanDocument.swift @@ -43,7 +43,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC var serverUrl = "" var titleServerUrl = "" var arrayImages: [UIImage] = [] - var fileName = CCUtility.createFileNameDate("scan", extension: "pdf") + var fileName = NCUtilityFileSystem().createFileNameDate("scan", ext: "pdf") var password: String = "" var fileType = "PDF" var isPDFWithOCRSwitchOn = false @@ -57,6 +57,9 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC var cellBackgoundColor = NCBrandColor.shared.secondarySystemGroupedBackground + let utilityFileSystem = NCUtilityFileSystem() + let utility = NCUtility() + let contentPresenter = NCContentPresenter() // MARK: - View Life Cycle @@ -64,7 +67,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC self.init() - if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate?.urlBase ?? "", userId: appDelegate?.userId ?? "") { + if serverUrl == utilityFileSystem.getHomeServer(urlBase: appDelegate?.urlBase ?? "", userId: appDelegate?.userId ?? "") { titleServerUrl = "/" } else { titleServerUrl = (serverUrl as NSString).lastPathComponent @@ -96,7 +99,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC initializeForm() - let value = CCUtility.getTextRecognitionStatus() + let value = NCKeychain().textRecognitionStatus setTextRecognition(newValue: value) NotificationCenter.default.addObserver(self, selector: #selector(appTerminateNotify), name: UIApplication.willTerminateNotification, object: nil) } @@ -301,8 +304,8 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC let fileNameNew = newValue as? String - if fileNameNew != nil { - self.fileName = CCUtility.removeForbiddenCharactersServer(fileNameNew) + if let fileNameNew = newValue as? String { + self.fileName = utility.removeForbiddenCharacters(fileNameNew) } else { self.fileName = "" } @@ -438,7 +441,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC self.updateFormRow(rowFileName) self.tableView.reloadData() - CCUtility.setTextRecognitionStatus(newValue) + NCKeychain().textRecognitionStatus = newValue self.form.delegate = self } @@ -449,7 +452,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC var newFileName: String = "" if fileName == nil || fileName == "" { - name = CCUtility.createFileNameDate("scan", extension: "pdf") ?? "scan.pdf" + name = utilityFileSystem.createFileNameDate("scan", ext: "pdf") } else { name = fileName! } @@ -473,7 +476,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC self.serverUrl = serverUrl! - if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate?.urlBase ?? "", userId: appDelegate?.userId ?? "") { + if serverUrl == utilityFileSystem.getHomeServer(urlBase: appDelegate?.urlBase ?? "", userId: appDelegate?.userId ?? "") { self.titleServerUrl = "/" } else { self.titleServerUrl = (serverUrl! as NSString).lastPathComponent @@ -783,7 +786,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC fileprivate func showDeleteAlert() { - let path = CCUtility.getDirectoryScan()! + let path = utilityFileSystem.directoryScan do { let filePaths = try FileManager.default.contentsOfDirectory(atPath: path) @@ -860,16 +863,11 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { // self.dismissAndUpload(metadataForUpload, fileType: fileType.uppercased()) - guard let fileNameGenerateExport = CCUtility.getDirectoryProviderStorageOcId(metadataForUpload.ocId, fileNameView: metadataForUpload.fileNameView) else { - NCActivityIndicator.shared.stop() - let error = NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_") - NCContentPresenter.shared.showError(error: error) - return - } + let fileNameGenerateExport = self.utilityFileSystem.getDirectoryProviderStorageOcId(metadataForUpload.ocId, fileNameView: metadataForUpload.fileNameView) guard let data = image.jpegData(compressionQuality: CGFloat(0.5)) else { NCActivityIndicator.shared.stop() let error = NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_") - NCContentPresenter.shared.showError(error: error) + self.contentPresenter.showError(error: error) return } @@ -878,7 +876,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC } catch { NCActivityIndicator.shared.stop() let error = NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_") - NCContentPresenter.shared.showError(error: error) + self.contentPresenter.showError(error: error) return } @@ -928,13 +926,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC func dismissAndUpload(_ metadata: tableMetadata, fileType: String?) { - guard let fileNameGenerateExport = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else { - NCActivityIndicator.shared.stop() - - let error = NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_") - NCContentPresenter.shared.showError(error: error) - return - } + let fileNameGenerateExport = utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) let fileUrl = URL(fileURLWithPath: fileNameGenerateExport) // Text Recognition TXT @@ -972,7 +964,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC } catch { NCActivityIndicator.shared.stop() let error = NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_") - NCContentPresenter.shared.showError(error: error) + contentPresenter.showError(error: error) return } } @@ -986,7 +978,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC if !char.isASCII { NCActivityIndicator.shared.stop() let error = NKError(errorCode: NCGlobal.shared.errorForbidden, errorDescription: "_password_ascii_") - NCContentPresenter.shared.showError(error: error) + contentPresenter.showError(error: error) return } } @@ -1065,7 +1057,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC // let image = changeCompressionImage(self.arrayImages[0]) guard let data = image.jpegData(compressionQuality: CGFloat(0.5)) else { NCActivityIndicator.shared.stop() - NCContentPresenter.shared.messageNotification("_error_", error: NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_"), delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info) + contentPresenter.messageNotification("_error_", error: NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_"), delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info) return } @@ -1073,7 +1065,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC try data.write(to: fileUrl, options: .atomic) } catch { NCActivityIndicator.shared.stop() - NCContentPresenter.shared.messageNotification("_error_", error: NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_"), delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info) + contentPresenter.messageNotification("_error_", error: NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_"), delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info) return } } @@ -1089,7 +1081,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC // let image = changeCompressionImage(self.arrayImages[0]) guard let data = image.jpegData(compressionQuality: CGFloat(0.5)) else { NCActivityIndicator.shared.stop() - NCContentPresenter.shared.messageNotification("_error_", error: NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_"), delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info) + contentPresenter.messageNotification("_error_", error: NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_"), delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info) return } @@ -1097,13 +1089,13 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC try data.write(to: NSURL.fileURL(withPath: fileNameGenerateExport), options: .atomic) } catch { NCActivityIndicator.shared.stop() - NCContentPresenter.shared.messageNotification("_error_", error: NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_"), delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info) + contentPresenter.messageNotification("_error_", error: NKError(errorCode: NCGlobal.shared.errorCreationFile, errorDescription: "_error_creation_file_"), delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.info) return } } } - metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNameGenerateExport) + metadata.size = utilityFileSystem.getFileSize(filePath: fileNameGenerateExport) NCActivityIndicator.shared.stop() @@ -1112,9 +1104,9 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC // Request delete all image scanned let alertController = UIAlertController(title: "", message: NSLocalizedString("_delete_all_scanned_images_", comment: ""), preferredStyle: .alert) - let actionYes = UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (_: UIAlertAction) in + let actionYes = UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { [self] (_: UIAlertAction) in - let path = CCUtility.getDirectoryScan()! + let path = utilityFileSystem.directoryScan do { let filePaths = try FileManager.default.contentsOfDirectory(atPath: path) diff --git a/iOSClient/Scan document/NCDocumentCamera.swift b/iOSClient/Scan document/NCDocumentCamera.swift index 7dc5e773d9..95df654db9 100644 --- a/iOSClient/Scan document/NCDocumentCamera.swift +++ b/iOSClient/Scan document/NCDocumentCamera.swift @@ -84,7 +84,7 @@ class NCDocumentCamera: NSObject, VNDocumentCameraViewControllerDelegate { var itemsDestination: [String] = [] do { - let atPath = CCUtility.getDirectoryScan()! + let atPath = utilityFileSystem.directoryScan let directoryContents = try FileManager.default.contentsOfDirectory(atPath: atPath) for fileName in directoryContents { if fileName.first != "." { @@ -101,7 +101,7 @@ class NCDocumentCamera: NSObject, VNDocumentCameraViewControllerDelegate { if !itemsDestination.contains(fileName) { - let fileNamePathAt = CCUtility.getDirectoryScan() + "/" + fileName + let fileNamePathAt = utilityFileSystem.directoryScan + "/" + fileName guard let data = try? Data(contentsOf: URL(fileURLWithPath: fileNamePathAt)) else { return } guard let image = UIImage(data: data) else { return } From 4171e94637e813a337bf74dc204ec40e81ad78dd Mon Sep 17 00:00:00 2001 From: TSI-amrutwaghmare <96108296+TSI-amrutwaghmare@users.noreply.github.com> Date: Wed, 6 Dec 2023 14:54:08 +0530 Subject: [PATCH 3/3] NMC 1988 - Merging conflicts resolve after nextcloud 4.9.3 release --- iOSClient/Scan document/NCCreateFormUploadScanDocument.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/iOSClient/Scan document/NCCreateFormUploadScanDocument.swift b/iOSClient/Scan document/NCCreateFormUploadScanDocument.swift index 071d2a49d1..4a71b02073 100644 --- a/iOSClient/Scan document/NCCreateFormUploadScanDocument.swift +++ b/iOSClient/Scan document/NCCreateFormUploadScanDocument.swift @@ -769,7 +769,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC } - let metadataForUpload = NCManageDatabase.shared.createMetadata(account: appDelegate?.account ?? "", user: appDelegate?.user ?? "", userId: appDelegate?.userId ?? "", fileName: fileNameSave, fileNameView: fileNameSave, ocId: UUID().uuidString, serverUrl: serverUrl, urlBase: appDelegate?.urlBase ?? "", url: "", contentType: "", isLivePhoto: false) + let metadataForUpload = NCManageDatabase.shared.createMetadata(account: appDelegate?.account ?? "", user: appDelegate?.user ?? "", userId: appDelegate?.userId ?? "", fileName: fileNameSave, fileNameView: fileNameSave, ocId: UUID().uuidString, serverUrl: serverUrl, urlBase: appDelegate?.urlBase ?? "", url: "", contentType: "") metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile @@ -841,7 +841,7 @@ class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NC let image = changeCompressionImage(arrayImages[count]) - let metadataForUpload = NCManageDatabase.shared.createMetadata(account: appDelegate?.account ?? "", user: appDelegate?.user ?? "", userId: appDelegate?.userId ?? "", fileName: fileNameSave, fileNameView: fileNameSave, ocId: UUID().uuidString, serverUrl: serverUrl, urlBase: appDelegate?.urlBase ?? "", url: "", contentType: "", isLivePhoto: false) + let metadataForUpload = NCManageDatabase.shared.createMetadata(account: appDelegate?.account ?? "", user: appDelegate?.user ?? "", userId: appDelegate?.userId ?? "", fileName: fileNameSave, fileNameView: fileNameSave, ocId: UUID().uuidString, serverUrl: serverUrl, urlBase: appDelegate?.urlBase ?? "", url: "", contentType: "") metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile