NCUploadScanDocument.swift 23 KB

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