NCCreateFormUploadScanDocument.swift 30 KB

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