NCCreateFormUploadVoiceNote.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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 == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  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.sharedInstance.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. // Theming view
  73. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  74. changeTheming()
  75. }
  76. override func viewWillAppear(_ animated: Bool) {
  77. super.viewWillAppear(animated)
  78. updateTimerUI()
  79. }
  80. @objc func changeTheming() {
  81. appDelegate.changeTheming(self, tableView: tableView, collectionView: nil, form: true)
  82. labelTimer.textColor = NCBrandColor.sharedInstance.textView
  83. labelDuration.textColor = NCBrandColor.sharedInstance.textView
  84. initializeForm()
  85. }
  86. //MARK: XLForm
  87. func initializeForm() {
  88. let form : XLFormDescriptor = XLFormDescriptor() as XLFormDescriptor
  89. form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow
  90. var section : XLFormSectionDescriptor
  91. var row : XLFormRowDescriptor
  92. // Section: Destination Folder
  93. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: "").uppercased())
  94. form.addFormSection(section)
  95. row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: self.titleServerUrl)
  96. row.action.formSelector = #selector(changeDestinationFolder(_:))
  97. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  98. row.cellConfig["imageView.image"] = CCGraphics.changeThemingColorImage(UIImage(named: "folder")!, width: 50, height: 50, color: NCBrandColor.sharedInstance.brandElement) as UIImage
  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. // Section: File Name
  104. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_filename_", comment: "").uppercased())
  105. form.addFormSection(section)
  106. row = XLFormRowDescriptor(tag: "fileName", rowType: XLFormRowDescriptorTypeAccount, title: NSLocalizedString("_filename_", comment: ""))
  107. row.value = self.fileName
  108. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  109. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  110. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  111. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  112. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  113. row.cellConfig["textField.textColor"] = NCBrandColor.sharedInstance.textView
  114. section.addFormRow(row)
  115. self.form = form
  116. }
  117. override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) {
  118. super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
  119. if formRow.tag == "fileName" {
  120. self.form.delegate = nil
  121. if let fileNameNew = formRow.value {
  122. self.fileName = CCUtility.removeForbiddenCharactersServer(fileNameNew as? String)
  123. }
  124. formRow.value = self.fileName
  125. self.updateFormRow(formRow)
  126. self.form.delegate = self
  127. }
  128. }
  129. override func textFieldDidBeginEditing(_ textField: UITextField) {
  130. let cell = textField.formDescriptorCell()
  131. let tag = cell?.rowDescriptor.tag
  132. if tag == "fileName" {
  133. CCUtility.selectFileName(from: textField)
  134. }
  135. }
  136. //MARK: TableViewDelegate
  137. override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
  138. let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
  139. header.textLabel?.font = UIFont.systemFont(ofSize: 13.0)
  140. header.textLabel?.textColor = .gray
  141. header.tintColor = NCBrandColor.sharedInstance.backgroundForm
  142. }
  143. // MARK: - Action
  144. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, buttonType: String, overwrite: Bool) {
  145. if serverUrl != nil {
  146. self.serverUrl = serverUrl!
  147. if serverUrl == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  148. self.titleServerUrl = "/"
  149. } else {
  150. self.titleServerUrl = (serverUrl! as NSString).lastPathComponent
  151. }
  152. // Update
  153. let row : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  154. row.title = self.titleServerUrl
  155. self.updateFormRow(row)
  156. }
  157. }
  158. @objc func save() {
  159. let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  160. guard let name = rowFileName.value else {
  161. return
  162. }
  163. let ext = (name as! NSString).pathExtension.uppercased()
  164. var fileNameSave = ""
  165. if (ext == "") {
  166. fileNameSave = name as! String + ".m4a"
  167. } else {
  168. fileNameSave = (name as! NSString).deletingPathExtension + ".m4a"
  169. }
  170. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: self.appDelegate.activeAccount, fileName: fileNameSave, ocId: UUID().uuidString, serverUrl: self.serverUrl, url: "", contentType: "")
  171. metadataForUpload.session = NCCommunicationCommon.shared.sessionIdentifierBackground
  172. metadataForUpload.sessionSelector = selectorUploadFile
  173. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  174. if NCUtility.sharedInstance.getMetadataConflict(account: appDelegate.activeAccount, serverUrl: serverUrl, fileName: fileNameSave) != nil {
  175. guard let conflictViewController = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict else { return }
  176. conflictViewController.textLabelDetailNewFile = NSLocalizedString("_now_", comment: "")
  177. conflictViewController.serverUrl = serverUrl
  178. conflictViewController.metadatasUploadInConflict = [metadataForUpload]
  179. conflictViewController.delegate = self
  180. self.present(conflictViewController, animated: true, completion: nil)
  181. } else {
  182. dismissAndUpload(metadataForUpload)
  183. }
  184. }
  185. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  186. if metadatas != nil && metadatas!.count > 0 {
  187. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  188. self.dismissAndUpload(metadatas![0])
  189. }
  190. }
  191. }
  192. func dismissAndUpload(_ metadata: tableMetadata) {
  193. CCUtility.copyFile(atPath: self.fileNamePath, toPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  194. NCManageDatabase.sharedInstance.addMetadata(metadata)
  195. self.appDelegate.startLoadAutoUpload()
  196. self.dismiss(animated: true, completion: nil)
  197. }
  198. @objc func cancel() {
  199. try? FileManager.default.removeItem(atPath: fileNamePath)
  200. self.dismiss(animated: true, completion: nil)
  201. }
  202. @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) {
  203. self.deselectFormRow(sender)
  204. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  205. let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
  206. let viewController = navigationController.topViewController as! NCSelect
  207. viewController.delegate = self
  208. viewController.hideButtonCreateFolder = false
  209. viewController.includeDirectoryE2EEncryption = true
  210. viewController.includeImages = false
  211. viewController.layoutViewSelect = k_layout_view_move
  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.sharedInstance.formatSecondsToString(counterSecondPlayer)
  221. labelDuration.text = NCUtility.sharedInstance.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.sharedInstance.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: "audioStop")!, width: 200, height: 200, color: NCBrandColor.sharedInstance.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.sharedInstance.icon), for: .normal)
  250. }
  251. }