NCCreateFormUploadRichdocuments.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. //
  2. // CCCreateCloud.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 14/11/18.
  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. // MARK: -
  25. class NCCreateFormUploadRichdocuments: XLFormViewController, NCSelectDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
  26. var typeTemplate = ""
  27. var serverUrl = ""
  28. var fileNameFolder = ""
  29. var fileName = ""
  30. var fileNameExtension = ""
  31. var titleForm = ""
  32. var listOfTemplate = [NCRichDocumentTemplate]()
  33. var selectTemplate: NCRichDocumentTemplate?
  34. @IBOutlet weak var indicator: UIActivityIndicatorView!
  35. @IBOutlet weak var collectionView: UICollectionView!
  36. @IBOutlet weak var collectionViewHeigth: NSLayoutConstraint!
  37. // Layout
  38. let numItems = 2
  39. let sectionInsets: CGFloat = 10
  40. let highLabelName: CGFloat = 20
  41. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  42. // MARK: - View Life Cycle
  43. override func viewDidLoad() {
  44. super.viewDidLoad()
  45. if serverUrl == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  46. fileNameFolder = "/"
  47. } else {
  48. fileNameFolder = (serverUrl as NSString).lastPathComponent
  49. }
  50. self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
  51. let cancelButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(cancel))
  52. let saveButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
  53. self.navigationItem.leftBarButtonItem = cancelButton
  54. self.navigationItem.rightBarButtonItem = saveButton
  55. self.navigationItem.rightBarButtonItem?.isEnabled = false
  56. // title
  57. self.title = titleForm
  58. // Theming view
  59. NotificationCenter.default.addObserver(self, selector: #selector(self.changeTheming), name: NSNotification.Name(rawValue: "changeTheming"), object: nil)
  60. changeTheming()
  61. // load the templates available
  62. getTemplate()
  63. }
  64. @objc func changeTheming() {
  65. appDelegate.changeTheming(self, tableView: tableView, collectionView: collectionView, form: false)
  66. initializeForm()
  67. }
  68. // MARK: - Tableview (XLForm)
  69. func initializeForm() {
  70. let form : XLFormDescriptor = XLFormDescriptor(title: NSLocalizedString("_upload_photos_videos_", comment: "")) as XLFormDescriptor
  71. form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow
  72. var section : XLFormSectionDescriptor
  73. var row : XLFormRowDescriptor
  74. // Section: Destination Folder
  75. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: "").uppercased())
  76. form.addFormSection(section)
  77. row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: fileNameFolder)
  78. row.action.formSelector = #selector(changeDestinationFolder(_:))
  79. row.value = fileNameFolder
  80. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  81. row.cellConfig["imageView.image"] = CCGraphics.changeThemingColorImage(UIImage(named: "folder")!, width: 50, height: 50, color: NCBrandColor.sharedInstance.brandElement) as UIImage
  82. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
  83. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  84. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  85. section.addFormRow(row)
  86. // Section: File Name
  87. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_filename_", comment: "").uppercased())
  88. form.addFormSection(section)
  89. row = XLFormRowDescriptor(tag: "fileName", rowType: XLFormRowDescriptorTypeAccount, title: NSLocalizedString("_filename_", comment: ""))
  90. row.value = fileName
  91. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  92. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  93. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  94. row.cellConfig["textField.textColor"] = NCBrandColor.sharedInstance.textView
  95. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
  96. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  97. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  98. section.addFormRow(row)
  99. self.form = form
  100. }
  101. override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
  102. let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
  103. header.textLabel?.font = UIFont.systemFont(ofSize: 13.0)
  104. header.textLabel?.textColor = .gray
  105. header.tintColor = NCBrandColor.sharedInstance.backgroundForm
  106. }
  107. // MARK: - CollectionView
  108. func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  109. return listOfTemplate.count
  110. }
  111. func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  112. let itemWidth: CGFloat = (collectionView.frame.width - (sectionInsets * 4) - CGFloat(numItems)) / CGFloat(numItems)
  113. let itemHeight: CGFloat = itemWidth + highLabelName
  114. collectionViewHeigth.constant = itemHeight + sectionInsets
  115. return CGSize(width: itemWidth, height: itemHeight)
  116. }
  117. func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  118. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
  119. let template = listOfTemplate[indexPath.row]
  120. // image
  121. let imagePreview = cell.viewWithTag(100) as! UIImageView
  122. if template.preview != "" {
  123. let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + template.name + ".png"
  124. if FileManager.default.fileExists(atPath: fileNameLocalPath) {
  125. let imageURL = URL(fileURLWithPath: fileNameLocalPath)
  126. if let image = UIImage(contentsOfFile: imageURL.path) {
  127. imagePreview.image = image
  128. }
  129. } else {
  130. getImage(template: template, indexPath: indexPath)
  131. }
  132. }
  133. // name
  134. let name = cell.viewWithTag(200) as! UILabel
  135. name.text = template.name
  136. name.textColor = NCBrandColor.sharedInstance.backgroundView
  137. // select
  138. let imageSelect = cell.viewWithTag(300) as! UIImageView
  139. if selectTemplate != nil && selectTemplate?.name == template.name {
  140. cell.backgroundColor = NCBrandColor.sharedInstance.textView
  141. imageSelect.image = UIImage(named: "plus100")
  142. imageSelect.isHidden = false
  143. } else {
  144. cell.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  145. imageSelect.isHidden = true
  146. }
  147. return cell
  148. }
  149. func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  150. let template = listOfTemplate[indexPath.row]
  151. selectTemplate = template
  152. fileNameExtension = template.extension
  153. collectionView.reloadData()
  154. }
  155. // MARK: - Action
  156. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String) {
  157. guard let serverUrl = serverUrl else {
  158. return
  159. }
  160. self.serverUrl = serverUrl
  161. if serverUrl == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  162. fileNameFolder = "/"
  163. } else {
  164. fileNameFolder = (serverUrl as NSString).lastPathComponent
  165. }
  166. let buttonDestinationFolder : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  167. buttonDestinationFolder.title = fileNameFolder
  168. self.tableView.reloadData()
  169. }
  170. @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) {
  171. self.deselectFormRow(sender)
  172. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  173. let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
  174. let viewController = navigationController.topViewController as! NCSelect
  175. viewController.delegate = self
  176. viewController.hideButtonCreateFolder = false
  177. viewController.includeDirectoryE2EEncryption = false
  178. viewController.includeImages = false
  179. viewController.layoutViewSelect = k_layout_view_move
  180. viewController.selectFile = false
  181. viewController.titleButtonDone = NSLocalizedString("_select_", comment: "")
  182. viewController.type = ""
  183. navigationController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  184. self.present(navigationController, animated: true, completion: nil)
  185. }
  186. @objc func save() {
  187. guard let selectTemplate = self.selectTemplate else {
  188. return
  189. }
  190. let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  191. guard let fileNameForm = rowFileName.value else {
  192. return
  193. }
  194. if fileNameForm as! String == "" {
  195. return
  196. } else {
  197. fileName = (fileNameForm as! NSString).deletingPathExtension + "." + fileNameExtension
  198. fileName = CCUtility.returnFileNamePath(fromFileName: fileName, serverUrl: serverUrl, activeUrl: appDelegate.activeUrl)
  199. }
  200. OCNetworking.sharedManager().createNewRichdocuments(withAccount: appDelegate.activeAccount, fileName: fileName, serverUrl: serverUrl, templateID: "\(selectTemplate.templateID)", completion: { (account, url, message, errorCode) in
  201. if errorCode == 0 && account == self.appDelegate.activeAccount {
  202. if url != nil && url!.count > 0 {
  203. self.dismiss(animated: true, completion: {
  204. let metadata = CCUtility.createMetadata(withAccount: self.appDelegate.activeAccount, date: Date(), directory: false, ocId: CCUtility.createRandomString(12), serverUrl: self.serverUrl, fileName: (fileNameForm as! NSString).deletingPathExtension + "." + self.fileNameExtension, etag: "", size: 0, status: Double(k_metadataStatusNormal), url:url)
  205. self.appDelegate.activeMain.shouldPerformSegue(metadata, selector: "")
  206. })
  207. }
  208. } else if errorCode != 0 {
  209. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  210. } else {
  211. print("[LOG] It has been changed user during networking process, error.")
  212. }
  213. })
  214. }
  215. @objc func cancel() {
  216. self.dismiss(animated: true, completion: nil)
  217. }
  218. // MARK: NC API
  219. func getTemplate() {
  220. indicator.color = NCBrandColor.sharedInstance.brand
  221. indicator.startAnimating()
  222. OCNetworking.sharedManager().getTemplatesRichdocuments(withAccount: appDelegate.activeAccount, typeTemplate: typeTemplate, completion: { (account, listOfTemplate, message, errorCode) in
  223. self.indicator.stopAnimating()
  224. if errorCode == 0 && account == self.appDelegate.activeAccount {
  225. self.listOfTemplate = listOfTemplate as! [NCRichDocumentTemplate]
  226. // default: template empty
  227. for template: NCRichDocumentTemplate in self.listOfTemplate {
  228. if template.preview == "" {
  229. self.selectTemplate = template
  230. self.fileNameExtension = template.extension
  231. self.navigationItem.rightBarButtonItem?.isEnabled = true
  232. }
  233. }
  234. self.collectionView.reloadData()
  235. } else if errorCode != 0 {
  236. self.appDelegate.messageNotification("_error_", description: message, visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  237. } else {
  238. print("[LOG] It has been changed user during networking process, error.")
  239. }
  240. })
  241. }
  242. func getImage(template: NCRichDocumentTemplate, indexPath: IndexPath) {
  243. let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + template.name + ".png"
  244. OCNetworking.sharedManager().download(withAccount: appDelegate.activeAccount, url: template.preview, fileNameLocalPath: fileNameLocalPath, encode:true, completion: { (account, message, errorCode) in
  245. if errorCode == 0 && account == self.appDelegate.activeAccount {
  246. self.collectionView.reloadItems(at: [indexPath])
  247. } else if errorCode != 0 {
  248. print("\(errorCode)")
  249. } else {
  250. print("[LOG] It has been changed user during networking process, error.")
  251. }
  252. })
  253. }
  254. }