NCUploadScanDocument.swift 18 KB

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