NCCreateFormUploadDocuments.swift 23 KB

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