NCCreateFormUploadScanDocument.swift 30 KB

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