NCUploadScanDocument.swift 18 KB

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