NCCreateFormUploadDocuments.swift 23 KB

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