NCCreateFormUploadDocuments.swift 21 KB

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