NCCreateFormUploadDocuments.swift 16 KB

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