NCCreateFormUploadAssets.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. //
  2. // NCCreateFormUploadAssets.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 14/11/2018.
  6. // Copyright © 2018 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import Foundation
  24. @objc protocol createFormUploadAssetsDelegate {
  25. func dismissFormUploadAssets()
  26. }
  27. class NCCreateFormUploadAssets: XLFormViewController, NCSelectDelegate, PhotoEditorDelegate {
  28. var serverUrl: String = ""
  29. var titleServerUrl: String?
  30. var assets = NSMutableArray()
  31. var cryptated: Bool = false
  32. var session: String = ""
  33. weak var delegate: createFormUploadAssetsDelegate?
  34. let requestOptions = PHImageRequestOptions()
  35. var imagePreview: UIImage?
  36. let targetSizeImagePreview = CGSize(width:100, height: 100)
  37. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  38. @objc convenience init(serverUrl : String, assets : NSMutableArray, cryptated : Bool, session : String, delegate: createFormUploadAssetsDelegate) {
  39. self.init()
  40. if serverUrl == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  41. titleServerUrl = "/"
  42. } else {
  43. titleServerUrl = (serverUrl as NSString).lastPathComponent
  44. }
  45. self.serverUrl = serverUrl
  46. self.assets = assets
  47. self.cryptated = cryptated
  48. self.session = session
  49. self.delegate = delegate
  50. requestOptions.resizeMode = PHImageRequestOptionsResizeMode.exact
  51. requestOptions.deliveryMode = PHImageRequestOptionsDeliveryMode.highQualityFormat
  52. requestOptions.isSynchronous = true
  53. if assets.count == 1 && (assets[0] as! PHAsset).mediaType == PHAssetMediaType.image {
  54. PHImageManager.default().requestImage(for: assets[0] as! PHAsset, targetSize: targetSizeImagePreview, contentMode: PHImageContentMode.aspectFill, options: requestOptions, resultHandler: { (image, info) in
  55. self.imagePreview = image
  56. self.initializeForm()
  57. })
  58. } else {
  59. self.initializeForm()
  60. }
  61. }
  62. //MARK: XLFormDescriptorDelegate
  63. func initializeForm() {
  64. let form : XLFormDescriptor = XLFormDescriptor(title: NSLocalizedString("_upload_photos_videos_", comment: "")) as XLFormDescriptor
  65. form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow
  66. var section : XLFormSectionDescriptor
  67. var row : XLFormRowDescriptor
  68. // Section Photo Editor only for one photo
  69. if assets.count == 1 && (assets[0] as! PHAsset).mediaType == PHAssetMediaType.image && self.imagePreview != nil {
  70. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_modify_photo_", comment: ""))
  71. form.addFormSection(section)
  72. row = XLFormRowDescriptor(tag: "ButtonPhotoEditor", rowType: XLFormRowDescriptorTypeButton, title: NSLocalizedString("_modify_photo_", comment: ""))
  73. row.action.formSelector = #selector(photoEditor(_:))
  74. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  75. row.cellConfig["imageView.image"] = self.imagePreview
  76. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  77. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
  78. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  79. section.addFormRow(row)
  80. }
  81. // Section: Destination Folder
  82. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: ""))
  83. form.addFormSection(section)
  84. row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: self.titleServerUrl)
  85. row.action.formSelector = #selector(changeDestinationFolder(_:))
  86. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  87. row.cellConfig["imageView.image"] = CCGraphics.changeThemingColorImage(UIImage(named: "folder")!, width: 50, height: 50, color: NCBrandColor.sharedInstance.brandElement) as UIImage
  88. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
  89. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  90. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  91. section.addFormRow(row)
  92. // User folder Autoupload
  93. row = XLFormRowDescriptor(tag: "useFolderAutoUpload", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_use_folder_auto_upload_", comment: ""))
  94. row.value = 0
  95. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  96. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  97. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  98. section.addFormRow(row)
  99. // Use Sub folder
  100. row = XLFormRowDescriptor(tag: "useSubFolder", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_autoupload_create_subfolder_", comment: ""))
  101. let tableAccount = NCManageDatabase.sharedInstance.getAccountActive()
  102. if tableAccount?.autoUploadCreateSubfolder == true {
  103. row.value = 1
  104. } else {
  105. row.value = 0
  106. }
  107. row.hidden = "$\("useFolderAutoUpload") == 0"
  108. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  109. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  110. section.addFormRow(row)
  111. // Section Mode filename
  112. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_mode_filename_", comment: ""))
  113. form.addFormSection(section)
  114. // Maintain the original fileName
  115. row = XLFormRowDescriptor(tag: "maintainOriginalFileName", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_maintain_original_filename_", comment: ""))
  116. row.value = CCUtility.getOriginalFileName(k_keyFileNameOriginal)
  117. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  118. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  119. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  120. section.addFormRow(row)
  121. // Add File Name Type
  122. row = XLFormRowDescriptor(tag: "addFileNameType", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_add_filenametype_", comment: ""))
  123. row.value = CCUtility.getFileNameType(k_keyFileNameType)
  124. row.hidden = "$\("maintainOriginalFileName") == 1"
  125. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  126. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  127. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  128. section.addFormRow(row)
  129. // Section: Rename File Name
  130. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_filename_", comment: ""))
  131. form.addFormSection(section)
  132. row = XLFormRowDescriptor(tag: "maskFileName", rowType: XLFormRowDescriptorTypeAccount, title: (NSLocalizedString("_filename_", comment: "")))
  133. let fileNameMask : String = CCUtility.getFileNameMask(k_keyFileNameMask)
  134. if fileNameMask.count > 0 {
  135. row.value = fileNameMask
  136. }
  137. row.hidden = "$\("maintainOriginalFileName") == 1"
  138. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  139. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  140. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  141. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  142. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  143. row.cellConfig["textField.textColor"] = NCBrandColor.sharedInstance.textView
  144. section.addFormRow(row)
  145. // Section: Preview File Name
  146. row = XLFormRowDescriptor(tag: "previewFileName", rowType: XLFormRowDescriptorTypeTextView, title: "")
  147. row.height = 180
  148. row.disabled = true
  149. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  150. row.cellConfig["textView.backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  151. row.cellConfig["textView.font"] = UIFont.systemFont(ofSize: 14.0)
  152. row.cellConfig["textView.textColor"] = NCBrandColor.sharedInstance.textView
  153. section.addFormRow(row)
  154. self.form = form
  155. }
  156. override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) {
  157. super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
  158. if formRow.tag == "useFolderAutoUpload" {
  159. if (formRow.value! as AnyObject).boolValue == true {
  160. let buttonDestinationFolder : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  161. buttonDestinationFolder.hidden = true
  162. } else{
  163. let buttonDestinationFolder : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  164. buttonDestinationFolder.hidden = false
  165. }
  166. }
  167. else if formRow.tag == "useSubFolder" {
  168. if (formRow.value! as AnyObject).boolValue == true {
  169. } else{
  170. }
  171. }
  172. else if formRow.tag == "maintainOriginalFileName" {
  173. CCUtility.setOriginalFileName((formRow.value! as AnyObject).boolValue, key: k_keyFileNameOriginal)
  174. self.reloadForm()
  175. }
  176. else if formRow.tag == "addFileNameType" {
  177. CCUtility.setFileNameType((formRow.value! as AnyObject).boolValue, key: k_keyFileNameType)
  178. self.reloadForm()
  179. }
  180. else if formRow.tag == "maskFileName" {
  181. let fileName = formRow.value as? String
  182. self.form.delegate = nil
  183. if let fileName = fileName {
  184. formRow.value = CCUtility.removeForbiddenCharactersServer(fileName)
  185. }
  186. self.form.delegate = self
  187. let previewFileName : XLFormRowDescriptor = self.form.formRow(withTag: "previewFileName")!
  188. previewFileName.value = self.previewFileName(valueRename: formRow.value as? String)
  189. // reload cell
  190. if fileName != nil {
  191. if newValue as! String != formRow.value as! String {
  192. self.reloadFormRow(formRow)
  193. appDelegate.messageNotification("_info_", description: "_forbidden_characters_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: 0)
  194. }
  195. }
  196. self.reloadFormRow(previewFileName)
  197. }
  198. }
  199. // MARK: - View Life Cycle
  200. override func viewDidLoad() {
  201. super.viewDidLoad()
  202. let cancelButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(cancel))
  203. let saveButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
  204. self.navigationItem.leftBarButtonItem = cancelButton
  205. self.navigationItem.rightBarButtonItem = saveButton
  206. self.navigationController?.navigationBar.isTranslucent = false
  207. self.navigationController?.navigationBar.barTintColor = NCBrandColor.sharedInstance.brand
  208. self.navigationController?.navigationBar.tintColor = NCBrandColor.sharedInstance.brandText
  209. self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: NCBrandColor.sharedInstance.brandText]
  210. self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
  211. self.tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundForm
  212. self.reloadForm()
  213. }
  214. override func viewWillDisappear(_ animated: Bool)
  215. {
  216. super.viewWillDisappear(animated)
  217. self.delegate?.dismissFormUploadAssets()
  218. }
  219. func reloadForm() {
  220. self.form.delegate = nil
  221. let buttonDestinationFolder : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  222. buttonDestinationFolder.title = self.titleServerUrl
  223. let maskFileName : XLFormRowDescriptor = self.form.formRow(withTag: "maskFileName")!
  224. let previewFileName : XLFormRowDescriptor = self.form.formRow(withTag: "previewFileName")!
  225. previewFileName.value = self.previewFileName(valueRename: maskFileName.value as? String)
  226. self.tableView.reloadData()
  227. self.form.delegate = self
  228. }
  229. // MARK: - Action
  230. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String) {
  231. if serverUrl != nil {
  232. self.serverUrl = serverUrl!
  233. if serverUrl == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  234. self.titleServerUrl = "/"
  235. } else {
  236. self.titleServerUrl = (serverUrl! as NSString).lastPathComponent
  237. }
  238. // Update
  239. let row : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  240. row.title = self.titleServerUrl
  241. self.updateFormRow(row)
  242. }
  243. }
  244. @objc func save() {
  245. self.dismiss(animated: true, completion: {
  246. let useFolderPhotoRow : XLFormRowDescriptor = self.form.formRow(withTag: "useFolderAutoUpload")!
  247. let useSubFolderRow : XLFormRowDescriptor = self.form.formRow(withTag: "useSubFolder")!
  248. var useSubFolder : Bool = false
  249. if (useFolderPhotoRow.value! as AnyObject).boolValue == true {
  250. self.serverUrl = NCManageDatabase.sharedInstance.getAccountAutoUploadPath(self.appDelegate.activeUrl)
  251. useSubFolder = (useSubFolderRow.value! as AnyObject).boolValue
  252. }
  253. self.appDelegate.activeMain.uploadFileAsset(self.assets, serverUrl: self.serverUrl, useSubFolder: useSubFolder, session: self.session)
  254. })
  255. }
  256. @objc func cancel() {
  257. self.dismiss(animated: true, completion: nil)
  258. }
  259. // MARK: - Utility
  260. func previewFileName(valueRename : String?) -> String {
  261. var returnString: String = ""
  262. let asset = assets[0] as! PHAsset
  263. if (CCUtility.getOriginalFileName(k_keyFileNameOriginal)) {
  264. return (NSLocalizedString("_filename_", comment: "") + ": " + (asset.value(forKey: "filename") as! String))
  265. } else if let valueRename = valueRename {
  266. let valueRenameTrimming = valueRename.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
  267. if valueRenameTrimming.count > 0 {
  268. self.form.delegate = nil
  269. CCUtility.setFileNameMask(valueRename, key: k_keyFileNameMask)
  270. self.form.delegate = self
  271. returnString = CCUtility.createFileName(asset.value(forKey: "filename") as! String?, fileDate: asset.creationDate, fileType: asset.mediaType, keyFileName: k_keyFileNameMask, keyFileNameType: k_keyFileNameType, keyFileNameOriginal: k_keyFileNameOriginal)
  272. } else {
  273. CCUtility.setFileNameMask("", key: k_keyFileNameMask)
  274. returnString = CCUtility.createFileName(asset.value(forKey: "filename") as! String?, fileDate: asset.creationDate, fileType: asset.mediaType, keyFileName: nil, keyFileNameType: k_keyFileNameType, keyFileNameOriginal: k_keyFileNameOriginal)
  275. }
  276. } else {
  277. CCUtility.setFileNameMask("", key: k_keyFileNameMask)
  278. returnString = CCUtility.createFileName(asset.value(forKey: "filename") as! String?, fileDate: asset.creationDate, fileType: asset.mediaType, keyFileName: nil, keyFileNameType: k_keyFileNameType, keyFileNameOriginal: k_keyFileNameOriginal)
  279. }
  280. return String(format: NSLocalizedString("_preview_filename_", comment: ""), "MM,MMM,DD,YY,YYYY and HH,hh,mm,ss,ampm") + ":" + "\n\n" + returnString
  281. }
  282. @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) {
  283. self.deselectFormRow(sender)
  284. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  285. let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
  286. let viewController = navigationController.topViewController as! NCSelect
  287. viewController.delegate = self
  288. viewController.hideButtonCreateFolder = false
  289. viewController.includeDirectoryE2EEncryption = true
  290. viewController.includeImages = false
  291. viewController.layoutViewSelect = k_layout_view_move
  292. viewController.selectFile = false
  293. viewController.titleButtonDone = NSLocalizedString("_select_", comment: "")
  294. viewController.type = ""
  295. navigationController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  296. self.present(navigationController, animated: true, completion: nil)
  297. }
  298. @objc func photoEditor(_ sender: XLFormRowDescriptor) {
  299. self.deselectFormRow(sender)
  300. PHImageManager.default().requestImage(for: assets[0] as! PHAsset, targetSize: PHImageManagerMaximumSize, contentMode: PHImageContentMode.default, options: requestOptions, resultHandler: { (image, info) in
  301. let photoEditor = PhotoEditorViewController(nibName:"PhotoEditorViewController",bundle: Bundle(for: PhotoEditorViewController.self))
  302. photoEditor.image = image
  303. photoEditor.photoEditorDelegate = self
  304. photoEditor.hiddenControls = [.save, .share, .sticker]
  305. photoEditor.cancelButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorCancel")!, multiplier:2, color: .white)
  306. photoEditor.cropButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorCrop")!, multiplier:2, color: .white)
  307. photoEditor.drawButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorDraw")!, multiplier:2, color: .white)
  308. photoEditor.textButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorText")!, multiplier:2, color: .white)
  309. photoEditor.clearButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorClear")!, multiplier:2, color: .white)
  310. photoEditor.continueButtonImage = CCGraphics.changeThemingColorImage(UIImage(named: "photoEditorDone")!, multiplier:2, color: .white)
  311. self.present(photoEditor, animated: true, completion: nil)
  312. })
  313. }
  314. // MARK: - Photo Editor Delegate
  315. func doneEditing(image: UIImage) {
  316. UIImageWriteToSavedPhotosAlbum(image, self, #selector(imageSaved(_:didFinishSavingWithError:contextInfo:)), nil)
  317. }
  318. @objc func imageSaved(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
  319. let fetchOptions = PHFetchOptions()
  320. fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
  321. let fetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)
  322. if let asset = fetchResult.firstObject {
  323. self.assets = NSMutableArray(array: [asset])
  324. }
  325. // Preview
  326. PHImageManager.default().requestImage(for: assets[0] as! PHAsset, targetSize: targetSizeImagePreview, contentMode: PHImageContentMode.aspectFill, options: requestOptions, resultHandler: { (image, info) in
  327. let row : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonPhotoEditor")!
  328. row.cellConfig["imageView.image"] = image
  329. self.updateFormRow(row)
  330. })
  331. }
  332. func canceledEditing() {
  333. print("Canceled")
  334. }
  335. }