NCCreateFormUploadScanDocument.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. //
  2. // NCCreateFormUploadScanDocument.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 14/11/2018.
  6. // Copyright © 2017 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 Foundation
  24. import PDFGenerator
  25. import WeScan
  26. class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate {
  27. enum typeDpiQuality {
  28. case low
  29. case medium
  30. case hight
  31. }
  32. var dpiQuality: typeDpiQuality = typeDpiQuality.medium
  33. var serverUrl = ""
  34. var titleServerUrl = ""
  35. var arrayImages = [UIImage]()
  36. var fileName = CCUtility.createFileNameDate("scan", extension: "pdf")
  37. var password : PDFPassword = ""
  38. var fileType = "PDF"
  39. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  40. convenience init(serverUrl: String, arrayImages: [UIImage]) {
  41. self.init()
  42. if serverUrl == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  43. titleServerUrl = "/"
  44. } else {
  45. titleServerUrl = (serverUrl as NSString).lastPathComponent
  46. }
  47. self.serverUrl = serverUrl
  48. self.arrayImages = arrayImages
  49. initializeForm()
  50. }
  51. //MARK: XLFormDescriptorDelegate
  52. func initializeForm() {
  53. let form : XLFormDescriptor = XLFormDescriptor(title: NSLocalizedString("_save_settings_", comment: "")) as XLFormDescriptor
  54. form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow
  55. var section : XLFormSectionDescriptor
  56. var row : XLFormRowDescriptor
  57. // Section: Destination Folder
  58. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: ""))
  59. form.addFormSection(section)
  60. row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: self.titleServerUrl)
  61. row.action.formSelector = #selector(changeDestinationFolder(_:))
  62. row.cellConfig["imageView.image"] = CCGraphics.changeThemingColorImage(UIImage(named: "folder")!, width: 50, height: 50, color: NCBrandColor.sharedInstance.brandElement) as UIImage
  63. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
  64. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  65. section.addFormRow(row)
  66. // Section: Quality
  67. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_quality_image_title_", comment: ""))
  68. form.addFormSection(section)
  69. row = XLFormRowDescriptor(tag: "compressionQuality", rowType: XLFormRowDescriptorTypeSlider)
  70. row.value = 0.5
  71. row.title = NSLocalizedString("_quality_medium_", comment: "")
  72. row.cellConfig["slider.minimumTrackTintColor"] = NCBrandColor.sharedInstance.brand
  73. row.cellConfig["slider.maximumValue"] = 1
  74. row.cellConfig["slider.minimumValue"] = 0
  75. row.cellConfig["steps"] = 2
  76. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.center.rawValue
  77. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  78. section.addFormRow(row)
  79. // Section: Password
  80. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_pdf_password_", comment: ""))
  81. form.addFormSection(section)
  82. row = XLFormRowDescriptor(tag: "password", rowType: XLFormRowDescriptorTypePassword, title: NSLocalizedString("_password_", comment: ""))
  83. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  84. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  85. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  86. section.addFormRow(row)
  87. // Section: File
  88. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_file_creation_", comment: ""))
  89. form.addFormSection(section)
  90. if arrayImages.count == 1 {
  91. row = XLFormRowDescriptor(tag: "filetype", rowType: XLFormRowDescriptorTypeSelectorSegmentedControl, title: NSLocalizedString("_file_type_", comment: ""))
  92. row.selectorOptions = ["PDF","JPG"]
  93. row.value = "PDF"
  94. row.cellConfig["tintColor"] = NCBrandColor.sharedInstance.brand
  95. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  96. section.addFormRow(row)
  97. }
  98. row = XLFormRowDescriptor(tag: "fileName", rowType: XLFormRowDescriptorTypeAccount, title: NSLocalizedString("_filename_", comment: ""))
  99. row.value = self.fileName
  100. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  101. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  102. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  103. section.addFormRow(row)
  104. self.form = form
  105. }
  106. override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) {
  107. super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
  108. if formRow.tag == "fileName" {
  109. self.form.delegate = nil
  110. let fileNameNew = newValue as? String
  111. if fileNameNew != nil {
  112. self.fileName = CCUtility.removeForbiddenCharactersServer(fileNameNew)
  113. } else {
  114. self.fileName = ""
  115. }
  116. formRow.value = self.fileName
  117. self.updateFormRow(formRow)
  118. self.form.delegate = self
  119. }
  120. if formRow.tag == "compressionQuality" {
  121. self.form.delegate = nil
  122. //let row : XLFormRowDescriptor = self.form.formRow(withTag: "descriptionQuality")!
  123. let newQuality = newValue as? NSNumber
  124. let compressionQuality = (newQuality?.doubleValue)!
  125. if compressionQuality >= 0.0 && compressionQuality <= 0.3 {
  126. formRow.title = NSLocalizedString("_quality_low_", comment: "")
  127. dpiQuality = typeDpiQuality.low
  128. } else if compressionQuality > 0.3 && compressionQuality <= 0.6 {
  129. formRow.title = NSLocalizedString("_quality_medium_", comment: "")
  130. dpiQuality = typeDpiQuality.medium
  131. } else if compressionQuality > 0.6 && compressionQuality <= 1.0 {
  132. formRow.title = NSLocalizedString("_quality_high_", comment: "")
  133. dpiQuality = typeDpiQuality.hight
  134. }
  135. self.updateFormRow(formRow)
  136. self.form.delegate = self
  137. }
  138. if formRow.tag == "password" {
  139. let stringPassword = newValue as? String
  140. if stringPassword != nil {
  141. password = PDFPassword(stringPassword!)
  142. } else {
  143. password = PDFPassword("")
  144. }
  145. }
  146. if formRow.tag == "filetype" {
  147. fileType = newValue as! String
  148. let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  149. let rowPassword : XLFormRowDescriptor = self.form.formRow(withTag: "password")!
  150. // rowFileName
  151. guard var name = rowFileName.value else {
  152. return
  153. }
  154. if name as! String == "" {
  155. name = CCUtility.createFileNameDate("scan", extension: "pdf") ?? "scan.pdf"
  156. }
  157. let ext = (name as! NSString).pathExtension.uppercased()
  158. var newFileName = ""
  159. if (ext == "") {
  160. newFileName = name as! String + "." + fileType.lowercased()
  161. } else {
  162. newFileName = (name as! NSString).deletingPathExtension + "." + fileType.lowercased()
  163. }
  164. rowFileName.value = newFileName
  165. self.updateFormRow(rowFileName)
  166. // rowPassword
  167. if fileType == "JPG" {
  168. rowPassword.value = ""
  169. password = PDFPassword("")
  170. rowPassword.disabled = true
  171. } else {
  172. rowPassword.disabled = false
  173. }
  174. self.updateFormRow(rowPassword)
  175. }
  176. }
  177. override func textFieldDidBeginEditing(_ textField: UITextField) {
  178. let cell = textField.formDescriptorCell()
  179. let tag = cell?.rowDescriptor.tag
  180. if tag == "fileName" {
  181. CCUtility.selectFileName(from: textField)
  182. }
  183. }
  184. // MARK: - View Life Cycle
  185. override func viewDidLoad() {
  186. super.viewDidLoad()
  187. let saveButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
  188. self.navigationItem.rightBarButtonItem = saveButton
  189. self.navigationController?.navigationBar.isTranslucent = false
  190. self.navigationController?.navigationBar.barTintColor = NCBrandColor.sharedInstance.brand
  191. self.navigationController?.navigationBar.tintColor = NCBrandColor.sharedInstance.brandText
  192. self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: NCBrandColor.sharedInstance.brandText]
  193. self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
  194. // self.tableView.sectionHeaderHeight = 10
  195. // self.tableView.sectionFooterHeight = 10
  196. // self.tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  197. // let row : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  198. // let rowCell = row.cell(forForm: self)
  199. // rowCell.becomeFirstResponder()
  200. }
  201. // MARK: - Action
  202. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String) {
  203. if serverUrl != nil {
  204. self.serverUrl = serverUrl!
  205. if serverUrl == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  206. self.titleServerUrl = "/"
  207. } else {
  208. self.titleServerUrl = (serverUrl! as NSString).lastPathComponent
  209. }
  210. // Update
  211. let row : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  212. row.title = self.titleServerUrl
  213. self.updateFormRow(row)
  214. }
  215. }
  216. @objc func save() {
  217. let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  218. guard let name = rowFileName.value else {
  219. return
  220. }
  221. if name as! String == "" {
  222. return
  223. }
  224. let ext = (name as! NSString).pathExtension.uppercased()
  225. var fileNameSave = ""
  226. if (ext == "") {
  227. fileNameSave = name as! String + "." + fileType.lowercased()
  228. } else {
  229. fileNameSave = (name as! NSString).deletingPathExtension + "." + fileType.lowercased()
  230. }
  231. let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", appDelegate.activeAccount, self.serverUrl, fileNameSave))
  232. if (metadata != nil) {
  233. let alertController = UIAlertController(title: fileNameSave, message: NSLocalizedString("_file_already_exists_", comment: ""), preferredStyle: .alert)
  234. let cancelAction = UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .default) { (action:UIAlertAction) in
  235. }
  236. let overwriteAction = UIAlertAction(title: NSLocalizedString("_overwrite_", comment: ""), style: .cancel) { (action:UIAlertAction) in
  237. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", self.appDelegate.activeAccount, self.serverUrl, fileNameSave))
  238. self.dismissAndUpload(fileNameSave, fileID: CCUtility.createMetadataID(fromAccount: self.appDelegate.activeAccount, serverUrl: self.serverUrl, fileNameView: fileNameSave, directory: false)!, serverUrl: self.serverUrl)
  239. }
  240. alertController.addAction(cancelAction)
  241. alertController.addAction(overwriteAction)
  242. self.present(alertController, animated: true, completion:nil)
  243. } else {
  244. dismissAndUpload(fileNameSave, fileID: CCUtility.createMetadataID(fromAccount: appDelegate.activeAccount, serverUrl: serverUrl, fileNameView: fileNameSave, directory: false)!, serverUrl: serverUrl)
  245. }
  246. }
  247. func dismissAndUpload(_ fileNameSave: String, fileID: String, serverUrl: String) {
  248. guard let fileNameGenerateExport = CCUtility.getDirectoryProviderStorageFileID(fileID, fileNameView: fileNameSave) else {
  249. self.appDelegate.messageNotification("_error_", description: "_error_creation_file_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: 0)
  250. return
  251. }
  252. if fileType == "PDF" {
  253. var pdfPages = [PDFPage]()
  254. //Generate PDF
  255. for var image in self.arrayImages {
  256. image = changeImageFromQuality(image, dpiQuality: dpiQuality)
  257. guard let data = image.jpegData(compressionQuality: 0.5) else {
  258. self.appDelegate.messageNotification("_error_", description: "_error_creation_file_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: 0)
  259. return
  260. }
  261. let page = PDFPage.image(UIImage(data: data)!)
  262. pdfPages.append(page)
  263. }
  264. do {
  265. try PDFGenerator.generate(pdfPages, to: fileNameGenerateExport, password: password)
  266. } catch {
  267. self.appDelegate.messageNotification("_error_", description: "_error_creation_file_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: 0)
  268. return
  269. }
  270. }
  271. if fileType == "JPG" {
  272. let image = changeImageFromQuality(self.arrayImages[0], dpiQuality: dpiQuality)
  273. guard let data = image.jpegData(compressionQuality: CGFloat(0.5)) else {
  274. self.appDelegate.messageNotification("_error_", description: "_error_creation_file_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: 0)
  275. return
  276. }
  277. do {
  278. try data.write(to: NSURL.fileURL(withPath: fileNameGenerateExport), options: .atomic)
  279. } catch {
  280. self.appDelegate.messageNotification("_error_", description: "_error_creation_file_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: 0)
  281. return
  282. }
  283. }
  284. //Create metadata for upload
  285. let metadataForUpload = tableMetadata()
  286. metadataForUpload.account = self.appDelegate.activeAccount
  287. metadataForUpload.date = NSDate()
  288. metadataForUpload.fileID = fileID
  289. metadataForUpload.fileName = fileNameSave
  290. metadataForUpload.fileNameView = fileNameSave
  291. metadataForUpload.serverUrl = serverUrl
  292. metadataForUpload.session = k_upload_session
  293. metadataForUpload.sessionSelector = selectorUploadFile
  294. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  295. _ = NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  296. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: self.serverUrl, fileID: nil, action: Int32(k_action_NULL))
  297. self.appDelegate.startLoadAutoDownloadUpload()
  298. // Request delete all image scanned
  299. let alertController = UIAlertController(title: "", message: NSLocalizedString("_delete_all_scanned_images_", comment: ""), preferredStyle: .alert)
  300. let actionYes = UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (action:UIAlertAction) in
  301. let path = CCUtility.getDirectoryScan()!
  302. do {
  303. let filePaths = try FileManager.default.contentsOfDirectory(atPath: path)
  304. for filePath in filePaths {
  305. try FileManager.default.removeItem(atPath: path + "/" + filePath)
  306. }
  307. } catch let error as NSError {
  308. print("Error: \(error.debugDescription)")
  309. }
  310. self.dismiss(animated: true, completion: nil)
  311. }
  312. let actionNo = UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (action:UIAlertAction) in
  313. self.dismiss(animated: true, completion: nil)
  314. }
  315. alertController.addAction(actionYes)
  316. alertController.addAction(actionNo)
  317. self.present(alertController, animated: true, completion:nil)
  318. }
  319. func cancel() {
  320. self.dismiss(animated: true, completion: nil)
  321. }
  322. @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) {
  323. self.deselectFormRow(sender)
  324. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  325. let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
  326. let viewController = navigationController.topViewController as! NCSelect
  327. viewController.delegate = self
  328. viewController.hideButtonCreateFolder = false
  329. viewController.includeDirectoryE2EEncryption = true
  330. viewController.includeImages = false
  331. viewController.layoutViewSelect = k_layout_view_move
  332. viewController.selectFile = false
  333. viewController.titleButtonDone = NSLocalizedString("_select_", comment: "")
  334. viewController.type = ""
  335. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  336. self.present(navigationController, animated: true, completion: nil)
  337. }
  338. func changeImageFromQuality(_ image: UIImage, dpiQuality: typeDpiQuality) -> UIImage {
  339. let imageWidthInPixels = image.size.width * image.scale
  340. let imageHeightInPixels = image.size.height * image.scale
  341. switch dpiQuality {
  342. case typeDpiQuality.low: // 72 DPI
  343. if imageWidthInPixels > 595 || imageHeightInPixels > 842 {
  344. return CCGraphics.scale(image, to: CGSize(width: 595, height: 842), isAspectRation: true)
  345. }
  346. case typeDpiQuality.medium: // 150 DPI
  347. if imageWidthInPixels > 1240 || imageHeightInPixels > 1754 {
  348. return CCGraphics.scale(image, to: CGSize(width: 1240, height: 1754), isAspectRation: true)
  349. }
  350. case typeDpiQuality.hight: // 200 DPI
  351. if imageWidthInPixels > 1654 || imageHeightInPixels > 2339 {
  352. return CCGraphics.scale(image, to: CGSize(width: 1654, height: 2339), isAspectRation: true)
  353. }
  354. }
  355. return image
  356. }
  357. }
  358. class NCCreateScanDocument : NSObject, ImageScannerControllerDelegate {
  359. @objc static let sharedInstance: NCCreateScanDocument = {
  360. let instance = NCCreateScanDocument()
  361. return instance
  362. }()
  363. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  364. var viewController: UIViewController?
  365. var openScan: Bool = false
  366. func openScannerDocument(viewController: UIViewController, openScan: Bool) {
  367. self.viewController = viewController
  368. self.openScan = openScan
  369. let scannerVC = ImageScannerController()
  370. scannerVC.imageScannerDelegate = self
  371. self.viewController?.present(scannerVC, animated: true, completion: nil)
  372. }
  373. func imageScannerController(_ scanner: ImageScannerController, didFinishScanningWithResults results: ImageScannerResults) {
  374. let fileName = CCUtility.createFileName("scan.png", fileDate: Date(), fileType: PHAssetMediaType.image, keyFileName: k_keyFileNameMask, keyFileNameType: k_keyFileNameType, keyFileNameOriginal: k_keyFileNameOriginal)!
  375. let fileNamePath = CCUtility.getDirectoryScan() + "/" + fileName
  376. // V 1.0
  377. if (results.doesUserPreferEnhancedImage && results.enhancedImage != nil) {
  378. do {
  379. try results.enhancedImage!.pngData()?.write(to: NSURL.fileURL(withPath: fileNamePath), options: .atomic)
  380. } catch { }
  381. } else {
  382. do {
  383. try results.scannedImage.pngData()?.write(to: NSURL.fileURL(withPath: fileNamePath), options: .atomic)
  384. } catch { }
  385. }
  386. // 0.9.1
  387. /*
  388. do {
  389. try results.scannedImage.pngData()?.write(to: NSURL.fileURL(withPath: fileNamePath), options: .atomic)
  390. } catch { }
  391. */
  392. scanner.dismiss(animated: true, completion: {
  393. if (self.openScan) {
  394. let storyboard = UIStoryboard(name: "Scan", bundle: nil)
  395. let controller = storyboard.instantiateInitialViewController()!
  396. controller.modalPresentationStyle = UIModalPresentationStyle.pageSheet
  397. self.viewController?.present(controller, animated: true, completion: nil)
  398. }
  399. })
  400. }
  401. func imageScannerControllerDidCancel(_ scanner: ImageScannerController) {
  402. scanner.dismiss(animated: true, completion: nil)
  403. }
  404. func imageScannerController(_ scanner: ImageScannerController, didFailWithError error: Error) {
  405. appDelegate.messageNotification("_error_", description: error.localizedDescription, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  406. }
  407. }