NCCreateFormUploadDocuments.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. NCCommunication.sharedInstance.NCTextCreateFile(urlString: appDelegate.activeUrl, fileNamePath: fileName, editor: "text", templateId: selectTemplate.identifier, account: self.appDelegate.activeAccount) { (account, url, errorCode, errorMessage) in
  203. if errorCode == 0 && account == self.appDelegate.activeAccount {
  204. if url != nil && url!.count > 0 {
  205. self.dismiss(animated: true, completion: {
  206. 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, contentType: "text/markdown")
  207. self.appDelegate.activeMain.shouldPerformSegue(metadata, selector: "")
  208. })
  209. }
  210. } else if errorCode != 0 {
  211. NCContentPresenter.shared.messageNotification("_error_", description: errorMessage, delay: TimeInterval(k_dismissAfterSecond), type:NCContentPresenter.messageType.error, errorCode: errorCode)
  212. } else {
  213. print("[LOG] It has been changed user during networking process, error.")
  214. }
  215. }
  216. } else {
  217. OCNetworking.sharedManager().createNewRichdocuments(withAccount: appDelegate.activeAccount, fileName: fileName, serverUrl: serverUrl, templateID: selectTemplate.identifier, completion: { (account, url, message, errorCode) in
  218. if errorCode == 0 && account == self.appDelegate.activeAccount {
  219. if url != nil && url!.count > 0 {
  220. self.dismiss(animated: true, completion: {
  221. 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, contentType: "")
  222. self.appDelegate.activeMain.shouldPerformSegue(metadata, selector: "")
  223. })
  224. }
  225. } else if errorCode != 0 {
  226. NCContentPresenter.shared.messageNotification("_error_", description: message, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  227. } else {
  228. print("[LOG] It has been changed user during networking process, error.")
  229. }
  230. })
  231. }
  232. }
  233. @objc func cancel() {
  234. self.dismiss(animated: true, completion: nil)
  235. }
  236. // MARK: NC API
  237. func getTemplate() {
  238. indicator.color = NCBrandColor.sharedInstance.brand
  239. indicator.startAnimating()
  240. if self.typeTemplate == k_nextcloudtext_document {
  241. // default
  242. fileNameExtension = "md"
  243. NCCommunication.sharedInstance.NCTextGetListOfTemplates(urlString: appDelegate.activeUrl, account: appDelegate.activeAccount) { (account, templates, errorCode, errorMessage) in
  244. self.indicator.stopAnimating()
  245. if errorCode == 0 && account == self.appDelegate.activeAccount {
  246. for template in templates {
  247. let temp = NCEditorTemplates()
  248. temp.identifier = template.identifier
  249. temp.ext = template.ext
  250. temp.name = template.name
  251. temp.preview = template.preview
  252. self.listOfTemplate.append(temp)
  253. // default: template empty
  254. if temp.preview == "" {
  255. self.selectTemplate = temp
  256. self.fileNameExtension = template.ext
  257. self.navigationItem.rightBarButtonItem?.isEnabled = true
  258. }
  259. }
  260. // NOT ALIGNED getTemplatesRichdocuments
  261. if templates.count == 0 {
  262. let temp = NCEditorTemplates()
  263. temp.identifier = ""
  264. temp.ext = "md"
  265. temp.name = "Empty"
  266. temp.preview = ""
  267. self.listOfTemplate.append(temp)
  268. self.selectTemplate = temp
  269. self.fileNameExtension = temp.ext
  270. self.navigationItem.rightBarButtonItem?.isEnabled = true
  271. }
  272. self.collectionView.reloadData()
  273. } else if errorCode != 0 {
  274. NCContentPresenter.shared.messageNotification("_error_", description: errorMessage, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  275. } else {
  276. print("[LOG] It has been changed user during networking process, error.")
  277. }
  278. }
  279. } else {
  280. // default
  281. OCNetworking.sharedManager().getTemplatesRichdocuments(withAccount: appDelegate.activeAccount, typeTemplate: typeTemplate, completion: { (account, templates, message, errorCode) in
  282. self.indicator.stopAnimating()
  283. if errorCode == 0 && account == self.appDelegate.activeAccount {
  284. for template in templates as! [NCRichDocumentTemplate] {
  285. let temp = NCEditorTemplates()
  286. temp.identifier = "\(template.templateID)"
  287. temp.delete = template.delete
  288. temp.ext = template.extension
  289. temp.name = template.name
  290. temp.preview = template.preview
  291. temp.type = template.type
  292. self.listOfTemplate.append(temp)
  293. // default: template empty
  294. if temp.preview == "" {
  295. self.selectTemplate = temp
  296. self.fileNameExtension = temp.ext
  297. self.navigationItem.rightBarButtonItem?.isEnabled = true
  298. }
  299. }
  300. self.collectionView.reloadData()
  301. } else if errorCode != 0 {
  302. NCContentPresenter.shared.messageNotification("_error_", description: message, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: errorCode)
  303. } else {
  304. print("[LOG] It has been changed user during networking process, error.")
  305. }
  306. })
  307. }
  308. }
  309. func getImageFromTemplate(name: String, preview: String, indexPath: IndexPath) {
  310. let fileNameLocalPath = CCUtility.getDirectoryUserData() + "/" + name + ".png"
  311. OCNetworking.sharedManager().download(withAccount: appDelegate.activeAccount, url: preview, fileNameLocalPath: fileNameLocalPath, encode:true, completion: { (account, message, errorCode) in
  312. if errorCode == 0 && account == self.appDelegate.activeAccount {
  313. self.collectionView.reloadItems(at: [indexPath])
  314. } else if errorCode != 0 {
  315. print("\(errorCode)")
  316. } else {
  317. print("[LOG] It has been changed user during networking process, error.")
  318. }
  319. })
  320. }
  321. }