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