NCCreateFormUploadVoiceNote.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. //
  2. // NCCreateFormUploadVoiceNote.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 9/03/2019.
  6. // Copyright © 2019 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. class NCCreateFormUploadVoiceNote: XLFormViewController, NCSelectDelegate, AVAudioPlayerDelegate, NCCreateFormUploadConflictDelegate {
  26. @IBOutlet weak var buttonPlayStop: UIButton!
  27. @IBOutlet weak var labelTimer: UILabel!
  28. @IBOutlet weak var labelDuration: UILabel!
  29. @IBOutlet weak var progressView: UIProgressView!
  30. private var serverUrl = ""
  31. private var titleServerUrl = ""
  32. private var fileName = ""
  33. private var fileNamePath = ""
  34. private var durationPlayer: TimeInterval = 0
  35. private var counterSecondPlayer: TimeInterval = 0
  36. private var audioPlayer: AVAudioPlayer!
  37. private var timer = Timer()
  38. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  39. // MARK: - View Life Cycle
  40. override func viewDidLoad() {
  41. super.viewDidLoad()
  42. view.backgroundColor = NCBrandColor.shared.systemGroupedBackground
  43. self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(cancel))
  44. self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
  45. self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
  46. tableView.backgroundColor = NCBrandColor.shared.systemGroupedBackground
  47. // title
  48. self.title = NSLocalizedString("_voice_memo_title_", comment: "")
  49. // Button Play Stop
  50. buttonPlayStop.setImage(UIImage(named: "audioPlay")!.image(color: NCBrandColor.shared.gray, size: 100), for: .normal)
  51. // Progress view
  52. progressView.progress = 0
  53. progressView.progressTintColor = .green
  54. progressView.trackTintColor = UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 247.0/255.0, alpha: 1.0)
  55. labelTimer.textColor = NCBrandColor.shared.label
  56. labelDuration.textColor = NCBrandColor.shared.label
  57. initializeForm()
  58. }
  59. override func viewWillAppear(_ animated: Bool) {
  60. super.viewWillAppear(animated)
  61. updateTimerUI()
  62. }
  63. public func setup(serverUrl: String, fileNamePath: String, fileName: String) {
  64. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account) {
  65. titleServerUrl = "/"
  66. } else {
  67. titleServerUrl = (serverUrl as NSString).lastPathComponent
  68. }
  69. self.fileName = fileName
  70. self.serverUrl = serverUrl
  71. self.fileNamePath = fileNamePath
  72. // player
  73. do {
  74. try audioPlayer = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileNamePath))
  75. audioPlayer.prepareToPlay()
  76. audioPlayer.delegate = self
  77. durationPlayer = TimeInterval(audioPlayer.duration)
  78. } catch {
  79. buttonPlayStop.isEnabled = false
  80. }
  81. }
  82. //MARK: XLForm
  83. func initializeForm() {
  84. let form : XLFormDescriptor = XLFormDescriptor() as XLFormDescriptor
  85. form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow
  86. var section : XLFormSectionDescriptor
  87. var row : XLFormRowDescriptor
  88. // Section: Destination Folder
  89. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: "").uppercased())
  90. form.addFormSection(section)
  91. row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: self.titleServerUrl)
  92. row.action.formSelector = #selector(changeDestinationFolder(_:))
  93. row.cellConfig["backgroundColor"] = NCBrandColor.shared.secondarySystemGroupedBackground
  94. row.cellConfig["imageView.image"] = UIImage(named: "folder")!.image(color: NCBrandColor.shared.brandElement, size: 25)
  95. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
  96. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  97. row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label
  98. section.addFormRow(row)
  99. // Section: File Name
  100. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_filename_", comment: "").uppercased())
  101. form.addFormSection(section)
  102. row = XLFormRowDescriptor(tag: "fileName", rowType: XLFormRowDescriptorTypeAccount, title: NSLocalizedString("_filename_", comment: ""))
  103. row.value = self.fileName
  104. row.cellConfig["backgroundColor"] = NCBrandColor.shared.secondarySystemGroupedBackground
  105. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  106. row.cellConfig["textLabel.textColor"] = NCBrandColor.shared.label
  107. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  108. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  109. row.cellConfig["textField.textColor"] = NCBrandColor.shared.label
  110. section.addFormRow(row)
  111. self.form = form
  112. }
  113. override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) {
  114. super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
  115. if formRow.tag == "fileName" {
  116. self.form.delegate = nil
  117. if let fileNameNew = formRow.value {
  118. self.fileName = CCUtility.removeForbiddenCharactersServer(fileNameNew as? String)
  119. }
  120. formRow.value = self.fileName
  121. self.updateFormRow(formRow)
  122. self.form.delegate = self
  123. }
  124. }
  125. //MARK: TableViewDelegate
  126. override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
  127. let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
  128. header.textLabel?.font = UIFont.systemFont(ofSize: 13.0)
  129. header.textLabel?.textColor = .gray
  130. header.tintColor = NCBrandColor.shared.secondarySystemGroupedBackground
  131. }
  132. // MARK: - Action
  133. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  134. if serverUrl != nil {
  135. self.serverUrl = serverUrl!
  136. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, account: appDelegate.account) {
  137. self.titleServerUrl = "/"
  138. } else {
  139. self.titleServerUrl = (serverUrl! as NSString).lastPathComponent
  140. }
  141. // Update
  142. let row : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  143. row.title = self.titleServerUrl
  144. self.updateFormRow(row)
  145. }
  146. }
  147. @objc func save() {
  148. let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  149. guard let name = rowFileName.value else {
  150. return
  151. }
  152. let ext = (name as! NSString).pathExtension.uppercased()
  153. var fileNameSave = ""
  154. if (ext == "") {
  155. fileNameSave = name as! String + ".m4a"
  156. } else {
  157. fileNameSave = (name as! NSString).deletingPathExtension + ".m4a"
  158. }
  159. let metadataForUpload = NCManageDatabase.shared.createMetadata(account: self.appDelegate.account, fileName: fileNameSave, fileNameView: fileNameSave, ocId: UUID().uuidString, serverUrl: self.serverUrl, urlBase: self.appDelegate.urlBase ,url: "", contentType: "", livePhoto: false, chunk: false)
  160. metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground
  161. metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile
  162. metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload
  163. if NCManageDatabase.shared.getMetadataConflict(account: appDelegate.account, serverUrl: serverUrl, fileName: fileNameSave) != nil {
  164. guard let conflictViewController = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict else { return }
  165. conflictViewController.textLabelDetailNewFile = NSLocalizedString("_now_", comment: "")
  166. conflictViewController.serverUrl = serverUrl
  167. conflictViewController.metadatasUploadInConflict = [metadataForUpload]
  168. conflictViewController.delegate = self
  169. self.present(conflictViewController, animated: true, completion: nil)
  170. } else {
  171. dismissAndUpload(metadataForUpload)
  172. }
  173. }
  174. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  175. if metadatas != nil && metadatas!.count > 0 {
  176. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  177. self.dismissAndUpload(metadatas![0])
  178. }
  179. }
  180. }
  181. func dismissAndUpload(_ metadata: tableMetadata) {
  182. CCUtility.copyFile(atPath: self.fileNamePath, toPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  183. appDelegate.networkingProcessUpload?.createProcessUploads(metadatas: [metadata])
  184. self.dismiss(animated: true, completion: nil)
  185. }
  186. @objc func cancel() {
  187. try? FileManager.default.removeItem(atPath: fileNamePath)
  188. self.dismiss(animated: true, completion: nil)
  189. }
  190. @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) {
  191. self.deselectFormRow(sender)
  192. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  193. let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
  194. let viewController = navigationController.topViewController as! NCSelect
  195. viewController.delegate = self
  196. viewController.typeOfCommandView = .selectCreateFolder
  197. viewController.includeDirectoryE2EEncryption = true
  198. self.present(navigationController, animated: true, completion: nil)
  199. }
  200. //MARK: Player - Timer
  201. func updateTimerUI() {
  202. labelTimer.text = String.init().formatSecondsToString(counterSecondPlayer)
  203. labelDuration.text = String.init().formatSecondsToString(durationPlayer)
  204. progressView.progress = Float(counterSecondPlayer / durationPlayer)
  205. }
  206. @objc func updateTimer() {
  207. counterSecondPlayer += 1
  208. updateTimerUI()
  209. }
  210. @IBAction func playStop(_ sender: Any) {
  211. if audioPlayer.isPlaying {
  212. audioPlayer.currentTime = 0.0
  213. audioPlayer.stop()
  214. timer.invalidate()
  215. counterSecondPlayer = 0
  216. progressView.progress = 0
  217. updateTimerUI()
  218. buttonPlayStop.setImage(UIImage(named: "audioPlay")!.image(color: NCBrandColor.shared.gray, size: 100), for: .normal)
  219. } else {
  220. audioPlayer.prepareToPlay()
  221. audioPlayer.play()
  222. timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
  223. buttonPlayStop.setImage(UIImage(named: "stop")!.image(color: NCBrandColor.shared.gray, size: 100), for: .normal)
  224. }
  225. }
  226. func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
  227. timer.invalidate()
  228. counterSecondPlayer = 0
  229. progressView.progress = 0
  230. updateTimerUI()
  231. buttonPlayStop.setImage(UIImage(named: "audioPlay")!.image(color: NCBrandColor.shared.gray, size: 100), for: .normal)
  232. }
  233. }