NCCreateFormUploadDocuments.swift 21 KB

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