NCUploadScanDocument.swift 23 KB

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