NCCreateFormUploadScanDocument.swift 30 KB

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