NCCreateFormUploadDocuments.swift 22 KB

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