NCUploadScanDocument.swift 18 KB

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