NCCreateFormUploadVoiceNote.swift 13 KB

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