NCUploadScanDocument.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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. var fileName: String = ""
  41. var userBaseUrl: NCUserBaseUrl
  42. var serverUrl: String
  43. var url: URL = Bundle.main.url(forResource: "Reasons to use Nextcloud", withExtension: "pdf")!
  44. var metadata = tableMetadata()
  45. var images: [UIImage]
  46. let fileNameDefault = NSTemporaryDirectory() + "scandocument.pdf"
  47. init(images: [UIImage], userBaseUrl: NCUserBaseUrl, serverUrl: String) {
  48. self.images = images
  49. self.userBaseUrl = userBaseUrl
  50. self.serverUrl = serverUrl
  51. }
  52. func save(completion: @escaping (_ openConflictViewController: Bool) -> Void) {
  53. guard !fileName.isEmpty else { return }
  54. let ext = (fileName as NSString).pathExtension.uppercased()
  55. var fileNameSave = ""
  56. if ext.isEmpty {
  57. fileNameSave = fileName + ".pdf"
  58. } else {
  59. fileNameSave = (fileName as NSString).deletingPathExtension + ".pdf"
  60. }
  61. // Create metadata for upload
  62. metadata = NCManageDatabase.shared.createMetadata(account: userBaseUrl.account,
  63. user: userBaseUrl.user,
  64. userId: userBaseUrl.userId,
  65. fileName: fileNameSave,
  66. fileNameView: fileNameSave,
  67. ocId: UUID().uuidString,
  68. serverUrl: serverUrl,
  69. urlBase: userBaseUrl.urlBase,
  70. url: "",
  71. contentType: "")
  72. metadata.session = NCNetworking.shared.sessionIdentifierBackground
  73. metadata.sessionSelector = NCGlobal.shared.selectorUploadFile
  74. metadata.status = NCGlobal.shared.metadataStatusWaitUpload
  75. if NCManageDatabase.shared.getMetadataConflict(account: userBaseUrl.account, serverUrl: serverUrl, fileNameView: fileNameSave) != nil {
  76. completion(true)
  77. } else {
  78. uploadMetadata()
  79. completion(false)
  80. }
  81. }
  82. func uploadMetadata() {
  83. guard let fileNameGenerateExport = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else { return }
  84. NCUtilityFileSystem.shared.copyFile(atPath: fileNameDefault, toPath: fileNameGenerateExport)
  85. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNameGenerateExport)
  86. NCNetworkingProcessUpload.shared.createProcessUploads(metadatas: [metadata], completion: { _ in })
  87. }
  88. func createPDFPreview(quality: Double) -> Data {
  89. let pdfData = NSMutableData()
  90. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
  91. if var image = images.first {
  92. image = changeCompressionImage(image, quality: quality)
  93. let bounds = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
  94. UIGraphicsBeginPDFPageWithInfo(bounds, nil)
  95. image.draw(in: bounds)
  96. }
  97. UIGraphicsEndPDFContext()
  98. return pdfData as Data
  99. }
  100. func createPDF(password: String = "", isTextRecognition: Bool = false, quality: Double) {
  101. guard !images.isEmpty else { return }
  102. let pdfData = NSMutableData()
  103. if password.isEmpty {
  104. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
  105. } else {
  106. for char in password.unicodeScalars {
  107. if !char.isASCII {
  108. NCActivityIndicator.shared.stop()
  109. let error = NKError(errorCode: NCGlobal.shared.errorForbidden, errorDescription: "_password_ascii_")
  110. NCContentPresenter.shared.showError(error: error)
  111. return
  112. }
  113. }
  114. let info: [AnyHashable: Any] = [kCGPDFContextUserPassword as String: password, kCGPDFContextOwnerPassword as String: password]
  115. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, info)
  116. }
  117. for var image in images {
  118. image = changeCompressionImage(image, quality: quality)
  119. let bounds = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
  120. if isTextRecognition {
  121. UIGraphicsBeginPDFPageWithInfo(bounds, nil)
  122. image.draw(in: bounds)
  123. } else {
  124. UIGraphicsBeginPDFPageWithInfo(bounds, nil)
  125. image.draw(in: bounds)
  126. }
  127. }
  128. UIGraphicsEndPDFContext()
  129. do {
  130. url = URL(fileURLWithPath: fileNameDefault)
  131. try pdfData.write(to: url, options: .atomic)
  132. } catch {
  133. print("error catched")
  134. }
  135. }
  136. func changeCompressionImage(_ image: UIImage, quality: Double) -> UIImage {
  137. var compressionQuality: CGFloat = 0.0
  138. var baseHeight: Float = 595.2 // A4
  139. var baseWidth: Float = 841.8 // A4
  140. switch quality {
  141. case 0:
  142. baseHeight *= 1
  143. baseWidth *= 1
  144. compressionQuality = 0.2
  145. case 1:
  146. baseHeight *= 2
  147. baseWidth *= 2
  148. compressionQuality = 0.3
  149. case 2:
  150. baseHeight *= 3
  151. baseWidth *= 3
  152. compressionQuality = 0.4
  153. case 3:
  154. baseHeight *= 4
  155. baseWidth *= 4
  156. compressionQuality = 0.5
  157. default:
  158. break
  159. }
  160. var newHeight = Float(image.size.height)
  161. var newWidth = Float(image.size.width)
  162. var imgRatio: Float = newWidth / newHeight
  163. let baseRatio: Float = baseWidth / baseHeight
  164. if newHeight > baseHeight || newWidth > baseWidth {
  165. if imgRatio < baseRatio {
  166. imgRatio = baseHeight / newHeight
  167. newWidth = imgRatio * newWidth
  168. newHeight = baseHeight
  169. } else if imgRatio > baseRatio {
  170. imgRatio = baseWidth / newWidth
  171. newHeight = imgRatio * newHeight
  172. newWidth = baseWidth
  173. } else {
  174. newHeight = baseHeight
  175. newWidth = baseWidth
  176. }
  177. }
  178. let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(newWidth), height: CGFloat(newHeight))
  179. UIGraphicsBeginImageContext(rect.size)
  180. image.draw(in: rect)
  181. let img = UIGraphicsGetImageFromCurrentImageContext()
  182. let imageData = img?.jpegData(compressionQuality: CGFloat(compressionQuality))
  183. UIGraphicsEndImageContext()
  184. if let imageData = imageData, let image = UIImage(data: imageData) {
  185. return image
  186. }
  187. return image
  188. }
  189. }
  190. // MARK: - Delegate
  191. extension NCUploadScanDocument: NCSelectDelegate {
  192. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  193. if let serverUrl = serverUrl {
  194. CCUtility.setDirectoryScanDocument(serverUrl)
  195. self.serverUrl = serverUrl
  196. }
  197. }
  198. }
  199. extension NCUploadScanDocument: NCCreateFormUploadConflictDelegate {
  200. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  201. if metadatas == nil { return }
  202. uploadMetadata()
  203. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDismissScanDocument)
  204. }
  205. }
  206. // MARK: - View
  207. struct UploadScanDocumentView: View {
  208. @State var quality = CCUtility.getQualityScanDocument()
  209. @State var password: String = ""
  210. @State var isSecuredPassword: Bool = true
  211. @State var isTextRecognition: Bool = CCUtility.getTextRecognitionStatus()
  212. @State var isPresentedSelect = false
  213. @State var isPresentedUploadConflict = false
  214. var metadatasConflict: [tableMetadata] = []
  215. @ObservedObject var uploadScanDocument: NCUploadScanDocument
  216. @Environment(\.presentationMode) var presentationMode
  217. init(_ uploadScanDocument: NCUploadScanDocument) {
  218. self.uploadScanDocument = uploadScanDocument
  219. }
  220. var body: some View {
  221. GeometryReader { geo in
  222. List {
  223. Section(header: Text(NSLocalizedString("_file_creation_", comment: ""))) {
  224. HStack {
  225. Label {
  226. if NCUtilityFileSystem.shared.getHomeServer(urlBase: uploadScanDocument.userBaseUrl.urlBase, userId: uploadScanDocument.userBaseUrl.userId) == uploadScanDocument.serverUrl {
  227. Text("/")
  228. .frame(maxWidth: .infinity, alignment: .trailing)
  229. } else {
  230. Text((uploadScanDocument.serverUrl as NSString).lastPathComponent)
  231. .frame(maxWidth: .infinity, alignment: .trailing)
  232. }
  233. } icon: {
  234. Image("folder")
  235. .renderingMode(.template)
  236. .resizable()
  237. .scaledToFit()
  238. .foregroundColor(Color(NCBrandColor.shared.brand))
  239. }
  240. }
  241. .contentShape(Rectangle())
  242. .onTapGesture {
  243. isPresentedSelect = true
  244. }
  245. .complexModifier { view in
  246. if #available(iOS 16, *) {
  247. view.alignmentGuide(.listRowSeparatorLeading) { _ in
  248. return 0
  249. }
  250. }
  251. }
  252. HStack {
  253. Text(NSLocalizedString("_filename_", comment: ""))
  254. TextField(NSLocalizedString("_enter_filename_", comment: ""), text: $uploadScanDocument.fileName)
  255. .multilineTextAlignment(.trailing)
  256. }
  257. HStack {
  258. Group {
  259. Text(NSLocalizedString("_password_", comment: ""))
  260. if isSecuredPassword {
  261. SecureField(NSLocalizedString("_enter_password_", comment: ""), text: $password)
  262. .multilineTextAlignment(.trailing)
  263. } else {
  264. TextField(NSLocalizedString("_enter_password_", comment: ""), text: $password)
  265. .multilineTextAlignment(.trailing)
  266. }
  267. }
  268. Button(action: {
  269. isSecuredPassword.toggle()
  270. }) {
  271. Image(systemName: self.isSecuredPassword ? "eye.slash" : "eye")
  272. .accentColor(.gray)
  273. }
  274. }
  275. HStack {
  276. Toggle(NSLocalizedString("_text_recognition_", comment: ""), isOn: $isTextRecognition)
  277. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand)))
  278. .onChange(of: isTextRecognition) { newValue in
  279. CCUtility.setTextRecognitionStatus(newValue)
  280. }
  281. }
  282. }
  283. Section(header: Text(NSLocalizedString("_quality_image_title_", comment: ""))) {
  284. VStack {
  285. Slider(value: $quality, in: 0...3, step: 1, onEditingChanged: { touch in
  286. if !touch {
  287. CCUtility.setQualityScanDocument(quality)
  288. // uploadScanDocument.createPDF(password: password, isTextRecognition: isTextRecognition, quality: quality)
  289. }
  290. })
  291. .accentColor(Color(NCBrandColor.shared.brand))
  292. }
  293. PDFKitRepresentedView(quality: $quality, uploadScanDocument: uploadScanDocument)
  294. .frame(maxWidth: .infinity, minHeight: geo.size.height / 2.7)
  295. }.complexModifier { view in
  296. if #available(iOS 15, *) {
  297. view.listRowSeparator(.hidden)
  298. }
  299. }
  300. Button(NSLocalizedString("_save_", comment: "")) {
  301. // presentationMode.wrappedValue.dismiss()
  302. uploadScanDocument.save { openConflictViewController in
  303. if openConflictViewController {
  304. isPresentedUploadConflict = true
  305. } else {
  306. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDismissScanDocument)
  307. }
  308. }
  309. }
  310. .buttonStyle(ButtonUploadScanDocumenStyle(disabled: uploadScanDocument.fileName.isEmpty))
  311. .frame(maxWidth: .infinity, alignment: .center)
  312. .listRowBackground(Color(UIColor.systemGroupedBackground))
  313. }
  314. }
  315. .background(Color(UIColor.systemGroupedBackground))
  316. .sheet(isPresented: $isPresentedSelect) {
  317. NCSelectRepresentedView(uploadScanDocument: uploadScanDocument)
  318. }
  319. .sheet(isPresented: $isPresentedUploadConflict) {
  320. NCUploadConflictRepresentedView(uploadScanDocument: uploadScanDocument)
  321. }
  322. }
  323. }
  324. struct ButtonUploadScanDocumenStyle: ButtonStyle {
  325. var disabled = false
  326. func makeBody(configuration: Configuration) -> some View {
  327. configuration.label
  328. .padding(.horizontal, 40)
  329. .padding(.vertical, 10)
  330. .background(disabled ? Color(UIColor.systemGray4) : Color(NCBrandColor.shared.brand))
  331. .foregroundColor(.white)
  332. .clipShape(Capsule())
  333. }
  334. }
  335. // MARK: - UIViewControllerRepresentable
  336. struct NCSelectRepresentedView: UIViewControllerRepresentable {
  337. typealias UIViewControllerType = UINavigationController
  338. @ObservedObject var uploadScanDocument: NCUploadScanDocument
  339. func makeUIViewController(context: Context) -> UINavigationController {
  340. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  341. let navigationController = storyboard.instantiateInitialViewController() as? UINavigationController
  342. let viewController = navigationController?.topViewController as? NCSelect
  343. viewController?.delegate = uploadScanDocument
  344. viewController?.typeOfCommandView = .selectCreateFolder
  345. viewController?.includeDirectoryE2EEncryption = true
  346. return navigationController!
  347. }
  348. func updateUIViewController(_ uiViewController: UINavigationController, context: Context) {
  349. }
  350. }
  351. struct NCUploadConflictRepresentedView: UIViewControllerRepresentable {
  352. typealias UIViewControllerType = NCCreateFormUploadConflict
  353. @ObservedObject var uploadScanDocument: NCUploadScanDocument
  354. func makeUIViewController(context: Context) -> NCCreateFormUploadConflict {
  355. let storyboard = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil)
  356. let viewController = storyboard.instantiateInitialViewController() as? NCCreateFormUploadConflict
  357. viewController?.delegate = uploadScanDocument
  358. viewController?.textLabelDetailNewFile = NSLocalizedString("_now_", comment: "")
  359. viewController?.serverUrl = uploadScanDocument.serverUrl
  360. viewController?.metadatasUploadInConflict = [uploadScanDocument.metadata]
  361. return viewController!
  362. }
  363. func updateUIViewController(_ uiViewController: NCCreateFormUploadConflict, context: Context) {
  364. }
  365. }
  366. struct PDFKitRepresentedView: UIViewRepresentable {
  367. typealias UIView = PDFView
  368. @Binding var quality: Double
  369. @ObservedObject var uploadScanDocument: NCUploadScanDocument
  370. let fileNameDefault = NSTemporaryDirectory() + "scandocument.pdf"
  371. func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) -> PDFKitRepresentedView.UIViewType {
  372. let pdfView = PDFView()
  373. pdfView.autoScales = true
  374. pdfView.backgroundColor = .clear
  375. pdfView.displayMode = .singlePage
  376. pdfView.displayDirection = .vertical
  377. return pdfView
  378. }
  379. func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFKitRepresentedView>) {
  380. let data = uploadScanDocument.createPDFPreview(quality: quality)
  381. uiView.document = PDFDocument(data: data)
  382. }
  383. }
  384. // MARK: - Preview
  385. struct UploadScanDocumentView_Previews: PreviewProvider {
  386. static var previews: some View {
  387. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  388. let uploadScanDocument = NCUploadScanDocument(images: [], userBaseUrl: appDelegate, serverUrl: "ABCD")
  389. UploadScanDocumentView(uploadScanDocument)
  390. }
  391. }
  392. }