CCCreateCloud.swift 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  1. //
  2. // CCCreateCloud.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 09/01/17.
  6. // Copyright © 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  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. // MARK: -
  25. class CreateMenuAdd: NSObject {
  26. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  27. let fontButton = [NSAttributedString.Key.font:UIFont(name: "HelveticaNeue", size: 16)!, NSAttributedString.Key.foregroundColor: UIColor.black]
  28. let fontEncrypted = [NSAttributedString.Key.font:UIFont(name: "HelveticaNeue", size: 16)!, NSAttributedString.Key.foregroundColor: NCBrandColor.sharedInstance.encrypted as UIColor]
  29. let fontCancel = [NSAttributedString.Key.font:UIFont(name: "HelveticaNeue-Bold", size: 17)!, NSAttributedString.Key.foregroundColor: UIColor.black]
  30. let fontDisable = [NSAttributedString.Key.font:UIFont(name: "HelveticaNeue", size: 16)!, NSAttributedString.Key.foregroundColor: UIColor.darkGray]
  31. let colorLightGray = UIColor(red: 250.0/255.0, green: 250.0/255.0, blue: 250.0/255.0, alpha: 1)
  32. let colorGray = UIColor(red: 150.0/255.0, green: 150.0/255.0, blue: 150.0/255.0, alpha: 1)
  33. var colorIcon = NCBrandColor.sharedInstance.brandElement
  34. @objc init (themingColor : UIColor) {
  35. super.init()
  36. colorIcon = themingColor
  37. }
  38. @objc func createMenu(view : UIView) {
  39. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  40. let actionSheet = AHKActionSheet.init(view: view, title: nil)!
  41. actionSheet.animationDuration = 0.2
  42. actionSheet.automaticallyTintButtonImages = 0
  43. actionSheet.buttonHeight = 50.0
  44. actionSheet.cancelButtonHeight = 50.0
  45. actionSheet.separatorHeight = 5.0
  46. actionSheet.separatorColor = NCBrandColor.sharedInstance.seperator
  47. actionSheet.buttonTextAttributes = fontButton
  48. actionSheet.encryptedButtonTextAttributes = fontEncrypted
  49. actionSheet.cancelButtonTextAttributes = fontCancel
  50. actionSheet.disableButtonTextAttributes = fontDisable
  51. actionSheet.cancelButtonTitle = NSLocalizedString("_cancel_", comment: "")
  52. actionSheet.addButton(withTitle: NSLocalizedString("_upload_photos_videos_", comment: ""), image: CCGraphics.changeThemingColorImage(UIImage(named: "media"), multiplier:2, color: colorGray), backgroundColor: NCBrandColor.sharedInstance.backgroundView, height: 50.0, type: AHKActionSheetButtonType.default, handler: {(AHKActionSheet) -> Void in
  53. appDelegate.activeMain.openAssetsPickerController()
  54. })
  55. actionSheet.addButton(withTitle: NSLocalizedString("_upload_file_", comment: ""), image: CCGraphics.changeThemingColorImage(UIImage(named: "file"), multiplier:2, color: colorGray), backgroundColor: NCBrandColor.sharedInstance.backgroundView, height: 50.0, type: AHKActionSheetButtonType.default, handler: {(AHKActionSheet) -> Void in
  56. appDelegate.activeMain.openImportDocumentPicker()
  57. })
  58. actionSheet.addButton(withTitle: NSLocalizedString("_upload_file_text_", comment: ""), image: CCGraphics.changeThemingColorImage(UIImage(named: "file_txt"), multiplier:2, color: colorGray), backgroundColor: NCBrandColor.sharedInstance.backgroundView, height: 50.0, type: AHKActionSheetButtonType.default, handler: {(AHKActionSheet) -> Void in
  59. let storyboard = UIStoryboard(name: "NCText", bundle: nil)
  60. let controller = storyboard.instantiateViewController(withIdentifier: "NCText")
  61. controller.modalPresentationStyle = UIModalPresentationStyle.pageSheet
  62. appDelegate.activeMain.present(controller, animated: true, completion: nil)
  63. })
  64. if #available(iOS 11.0, *) {
  65. actionSheet.addButton(withTitle: NSLocalizedString("_scans_document_", comment: ""), image: CCGraphics.changeThemingColorImage(UIImage(named: "scan"), multiplier:2, color: colorGray), backgroundColor: NCBrandColor.sharedInstance.backgroundView, height: 50.0, type: AHKActionSheetButtonType.default, handler: {(AHKActionSheet) -> Void in
  66. NCCreateScanDocument.sharedInstance.openScannerDocument(viewController: appDelegate.activeMain, openScan: true)
  67. })
  68. }
  69. actionSheet.addButton(withTitle: NSLocalizedString("_create_folder_", comment: ""), image: CCGraphics.changeThemingColorImage(UIImage(named: "folder"), multiplier:2, color: colorIcon), backgroundColor: NCBrandColor.sharedInstance.backgroundView, height: 50.0 ,type: AHKActionSheetButtonType.default, handler: {(AHKActionSheet) -> Void in
  70. appDelegate.activeMain.createFolder()
  71. })
  72. actionSheet.show()
  73. }
  74. }
  75. // MARK: -
  76. @objc protocol createFormUploadAssetsDelegate {
  77. func dismissFormUploadAssets()
  78. }
  79. // MARK: -
  80. class CreateFormUploadAssets: XLFormViewController, CCMoveDelegate {
  81. var serverUrl : String = ""
  82. var titleServerUrl : String?
  83. var assets: NSMutableArray = []
  84. var cryptated : Bool = false
  85. var session : String = ""
  86. weak var delegate: createFormUploadAssetsDelegate?
  87. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  88. @objc convenience init(serverUrl : String, assets : NSMutableArray, cryptated : Bool, session : String, delegate: createFormUploadAssetsDelegate) {
  89. self.init()
  90. if serverUrl == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  91. titleServerUrl = "/"
  92. } else {
  93. titleServerUrl = (serverUrl as NSString).lastPathComponent
  94. }
  95. self.serverUrl = serverUrl
  96. self.assets = assets
  97. self.cryptated = cryptated
  98. self.session = session
  99. self.delegate = delegate
  100. self.initializeForm()
  101. }
  102. //MARK: XLFormDescriptorDelegate
  103. func initializeForm() {
  104. let form : XLFormDescriptor = XLFormDescriptor(title: NSLocalizedString("_upload_photos_videos_", comment: "")) as XLFormDescriptor
  105. form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow
  106. var section : XLFormSectionDescriptor
  107. var row : XLFormRowDescriptor
  108. // Section: Destination Folder
  109. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: ""))
  110. form.addFormSection(section)
  111. row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: self.titleServerUrl)
  112. row.action.formSelector = #selector(changeDestinationFolder(_:))
  113. let imageFolder = CCGraphics.changeThemingColorImage(UIImage(named: "folder")!, multiplier:2, color: NCBrandColor.sharedInstance.brandElement) as UIImage
  114. row.cellConfig["imageView.image"] = imageFolder
  115. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
  116. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  117. section.addFormRow(row)
  118. // User folder Media
  119. row = XLFormRowDescriptor(tag: "useFolderMedia", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_use_folder_media_", comment: ""))
  120. row.value = 0
  121. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  122. section.addFormRow(row)
  123. // Use Sub folder
  124. row = XLFormRowDescriptor(tag: "useSubFolder", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_autoupload_create_subfolder_", comment: ""))
  125. let tableAccount = NCManageDatabase.sharedInstance.getAccountActive()
  126. if tableAccount?.autoUploadCreateSubfolder == true {
  127. row.value = 1
  128. } else {
  129. row.value = 0
  130. }
  131. row.hidden = "$\("useFolderMedia") == 0"
  132. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  133. section.addFormRow(row)
  134. // Section Mode filename
  135. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_mode_filename_", comment: ""))
  136. form.addFormSection(section)
  137. // Maintain the original fileName
  138. row = XLFormRowDescriptor(tag: "maintainOriginalFileName", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_maintain_original_filename_", comment: ""))
  139. row.value = CCUtility.getOriginalFileName(k_keyFileNameOriginal)
  140. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  141. section.addFormRow(row)
  142. // Add File Name Type
  143. row = XLFormRowDescriptor(tag: "addFileNameType", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_add_filenametype_", comment: ""))
  144. row.value = CCUtility.getFileNameType(k_keyFileNameType)
  145. row.hidden = "$\("maintainOriginalFileName") == 1"
  146. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  147. section.addFormRow(row)
  148. // Section: Rename File Name
  149. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_filename_", comment: ""))
  150. form.addFormSection(section)
  151. row = XLFormRowDescriptor(tag: "maskFileName", rowType: XLFormRowDescriptorTypeAccount, title: (NSLocalizedString("_filename_", comment: "")))
  152. let fileNameMask : String = CCUtility.getFileNameMask(k_keyFileNameMask)
  153. if fileNameMask.count > 0 {
  154. row.value = fileNameMask
  155. }
  156. row.hidden = "$\("maintainOriginalFileName") == 1"
  157. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  158. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  159. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  160. section.addFormRow(row)
  161. // Section: Preview File Name
  162. row = XLFormRowDescriptor(tag: "previewFileName", rowType: XLFormRowDescriptorTypeTextView, title: "")
  163. row.height = 180
  164. row.disabled = true
  165. row.cellConfig["textView.backgroundColor"] = NCBrandColor.sharedInstance.backgroundView
  166. row.cellConfig["textView.font"] = UIFont.systemFont(ofSize: 14.0)
  167. section.addFormRow(row)
  168. self.form = form
  169. }
  170. override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) {
  171. super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
  172. if formRow.tag == "useFolderMedia" {
  173. if (formRow.value! as AnyObject).boolValue == true {
  174. let buttonDestinationFolder : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  175. buttonDestinationFolder.hidden = true
  176. } else{
  177. let buttonDestinationFolder : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  178. buttonDestinationFolder.hidden = false
  179. }
  180. }
  181. else if formRow.tag == "useSubFolder" {
  182. if (formRow.value! as AnyObject).boolValue == true {
  183. } else{
  184. }
  185. }
  186. else if formRow.tag == "maintainOriginalFileName" {
  187. CCUtility.setOriginalFileName((formRow.value! as AnyObject).boolValue, key: k_keyFileNameOriginal)
  188. self.reloadForm()
  189. }
  190. else if formRow.tag == "addFileNameType" {
  191. CCUtility.setFileNameType((formRow.value! as AnyObject).boolValue, key: k_keyFileNameType)
  192. self.reloadForm()
  193. }
  194. else if formRow.tag == "maskFileName" {
  195. let fileName = formRow.value as? String
  196. self.form.delegate = nil
  197. if let fileName = fileName {
  198. formRow.value = CCUtility.removeForbiddenCharactersServer(fileName)
  199. }
  200. self.form.delegate = self
  201. let previewFileName : XLFormRowDescriptor = self.form.formRow(withTag: "previewFileName")!
  202. previewFileName.value = self.previewFileName(valueRename: formRow.value as? String)
  203. // reload cell
  204. if fileName != nil {
  205. if newValue as! String != formRow.value as! String {
  206. self.reloadFormRow(formRow)
  207. appDelegate.messageNotification("_info_", description: "_forbidden_characters_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: 0)
  208. }
  209. }
  210. self.reloadFormRow(previewFileName)
  211. }
  212. }
  213. // MARK: - View Life Cycle
  214. override func viewDidLoad() {
  215. super.viewDidLoad()
  216. let cancelButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(cancel))
  217. let saveButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
  218. self.navigationItem.leftBarButtonItem = cancelButton
  219. self.navigationItem.rightBarButtonItem = saveButton
  220. self.navigationController?.navigationBar.isTranslucent = false
  221. self.navigationController?.navigationBar.barTintColor = NCBrandColor.sharedInstance.brand
  222. self.navigationController?.navigationBar.tintColor = NCBrandColor.sharedInstance.brandText
  223. self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: NCBrandColor.sharedInstance.brandText]
  224. self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
  225. self.reloadForm()
  226. }
  227. override func viewWillDisappear(_ animated: Bool)
  228. {
  229. super.viewWillDisappear(animated)
  230. self.delegate?.dismissFormUploadAssets()
  231. }
  232. func reloadForm() {
  233. self.form.delegate = nil
  234. let buttonDestinationFolder : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  235. buttonDestinationFolder.title = self.titleServerUrl
  236. let maskFileName : XLFormRowDescriptor = self.form.formRow(withTag: "maskFileName")!
  237. let previewFileName : XLFormRowDescriptor = self.form.formRow(withTag: "previewFileName")!
  238. previewFileName.value = self.previewFileName(valueRename: maskFileName.value as? String)
  239. self.tableView.reloadData()
  240. self.form.delegate = self
  241. }
  242. // MARK: - Action
  243. func moveServerUrl(to serverUrlTo: String!, title: String!) {
  244. self.serverUrl = serverUrlTo
  245. if let title = title {
  246. self.titleServerUrl = title
  247. } else {
  248. self.titleServerUrl = "/"
  249. }
  250. self.reloadForm()
  251. }
  252. @objc func save() {
  253. self.dismiss(animated: true, completion: {
  254. let useFolderPhotoRow : XLFormRowDescriptor = self.form.formRow(withTag: "useFolderMedia")!
  255. let useSubFolderRow : XLFormRowDescriptor = self.form.formRow(withTag: "useSubFolder")!
  256. var useSubFolder : Bool = false
  257. if (useFolderPhotoRow.value! as AnyObject).boolValue == true {
  258. self.serverUrl = NCManageDatabase.sharedInstance.getAccountAutoUploadPath(self.appDelegate.activeUrl)
  259. useSubFolder = (useSubFolderRow.value! as AnyObject).boolValue
  260. }
  261. self.appDelegate.activeMain.uploadFileAsset(self.assets, serverUrl: self.serverUrl, useSubFolder: useSubFolder, session: self.session)
  262. })
  263. }
  264. @objc func cancel() {
  265. self.dismiss(animated: true, completion: nil)
  266. }
  267. // MARK: - Utility
  268. func previewFileName(valueRename : String?) -> String {
  269. var returnString: String = ""
  270. let asset = assets[0] as! PHAsset
  271. if (CCUtility.getOriginalFileName(k_keyFileNameOriginal)) {
  272. return (NSLocalizedString("_filename_", comment: "") + ": " + (asset.value(forKey: "filename") as! String))
  273. } else if let valueRename = valueRename {
  274. let valueRenameTrimming = valueRename.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
  275. if valueRenameTrimming.count > 0 {
  276. self.form.delegate = nil
  277. CCUtility.setFileNameMask(valueRename, key: k_keyFileNameMask)
  278. self.form.delegate = self
  279. returnString = CCUtility.createFileName(asset.value(forKey: "filename") as! String?, fileDate: asset.creationDate, fileType: asset.mediaType, keyFileName: k_keyFileNameMask, keyFileNameType: k_keyFileNameType, keyFileNameOriginal: k_keyFileNameOriginal)
  280. } else {
  281. CCUtility.setFileNameMask("", key: k_keyFileNameMask)
  282. returnString = CCUtility.createFileName(asset.value(forKey: "filename") as! String?, fileDate: asset.creationDate, fileType: asset.mediaType, keyFileName: nil, keyFileNameType: k_keyFileNameType, keyFileNameOriginal: k_keyFileNameOriginal)
  283. }
  284. } else {
  285. CCUtility.setFileNameMask("", key: k_keyFileNameMask)
  286. returnString = CCUtility.createFileName(asset.value(forKey: "filename") as! String?, fileDate: asset.creationDate, fileType: asset.mediaType, keyFileName: nil, keyFileNameType: k_keyFileNameType, keyFileNameOriginal: k_keyFileNameOriginal)
  287. }
  288. return String(format: NSLocalizedString("_preview_filename_", comment: ""), "MM,MMM,DD,YY,YYYY and HH,hh,mm,ss,ampm") + ":" + "\n\n" + returnString
  289. }
  290. @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) {
  291. self.deselectFormRow(sender)
  292. let storyboard : UIStoryboard = UIStoryboard(name: "CCMove", bundle: nil)
  293. let navigationController = storyboard.instantiateViewController(withIdentifier: "CCMove") as! UINavigationController
  294. let viewController : CCMove = navigationController.topViewController as! CCMove
  295. viewController.delegate = self;
  296. viewController.tintColor = NCBrandColor.sharedInstance.brandText
  297. viewController.barTintColor = NCBrandColor.sharedInstance.brand
  298. viewController.tintColorTitle = NCBrandColor.sharedInstance.brandText
  299. viewController.move.title = NSLocalizedString("_select_", comment: "");
  300. viewController.networkingOperationQueue = appDelegate.netQueue
  301. // E2EE
  302. viewController.includeDirectoryE2EEncryption = true;
  303. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  304. self.present(navigationController, animated: true, completion: nil)
  305. }
  306. }
  307. // MARK: -
  308. class CreateFormUploadFileText: XLFormViewController, CCMoveDelegate {
  309. var serverUrl = ""
  310. var titleServerUrl = ""
  311. var fileName = ""
  312. var text = ""
  313. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  314. convenience init(serverUrl: String, text: String, fileName: String) {
  315. self.init()
  316. if serverUrl == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  317. titleServerUrl = "/"
  318. } else {
  319. titleServerUrl = (serverUrl as NSString).lastPathComponent
  320. }
  321. self.fileName = fileName
  322. self.serverUrl = serverUrl
  323. self.text = text
  324. initializeForm()
  325. }
  326. //MARK: XLFormDescriptorDelegate
  327. func initializeForm() {
  328. let form : XLFormDescriptor = XLFormDescriptor() as XLFormDescriptor
  329. form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow
  330. var section : XLFormSectionDescriptor
  331. var row : XLFormRowDescriptor
  332. // Section: Destination Folder
  333. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: ""))
  334. form.addFormSection(section)
  335. row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: self.titleServerUrl)
  336. row.action.formSelector = #selector(changeDestinationFolder(_:))
  337. let imageFolder = CCGraphics.changeThemingColorImage(UIImage(named: "folder")!, multiplier:2, color: NCBrandColor.sharedInstance.brandElement) as UIImage
  338. row.cellConfig["imageView.image"] = imageFolder
  339. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
  340. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  341. section.addFormRow(row)
  342. // Section: File Name
  343. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_filename_", comment: ""))
  344. form.addFormSection(section)
  345. row = XLFormRowDescriptor(tag: "fileName", rowType: XLFormRowDescriptorTypeAccount, title: NSLocalizedString("_filename_", comment: ""))
  346. row.value = self.fileName
  347. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  348. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  349. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  350. section.addFormRow(row)
  351. self.form = form
  352. }
  353. override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) {
  354. super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
  355. if formRow.tag == "fileName" {
  356. self.form.delegate = nil
  357. if let fileNameNew = formRow.value {
  358. self.fileName = CCUtility.removeForbiddenCharactersServer(fileNameNew as? String)
  359. }
  360. formRow.value = self.fileName
  361. self.title = fileName
  362. self.updateFormRow(formRow)
  363. self.form.delegate = self
  364. }
  365. }
  366. // MARK: - View Life Cycle
  367. override func viewDidLoad() {
  368. super.viewDidLoad()
  369. let saveButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
  370. self.navigationItem.rightBarButtonItem = saveButton
  371. self.navigationController?.navigationBar.isTranslucent = false
  372. self.navigationController?.navigationBar.barTintColor = NCBrandColor.sharedInstance.brand
  373. self.navigationController?.navigationBar.tintColor = NCBrandColor.sharedInstance.brandText
  374. self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: NCBrandColor.sharedInstance.brandText]
  375. self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
  376. }
  377. // MARK: - Action
  378. func moveServerUrl(to serverUrlTo: String!, title: String!) {
  379. self.serverUrl = serverUrlTo
  380. if let title = title {
  381. self.titleServerUrl = title
  382. } else {
  383. self.titleServerUrl = "/"
  384. }
  385. // Update
  386. let row : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  387. row.title = self.titleServerUrl
  388. self.updateFormRow(row)
  389. }
  390. @objc func save() {
  391. let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  392. guard let name = rowFileName.value else {
  393. return
  394. }
  395. let ext = (name as! NSString).pathExtension.uppercased()
  396. var fileNameSave = ""
  397. if (ext == "") {
  398. fileNameSave = name as! String + ".txt"
  399. } else if (CCUtility.isDocumentModifiableExtension(ext)) {
  400. fileNameSave = name as! String
  401. } else {
  402. fileNameSave = (name as! NSString).deletingPathExtension + ".txt"
  403. }
  404. guard let directoryID = NCManageDatabase.sharedInstance.getDirectoryID(self.serverUrl) else {
  405. return
  406. }
  407. let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "directoryID == %@ AND fileNameView == %@", directoryID, fileNameSave))
  408. if (metadata != nil) {
  409. let alertController = UIAlertController(title: fileNameSave, message: NSLocalizedString("_file_already_exists_", comment: ""), preferredStyle: .alert)
  410. let cancelAction = UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .default) { (action:UIAlertAction) in
  411. }
  412. let overwriteAction = UIAlertAction(title: NSLocalizedString("_overwrite_", comment: ""), style: .cancel) { (action:UIAlertAction) in
  413. self.dismissAndUpload(fileNameSave, fileID: metadata!.fileID, directoryID: directoryID)
  414. }
  415. alertController.addAction(cancelAction)
  416. alertController.addAction(overwriteAction)
  417. self.present(alertController, animated: true, completion:nil)
  418. } else {
  419. let directoryID = NCManageDatabase.sharedInstance.getDirectoryID(self.serverUrl)!
  420. dismissAndUpload(fileNameSave, fileID: directoryID + fileNameSave, directoryID: directoryID)
  421. }
  422. }
  423. func dismissAndUpload(_ fileNameSave: String, fileID: String, directoryID: String) {
  424. self.dismiss(animated: true, completion: {
  425. let data = self.text.data(using: .utf8)
  426. let success = FileManager.default.createFile(atPath: CCUtility.getDirectoryProviderStorageFileID(fileID, fileNameView: fileNameSave), contents: data, attributes: nil)
  427. if success {
  428. let metadataForUpload = tableMetadata()
  429. metadataForUpload.account = self.appDelegate.activeAccount
  430. metadataForUpload.date = NSDate()
  431. metadataForUpload.directoryID = directoryID
  432. metadataForUpload.fileID = fileID
  433. metadataForUpload.fileName = fileNameSave
  434. metadataForUpload.fileNameView = fileNameSave
  435. metadataForUpload.session = k_upload_session
  436. metadataForUpload.sessionSelector = selectorUploadFile
  437. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  438. _ = NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  439. self.appDelegate.perform(#selector(self.appDelegate.loadAutoDownloadUpload), on: Thread.main, with: nil, waitUntilDone: true)
  440. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: self.serverUrl, fileID: nil, action: Int32(k_action_NULL))
  441. } else {
  442. self.appDelegate.messageNotification("_error_", description: "_error_creation_file_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: 0)
  443. }
  444. })
  445. }
  446. func cancel() {
  447. self.dismiss(animated: true, completion: nil)
  448. }
  449. @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) {
  450. self.deselectFormRow(sender)
  451. let storyboard : UIStoryboard = UIStoryboard(name: "CCMove", bundle: nil)
  452. let navigationController = storyboard.instantiateViewController(withIdentifier: "CCMove") as! UINavigationController
  453. let viewController : CCMove = navigationController.topViewController as! CCMove
  454. viewController.delegate = self;
  455. viewController.tintColor = NCBrandColor.sharedInstance.brandText
  456. viewController.barTintColor = NCBrandColor.sharedInstance.brand
  457. viewController.tintColorTitle = NCBrandColor.sharedInstance.brandText
  458. viewController.move.title = NSLocalizedString("_select_", comment: "");
  459. viewController.networkingOperationQueue = appDelegate.netQueue
  460. // E2EE
  461. viewController.includeDirectoryE2EEncryption = true;
  462. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  463. self.present(navigationController, animated: true, completion: nil)
  464. }
  465. }
  466. //MARK: -
  467. class CreateFormUploadScanDocument: XLFormViewController, CCMoveDelegate {
  468. var serverUrl = ""
  469. var titleServerUrl = ""
  470. var arrayImages = [UIImage]()
  471. var fileName = CCUtility.createFileNameDate("scan", extension: "pdf")
  472. var password : PDFPassword = ""
  473. var compressionQuality: Double = 0.5
  474. var fileType = "PDF"
  475. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  476. convenience init(serverUrl: String, arrayImages: [UIImage]) {
  477. self.init()
  478. if serverUrl == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  479. titleServerUrl = "/"
  480. } else {
  481. titleServerUrl = (serverUrl as NSString).lastPathComponent
  482. }
  483. self.serverUrl = serverUrl
  484. self.arrayImages = arrayImages
  485. initializeForm()
  486. }
  487. //MARK: XLFormDescriptorDelegate
  488. func initializeForm() {
  489. let form : XLFormDescriptor = XLFormDescriptor(title: NSLocalizedString("_save_settings_", comment: "")) as XLFormDescriptor
  490. form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow
  491. var section : XLFormSectionDescriptor
  492. var row : XLFormRowDescriptor
  493. // Section: Destination Folder
  494. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: ""))
  495. form.addFormSection(section)
  496. row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: self.titleServerUrl)
  497. row.action.formSelector = #selector(changeDestinationFolder(_:))
  498. let imageFolder = CCGraphics.changeThemingColorImage(UIImage(named: "folder")!, multiplier:2, color: NCBrandColor.sharedInstance.brandElement) as UIImage
  499. row.cellConfig["imageView.image"] = imageFolder
  500. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
  501. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  502. section.addFormRow(row)
  503. // Section: Quality
  504. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_quality_image_title_", comment: ""))
  505. form.addFormSection(section)
  506. row = XLFormRowDescriptor(tag: "compressionQuality", rowType: XLFormRowDescriptorTypeSlider)
  507. row.value = 0.5
  508. row.title = NSLocalizedString("_quality_medium_", comment: "")
  509. row.cellConfig["slider.minimumTrackTintColor"] = NCBrandColor.sharedInstance.brand
  510. row.cellConfig["slider.maximumValue"] = 1
  511. row.cellConfig["slider.minimumValue"] = 0
  512. row.cellConfig["steps"] = 2
  513. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.center.rawValue
  514. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  515. section.addFormRow(row)
  516. // Section: Password
  517. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_pdf_password_", comment: ""))
  518. form.addFormSection(section)
  519. row = XLFormRowDescriptor(tag: "password", rowType: XLFormRowDescriptorTypePassword, title: NSLocalizedString("_password_", comment: ""))
  520. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  521. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  522. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  523. section.addFormRow(row)
  524. // Section: File
  525. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_file_creation_", comment: ""))
  526. form.addFormSection(section)
  527. if arrayImages.count == 1 {
  528. row = XLFormRowDescriptor(tag: "filetype", rowType: XLFormRowDescriptorTypeSelectorSegmentedControl, title: NSLocalizedString("_file_type_", comment: ""))
  529. row.selectorOptions = ["PDF","JPG"]
  530. row.value = "PDF"
  531. row.cellConfig["tintColor"] = NCBrandColor.sharedInstance.brand
  532. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  533. section.addFormRow(row)
  534. }
  535. row = XLFormRowDescriptor(tag: "fileName", rowType: XLFormRowDescriptorTypeAccount, title: NSLocalizedString("_filename_", comment: ""))
  536. row.value = self.fileName
  537. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  538. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  539. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  540. section.addFormRow(row)
  541. self.form = form
  542. }
  543. override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) {
  544. super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
  545. if formRow.tag == "fileName" {
  546. self.form.delegate = nil
  547. let fileNameNew = newValue as? String
  548. if fileNameNew != nil {
  549. self.fileName = CCUtility.removeForbiddenCharactersServer(fileNameNew)
  550. } else {
  551. self.fileName = ""
  552. }
  553. formRow.value = self.fileName
  554. self.updateFormRow(formRow)
  555. self.form.delegate = self
  556. }
  557. if formRow.tag == "compressionQuality" {
  558. self.form.delegate = nil
  559. //let row : XLFormRowDescriptor = self.form.formRow(withTag: "descriptionQuality")!
  560. let newQuality = newValue as? NSNumber
  561. compressionQuality = (newQuality?.doubleValue)!
  562. if compressionQuality >= 0.0 && compressionQuality <= 0.3 {
  563. formRow.title = NSLocalizedString("_quality_low_", comment: "")
  564. compressionQuality = 0.1
  565. } else if compressionQuality >= 0.4 && compressionQuality <= 0.6 {
  566. formRow.title = NSLocalizedString("_quality_medium_", comment: "")
  567. compressionQuality = 0.5
  568. } else if compressionQuality >= 0.7 && compressionQuality <= 1.0 {
  569. formRow.title = NSLocalizedString("_quality_high_", comment: "")
  570. compressionQuality = 0.8
  571. }
  572. self.updateFormRow(formRow)
  573. self.form.delegate = self
  574. }
  575. if formRow.tag == "password" {
  576. let stringPassword = newValue as? String
  577. if stringPassword != nil {
  578. password = PDFPassword(stringPassword!)
  579. } else {
  580. password = PDFPassword("")
  581. }
  582. }
  583. if formRow.tag == "filetype" {
  584. fileType = newValue as! String
  585. let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  586. let rowPassword : XLFormRowDescriptor = self.form.formRow(withTag: "password")!
  587. // rowFileName
  588. guard var name = rowFileName.value else {
  589. return
  590. }
  591. if name as! String == "" {
  592. name = CCUtility.createFileNameDate("scan", extension: "pdf")
  593. }
  594. let ext = (name as! NSString).pathExtension.uppercased()
  595. var newFileName = ""
  596. if (ext == "") {
  597. newFileName = name as! String + "." + fileType.lowercased()
  598. } else {
  599. newFileName = (name as! NSString).deletingPathExtension + "." + fileType.lowercased()
  600. }
  601. rowFileName.value = newFileName
  602. self.updateFormRow(rowFileName)
  603. // rowPassword
  604. if fileType == "JPG" {
  605. rowPassword.value = ""
  606. password = PDFPassword("")
  607. rowPassword.disabled = true
  608. } else {
  609. rowPassword.disabled = false
  610. }
  611. self.updateFormRow(rowPassword)
  612. }
  613. }
  614. // MARK: - View Life Cycle
  615. override func viewDidLoad() {
  616. super.viewDidLoad()
  617. let saveButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
  618. self.navigationItem.rightBarButtonItem = saveButton
  619. self.navigationController?.navigationBar.isTranslucent = false
  620. self.navigationController?.navigationBar.barTintColor = NCBrandColor.sharedInstance.brand
  621. self.navigationController?.navigationBar.tintColor = NCBrandColor.sharedInstance.brandText
  622. self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: NCBrandColor.sharedInstance.brandText]
  623. self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
  624. // self.tableView.sectionHeaderHeight = 10
  625. // self.tableView.sectionFooterHeight = 10
  626. // self.tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  627. // let row : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  628. // let rowCell = row.cell(forForm: self)
  629. // rowCell.becomeFirstResponder()
  630. }
  631. // MARK: - Action
  632. func moveServerUrl(to serverUrlTo: String!, title: String!) {
  633. self.serverUrl = serverUrlTo
  634. if let title = title {
  635. self.titleServerUrl = title
  636. } else {
  637. self.titleServerUrl = "/"
  638. }
  639. // Update
  640. let row : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  641. row.title = self.titleServerUrl
  642. self.updateFormRow(row)
  643. }
  644. @objc func save() {
  645. let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  646. guard let name = rowFileName.value else {
  647. return
  648. }
  649. if name as! String == "" {
  650. return
  651. }
  652. let ext = (name as! NSString).pathExtension.uppercased()
  653. var fileNameSave = ""
  654. if (ext == "") {
  655. fileNameSave = name as! String + "." + fileType.lowercased()
  656. } else {
  657. fileNameSave = (name as! NSString).deletingPathExtension + "." + fileType.lowercased()
  658. }
  659. guard let directoryID = NCManageDatabase.sharedInstance.getDirectoryID(self.serverUrl) else {
  660. return
  661. }
  662. let metadata = NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "directoryID == %@ AND fileNameView == %@", directoryID, fileNameSave))
  663. if (metadata != nil) {
  664. let alertController = UIAlertController(title: fileNameSave, message: NSLocalizedString("_file_already_exists_", comment: ""), preferredStyle: .alert)
  665. let cancelAction = UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .default) { (action:UIAlertAction) in
  666. }
  667. let overwriteAction = UIAlertAction(title: NSLocalizedString("_overwrite_", comment: ""), style: .cancel) { (action:UIAlertAction) in
  668. NCManageDatabase.sharedInstance.deleteMetadata(predicate: NSPredicate(format: "directoryID == %@ AND fileNameView == %@", directoryID, fileNameSave), clearDateReadDirectoryID: directoryID)
  669. self.dismissAndUpload(fileNameSave, fileID: directoryID + fileNameSave, directoryID: directoryID)
  670. }
  671. alertController.addAction(cancelAction)
  672. alertController.addAction(overwriteAction)
  673. self.present(alertController, animated: true, completion:nil)
  674. } else {
  675. let directoryID = NCManageDatabase.sharedInstance.getDirectoryID(self.serverUrl)!
  676. dismissAndUpload(fileNameSave, fileID: directoryID + fileNameSave, directoryID: directoryID)
  677. }
  678. }
  679. func dismissAndUpload(_ fileNameSave: String, fileID: String, directoryID: String) {
  680. guard let fileNameGenerateExport = CCUtility.getDirectoryProviderStorageFileID(fileID, fileNameView: fileNameSave) else {
  681. self.appDelegate.messageNotification("_error_", description: "_error_creation_file_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: 0)
  682. return
  683. }
  684. if fileType == "PDF" {
  685. var pdfPages = [PDFPage]()
  686. //Generate PDF
  687. for image in self.arrayImages {
  688. guard let data = image.jpegData(compressionQuality: CGFloat(compressionQuality)) else {
  689. self.appDelegate.messageNotification("_error_", description: "_error_creation_file_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: 0)
  690. return
  691. }
  692. let page = PDFPage.image(UIImage(data: data)!)
  693. pdfPages.append(page)
  694. }
  695. do {
  696. try PDFGenerator.generate(pdfPages, to: fileNameGenerateExport, password: password)
  697. } catch {
  698. self.appDelegate.messageNotification("_error_", description: "_error_creation_file_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: 0)
  699. return
  700. }
  701. }
  702. if fileType == "JPG" {
  703. guard let data = self.arrayImages[0].jpegData(compressionQuality: CGFloat(compressionQuality)) else {
  704. self.appDelegate.messageNotification("_error_", description: "_error_creation_file_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: 0)
  705. return
  706. }
  707. do {
  708. try data.write(to: NSURL.fileURL(withPath: fileNameGenerateExport), options: .atomic)
  709. } catch {
  710. self.appDelegate.messageNotification("_error_", description: "_error_creation_file_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: 0)
  711. return
  712. }
  713. }
  714. //Create metadata for upload
  715. let metadataForUpload = tableMetadata()
  716. metadataForUpload.account = self.appDelegate.activeAccount
  717. metadataForUpload.date = NSDate()
  718. metadataForUpload.directoryID = directoryID
  719. metadataForUpload.fileID = fileID
  720. metadataForUpload.fileName = fileNameSave
  721. metadataForUpload.fileNameView = fileNameSave
  722. metadataForUpload.session = k_upload_session
  723. metadataForUpload.sessionSelector = selectorUploadFile
  724. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  725. _ = NCManageDatabase.sharedInstance.addMetadata(metadataForUpload)
  726. self.appDelegate.perform(#selector(self.appDelegate.loadAutoDownloadUpload), on: Thread.main, with: nil, waitUntilDone: true)
  727. NCMainCommon.sharedInstance.reloadDatasource(ServerUrl: self.serverUrl, fileID: nil, action: Int32(k_action_NULL))
  728. self.dismiss(animated: true, completion: nil)
  729. }
  730. func cancel() {
  731. self.dismiss(animated: true, completion: nil)
  732. }
  733. @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) {
  734. self.deselectFormRow(sender)
  735. let storyboard : UIStoryboard = UIStoryboard(name: "CCMove", bundle: nil)
  736. let navigationController = storyboard.instantiateViewController(withIdentifier: "CCMove") as! UINavigationController
  737. let viewController : CCMove = navigationController.topViewController as! CCMove
  738. viewController.delegate = self;
  739. viewController.tintColor = NCBrandColor.sharedInstance.brandText
  740. viewController.barTintColor = NCBrandColor.sharedInstance.brand
  741. viewController.tintColorTitle = NCBrandColor.sharedInstance.brandText
  742. viewController.move.title = NSLocalizedString("_select_", comment: "");
  743. viewController.networkingOperationQueue = appDelegate.netQueue
  744. // E2EE
  745. viewController.includeDirectoryE2EEncryption = true;
  746. navigationController.modalPresentationStyle = UIModalPresentationStyle.formSheet
  747. self.present(navigationController, animated: true, completion: nil)
  748. }
  749. }
  750. class NCCreateScanDocument : NSObject, ImageScannerControllerDelegate {
  751. @objc static let sharedInstance: NCCreateScanDocument = {
  752. let instance = NCCreateScanDocument()
  753. return instance
  754. }()
  755. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  756. var viewController: UIViewController?
  757. var openScan: Bool = false
  758. @available(iOS 10, *)
  759. func openScannerDocument(viewController: UIViewController, openScan: Bool) {
  760. self.viewController = viewController
  761. self.openScan = openScan
  762. let scannerVC = ImageScannerController()
  763. scannerVC.imageScannerDelegate = self
  764. self.viewController?.present(scannerVC, animated: true, completion: nil)
  765. }
  766. @available(iOS 10, *)
  767. func imageScannerController(_ scanner: ImageScannerController, didFinishScanningWithResults results: ImageScannerResults) {
  768. let fileName = CCUtility.createFileName("scan.png", fileDate: Date(), fileType: PHAssetMediaType.image, keyFileName: k_keyFileNameMask, keyFileNameType: k_keyFileNameType, keyFileNameOriginal: k_keyFileNameOriginal)!
  769. let fileNamePath = CCUtility.getDirectoryScan() + "/" + fileName
  770. // A4 74 DPI : 595 x 842 px
  771. var image = results.scannedImage
  772. let imageWidthInPixels = image.size.width * results.scannedImage.scale
  773. let imageHeightInPixels = image.size.height * results.scannedImage.scale
  774. if imageWidthInPixels > 595 || imageHeightInPixels > 842 {
  775. image = CCGraphics.scale(image, to: CGSize(width: 595, height: 842), isAspectRation: true)
  776. }
  777. do {
  778. try image.pngData()?.write(to: NSURL.fileURL(withPath: fileNamePath), options: .atomic)
  779. } catch { }
  780. scanner.dismiss(animated: true, completion: {
  781. if (self.openScan) {
  782. let storyboard = UIStoryboard(name: "Scan", bundle: nil)
  783. let controller = storyboard.instantiateInitialViewController()!
  784. controller.modalPresentationStyle = UIModalPresentationStyle.pageSheet
  785. self.viewController?.present(controller, animated: true, completion: nil)
  786. }
  787. })
  788. }
  789. @available(iOS 10, *)
  790. func imageScannerControllerDidCancel(_ scanner: ImageScannerController) {
  791. scanner.dismiss(animated: true, completion: nil)
  792. }
  793. @available(iOS 10, *)
  794. func imageScannerController(_ scanner: ImageScannerController, didFailWithError error: Error) {
  795. appDelegate.messageNotification("_error_", description: error.localizedDescription, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  796. }
  797. }