NCSubtitlePlayer.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. //
  2. // NCSubtitlePlayer.swift
  3. // Nextcloud
  4. //
  5. // Created by Federico Malagoni on 18/02/22.
  6. // Copyright © 2022 Federico Malagoni. All rights reserved.
  7. // Copyright © 2022 Marino Faggiana All rights reserved.
  8. //
  9. // Author Federico Malagoni <federico.malagoni@astrairidium.com>
  10. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  11. //
  12. // This program is free software: you can redistribute it and/or modify
  13. // it under the terms of the GNU General Public License as published by
  14. // the Free Software Foundation, either version 3 of the License, or
  15. // (at your option) any later version.
  16. //
  17. // This program is distributed in the hope that it will be useful,
  18. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. // GNU General Public License for more details.
  21. //
  22. // You should have received a copy of the GNU General Public License
  23. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. //
  25. import Foundation
  26. import AVKit
  27. import NextcloudKit
  28. extension NCPlayer {
  29. private struct AssociatedKeys {
  30. static var FontKey = "FontKey"
  31. static var ColorKey = "FontKey"
  32. static var SubtitleKey = "SubtitleKey"
  33. static var SubtitleContainerViewKey = "SubtitleContainerViewKey"
  34. static var SubtitleContainerViewHeightKey = "SubtitleContainerViewHeightKey"
  35. static var SubtitleHeightKey = "SubtitleHeightKey"
  36. static var SubtitleWidthKey = "SubtitleWidthKey"
  37. static var SubtitleContainerViewWidthKey = "SubtitleContainerViewWidthKey"
  38. static var SubtitleBottomKey = "SubtitleBottomKey"
  39. static var PayloadKey = "PayloadKey"
  40. }
  41. private var widthProportion: CGFloat {
  42. return 0.9
  43. }
  44. private var bottomConstantPortrait: CGFloat {
  45. get {
  46. if UIDevice.current.hasNotch {
  47. return -60
  48. } else {
  49. return -40
  50. }
  51. } set {
  52. _ = newValue
  53. }
  54. }
  55. private var bottomConstantLandscape: CGFloat {
  56. get {
  57. if UIDevice.current.hasNotch {
  58. return -120
  59. } else {
  60. return -100
  61. }
  62. } set {
  63. _ = newValue
  64. }
  65. }
  66. var subtitleContainerView: UIView? {
  67. get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleContainerViewKey) as? UIView }
  68. set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleContainerViewKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)}
  69. }
  70. var subtitleLabel: UILabel? {
  71. get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleKey) as? UILabel }
  72. set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
  73. }
  74. fileprivate var subtitleLabelHeightConstraint: NSLayoutConstraint? {
  75. get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleHeightKey) as? NSLayoutConstraint }
  76. set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleHeightKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
  77. }
  78. fileprivate var subtitleContainerViewHeightConstraint: NSLayoutConstraint? {
  79. get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleContainerViewHeightKey) as? NSLayoutConstraint }
  80. set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleContainerViewHeightKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
  81. }
  82. fileprivate var subtitleLabelBottomConstraint: NSLayoutConstraint? {
  83. get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleBottomKey) as? NSLayoutConstraint }
  84. set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleBottomKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
  85. }
  86. fileprivate var subtitleLabelWidthConstraint: NSLayoutConstraint? {
  87. get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleWidthKey) as? NSLayoutConstraint }
  88. set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleWidthKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
  89. }
  90. fileprivate var subtitleContainerViewWidthConstraint: NSLayoutConstraint? {
  91. get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleContainerViewWidthKey) as? NSLayoutConstraint }
  92. set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleContainerViewWidthKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
  93. }
  94. fileprivate var parsedPayload: NSDictionary? {
  95. get { return objc_getAssociatedObject(self, &AssociatedKeys.PayloadKey) as? NSDictionary }
  96. set (value) { objc_setAssociatedObject(self, &AssociatedKeys.PayloadKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
  97. }
  98. func setUpForSubtitle() {
  99. self.subtitleUrls.removeAll()
  100. if let url = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) {
  101. let enumerator = FileManager.default.enumerator(atPath: url)
  102. let filePaths = (enumerator?.allObjects as? [String])
  103. if let filePaths = filePaths {
  104. let txtFilePaths = (filePaths.filter { $0.contains(".srt") }).sorted {
  105. guard let str1LastChar = $0.dropLast(4).last, let str2LastChar = $1.dropLast(4).last else {
  106. return false
  107. }
  108. return str1LastChar < str2LastChar
  109. }
  110. for txtFilePath in txtFilePaths {
  111. let subtitleUrl = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: txtFilePath))
  112. self.subtitleUrls.append(subtitleUrl)
  113. }
  114. }
  115. }
  116. let (all, existing) = NCManageDatabase.shared.getSubtitles(account: metadata.account, serverUrl: metadata.serverUrl, fileName: metadata.fileName)
  117. if !existing.isEmpty {
  118. for subtitle in existing {
  119. let subtitleUrl = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(subtitle.ocId, fileNameView: subtitle.fileName))
  120. self.subtitleUrls.append(subtitleUrl)
  121. }
  122. }
  123. if all.count != existing.count {
  124. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_subtitle_not_dowloaded_")
  125. NCContentPresenter.shared.showInfo(error: error)
  126. }
  127. self.setSubtitleToolbarIcon(subtitleUrls: subtitleUrls)
  128. self.hideSubtitle()
  129. }
  130. func setSubtitleToolbarIcon(subtitleUrls: [URL]) {
  131. if subtitleUrls.isEmpty {
  132. playerToolBar?.subtitleButton.isHidden = true
  133. } else {
  134. playerToolBar?.subtitleButton.isHidden = false
  135. }
  136. }
  137. func addSubtitlesTo(_ vc: UIViewController, _ playerToolBar: NCPlayerToolBar?) {
  138. addSubtitleLabel(vc, playerToolBar)
  139. NotificationCenter.default.addObserver(self, selector: #selector(deviceRotated(_:)), name: UIDevice.orientationDidChangeNotification, object: nil)
  140. }
  141. func loadText(filePath: URL, _ completion: @escaping (_ contents: String?) -> Void) {
  142. DispatchQueue.global(qos: .background).async {
  143. guard let data = try? Data(contentsOf: filePath),
  144. let encoding = NCUtility.shared.getEncondingDataType(data: data) else {
  145. return
  146. }
  147. if let decodedString = String(data: data, encoding: encoding) {
  148. completion(decodedString)
  149. } else {
  150. completion(nil)
  151. }
  152. }
  153. }
  154. func open(fileFromLocal url: URL) {
  155. subtitleLabel?.text = ""
  156. self.loadText(filePath: url) { contents in
  157. guard let contents = contents else {
  158. return
  159. }
  160. DispatchQueue.main.async {
  161. self.subtitleLabel?.text = ""
  162. self.show(subtitles: contents)
  163. }
  164. }
  165. }
  166. @objc public func hideSubtitle() {
  167. self.subtitleLabel?.isHidden = true
  168. self.subtitleContainerView?.isHidden = true
  169. self.currentSubtitle = nil
  170. }
  171. @objc public func showSubtitle(url: URL) {
  172. self.subtitleLabel?.isHidden = false
  173. self.subtitleContainerView?.isHidden = false
  174. self.currentSubtitle = url
  175. }
  176. private func show(subtitles string: String) {
  177. parsedPayload = try? NCSubtitles.parseSubRip(string)
  178. if let parsedPayload = parsedPayload {
  179. addPeriodicNotification(parsedPayload: parsedPayload)
  180. }
  181. }
  182. private func showByDictionary(dictionaryContent: NSMutableDictionary) {
  183. parsedPayload = dictionaryContent
  184. if let parsedPayload = parsedPayload {
  185. addPeriodicNotification(parsedPayload: parsedPayload)
  186. }
  187. }
  188. func addPeriodicNotification(parsedPayload: NSDictionary) {
  189. // Add periodic notifications
  190. let interval = CMTimeMake(value: 1, timescale: 60)
  191. self.player?.addPeriodicTimeObserver(forInterval: interval, queue: .main) { [weak self] time in
  192. guard let strongSelf = self, let label = strongSelf.subtitleLabel, let containerView = strongSelf.subtitleContainerView else {
  193. return
  194. }
  195. DispatchQueue.main.async {
  196. label.text = NCSubtitles.searchSubtitles(strongSelf.parsedPayload, time.seconds)
  197. strongSelf.adjustViewWidth(containerView: containerView)
  198. strongSelf.adjustLabelHeight(label: label)
  199. }
  200. }
  201. }
  202. @objc private func deviceRotated(_ notification: Notification) {
  203. guard let label = self.subtitleLabel,
  204. let containerView = self.subtitleContainerView else { return }
  205. DispatchQueue.main.async {
  206. self.adjustViewWidth(containerView: containerView)
  207. self.adjustLabelHeight(label: label)
  208. self.adjustLabelBottom(label: label)
  209. containerView.layoutIfNeeded()
  210. label.layoutIfNeeded()
  211. }
  212. }
  213. private func adjustLabelHeight(label: UILabel) {
  214. let baseSize = CGSize(width: label.bounds.width, height: .greatestFiniteMagnitude)
  215. let rect = label.sizeThatFits(baseSize)
  216. if label.text != nil {
  217. self.subtitleLabelHeightConstraint?.constant = rect.height + 5.0
  218. } else {
  219. self.subtitleLabelHeightConstraint?.constant = rect.height
  220. }
  221. }
  222. private func adjustLabelBottom(label: UILabel) {
  223. var bottomConstant: CGFloat = bottomConstantPortrait
  224. switch UIApplication.shared.statusBarOrientation {
  225. case .portrait:
  226. bottomConstant = bottomConstantLandscape
  227. case .landscapeLeft, .landscapeRight, .portraitUpsideDown:
  228. bottomConstant = bottomConstantPortrait
  229. default:
  230. ()
  231. }
  232. subtitleLabelBottomConstraint?.constant = bottomConstant
  233. }
  234. private func adjustViewWidth(containerView: UIView) {
  235. let widthConstant: CGFloat = UIScreen.main.bounds.width * widthProportion
  236. subtitleContainerViewWidthConstraint!.constant = widthConstant
  237. subtitleLabel?.preferredMaxLayoutWidth = (widthConstant - 20)
  238. }
  239. fileprivate func addSubtitleLabel(_ vc: UIViewController, _ playerToolBar: NCPlayerToolBar?) {
  240. guard subtitleLabel == nil,
  241. subtitleContainerView == nil else {
  242. return
  243. }
  244. subtitleContainerView = UIView()
  245. subtitleLabel = UILabel()
  246. subtitleContainerView?.translatesAutoresizingMaskIntoConstraints = false
  247. subtitleContainerView?.layer.cornerRadius = 5.0
  248. subtitleContainerView?.layer.masksToBounds = true
  249. subtitleContainerView?.layer.shouldRasterize = true
  250. subtitleContainerView?.layer.rasterizationScale = UIScreen.main.scale
  251. subtitleContainerView?.backgroundColor = UIColor.black.withAlphaComponent(0.35)
  252. subtitleLabel?.translatesAutoresizingMaskIntoConstraints = false
  253. subtitleLabel?.textAlignment = .center
  254. subtitleLabel?.numberOfLines = 0
  255. let fontSize = UIDevice.current.userInterfaceIdiom == .pad ? 38.0 : 20.0
  256. subtitleLabel?.font = UIFont.incosolataMedium(size: fontSize)
  257. subtitleLabel?.lineBreakMode = .byWordWrapping
  258. subtitleLabel?.textColor = .white
  259. subtitleLabel?.backgroundColor = .clear
  260. subtitleContainerView?.addSubview(subtitleLabel!)
  261. var isFound = false
  262. for v in vc.view.subviews where v is UIScrollView {
  263. if let scrollView = v as? UIScrollView {
  264. for subView in scrollView.subviews where subView is imageVideoContainerView {
  265. subView.addSubview(subtitleContainerView!)
  266. isFound = true
  267. break
  268. }
  269. }
  270. }
  271. if !isFound {
  272. vc.view.addSubview(subtitleContainerView!)
  273. }
  274. NSLayoutConstraint.activate([
  275. subtitleLabel!.centerXAnchor.constraint(equalTo: subtitleContainerView!.centerXAnchor),
  276. subtitleLabel!.centerYAnchor.constraint(equalTo: subtitleContainerView!.centerYAnchor)
  277. ])
  278. subtitleContainerViewHeightConstraint = NSLayoutConstraint(item: subtitleContainerView!, attribute: .height, relatedBy: .equal, toItem: subtitleLabel!, attribute: .height, multiplier: 1.0, constant: 0.0)
  279. vc.view?.addConstraint(subtitleContainerViewHeightConstraint!)
  280. var bottomConstant: CGFloat = bottomConstantPortrait
  281. switch UIApplication.shared.statusBarOrientation {
  282. case .portrait, .portraitUpsideDown:
  283. bottomConstant = bottomConstantLandscape
  284. case .landscapeLeft, .landscapeRight:
  285. bottomConstant = bottomConstantPortrait
  286. default:
  287. ()
  288. }
  289. let widthConstant: CGFloat = UIScreen.main.bounds.width * widthProportion
  290. NSLayoutConstraint.activate([
  291. subtitleContainerView!.centerXAnchor.constraint(equalTo: vc.view.centerXAnchor)
  292. ])
  293. subtitleContainerViewWidthConstraint = NSLayoutConstraint(item: subtitleContainerView!, attribute: .width, relatedBy: .lessThanOrEqual, toItem: nil,
  294. attribute: .width, multiplier: 1, constant: widthConstant)
  295. // setting default width == 0 because there is no text inside of the label
  296. subtitleLabelWidthConstraint = NSLayoutConstraint(item: subtitleLabel!, attribute: .width, relatedBy: .equal, toItem: subtitleContainerView,
  297. attribute: .width, multiplier: 1, constant: -20)
  298. subtitleLabelBottomConstraint = NSLayoutConstraint(item: subtitleContainerView!, attribute: .bottom, relatedBy: .equal, toItem: vc.view, attribute:
  299. .bottom, multiplier: 1, constant: bottomConstant)
  300. vc.view?.addConstraint(subtitleContainerViewWidthConstraint!)
  301. vc.view?.addConstraint(subtitleLabelWidthConstraint!)
  302. vc.view?.addConstraint(subtitleLabelBottomConstraint!)
  303. }
  304. internal func showAlertSubtitles() {
  305. let alert = UIAlertController(title: nil, message: NSLocalizedString("_subtitle_", comment: ""), preferredStyle: .actionSheet)
  306. for url in subtitleUrls {
  307. print("Play Subtitle at:\n\(url.path)")
  308. let videoUrlTitle = self.metadata.fileName.alphanumeric.dropLast(3)
  309. let subtitleUrlTitle = url.lastPathComponent.alphanumeric.dropLast(3)
  310. var titleSubtitle = String(subtitleUrlTitle.dropFirst(videoUrlTitle.count))
  311. if titleSubtitle.isEmpty {
  312. titleSubtitle = NSLocalizedString("_subtitle_", comment: "")
  313. }
  314. let action = UIAlertAction(title: titleSubtitle, style: .default, handler: { [self] _ in
  315. if NCUtilityFileSystem.shared.getFileSize(filePath: url.path) > 0 {
  316. self.open(fileFromLocal: url)
  317. if let viewController = viewController {
  318. self.addSubtitlesTo(viewController, self.playerToolBar)
  319. self.showSubtitle(url: url)
  320. }
  321. } else {
  322. let alertError = UIAlertController(title: NSLocalizedString("_error_", comment: ""), message: NSLocalizedString("_subtitle_not_found_", comment: ""), preferredStyle: .alert)
  323. alertError.addAction(UIKit.UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: nil))
  324. viewController?.present(alertError, animated: true, completion: nil)
  325. }
  326. })
  327. alert.addAction(action)
  328. if currentSubtitle == url {
  329. action.setValue(true, forKey: "checked")
  330. }
  331. }
  332. let disable = UIAlertAction(title: NSLocalizedString("_disable_", comment: ""), style: .default, handler: { _ in
  333. self.hideSubtitle()
  334. })
  335. alert.addAction(disable)
  336. if currentSubtitle == nil {
  337. disable.setValue(true, forKey: "checked")
  338. }
  339. alert.addAction(UIAlertAction(title: NSLocalizedString("_cancel_", comment: ""), style: .cancel, handler: { _ in
  340. }))
  341. alert.popoverPresentationController?.sourceView = self.viewController?.view
  342. self.viewController?.present(alert, animated: true, completion: nil)
  343. }
  344. }