Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clear playlistItems when navigating on YT #2587

Open
wants to merge 14 commits into
base: feature/Playlists
from
Open
Changes from 1 commit
Commits
File filter...
Filter file types
Jump to…
Jump to file
Failed to load files.

Always

Just for now

Fixed audio not playing in sync with CarPlay and video's not updating…

… the now-playing bar.
  • Loading branch information
Brandon-T committed Apr 13, 2020
commit d8f0f1cf7b928bc604e1d0e49abe4a57dbc4116b
@@ -2149,6 +2149,11 @@ extension BrowserViewController: TabDelegate {
guard let self = self else { return }
self.onUpdateNowPlaying(tab: tab)
}.bind(to: tab)

tab.existingPlaylistItems.observe { [weak self] _, _ in
guard let self = self else { return }
self.onUpdateNowPlaying(tab: tab)
}.bind(to: tab)
}

func tab(_ tab: Tab, willDeleteWebView webView: WKWebView) {
@@ -3558,7 +3563,7 @@ extension BrowserViewController: NowPlayingBarDelegate {
}

func onUpdateNowPlaying(tab: Tab) {
let items = tab.playlistItems.value
let items = tab.playlistItems.value + tab.existingPlaylistItems.value
if items.isEmpty {
if Playlist.shared.currentlyPlayingInfo.value != nil {
nowPlayingBar.state = .nowPlaying
@@ -123,6 +123,7 @@ extension BrowserViewController: WKNavigationDelegate {

if url.scheme == "about" {
self.tabManager.tabForWebView(webView)?.playlistItems.value = []
self.tabManager.tabForWebView(webView)?.existingPlaylistItems.value = []
decisionHandler(.allow)
return
}
@@ -260,6 +261,7 @@ extension BrowserViewController: WKNavigationDelegate {
self.tabManager.selectedTab?.blockAllAlerts = false
}
self.tabManager.tabForWebView(webView)?.playlistItems.value = []
self.tabManager.tabForWebView(webView)?.existingPlaylistItems.value = []
decisionHandler(.allow)
return
}
@@ -140,6 +140,8 @@ class PlaylistManager: TabContentScript {

do {
guard let item = try PlaylistInfo.from(message: message) else { return }

//Update playlist with new items..
if !Playlist.shared.itemExists(item: item) {
if let items = tab?.playlistItems, let index = items.value.firstIndex(where: { $0.src == item.src }) {
if items.value[index].duration < 0.01 {
@@ -152,7 +154,17 @@ class PlaylistManager: TabContentScript {
}
}
} else {
tab?.existingPlaylistItems.value.append(item)
//Update playlist with existing items..
if let items = tab?.existingPlaylistItems, let index = items.value.firstIndex(where: { $0.src == item.src }) {
if items.value[index].duration < 0.01 {
items.value[index].duration = item.duration
items.refresh()
}
} else {
if !item.src.isEmpty {
tab?.existingPlaylistItems.value.append(item)
}
}
}
} catch {
print(error)
@@ -10,18 +10,17 @@ import WebKit

class CarplayMediaManager: NSObject {
private var contentManager: MPPlayableContentManager
private var player: AVPlayer
private var playlistItems = [PlaylistInfo]()
private var cacheLoader = PlaylistCacheLoader()
private var webLoader = PlaylistWebLoader(handler: { _ in })
private var currentStation: PlaylistInfo?
public let playerView = VideoView()

public static let shared = CarplayMediaManager()

private override init() {
contentManager = MPPlayableContentManager.shared()
playlistItems = []
player = AVPlayer()

super.init()

@@ -35,12 +34,12 @@ class CarplayMediaManager: NSObject {
UIApplication.shared.beginReceivingRemoteControlEvents()

MPRemoteCommandCenter.shared().pauseCommand.addTarget { [weak self] _ in
self?.player.pause()
self?.playerView.pause()
return .success
}

MPRemoteCommandCenter.shared().playCommand.addTarget { [weak self] _ in
self?.player.play()
self?.playerView.play()
return .success
}

@@ -70,7 +69,7 @@ class CarplayMediaManager: NSObject {
MPMediaItemPropertyArtist: "Play"
]

player.addObserver(self, forKeyPath: "rate", options: .new, context: nil)
playerView.addObserver(self, forKeyPath: "rate", options: .new, context: nil)
contentManager.delegate = self
contentManager.dataSource = self
self.updateItems()
@@ -119,31 +118,6 @@ class CarplayMediaManager: NSObject {

extension CarplayMediaManager: MPPlayableContentDelegate {

private func load(url: URL, resourceDelegate: AVAssetResourceLoaderDelegate?) {
let asset = AVURLAsset(url: url)

if let delegate = resourceDelegate {
asset.resourceLoader.setDelegate(delegate, queue: .main)
}

if let currentItem = player.currentItem, currentItem.asset.isKind(of: AVURLAsset.self) && player.status == .readyToPlay {
if let asset = currentItem.asset as? AVURLAsset, asset.url.absoluteString == url.absoluteString {
player.pause()
player.play()
return
}
}

asset.loadValuesAsynchronously(forKeys: ["playable", "tracks", "duration"]) { [weak self] in
guard let self = self else { return }
DispatchQueue.main.async {
let item = AVPlayerItem(asset: asset)
self.player.replaceCurrentItem(with: item)
self.player.play()
}
}
}

private func displayLoadingResourceError() {
let alert = UIAlertController(title: "Sorry", message: "There was a problem loading the resource!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
@@ -163,34 +137,27 @@ extension CarplayMediaManager: MPPlayableContentDelegate {
let cache = Playlist.shared.getCache(item: item)
if cache.isEmpty {
if let url = URL(string: item.src) {
self.completion = completionHandler
self.load(url: url, resourceDelegate: nil)
self.playerView.load(url: url, resourceDelegate: nil)
} else {
self.webLoader.removeFromSuperview()
self.webLoader = PlaylistWebLoader(handler: { [weak self] item in
guard let self = self else { return }
if let item = item, let url = URL(string: item.src) {
self.completion = completionHandler
self.load(url: url, resourceDelegate: nil)
self.playerView.load(url: url, resourceDelegate: nil)
} else {
completionHandler("Error Attempting to load Media")
self.displayLoadingResourceError()
}
})

if let url = URL(string: item.pageSrc) {
UIApplication.shared.keyWindow?.insertSubview(self.webLoader, at: 0)
self.webLoader.frame = CGRect(width: 100.0, height: 100.0)
self.webLoader.load(url: url)
} else {
completionHandler("Error Attempting to load Media")
self.displayLoadingResourceError()
}
}
} else {
self.completion = completionHandler
self.cacheLoader = PlaylistCacheLoader(cacheData: cache)
self.load(url: URL(string: "brave-ios://local-media-resource")!, resourceDelegate: self.cacheLoader)
let url = URL(string: "brave-media-ios://local-media-resource?time=\(Date().timeIntervalSince1970)")!
self.playerView.load(url: url, resourceDelegate: self.cacheLoader)
}
} else {
completionHandler(nil)
@@ -20,7 +20,7 @@ class PlaylistViewController: UIViewController {
$0.text = "Playlist"
}

private let playerView = VideoView()
private let playerView = CarplayMediaManager.shared.playerView
private var tableView = UITableView(frame: .zero, style: .grouped)
private var playlistItems = [PlaylistInfo]()
private var itemToBeAdded: PlaylistInfo?
@@ -41,15 +41,6 @@ class PlaylistViewController: UIViewController {
fatalError("init(coder:) has not been implemented")
}

deinit {
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback, options: [.allowAirPlay, .allowBluetooth, .duckOthers])
try AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
} catch {
print(error)
}
}

override func viewDidLoad() {
super.viewDidLoad()

@@ -109,12 +100,11 @@ class PlaylistViewController: UIViewController {
}.bind(to: self)
})

do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback, options: [.allowAirPlay, .allowBluetooth, .duckOthers])
try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
} catch {
print(error)
}
Playlist.shared.currentlyPlayingInfo.observe({ [weak self] _, _ in
guard let self = self else { return }
self.currentItem = self.playlistItems.firstIndex(where: { $0.pageSrc == Playlist.shared.currentlyPlayingInfo.value?.pageSrc }) ?? -1
self.tableView.reloadData()
}).bind(to: self)
}

private func updateItems() {
@@ -128,15 +118,9 @@ class PlaylistViewController: UIViewController {
playlistItems = Playlist.shared.getItems()
CarplayMediaManager.shared.updateItems()

currentItem = -1
for (index, item) in playlistItems.enumerated() {
if Playlist.shared.currentlyPlayingInfo.value?.pageSrc == item.pageSrc {
currentItem = index
break
}
}
currentItem = playlistItems.firstIndex(where: { $0.pageSrc == Playlist.shared.currentlyPlayingInfo.value?.pageSrc }) ?? -1

if currentItem != -1 {
if currentItem != -1 && !playerView.isPlaying {
self.tableView(tableView, didSelectRowAt: IndexPath(row: self.currentItem, section: 0))
}
}
@@ -148,6 +132,7 @@ class PlaylistViewController: UIViewController {
alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: { _ in
self.playlistItems = []
Playlist.shared.removeAll()
Playlist.shared.currentlyPlayingInfo.value = nil

self.dismiss(animated: true, completion: nil)
}))
@@ -347,15 +332,10 @@ extension PlaylistViewController: UITableViewDelegate {
}
}
} else {
// let directory = NSTemporaryDirectory()
// let fileName = "foo.m4v"
// let fullURL = NSURL.fileURL(withPathComponents: [directory, fileName])!
//
// try? cache.write(to: fullURL, options: .atomicWrite)
self.cacheLoader = PlaylistCacheLoader(cacheData: cache)
let url = URL(string: "brave-media-ios://local-media-resource?time=\(Date().timeIntervalSince1970)")!
self.playerView.load(url: url, resourceDelegate: self.cacheLoader)
self.activityIndicator.stopAnimating()
}
}

@@ -319,6 +319,13 @@ public class VideoView: UIView, VideoTrackerBarDelegate {

override init(frame: CGRect) {
super.init(frame: frame)

do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback, options: [.allowAirPlay, .allowBluetooth, .duckOthers])
try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
} catch {
print(error)
}

//Setup
self.backgroundColor = .black
@@ -404,6 +411,13 @@ public class VideoView: UIView, VideoTrackerBarDelegate {
}

deinit {
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback, options: [.allowAirPlay, .allowBluetooth, .duckOthers])
try AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
} catch {
print(error)
}

if let observer = self.playObserver {
player.removeTimeObserver(observer)
}
@@ -446,7 +460,6 @@ public class VideoView: UIView, VideoTrackerBarDelegate {

private func seekDirectionWithAnimation(_ seekBlock: () -> Void) {
isSeeking = true
//showOverlays(true, except: [], display: [trackBarBackground, playControlsStackView, castButton, fullScreenButton])
showOverlays(true)

seekBlock()
@@ -89,7 +89,7 @@ class MenuViewController: UITableViewController {
var allWithoutUrlButtons = allButtons
allWithoutUrlButtons.removeAll { $0 == .add || $0 == .share }

if tab?.playlistItems.value.isEmpty == true && Playlist.shared.getPlaylistCount() == 0 {
if Playlist.shared.getPlaylistCount() == 0 {
allButtons.removeAll { $0 == .playlist }
allWithoutUrlButtons.removeAll { $0 == .playlist }
}
@@ -163,7 +163,7 @@ class MenuViewController: UITableViewController {
case .add: openAddBookmark()
case .share: openShareSheet()
case .downloads: openDownloads()
case .playlist: tab?.playlistItems.value.isEmpty == true ? openPlaylists() : addPlaylists()
case .playlist: openPlaylists()
}
}

@@ -242,11 +242,6 @@ class MenuViewController: UITableViewController {
}

private func openPlaylists() {
let vc = PlaylistViewController(tabManager: bvc.tabManager)
open(vc, doneButton: DoneButton(style: .done, position: .left))
}

private func addPlaylists() {
let items = bvc.tabManager.selectedTab?.playlistItems.value ?? []

if items.count > 1 {
@@ -110,6 +110,7 @@
</array>
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
<string>remote-notification</string>
</array>
<key>UIBrowsableContentSupportsSectionedBrowsing</key>
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.