NCCreateFormUploadDocuments.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. 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: [NKEditorTemplates] = []
  42. var selectTemplate: NKEditorTemplates?
  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(urlBase: appDelegate.urlBase, userId: appDelegate.userId) {
  51. fileNameFolder = "/"
  52. } else {
  53. fileNameFolder = (serverUrl as NSString).lastPathComponent
  54. }
  55. self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
  56. view.backgroundColor = .systemGroupedBackground
  57. collectionView.backgroundColor = .systemGroupedBackground
  58. tableView.backgroundColor = .secondarySystemGroupedBackground
  59. let cancelButton: UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(cancel))
  60. let saveButton: UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
  61. self.navigationItem.leftBarButtonItem = cancelButton
  62. self.navigationItem.rightBarButtonItem = saveButton
  63. self.navigationItem.rightBarButtonItem?.isEnabled = false
  64. // title
  65. self.title = titleForm
  66. initializeForm()
  67. getTemplate()
  68. }
  69. // MARK: - Tableview (XLForm)
  70. func initializeForm() {
  71. let form: XLFormDescriptor = XLFormDescriptor() 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"] = tableView.backgroundColor
  82. row.cellConfig["imageView.image"] = UIImage(named: "folder")!.image(color: NCBrandColor.shared.brandElement, size: 25)
  83. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
  84. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  85. row.cellConfig["textLabel.textColor"] = UIColor.label
  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: XLFormRowDescriptorTypeText, title: NSLocalizedString("_filename_", comment: ""))
  91. row.value = fileName
  92. row.cellConfig["backgroundColor"] = tableView.backgroundColor
  93. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  94. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  95. row.cellConfig["textField.textColor"] = UIColor.label
  96. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
  97. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  98. row.cellConfig["textLabel.textColor"] = UIColor.label
  99. section.addFormRow(row)
  100. self.form = form
  101. //tableView.reloadData()
  102. //collectionView.reloadData()
  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 = tableView.backgroundColor
  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 = String(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 = .secondarySystemGroupedBackground
  140. // select
  141. let imageSelect = cell.viewWithTag(300) as! UIImageView
  142. if selectTemplate != nil && selectTemplate?.name == template.name {
  143. cell.backgroundColor = .label
  144. imageSelect.image = UIImage(named: "plus100")
  145. imageSelect.isHidden = false
  146. } else {
  147. cell.backgroundColor = .secondarySystemGroupedBackground
  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, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  160. guard let serverUrl = serverUrl else {
  161. return
  162. }
  163. self.serverUrl = serverUrl
  164. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId) {
  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.typeOfCommandView = .selectCreateFolder
  180. self.present(navigationController, animated: true, completion: nil)
  181. }
  182. @objc func save() {
  183. guard let selectTemplate = self.selectTemplate else {
  184. return
  185. }
  186. templateIdentifier = selectTemplate.identifier
  187. let rowFileName: XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  188. guard var fileNameForm = rowFileName.value else {
  189. return
  190. }
  191. if fileNameForm as! String == "" {
  192. return
  193. } else {
  194. //Trim whitespaces after checks above
  195. fileNameForm = (fileNameForm as! String).trimmingCharacters(in: .whitespacesAndNewlines)
  196. let result = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: fileNameForm as! String, mimeType: "", directory: false)
  197. if NCUtility.shared.isDirectEditing(account: appDelegate.account, contentType: result.mimeType).count == 0 {
  198. fileNameForm = (fileNameForm as! NSString).deletingPathExtension + "." + fileNameExtension
  199. }
  200. if NCManageDatabase.shared.getMetadataConflict(account: appDelegate.account, serverUrl: serverUrl, fileNameView: String(describing: fileNameForm)) != nil {
  201. 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: "")
  202. guard let conflict = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict else { return }
  203. conflict.textLabelDetailNewFile = NSLocalizedString("_now_", comment: "")
  204. conflict.alwaysNewFileNameNumber = true
  205. conflict.serverUrl = serverUrl
  206. conflict.metadatasUploadInConflict = [metadataForUpload]
  207. conflict.delegate = self
  208. self.present(conflict, animated: true, completion: nil)
  209. } else {
  210. let fileNamePath = CCUtility.returnFileNamePath(fromFileName: String(describing: fileNameForm), serverUrl: serverUrl, urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account)!
  211. createDocument(fileNamePath: fileNamePath, fileName: String(describing: fileNameForm))
  212. }
  213. }
  214. }
  215. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  216. if metadatas == nil || metadatas?.count == 0 {
  217. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  218. self.cancel()
  219. }
  220. } else {
  221. let fileName = metadatas![0].fileName
  222. let fileNamePath = CCUtility.returnFileNamePath(fromFileName: fileName, serverUrl: serverUrl, urlBase: appDelegate.urlBase, userId: appDelegate.userId, account: appDelegate.account)!
  223. createDocument(fileNamePath: fileNamePath, fileName: fileName)
  224. }
  225. }
  226. func createDocument(fileNamePath: String, fileName: String) {
  227. self.navigationItem.rightBarButtonItem?.isEnabled = false
  228. var UUID = NSUUID().uuidString
  229. UUID = "TEMP" + UUID.replacingOccurrences(of: "-", with: "")
  230. if self.editorId == NCGlobal.shared.editorText || self.editorId == NCGlobal.shared.editorOnlyoffice {
  231. var options = NKRequestOptions()
  232. if self.editorId == NCGlobal.shared.editorOnlyoffice {
  233. options = NKRequestOptions(customUserAgent: NCUtility.shared.getCustomUserAgentOnlyOffice())
  234. } else if editorId == NCGlobal.shared.editorText {
  235. options = NKRequestOptions(customUserAgent: NCUtility.shared.getCustomUserAgentNCText())
  236. }
  237. NextcloudKit.shared.NCTextCreateFile(fileNamePath: fileNamePath, editorId: editorId, creatorId: creatorId, templateId: templateIdentifier, options: options) { account, url, data, error in
  238. guard error == .success, account == self.appDelegate.account, let url = url else {
  239. self.navigationItem.rightBarButtonItem?.isEnabled = true
  240. NCContentPresenter.shared.showError(error: error, data: data)
  241. return
  242. }
  243. var results = NextcloudKit.shared.nkCommonInstance.getInternalType(fileName: fileName, mimeType: "", directory: false)
  244. //FIXME: iOS 12.0,* don't detect UTI text/markdown, text/x-markdown
  245. if results.mimeType.isEmpty {
  246. results.mimeType = "text/x-markdown"
  247. }
  248. self.dismiss(animated: true, completion: {
  249. 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)
  250. if let viewController = self.appDelegate.activeViewController {
  251. NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: nil)
  252. }
  253. })
  254. }
  255. }
  256. if self.editorId == NCGlobal.shared.editorCollabora {
  257. NextcloudKit.shared.createRichdocuments(path: fileNamePath, templateId: templateIdentifier) { account, url, data, error in
  258. guard error == .success, account == self.appDelegate.account, let url = url else {
  259. self.navigationItem.rightBarButtonItem?.isEnabled = true
  260. NCContentPresenter.shared.showError(error: error, data: data)
  261. return
  262. }
  263. self.dismiss(animated: true, completion: {
  264. let createFileName = (fileName as NSString).deletingPathExtension + "." + self.fileNameExtension
  265. 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: "")
  266. if let viewController = self.appDelegate.activeViewController {
  267. NCViewer.shared.view(viewController: viewController, metadata: metadata, metadatas: [metadata], imageIcon: nil)
  268. }
  269. })
  270. }
  271. }
  272. }
  273. @objc func cancel() {
  274. self.dismiss(animated: true, completion: nil)
  275. }
  276. // MARK: NC API
  277. func getTemplate() {
  278. indicator.color = NCBrandColor.shared.brandElement
  279. indicator.startAnimating()
  280. if self.editorId == NCGlobal.shared.editorText || self.editorId == NCGlobal.shared.editorOnlyoffice {
  281. var options = NKRequestOptions()
  282. if self.editorId == NCGlobal.shared.editorOnlyoffice {
  283. options = NKRequestOptions(customUserAgent: NCUtility.shared.getCustomUserAgentOnlyOffice())
  284. } else if editorId == NCGlobal.shared.editorText {
  285. options = NKRequestOptions(customUserAgent: NCUtility.shared.getCustomUserAgentNCText())
  286. }
  287. NextcloudKit.shared.NCTextGetListOfTemplates(options: options) { account, templates, data, error in
  288. self.indicator.stopAnimating()
  289. if error == .success && account == self.appDelegate.account {
  290. for template in templates {
  291. let temp = NKEditorTemplates()
  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. }
  305. if self.listOfTemplate.count == 0 {
  306. let temp = NKEditorTemplates()
  307. temp.identifier = ""
  308. if self.editorId == NCGlobal.shared.editorText {
  309. temp.ext = "md"
  310. } else if self.editorId == NCGlobal.shared.editorOnlyoffice && self.typeTemplate == NCGlobal.shared.templateDocument {
  311. temp.ext = "docx"
  312. } else if self.editorId == NCGlobal.shared.editorOnlyoffice && self.typeTemplate == NCGlobal.shared.templateSpreadsheet {
  313. temp.ext = "xlsx"
  314. } else if self.editorId == NCGlobal.shared.editorOnlyoffice && self.typeTemplate == NCGlobal.shared.templatePresentation {
  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. }
  326. }
  327. if self.editorId == NCGlobal.shared.editorCollabora {
  328. NextcloudKit.shared.getTemplatesRichdocuments(typeTemplate: typeTemplate) { account, templates, data, error in
  329. self.indicator.stopAnimating()
  330. if error == .success && account == self.appDelegate.account {
  331. for template in templates! {
  332. let temp = NKEditorTemplates()
  333. temp.identifier = "\(template.templateId)"
  334. temp.delete = template.delete
  335. temp.ext = template.ext
  336. temp.name = template.name
  337. temp.preview = template.preview
  338. temp.type = template.type
  339. self.listOfTemplate.append(temp)
  340. // default: template empty
  341. if temp.preview == "" {
  342. self.selectTemplate = temp
  343. self.fileNameExtension = temp.ext
  344. self.navigationItem.rightBarButtonItem?.isEnabled = true
  345. }
  346. }
  347. }
  348. if self.listOfTemplate.count == 0 {
  349. let temp = NKEditorTemplates()
  350. temp.identifier = ""
  351. if self.typeTemplate == NCGlobal.shared.templateDocument {
  352. temp.ext = "docx"
  353. } else if self.typeTemplate == NCGlobal.shared.templateSpreadsheet {
  354. temp.ext = "xlsx"
  355. } else if self.typeTemplate == NCGlobal.shared.templatePresentation {
  356. temp.ext = "pptx"
  357. }
  358. temp.name = "Empty"
  359. temp.preview = ""
  360. self.listOfTemplate.append(temp)
  361. self.selectTemplate = temp
  362. self.fileNameExtension = temp.ext
  363. self.navigationItem.rightBarButtonItem?.isEnabled = true
  364. }
  365. self.collectionView.reloadData()
  366. }
  367. }
  368. }
  369. func getImageFromTemplate(name: String, preview: String, indexPath: IndexPath) {
  370. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + name + ".png"
  371. NextcloudKit.shared.download(serverUrlFileName: preview, fileNameLocalPath: fileNameLocalPath, requestHandler: { _ in
  372. }, taskHandler: { _ in
  373. }, progressHandler: { _ in
  374. }) { account, _, _, _, _, _, error in
  375. if error == .success && account == self.appDelegate.account {
  376. self.collectionView.reloadItems(at: [indexPath])
  377. } else if error != .success {
  378. print("\(error.errorCode)")
  379. } else {
  380. print("[LOG] It has been changed user during networking process, error.")
  381. }
  382. }
  383. }
  384. }