NCUploadScanDocument.swift 18 KB

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