NCUploadScanDocument.swift 22 KB

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