NCUploadScanDocument.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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.2
  135. case 1:
  136. baseHeight *= 2
  137. baseWidth *= 2
  138. compressionQuality = 0.4
  139. case 2:
  140. baseHeight *= 3
  141. baseWidth *= 3
  142. compressionQuality = 0.6
  143. case 3:
  144. baseHeight *= 4
  145. baseWidth *= 4
  146. compressionQuality = 0.8
  147. default:
  148. break
  149. }
  150. var newHeight = Float(image.size.height)
  151. var newWidth = Float(image.size.width)
  152. var imgRatio: Float = newWidth / newHeight
  153. let baseRatio: Float = baseWidth / baseHeight
  154. if newHeight > baseHeight || newWidth > baseWidth {
  155. if imgRatio < baseRatio {
  156. imgRatio = baseHeight / newHeight
  157. newWidth = imgRatio * newWidth
  158. newHeight = baseHeight
  159. } else if imgRatio > baseRatio {
  160. imgRatio = baseWidth / newWidth
  161. newHeight = imgRatio * newHeight
  162. newWidth = baseWidth
  163. } else {
  164. newHeight = baseHeight
  165. newWidth = baseWidth
  166. }
  167. }
  168. let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(newWidth), height: CGFloat(newHeight))
  169. UIGraphicsBeginImageContext(rect.size)
  170. image.draw(in: rect)
  171. let img = UIGraphicsGetImageFromCurrentImageContext()
  172. let imageData = img?.jpegData(compressionQuality: CGFloat(compressionQuality))
  173. UIGraphicsEndImageContext()
  174. if let imageData = imageData, let image = UIImage(data: imageData) {
  175. return image
  176. }
  177. return image
  178. }
  179. }
  180. // MARK: - Delegate
  181. extension NCUploadScanDocument: NCSelectDelegate {
  182. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  183. if let serverUrl = serverUrl {
  184. CCUtility.setDirectoryScanDocument(serverUrl)
  185. self.serverUrl = serverUrl
  186. }
  187. }
  188. }
  189. extension NCUploadScanDocument: NCCreateFormUploadConflictDelegate {
  190. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  191. if metadatas == nil { return }
  192. uploadMetadata()
  193. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDismissScanDocument)
  194. }
  195. }
  196. // MARK: - View
  197. struct UploadScanDocumentView: View {
  198. @State var quality = CCUtility.getQualityScanDocument()
  199. @State var password: String = ""
  200. @State var isSecuredPassword: Bool = true
  201. @State var isTextRecognition: Bool = CCUtility.getTextRecognitionStatus()
  202. @State var isPresentedSelect = false
  203. @State var isPresentedUploadConflict = false
  204. var metadatasConflict: [tableMetadata] = []
  205. @ObservedObject var uploadScanDocument: NCUploadScanDocument
  206. @Environment(\.presentationMode) var presentationMode
  207. init(_ uploadScanDocument: NCUploadScanDocument) {
  208. self.uploadScanDocument = uploadScanDocument
  209. }
  210. var body: some View {
  211. GeometryReader { geo in
  212. List {
  213. Section(header: Text(NSLocalizedString("_file_creation_", comment: ""))) {
  214. HStack {
  215. Label {
  216. if NCUtilityFileSystem.shared.getHomeServer(urlBase: uploadScanDocument.userBaseUrl.urlBase, userId: uploadScanDocument.userBaseUrl.userId) == uploadScanDocument.serverUrl {
  217. Text("/")
  218. .frame(maxWidth: .infinity, alignment: .trailing)
  219. } else {
  220. Text((uploadScanDocument.serverUrl as NSString).lastPathComponent)
  221. .frame(maxWidth: .infinity, alignment: .trailing)
  222. }
  223. } icon: {
  224. Image("folder")
  225. .renderingMode(.template)
  226. .resizable()
  227. .scaledToFit()
  228. .foregroundColor(Color(NCBrandColor.shared.brand))
  229. }
  230. }
  231. .contentShape(Rectangle())
  232. .onTapGesture {
  233. isPresentedSelect = true
  234. }
  235. .complexModifier { view in
  236. if #available(iOS 16, *) {
  237. view.alignmentGuide(.listRowSeparatorLeading) { _ in
  238. return 0
  239. }
  240. }
  241. }
  242. HStack {
  243. Text(NSLocalizedString("_filename_", comment: ""))
  244. TextField(NSLocalizedString("_enter_filename_", comment: ""), text: $uploadScanDocument.fileName)
  245. .multilineTextAlignment(.trailing)
  246. }
  247. HStack {
  248. Group {
  249. Text(NSLocalizedString("_password_", comment: ""))
  250. if isSecuredPassword {
  251. SecureField(NSLocalizedString("_enter_password_", comment: ""), text: $password)
  252. .multilineTextAlignment(.trailing)
  253. } else {
  254. TextField(NSLocalizedString("_enter_password_", comment: ""), text: $password)
  255. .multilineTextAlignment(.trailing)
  256. }
  257. }
  258. Button(action: {
  259. isSecuredPassword.toggle()
  260. }) {
  261. Image(systemName: self.isSecuredPassword ? "eye.slash" : "eye")
  262. .accentColor(.gray)
  263. }
  264. }
  265. HStack {
  266. Toggle(NSLocalizedString("_text_recognition_", comment: ""), isOn: $isTextRecognition)
  267. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand)))
  268. .onChange(of: isTextRecognition) { newValue in
  269. CCUtility.setTextRecognitionStatus(newValue)
  270. }
  271. }
  272. }
  273. Section(header: Text(NSLocalizedString("_quality_image_title_", comment: "")), footer: Text( NSLocalizedString("_file_size_", comment: "") + " \(uploadScanDocument.size)")) {
  274. VStack {
  275. Slider(value: $quality, in: 0...3, step: 1, onEditingChanged: { touch in
  276. if !touch {
  277. CCUtility.setQualityScanDocument(quality)
  278. uploadScanDocument.createPDF(quality: quality)
  279. }
  280. })
  281. .accentColor(Color(NCBrandColor.shared.brand))
  282. }
  283. PDFKitRepresentedView(uploadScanDocument.url)
  284. .frame(maxWidth: .infinity, minHeight: geo.size.height / 2.7)
  285. }.complexModifier { view in
  286. if #available(iOS 15, *) {
  287. view.listRowSeparator(.hidden)
  288. }
  289. }
  290. Button(NSLocalizedString("_save_", comment: "")) {
  291. // presentationMode.wrappedValue.dismiss()
  292. uploadScanDocument.save { openConflictViewController in
  293. if openConflictViewController {
  294. isPresentedUploadConflict = true
  295. } else {
  296. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterDismissScanDocument)
  297. }
  298. }
  299. }
  300. .buttonStyle(ButtonUploadScanDocumenStyle(disabled: uploadScanDocument.fileName.isEmpty))
  301. .frame(maxWidth: .infinity, alignment: .center)
  302. .listRowBackground(Color(UIColor.systemGroupedBackground))
  303. }
  304. }
  305. .background(Color(UIColor.systemGroupedBackground))
  306. .sheet(isPresented: $isPresentedSelect) {
  307. NCSelectRepresentedView(uploadScanDocument: uploadScanDocument)
  308. }
  309. .sheet(isPresented: $isPresentedUploadConflict) {
  310. NCUploadConflictRepresentedView(uploadScanDocument: uploadScanDocument)
  311. }
  312. }
  313. }
  314. struct ButtonUploadScanDocumenStyle: ButtonStyle {
  315. var disabled = false
  316. func makeBody(configuration: Configuration) -> some View {
  317. configuration.label
  318. .padding(.horizontal, 40)
  319. .padding(.vertical, 10)
  320. .background(disabled ? Color(UIColor.systemGray4) : Color(NCBrandColor.shared.brand))
  321. .foregroundColor(.white)
  322. .clipShape(Capsule())
  323. }
  324. }
  325. // MARK: - UIViewControllerRepresentable
  326. struct NCSelectRepresentedView: UIViewControllerRepresentable {
  327. typealias UIViewControllerType = UINavigationController
  328. @ObservedObject var uploadScanDocument: NCUploadScanDocument
  329. func makeUIViewController(context: Context) -> UINavigationController {
  330. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  331. let navigationController = storyboard.instantiateInitialViewController() as? UINavigationController
  332. let viewController = navigationController?.topViewController as? NCSelect
  333. viewController?.delegate = uploadScanDocument
  334. viewController?.typeOfCommandView = .selectCreateFolder
  335. viewController?.includeDirectoryE2EEncryption = true
  336. return navigationController!
  337. }
  338. func updateUIViewController(_ uiViewController: UINavigationController, context: Context) {
  339. }
  340. }
  341. struct NCUploadConflictRepresentedView: UIViewControllerRepresentable {
  342. typealias UIViewControllerType = NCCreateFormUploadConflict
  343. @ObservedObject var uploadScanDocument: NCUploadScanDocument
  344. func makeUIViewController(context: Context) -> NCCreateFormUploadConflict {
  345. let storyboard = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil)
  346. let viewController = storyboard.instantiateInitialViewController() as? NCCreateFormUploadConflict
  347. viewController?.delegate = uploadScanDocument
  348. viewController?.textLabelDetailNewFile = NSLocalizedString("_now_", comment: "")
  349. viewController?.serverUrl = uploadScanDocument.serverUrl
  350. viewController?.metadatasUploadInConflict = [uploadScanDocument.metadata]
  351. return viewController!
  352. }
  353. func updateUIViewController(_ uiViewController: NCCreateFormUploadConflict, context: Context) {
  354. }
  355. }
  356. struct PDFKitRepresentedView: UIViewRepresentable {
  357. let url: URL
  358. init(_ url: URL) {
  359. self.url = url
  360. }
  361. func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) -> PDFKitRepresentedView.UIViewType {
  362. let pdfView = PDFView()
  363. pdfView.document = PDFDocument(url: self.url)
  364. pdfView.autoScales = true
  365. pdfView.backgroundColor = .clear
  366. pdfView.displayMode = .singlePage
  367. pdfView.displayDirection = .vertical
  368. return pdfView
  369. }
  370. func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFKitRepresentedView>) {
  371. }
  372. }
  373. // MARK: - Preview
  374. struct UploadScanDocumentView_Previews: PreviewProvider {
  375. static var previews: some View {
  376. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  377. let uploadScanDocument = NCUploadScanDocument(images: [], userBaseUrl: appDelegate, serverUrl: "ABCD", fileName: CCUtility.createFileNameDate("scan", extension: "pdf"))
  378. UploadScanDocumentView(uploadScanDocument)
  379. // .previewDevice(PreviewDevice(rawValue: "iPhone 14 Pro"))
  380. // .previewDisplayName("iPhone 14")
  381. }
  382. }
  383. }