NCCreateFormUploadScanDocument.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. //
  2. // NCCreateFormUploadScanDocument.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 14/11/2018.
  6. // Copyright © 2018 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 WeScan
  25. import NCCommunication
  26. #if GOOGLEMOBILEVISION
  27. import GoogleMobileVision
  28. #endif
  29. class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NCCreateFormUploadConflictDelegate {
  30. enum typeDpiQuality {
  31. case low
  32. case medium
  33. case hight
  34. }
  35. var dpiQuality: typeDpiQuality = typeDpiQuality.medium
  36. var serverUrl = ""
  37. var titleServerUrl = ""
  38. var arrayImages = [UIImage]()
  39. var fileName = CCUtility.createFileNameDate("scan", extension: "pdf")
  40. var password: String = ""
  41. var fileType = "PDF"
  42. #if GOOGLEMOBILEVISION
  43. var textDetector: GMVDetector?
  44. #endif
  45. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  46. convenience init(serverUrl: String, arrayImages: [UIImage]) {
  47. self.init()
  48. if serverUrl == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  49. titleServerUrl = "/"
  50. } else {
  51. titleServerUrl = (serverUrl as NSString).lastPathComponent
  52. }
  53. self.serverUrl = serverUrl
  54. self.arrayImages = arrayImages
  55. }
  56. // MARK: - View Life Cycle
  57. override func viewDidLoad() {
  58. super.viewDidLoad()
  59. self.title = NSLocalizedString("_save_settings_", comment: "")
  60. let saveButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
  61. self.navigationItem.rightBarButtonItem = saveButton
  62. self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
  63. // self.tableView.sectionHeaderHeight = 10
  64. // self.tableView.sectionFooterHeight = 10
  65. // self.tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  66. // let row : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  67. // let rowCell = row.cell(forForm: self)
  68. // rowCell.becomeFirstResponder()
  69. #if GOOGLEMOBILEVISION
  70. textDetector = GMVDetector(ofType: GMVDetectorTypeText, options: nil)
  71. #endif
  72. // Theming view
  73. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  74. changeTheming()
  75. }
  76. @objc func changeTheming() {
  77. appDelegate.changeTheming(self, tableView: tableView, collectionView: nil, form: true)
  78. initializeForm()
  79. }
  80. //MARK: XLForm
  81. func initializeForm() {
  82. let form : XLFormDescriptor = XLFormDescriptor() as XLFormDescriptor
  83. form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow
  84. var section : XLFormSectionDescriptor
  85. var row : XLFormRowDescriptor
  86. // Section: Destination Folder
  87. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: ""))
  88. form.addFormSection(section)
  89. row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: self.titleServerUrl)
  90. row.action.formSelector = #selector(changeDestinationFolder(_:))
  91. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  92. row.cellConfig["imageView.image"] = CCGraphics.changeThemingColorImage(UIImage(named: "folder")!, width: 50, height: 50, color: NCBrandColor.sharedInstance.brandElement) as UIImage
  93. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
  94. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  95. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  96. section.addFormRow(row)
  97. // Section: Quality
  98. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_quality_image_title_", comment: ""))
  99. form.addFormSection(section)
  100. row = XLFormRowDescriptor(tag: "compressionQuality", rowType: XLFormRowDescriptorTypeSlider)
  101. row.value = 0.5
  102. row.title = NSLocalizedString("_quality_medium_", comment: "")
  103. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  104. row.cellConfig["slider.minimumTrackTintColor"] = NCBrandColor.sharedInstance.brand
  105. row.cellConfig["slider.maximumValue"] = 1
  106. row.cellConfig["slider.minimumValue"] = 0
  107. row.cellConfig["steps"] = 2
  108. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.center.rawValue
  109. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  110. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  111. section.addFormRow(row)
  112. // Section: Password
  113. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_pdf_password_", comment: ""))
  114. form.addFormSection(section)
  115. row = XLFormRowDescriptor(tag: "password", rowType: XLFormRowDescriptorTypePassword, title: NSLocalizedString("_password_", comment: ""))
  116. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  117. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  118. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  119. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  120. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  121. row.cellConfig["textField.textColor"] = NCBrandColor.sharedInstance.textView
  122. section.addFormRow(row)
  123. // Section: Text recognition
  124. #if GOOGLEMOBILEVISION
  125. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_text_recognition_", comment: ""))
  126. form.addFormSection(section)
  127. row = XLFormRowDescriptor(tag: "textRecognition", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_text_recognition_", comment: ""))
  128. row.value = 0
  129. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  130. row.cellConfig["imageView.image"] = CCGraphics.changeThemingColorImage(UIImage(named: "textRecognition")!, width: 50, height: 50, color: NCBrandColor.sharedInstance.brandElement) as UIImage
  131. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  132. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  133. section.addFormRow(row)
  134. #endif
  135. // Section: File
  136. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_file_creation_", comment: ""))
  137. form.addFormSection(section)
  138. row = XLFormRowDescriptor(tag: "filetype", rowType: XLFormRowDescriptorTypeSelectorSegmentedControl, title: NSLocalizedString("_file_type_", comment: ""))
  139. if arrayImages.count == 1 {
  140. row.selectorOptions = ["PDF","JPG"]
  141. } else {
  142. row.selectorOptions = ["PDF"]
  143. }
  144. row.value = "PDF"
  145. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  146. row.cellConfig["tintColor"] = NCBrandColor.sharedInstance.brand
  147. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  148. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  149. section.addFormRow(row)
  150. row = XLFormRowDescriptor(tag: "fileName", rowType: XLFormRowDescriptorTypeAccount, title: NSLocalizedString("_filename_", comment: ""))
  151. row.value = self.fileName
  152. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  153. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  154. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  155. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  156. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  157. row.cellConfig["textField.textColor"] = NCBrandColor.sharedInstance.textView
  158. section.addFormRow(row)
  159. self.form = form
  160. }
  161. override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) {
  162. super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
  163. if formRow.tag == "textRecognition" {
  164. let rowCompressionQuality: XLFormRowDescriptor = self.form.formRow(withTag: "compressionQuality")!
  165. let rowFileTape: XLFormRowDescriptor = self.form.formRow(withTag: "filetype")!
  166. let rowFileName: XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  167. let rowPassword: XLFormRowDescriptor = self.form.formRow(withTag: "password")!
  168. self.form.delegate = nil
  169. if newValue as! Int == 1 {
  170. rowFileTape.selectorOptions = ["PDF","TXT"]
  171. rowFileTape.value = "PDF"
  172. fileType = "PDF"
  173. rowPassword.disabled = true
  174. rowCompressionQuality.disabled = true
  175. } else {
  176. if arrayImages.count == 1 {
  177. rowFileTape.selectorOptions = ["PDF","JPG"]
  178. } else {
  179. rowFileTape.selectorOptions = ["PDF"]
  180. }
  181. rowFileTape.value = "PDF"
  182. fileType = "PDF"
  183. rowPassword.disabled = false
  184. rowCompressionQuality.disabled = false
  185. }
  186. rowFileName.value = createFileName(rowFileName.value as? String)
  187. self.updateFormRow(rowFileName)
  188. self.tableView.reloadData()
  189. self.form.delegate = self
  190. }
  191. if formRow.tag == "fileName" {
  192. self.form.delegate = nil
  193. let fileNameNew = newValue as? String
  194. if fileNameNew != nil {
  195. self.fileName = CCUtility.removeForbiddenCharactersServer(fileNameNew)
  196. } else {
  197. self.fileName = ""
  198. }
  199. formRow.value = self.fileName
  200. self.updateFormRow(formRow)
  201. self.form.delegate = self
  202. }
  203. if formRow.tag == "compressionQuality" {
  204. self.form.delegate = nil
  205. //let row : XLFormRowDescriptor = self.form.formRow(withTag: "descriptionQuality")!
  206. let newQuality = newValue as? NSNumber
  207. let compressionQuality = (newQuality?.doubleValue)!
  208. if compressionQuality >= 0.0 && compressionQuality <= 0.3 {
  209. formRow.title = NSLocalizedString("_quality_low_", comment: "")
  210. dpiQuality = typeDpiQuality.low
  211. } else if compressionQuality > 0.3 && compressionQuality <= 0.6 {
  212. formRow.title = NSLocalizedString("_quality_medium_", comment: "")
  213. dpiQuality = typeDpiQuality.medium
  214. } else if compressionQuality > 0.6 && compressionQuality <= 1.0 {
  215. formRow.title = NSLocalizedString("_quality_high_", comment: "")
  216. dpiQuality = typeDpiQuality.hight
  217. }
  218. self.updateFormRow(formRow)
  219. self.form.delegate = self
  220. }
  221. if formRow.tag == "password" {
  222. let stringPassword = newValue as? String
  223. if stringPassword != nil {
  224. password = stringPassword!
  225. } else {
  226. password = ""
  227. }
  228. }
  229. if formRow.tag == "filetype" {
  230. fileType = newValue as! String
  231. let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  232. let rowPassword : XLFormRowDescriptor = self.form.formRow(withTag: "password")!
  233. rowFileName.value = createFileName(rowFileName.value as? String)
  234. self.updateFormRow(rowFileName)
  235. // rowPassword
  236. if fileType == "JPG" || fileType == "TXT" {
  237. rowPassword.value = ""
  238. password = ""
  239. rowPassword.disabled = true
  240. } else {
  241. rowPassword.disabled = false
  242. }
  243. self.updateFormRow(rowPassword)
  244. }
  245. }
  246. override func textFieldDidBeginEditing(_ textField: UITextField) {
  247. let cell = textField.formDescriptorCell()
  248. let tag = cell?.rowDescriptor.tag
  249. if tag == "fileName" {
  250. CCUtility.selectFileName(from: textField)
  251. }
  252. }
  253. func createFileName(_ fileName: String?) -> String {
  254. var name: String = ""
  255. var newFileName: String = ""
  256. if fileName == nil || fileName == "" {
  257. name = CCUtility.createFileNameDate("scan", extension: "pdf") ?? "scan.pdf"
  258. } else {
  259. name = fileName!
  260. }
  261. let ext = (name as NSString).pathExtension.uppercased()
  262. if (ext == "") {
  263. newFileName = name + "." + fileType.lowercased()
  264. } else {
  265. newFileName = (name as NSString).deletingPathExtension + "." + fileType.lowercased()
  266. }
  267. return newFileName
  268. }
  269. // MARK: - Action
  270. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, buttonType: String, overwrite: Bool) {
  271. if serverUrl != nil {
  272. self.serverUrl = serverUrl!
  273. if serverUrl == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  274. self.titleServerUrl = "/"
  275. } else {
  276. self.titleServerUrl = (serverUrl! as NSString).lastPathComponent
  277. }
  278. // Update
  279. let row : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  280. row.title = self.titleServerUrl
  281. self.updateFormRow(row)
  282. }
  283. }
  284. @objc func save() {
  285. let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  286. guard let name = rowFileName.value else {
  287. return
  288. }
  289. if name as! String == "" {
  290. return
  291. }
  292. let ext = (name as! NSString).pathExtension.uppercased()
  293. var fileNameSave = ""
  294. if (ext == "") {
  295. fileNameSave = name as! String + "." + fileType.lowercased()
  296. } else {
  297. fileNameSave = (name as! NSString).deletingPathExtension + "." + fileType.lowercased()
  298. }
  299. //Create metadata for upload
  300. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.activeAccount, fileName: fileNameSave, ocId: UUID().uuidString, serverUrl: serverUrl, url: appDelegate.activeUrl, contentType: "")
  301. metadataForUpload.session = NCCommunicationCommon.shared.sessionIdentifierBackground
  302. metadataForUpload.sessionSelector = selectorUploadFile
  303. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  304. if NCUtility.sharedInstance.getMetadataConflict(account: appDelegate.activeAccount, serverUrl: serverUrl, fileName: fileNameSave) != nil {
  305. guard let conflictViewController = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict else { return }
  306. conflictViewController.textLabelDetailNewFile = NSLocalizedString("_now_", comment: "")
  307. conflictViewController.serverUrl = serverUrl
  308. conflictViewController.metadatasUploadInConflict = [metadataForUpload]
  309. conflictViewController.delegate = self
  310. self.present(conflictViewController, animated: true, completion: nil)
  311. } else {
  312. dismissAndUpload(metadataForUpload)
  313. }
  314. }
  315. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  316. if metadatas != nil && metadatas!.count > 0 {
  317. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  318. self.dismissAndUpload(metadatas![0])
  319. }
  320. }
  321. }
  322. func dismissAndUpload(_ metadata: tableMetadata) {
  323. guard let fileNameGenerateExport = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else {
  324. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: 0)
  325. return
  326. }
  327. #if GOOGLEMOBILEVISION
  328. // Text Recognition TXT
  329. if fileType == "TXT" && self.form.formRow(withTag: "textRecognition")!.value as! Int == 1 {
  330. var textFile = ""
  331. for image in self.arrayImages {
  332. guard let features = self.textDetector?.features(in: image, options: nil) as? [GMVTextBlockFeature] else {
  333. continue
  334. }
  335. for textBlock in features {
  336. guard let text = textBlock.value else {
  337. continue
  338. }
  339. textFile = textFile + text + "\n\n"
  340. }
  341. do {
  342. try textFile.write(to: NSURL(fileURLWithPath: fileNameGenerateExport) as URL , atomically: true, encoding: .utf8)
  343. } catch {
  344. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: 0)
  345. return
  346. }
  347. }
  348. }
  349. #endif
  350. if fileType == "PDF" {
  351. let pdfData = NSMutableData()
  352. if password.count > 0 {
  353. let info: [AnyHashable: Any] = [kCGPDFContextUserPassword as String : password, kCGPDFContextOwnerPassword as String : password]
  354. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, info)
  355. } else {
  356. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
  357. }
  358. let context = UIGraphicsGetCurrentContext()
  359. for var image in self.arrayImages {
  360. #if GOOGLEMOBILEVISION
  361. if self.form.formRow(withTag: "textRecognition")!.value as! Int == 1 {
  362. UIGraphicsBeginPDFPageWithInfo(CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height), nil)
  363. UIImageView.init(image:image).layer.render(in: context!)
  364. if let features = self.textDetector?.features(in: image, options: nil) as? [GMVTextBlockFeature] {
  365. for textBlock in features {
  366. for textLine in textBlock.lines {
  367. let bounds = textLine.bounds
  368. let text = textLine.value!
  369. var fontColor = UIColor.clear
  370. #if targetEnvironment(simulator)
  371. fontColor = UIColor.red
  372. #endif
  373. //print(text)
  374. let font = UIFont.systemFont(ofSize: bounds.size.height, weight: .regular)
  375. let bestFittingFont = NCUtility.sharedInstance.bestFittingFont(for: text, in: bounds, fontDescriptor: font.fontDescriptor)
  376. text.draw(in: bounds, withAttributes: [NSAttributedString.Key.font: bestFittingFont, NSAttributedString.Key.foregroundColor: fontColor])
  377. }
  378. }
  379. }
  380. } else {
  381. image = changeImageFromQuality(image, dpiQuality: dpiQuality)
  382. UIGraphicsBeginPDFPageWithInfo(CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height), nil)
  383. UIImageView.init(image:image).layer.render(in: context!)
  384. }
  385. #else
  386. image = changeImageFromQuality(image, dpiQuality: dpiQuality)
  387. UIGraphicsBeginPDFPageWithInfo(CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height), nil)
  388. UIImageView.init(image:image).layer.render(in: context!)
  389. #endif
  390. }
  391. UIGraphicsEndPDFContext();
  392. do {
  393. try pdfData.write(toFile: fileNameGenerateExport, options: .atomic)
  394. } catch {
  395. print("error catched")
  396. }
  397. }
  398. if fileType == "JPG" {
  399. let image = changeImageFromQuality(self.arrayImages[0], dpiQuality: dpiQuality)
  400. guard let data = image.jpegData(compressionQuality: CGFloat(0.5)) else {
  401. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: 0)
  402. return
  403. }
  404. do {
  405. try data.write(to: NSURL.fileURL(withPath: fileNameGenerateExport), options: .atomic)
  406. } catch {
  407. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: 0)
  408. return
  409. }
  410. }
  411. NCManageDatabase.sharedInstance.addMetadata(metadata)
  412. self.appDelegate.startLoadAutoUpload()
  413. // Request delete all image scanned
  414. let alertController = UIAlertController(title: "", message: NSLocalizedString("_delete_all_scanned_images_", comment: ""), preferredStyle: .alert)
  415. let actionYes = UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (action:UIAlertAction) in
  416. let path = CCUtility.getDirectoryScan()!
  417. do {
  418. let filePaths = try FileManager.default.contentsOfDirectory(atPath: path)
  419. for filePath in filePaths {
  420. try FileManager.default.removeItem(atPath: path + "/" + filePath)
  421. }
  422. } catch let error as NSError {
  423. print("Error: \(error.debugDescription)")
  424. }
  425. self.dismiss(animated: true, completion: nil)
  426. }
  427. let actionNo = UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (action:UIAlertAction) in
  428. self.dismiss(animated: true, completion: nil)
  429. }
  430. alertController.addAction(actionYes)
  431. alertController.addAction(actionNo)
  432. self.present(alertController, animated: true, completion:nil)
  433. }
  434. func cancel() {
  435. self.dismiss(animated: true, completion: nil)
  436. }
  437. @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) {
  438. self.deselectFormRow(sender)
  439. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  440. let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
  441. let viewController = navigationController.topViewController as! NCSelect
  442. viewController.delegate = self
  443. viewController.hideButtonCreateFolder = false
  444. viewController.includeDirectoryE2EEncryption = true
  445. viewController.includeImages = false
  446. viewController.layoutViewSelect = k_layout_view_move
  447. viewController.selectFile = false
  448. viewController.titleButtonDone = NSLocalizedString("_select_", comment: "")
  449. viewController.type = ""
  450. navigationController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  451. self.present(navigationController, animated: true, completion: nil)
  452. }
  453. func changeImageFromQuality(_ image: UIImage, dpiQuality: typeDpiQuality) -> UIImage {
  454. let imageWidthInPixels = image.size.width * image.scale
  455. let imageHeightInPixels = image.size.height * image.scale
  456. switch dpiQuality {
  457. case typeDpiQuality.low: // 72 DPI
  458. if imageWidthInPixels > 595 || imageHeightInPixels > 842 {
  459. return CCGraphics.scale(image, to: CGSize(width: 595, height: 842), isAspectRation: true)
  460. }
  461. case typeDpiQuality.medium: // 150 DPI
  462. if imageWidthInPixels > 1240 || imageHeightInPixels > 1754 {
  463. return CCGraphics.scale(image, to: CGSize(width: 1240, height: 1754), isAspectRation: true)
  464. }
  465. case typeDpiQuality.hight: // 200 DPI
  466. if imageWidthInPixels > 1654 || imageHeightInPixels > 2339 {
  467. return CCGraphics.scale(image, to: CGSize(width: 1654, height: 2339), isAspectRation: true)
  468. }
  469. }
  470. return image
  471. }
  472. }
  473. class NCCreateScanDocument : NSObject, ImageScannerControllerDelegate {
  474. @objc static let sharedInstance: NCCreateScanDocument = {
  475. let instance = NCCreateScanDocument()
  476. return instance
  477. }()
  478. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  479. var viewController: UIViewController?
  480. func openScannerDocument(viewController: UIViewController) {
  481. self.viewController = viewController
  482. let scannerVC = ImageScannerController()
  483. scannerVC.imageScannerDelegate = self
  484. scannerVC.navigationBar.isTranslucent = false
  485. scannerVC.navigationBar.barTintColor = NCBrandColor.sharedInstance.brand
  486. scannerVC.navigationBar.tintColor = NCBrandColor.sharedInstance.brandText
  487. scannerVC.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: NCBrandColor.sharedInstance.brandText]
  488. self.viewController?.present(scannerVC, animated: true, completion: nil)
  489. }
  490. func imageScannerController(_ scanner: ImageScannerController, didFinishScanningWithResults results: ImageScannerResults) {
  491. let fileName = CCUtility.createFileName("scan.png", fileDate: Date(), fileType: PHAssetMediaType.image, keyFileName: k_keyFileNameMask, keyFileNameType: k_keyFileNameType, keyFileNameOriginal: k_keyFileNameOriginal)!
  492. let fileNamePath = CCUtility.getDirectoryScan() + "/" + fileName
  493. let image: UIImage?
  494. if results.doesUserPreferEnhancedScan {
  495. image = results.enhancedScan?.image
  496. } else {
  497. image = results.croppedScan.image
  498. }
  499. if image != nil {
  500. do {
  501. try image!.pngData()?.write(to: NSURL.fileURL(withPath: fileNamePath))
  502. } catch { }
  503. }
  504. scanner.dismiss(animated: true, completion: {
  505. if self.viewController is DragDropViewController {
  506. (self.viewController as! DragDropViewController).loadImage()
  507. } else {
  508. let storyboard = UIStoryboard(name: "Scan", bundle: nil)
  509. let controller = storyboard.instantiateInitialViewController()!
  510. controller.modalPresentationStyle = UIModalPresentationStyle.pageSheet
  511. self.viewController?.present(controller, animated: true, completion: nil)
  512. }
  513. })
  514. }
  515. func imageScannerControllerDidCancel(_ scanner: ImageScannerController) {
  516. scanner.dismiss(animated: true, completion: nil)
  517. }
  518. func imageScannerController(_ scanner: ImageScannerController, didFailWithError error: Error) {
  519. NCContentPresenter.shared.messageNotification("_error_", description: error.localizedDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  520. }
  521. }