NCCreateFormUploadDocuments.swift 23 KB

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