NCCreateFormUploadVoiceNote.swift 14 KB

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