NCUploadScanDocument.swift 23 KB

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