NCSubtitlePlayer.swift 17 KB

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