NCCreateFormUploadVoiceNote.swift 13 KB

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