NCUploadScanDocument.swift 19 KB

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