NCCreateFormUploadDocuments.swift 24 KB

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