NCUploadScanDocument.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. //
  2. // NCUploadScanDocument.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 28/12/22.
  6. // Copyright © 2022 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import SwiftUI
  24. import NextcloudKit
  25. import Vision
  26. import VisionKit
  27. import Photos
  28. import PDFKit
  29. class NCUploadScanDocument: ObservableObject {
  30. internal var metadata = tableMetadata()
  31. internal var images: [UIImage]
  32. internal var password: String = ""
  33. internal var isTextRecognition: Bool = false
  34. internal var quality: Double = 0
  35. internal var removeAllFiles: Bool = false
  36. internal let utilityFileSystem = NCUtilityFileSystem()
  37. internal let database = NCManageDatabase.shared
  38. @Published var serverUrl: String
  39. @Published var showHUD: Bool = false
  40. @Published var controller: NCMainTabBarController?
  41. var session: NCSession.Session {
  42. NCSession.shared.getSession(controller: controller)
  43. }
  44. init(images: [UIImage], serverUrl: String, controller: NCMainTabBarController?) {
  45. self.images = images
  46. self.serverUrl = serverUrl
  47. self.controller = controller
  48. }
  49. func save(fileName: String, password: String = "", isTextRecognition: Bool = false, removeAllFiles: Bool, quality: Double, completion: @escaping (_ openConflictViewController: Bool, _ error: Bool) -> Void) {
  50. self.password = password
  51. self.isTextRecognition = isTextRecognition
  52. self.quality = quality
  53. self.removeAllFiles = removeAllFiles
  54. metadata = self.database.createMetadata(fileName: fileName,
  55. fileNameView: fileName,
  56. ocId: UUID().uuidString,
  57. serverUrl: serverUrl,
  58. url: "",
  59. contentType: "",
  60. session: session,
  61. sceneIdentifier: controller?.sceneIdentifier)
  62. metadata.session = NCNetworking.shared.sessionUploadBackground
  63. metadata.sessionSelector = NCGlobal.shared.selectorUploadFile
  64. metadata.status = NCGlobal.shared.metadataStatusWaitUpload
  65. metadata.sessionDate = Date()
  66. if self.database.getMetadataConflict(account: session.account, serverUrl: serverUrl, fileNameView: fileName) != nil {
  67. completion(true, false)
  68. } else {
  69. createPDF(metadata: metadata) { error in
  70. if !error {
  71. completion(false, false)
  72. }
  73. }
  74. }
  75. }
  76. func createPDF(metadata: tableMetadata, completion: @escaping (_ error: Bool) -> Void) {
  77. DispatchQueue.global(qos: .userInteractive).async {
  78. let fileNamePath = self.utilityFileSystem.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)
  79. let pdfData = NSMutableData()
  80. if self.password.isEmpty {
  81. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
  82. } else {
  83. for char in self.password.unicodeScalars {
  84. if !char.isASCII {
  85. let error = NKError(errorCode: NCGlobal.shared.errorForbidden, errorDescription: "_password_ascii_")
  86. NCContentPresenter().showError(error: error)
  87. return DispatchQueue.main.async { completion(true) }
  88. }
  89. }
  90. let info: [AnyHashable: Any] = [kCGPDFContextUserPassword as String: self.password, kCGPDFContextOwnerPassword as String: self.password]
  91. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, info)
  92. }
  93. for image in self.images {
  94. self.drawImage(image: image, quality: self.quality, isTextRecognition: self.isTextRecognition, fontColor: UIColor.clear)
  95. }
  96. UIGraphicsEndPDFContext()
  97. do {
  98. try pdfData.write(to: URL(fileURLWithPath: fileNamePath), options: .atomic)
  99. metadata.size = self.utilityFileSystem.getFileSize(filePath: fileNamePath)
  100. NCNetworkingProcess.shared.createProcessUploads(metadatas: [metadata])
  101. if self.removeAllFiles {
  102. let path = self.utilityFileSystem.directoryScan
  103. let filePaths = try FileManager.default.contentsOfDirectory(atPath: path)
  104. for filePath in filePaths {
  105. try FileManager.default.removeItem(atPath: path + "/" + filePath)
  106. }
  107. }
  108. } catch {
  109. print("Error: \(error)")
  110. }
  111. DispatchQueue.main.async { completion(false) }
  112. }
  113. }
  114. func createPDFPreview(quality: Double, isTextRecognition: Bool, completion: @escaping (_ data: Data) -> Void) {
  115. DispatchQueue.global(qos: .userInteractive).async {
  116. if let image = self.images.first {
  117. let pdfData = NSMutableData()
  118. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
  119. self.drawImage(image: image, quality: quality, isTextRecognition: isTextRecognition, fontColor: UIColor.red)
  120. UIGraphicsEndPDFContext()
  121. DispatchQueue.main.async { completion(pdfData as Data) }
  122. } else {
  123. let url = Bundle.main.url(forResource: "Reasons to use Nextcloud", withExtension: "pdf")!
  124. let data = try? Data(contentsOf: url)
  125. DispatchQueue.main.async { completion(data!) }
  126. }
  127. }
  128. }
  129. func fileName(_ fileName: String) -> String {
  130. let fileName = fileName.trimmingCharacters(in: .whitespacesAndNewlines)
  131. guard !fileName.isEmpty, fileName != ".", fileName.lowercased() != ".pdf" else { return "" }
  132. let ext = (fileName as NSString).pathExtension.uppercased()
  133. if ext.isEmpty {
  134. return fileName + ".pdf"
  135. } else {
  136. return (fileName as NSString).deletingPathExtension + ".pdf"
  137. }
  138. }
  139. private func changeCompressionImage(_ image: UIImage, quality: Double) -> UIImage {
  140. var compressionQuality: CGFloat = 0.0
  141. let baseHeight: Float = 595.2 // A4
  142. let baseWidth: Float = 841.8 // A4
  143. switch quality {
  144. case 0:
  145. compressionQuality = 0.1
  146. case 1:
  147. compressionQuality = 0.3
  148. case 2:
  149. compressionQuality = 0.5
  150. case 3:
  151. compressionQuality = 0.7
  152. case 4:
  153. compressionQuality = 0.9
  154. default:
  155. break
  156. }
  157. var newHeight = Float(image.size.height)
  158. var newWidth = Float(image.size.width)
  159. var imgRatio: Float = newWidth / newHeight
  160. let baseRatio: Float = baseWidth / baseHeight
  161. if newHeight > baseHeight || newWidth > baseWidth {
  162. if imgRatio < baseRatio {
  163. imgRatio = baseHeight / newHeight
  164. newWidth = imgRatio * newWidth
  165. newHeight = baseHeight
  166. } else if imgRatio > baseRatio {
  167. imgRatio = baseWidth / newWidth
  168. newHeight = imgRatio * newHeight
  169. newWidth = baseWidth
  170. } else {
  171. newHeight = baseHeight
  172. newWidth = baseWidth
  173. }
  174. }
  175. let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(newWidth), height: CGFloat(newHeight))
  176. UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
  177. image.draw(in: rect)
  178. let img = UIGraphicsGetImageFromCurrentImageContext()
  179. let imageData = img?.jpegData(compressionQuality: CGFloat(compressionQuality))
  180. UIGraphicsEndImageContext()
  181. if let imageData = imageData, let image = UIImage(data: imageData) {
  182. return image
  183. }
  184. return image
  185. }
  186. private func bestFittingFont(for text: String, in bounds: CGRect, fontDescriptor: UIFontDescriptor, fontColor: UIColor) -> [NSAttributedString.Key: Any] {
  187. let constrainingDimension = min(bounds.width, bounds.height)
  188. let properBounds = CGRect(origin: .zero, size: bounds.size)
  189. var attributes: [NSAttributedString.Key: Any] = [:]
  190. let infiniteBounds = CGSize(width: CGFloat.infinity, height: CGFloat.infinity)
  191. var bestFontSize: CGFloat = constrainingDimension
  192. // Search font (H)
  193. for fontSize in stride(from: bestFontSize, through: 0, by: -1) {
  194. let newFont = UIFont(descriptor: fontDescriptor, size: fontSize)
  195. attributes[.font] = newFont
  196. let currentFrame = text.boundingRect(with: infiniteBounds, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil)
  197. if properBounds.contains(currentFrame) {
  198. bestFontSize = fontSize
  199. break
  200. }
  201. }
  202. // Search kern (W)
  203. let font = UIFont(descriptor: fontDescriptor, size: bestFontSize)
  204. attributes = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: fontColor, NSAttributedString.Key.kern: 0] as [NSAttributedString.Key: Any]
  205. for kern in stride(from: 0, through: 100, by: 0.1) {
  206. let attributesTmp = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: fontColor, NSAttributedString.Key.kern: kern] as [NSAttributedString.Key: Any]
  207. let size = text.size(withAttributes: attributesTmp).width
  208. if size <= bounds.width {
  209. attributes = attributesTmp
  210. } else {
  211. break
  212. }
  213. }
  214. return attributes
  215. }
  216. private func drawImage(image: UIImage, quality: Double, isTextRecognition: Bool, fontColor: UIColor) {
  217. let image = changeCompressionImage(image, quality: quality)
  218. let bounds = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
  219. if isTextRecognition {
  220. UIGraphicsBeginPDFPageWithInfo(bounds, nil)
  221. image.draw(in: bounds)
  222. let requestHandler = VNImageRequestHandler(cgImage: image.cgImage!, options: [:])
  223. let request = VNRecognizeTextRequest { request, _ in
  224. guard let observations = request.results as? [VNRecognizedTextObservation] else { return }
  225. for observation in observations {
  226. guard let textLine = observation.topCandidates(1).first else { continue }
  227. var t: CGAffineTransform = CGAffineTransform.identity
  228. t = t.scaledBy(x: image.size.width, y: -image.size.height)
  229. t = t.translatedBy(x: 0, y: -1)
  230. let rect = observation.boundingBox.applying(t)
  231. let text = textLine.string
  232. let font = UIFont.systemFont(ofSize: rect.size.height, weight: .regular)
  233. let attributes = self.bestFittingFont(for: text, in: rect, fontDescriptor: font.fontDescriptor, fontColor: fontColor)
  234. text.draw(with: rect, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
  235. }
  236. }
  237. request.recognitionLevel = .accurate
  238. request.usesLanguageCorrection = true
  239. try? requestHandler.perform([request])
  240. } else {
  241. UIGraphicsBeginPDFPageWithInfo(bounds, nil)
  242. image.draw(in: bounds)
  243. }
  244. }
  245. }
  246. // MARK: - Delegate
  247. extension NCUploadScanDocument: NCSelectDelegate {
  248. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool, session: NCSession.Session) {
  249. if let serverUrl = serverUrl {
  250. self.serverUrl = serverUrl
  251. }
  252. }
  253. }
  254. extension NCUploadScanDocument: NCCreateFormUploadConflictDelegate {
  255. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  256. if let metadata = metadatas?.first {
  257. self.showHUD.toggle()
  258. createPDF(metadata: metadata) { error in
  259. if !error {
  260. self.showHUD.toggle()
  261. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDismissScanDocument)
  262. }
  263. }
  264. }
  265. }
  266. }
  267. // MARK: - View
  268. struct UploadScanDocumentView: View {
  269. @State var fileName = NCUtilityFileSystem().createFileNameDate("scan", ext: "")
  270. @State var footer = ""
  271. @State var password: String = ""
  272. @State var isSecuredPassword: Bool = true
  273. @State var isTextRecognition: Bool = NCKeychain().textRecognitionStatus
  274. @State var quality = NCKeychain().qualityScanDocument
  275. @State var removeAllFiles: Bool = NCKeychain().deleteAllScanImages
  276. @State var isPresentedSelect = false
  277. @State var isPresentedUploadConflict = false
  278. @ObservedObject var model: NCUploadScanDocument
  279. var metadatasConflict: [tableMetadata] = []
  280. init(model: NCUploadScanDocument) {
  281. self.model = model
  282. }
  283. func getTextServerUrl(_ serverUrl: String) -> String {
  284. if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", model.session.account, serverUrl)), let metadata = NCManageDatabase.shared.getMetadataFromOcId(directory.ocId) {
  285. return (metadata.fileNameView)
  286. } else {
  287. return (serverUrl as NSString).lastPathComponent
  288. }
  289. }
  290. var body: some View {
  291. GeometryReader { geo in
  292. ZStack(alignment: .top) {
  293. List {
  294. Section(header: Text(NSLocalizedString("_file_creation_", comment: "")), footer: Text(footer)) {
  295. HStack {
  296. Label {
  297. if NCUtilityFileSystem().getHomeServer(session: model.session) == model.serverUrl {
  298. Text("/")
  299. .frame(maxWidth: .infinity, alignment: .trailing)
  300. } else {
  301. Text(self.getTextServerUrl(model.serverUrl))
  302. .frame(maxWidth: .infinity, alignment: .trailing)
  303. }
  304. } icon: {
  305. Image("folder")
  306. .renderingMode(.template)
  307. .resizable()
  308. .scaledToFit()
  309. .foregroundColor(Color(NCBrandColor.shared.getElement(account: model.session.account)))
  310. }
  311. }
  312. .contentShape(Rectangle())
  313. .onTapGesture {
  314. isPresentedSelect = true
  315. }
  316. .complexModifier { view in
  317. if #available(iOS 16, *) {
  318. view.alignmentGuide(.listRowSeparatorLeading) { _ in
  319. return 0
  320. }
  321. }
  322. }
  323. HStack {
  324. Text(NSLocalizedString("_filename_", comment: ""))
  325. TextField(NSLocalizedString("_enter_filename_", comment: ""), text: $fileName)
  326. .modifier(TextFieldClearButton(text: $fileName))
  327. .multilineTextAlignment(.trailing)
  328. .onChange(of: fileName) { _ in
  329. let controller = (UIApplication.shared.firstWindow?.rootViewController as? NCMainTabBarController)
  330. if let fileNameError = FileNameValidator.shared.checkFileName(fileName, account: controller?.account) {
  331. footer = fileNameError.errorDescription
  332. } else {
  333. footer = ""
  334. }
  335. }
  336. }
  337. HStack {
  338. Group {
  339. Text(NSLocalizedString("_password_", comment: ""))
  340. if isSecuredPassword {
  341. SecureField(NSLocalizedString("_enter_password_", comment: ""), text: $password)
  342. .multilineTextAlignment(.trailing)
  343. } else {
  344. TextField(NSLocalizedString("_enter_password_", comment: ""), text: $password)
  345. .multilineTextAlignment(.trailing)
  346. }
  347. }
  348. Button(action: {
  349. isSecuredPassword.toggle()
  350. }) {
  351. Image(systemName: self.isSecuredPassword ? "eye.slash" : "eye")
  352. .foregroundColor(Color(UIColor.placeholderText))
  353. }
  354. .buttonStyle(BorderlessButtonStyle())
  355. }
  356. HStack {
  357. Toggle(NSLocalizedString("_text_recognition_", comment: ""), isOn: $isTextRecognition)
  358. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.getElement(account: model.session.account))))
  359. .onChange(of: isTextRecognition) { newValue in
  360. NCKeychain().textRecognitionStatus = newValue
  361. }
  362. }
  363. }
  364. .complexModifier { view in
  365. view.listRowSeparator(.hidden)
  366. }
  367. VStack(spacing: 20) {
  368. Toggle(NSLocalizedString("_delete_all_scanned_images_", comment: ""), isOn: $removeAllFiles)
  369. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.getElement(account: model.session.account))))
  370. .onChange(of: removeAllFiles) { newValue in
  371. NCKeychain().deleteAllScanImages = newValue
  372. }
  373. Button(NSLocalizedString("_save_", comment: "")) {
  374. let fileName = model.fileName(fileName)
  375. if !fileName.isEmpty {
  376. model.showHUD.toggle()
  377. model.save(fileName: fileName, password: password, isTextRecognition: isTextRecognition, removeAllFiles: removeAllFiles, quality: quality) { openConflictViewController, error in
  378. model.showHUD.toggle()
  379. if error {
  380. print("error")
  381. } else if openConflictViewController {
  382. isPresentedUploadConflict = true
  383. } else {
  384. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDismissScanDocument)
  385. }
  386. }
  387. }
  388. }
  389. .buttonStyle(ButtonRounded(disabled: fileName.isEmpty || !footer.isEmpty, account: model.session.account))
  390. .disabled(fileName.isEmpty || !footer.isEmpty)
  391. }
  392. Section(header: Text(NSLocalizedString("_quality_image_title_", comment: ""))) {
  393. VStack {
  394. Slider(value: $quality, in: 0...4, step: 1, onEditingChanged: { touch in
  395. if !touch {
  396. NCKeychain().qualityScanDocument = quality
  397. }
  398. })
  399. .accentColor(Color(NCBrandColor.shared.getElement(account: model.session.account)))
  400. }
  401. PDFKitRepresentedView(quality: $quality, isTextRecognition: $isTextRecognition, uploadScanDocument: model)
  402. .frame(maxWidth: .infinity, minHeight: geo.size.height / 2)
  403. }
  404. .complexModifier { view in
  405. view.listRowSeparator(.hidden)
  406. }
  407. }
  408. NCHUDView(showHUD: $model.showHUD, textLabel: NSLocalizedString("_wait_", comment: ""), image: "doc.badge.arrow.up", color: NCBrandColor.shared.getElement(account: model.session.account))
  409. .offset(y: model.showHUD ? 5 : -200)
  410. .animation(.easeOut, value: model.showHUD)
  411. }
  412. }
  413. .background(Color(UIColor.systemGroupedBackground))
  414. .sheet(isPresented: $isPresentedSelect) {
  415. NCSelectViewControllerRepresentable(delegate: model, session: model.session)
  416. }
  417. .sheet(isPresented: $isPresentedUploadConflict) {
  418. UploadConflictView(delegate: model, serverUrl: model.serverUrl, metadatasUploadInConflict: [model.metadata], metadatasNOConflict: [])
  419. }.onTapGesture {
  420. UIApplication.shared.connectedScenes.flatMap { ($0 as? UIWindowScene)?.windows ?? [] }.filter { $0.isKeyWindow }.first?.endEditing(true)
  421. }
  422. }
  423. }
  424. // MARK: - UIViewControllerRepresentable
  425. struct PDFKitRepresentedView: UIViewRepresentable {
  426. typealias UIView = PDFView
  427. @Binding var quality: Double
  428. @Binding var isTextRecognition: Bool
  429. @ObservedObject var uploadScanDocument: NCUploadScanDocument
  430. func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) -> PDFKitRepresentedView.UIViewType {
  431. let pdfView = PDFView()
  432. pdfView.autoScales = true
  433. pdfView.backgroundColor = .clear
  434. pdfView.displayMode = .singlePage
  435. pdfView.displayDirection = .vertical
  436. return pdfView
  437. }
  438. func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFKitRepresentedView>) {
  439. uploadScanDocument.createPDFPreview(quality: quality, isTextRecognition: isTextRecognition) { data in
  440. uiView.document = PDFDocument(data: data)
  441. uiView.document?.page(at: 0)?.annotations.forEach({
  442. $0.isReadOnly = true
  443. })
  444. uiView.autoScales = true
  445. }
  446. }
  447. }
  448. // MARK: - Preview
  449. struct UploadScanDocumentView_Previews: PreviewProvider {
  450. static var previews: some View {
  451. let model = NCUploadScanDocument(images: [], serverUrl: "ABCD", controller: nil)
  452. UploadScanDocumentView(model: model)
  453. }
  454. }