Skip to content

armgit / cra

Public Imported from GitHub
0

The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.

Protected media choices live in the data folder (protected-media.json)

Victor9a8dd3a65218
diff --git a/Packages/CraCore/Sources/CraCore/ProtectedMedia.swift b/Packages/CraCore/Sources/CraCore/ProtectedMedia.swift
index dcac9f4..19e04d7 100644
--- a/Packages/CraCore/Sources/CraCore/ProtectedMedia.swift
+++ b/Packages/CraCore/Sources/CraCore/ProtectedMedia.swift
@@ -175,3 +175,40 @@ public struct ProtectedMediaSites: Equatable, Sendable {
return path.map { $0.isEmpty ? host : host + $0 } ?? host
}
}
+
+/// protected-media.json in the data folder: the user's own choices about which engine plays a
+/// site (the Site Control Center's Safari's Engine switch, `ProtectedMediaSites.choosing`) and the
+/// services whose "plays with Safari's engine" toast was closed. In the data folder, not the
+/// defaults, so each profile folder and test instance (CRA_DATA_DIR) keeps its own.
+public struct ProtectedMediaChoices: Codable, Equatable, Sendable {
+ /// Sites the user sent to WebKit.
+ public var added: [String]
+ /// Listed entries the user took back to Chromium.
+ public var removed: [String]
+ /// Services whose toast was closed with its ✕.
+ public var told: [String]
+
+ public init(added: [String] = [], removed: [String] = [], told: [String] = []) {
+ self.added = added
+ self.removed = removed
+ self.told = told
+ }
+
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ added = try c.decodeIfPresent([String].self, forKey: .added) ?? []
+ removed = try c.decodeIfPresent([String].self, forKey: .removed) ?? []
+ told = try c.decodeIfPresent([String].self, forKey: .told) ?? []
+ }
+
+ /// After choosing `engine` for `url`'s site.
+ public func choosing(_ engine: PageEngine, for url: String) -> ProtectedMediaChoices {
+ let r = ProtectedMediaSites.choosing(engine, for: url, added: added, removed: removed)
+ return ProtectedMediaChoices(added: r.added, removed: r.removed, told: told)
+ }
+
+ /// After the user closed `service`'s toast.
+ public func telling(_ service: String) -> ProtectedMediaChoices {
+ told.contains(service) ? self : ProtectedMediaChoices(added: added, removed: removed, told: told + [service])
+ }
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/input/protected-media.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/input/protected-media.json
new file mode 100644
index 0000000..6d13c24
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/input/protected-media.json
@@ -0,0 +1,5 @@
+{
+ "added" : [ "www.viaplay.dk", "Stream.Example.org" ],
+ "removed" : [ "netflix.com" ],
+ "told" : [ "Spotify" ]
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/protected-media.json b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/protected-media.json
new file mode 100644
index 0000000..357375e
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/Fixtures/Model/recorded/protected-media.json
@@ -0,0 +1,12 @@
+{
+ "added" : [
+ "www.viaplay.dk",
+ "Stream.Example.org"
+ ],
+ "removed" : [
+ "netflix.com"
+ ],
+ "told" : [
+ "Spotify"
+ ]
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/ModelFixtureTests.swift b/Packages/CraCore/Tests/CraCoreTests/ModelFixtureTests.swift
index 4fbf7ff..eb1e71e 100644
--- a/Packages/CraCore/Tests/CraCoreTests/ModelFixtureTests.swift
+++ b/Packages/CraCore/Tests/CraCoreTests/ModelFixtureTests.swift
@@ -91,6 +91,24 @@ struct ModelFixtureTests {
/// pinned-extensions.json: the one list of before #107 loads as every profile's and stays an
/// array when saved; per-profile lists keep an emptied profile's empty list.
+ /// protected-media.json (docs/protected-media.md): the Safari's Engine choices and closed toasts,
+ /// kept as written; a file from before a key existed loads with that list empty.
+ @Test func protectedMediaChoicesLoadAsRecorded() throws {
+ let (loaded, recorded) = try Self.load("protected-media.json", as: ProtectedMediaChoices.self)
+ #expect(loaded == recorded)
+ #expect(try Self.roundTrips(loaded))
+ #expect(try Self.encoder.encode(loaded) == Self.data("recorded", "protected-media.json").dropLast(
+ try Self.data("recorded", "protected-media.json").last == 0x0A ? 1 : 0))
+ let sites = ProtectedMediaSites(extraHosts: loaded.added, removedHosts: loaded.removed)
+ #expect(sites.engine(for: "https://www.viaplay.dk/film") == .webKit)
+ #expect(sites.engine(for: "https://stream.example.org/") == .webKit)
+ #expect(sites.engine(for: "https://www.netflix.com/") == .chromium)
+ let empty = try Self.decoder.decode(ProtectedMediaChoices.self, from: Data(#"{"told":["Netflix"]}"#.utf8))
+ #expect(empty == ProtectedMediaChoices(told: ["Netflix"]))
+ #expect(empty.telling("Netflix") == empty && empty.telling("Max").told == ["Netflix", "Max"])
+ #expect(empty.choosing(.webKit, for: "https://www.viaplay.dk/").added == ["www.viaplay.dk"])
+ }
+
@Test(arguments: ["pinned-extensions.json", "pinned-extensions-profiles.json"])
func pinnedExtensionsLoadAsRecorded(name: String) throws {
let (loaded, recorded) = try Self.load(name, as: PinnedExtensions.self)
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index b67d1d6..7d12063 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -695,6 +695,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
if let v = dict["banner"] { SoftwareUpdater.shared.debugUpdated(v == "none" ? nil : v); return }
if let v = dict["bannerReady"] { SoftwareUpdater.shared.debugReady(v == "none" ? nil : v); return }
if dict["switcher"] != nil { main.debugTabSwitcher(); return }
+ // The Site Control Center's Safari's Engine switch for the focused page, without the pointer.
+ if let v = dict["safariEngine"] { main.debugChooseSafariEngine(v == "on"); return }
+ // Script in Cra's isolated world of the focused page: "Cra isolatedJS → <result>" on stdout.
+ if let js = dict["isolatedJS"] {
+ let params = String(decoding: (try? JSONSerialization.data(withJSONObject: ["expression": js, "returnByValue": true])) ?? Data(), as: UTF8.self)
+ main.currentBrowser?.evaluate(inIsolatedWorld: PageScript.world, params: params) { result, error in
+ NSLog("Cra isolatedJS → %@", result ?? "error: \(error ?? "?")")
+ }
+ return
+ }
// The sidebar player without the pointer: play/pause/next/previous/pip on the newest
// card ("state" only logs), then its cards: "Cra nowPlaying[<label>] <host> playing=… prev=… next=… video=… pip=…".
if let op = dict["nowPlaying"], let np = main.browsers.nowPlaying {
diff --git a/Sources/Cra/Services/WebKit/PageEngines.swift b/Sources/Cra/Services/WebKit/PageEngines.swift
index a410678..5c775b7 100644
--- a/Sources/Cra/Services/WebKit/PageEngines.swift
+++ b/Sources/Cra/Services/WebKit/PageEngines.swift
@@ -5,34 +5,38 @@ import CraCEF
/// (ProtectedMediaSites has the rules; docs/protected-media.md the why).
@MainActor
enum PageEngines {
- /// Read once per launch. `defaults write dk.kildahl.cra webKitProtectedMedia -bool NO` turns
- /// it off (every page Chromium's again); `webKitProtectedMediaHosts` and
- /// `webKitProtectedMediaRemovedHosts` (string arrays) change the list. A test instance sets
- /// CRA_WEBKIT_DRM=0|1 and CRA_WEBKIT_HOSTS=<host,host> (the scenarios' 127.0.0.1).
- /// The Site Control Center's Safari's Engine switch writes the two lists (`choose`).
+ /// The list, with the user's own choices (protected-media.json) on it. `defaults write
+ /// dk.kildahl.cra webKitProtectedMedia -bool NO` turns it all off (every page Chromium's again).
+ /// A test instance sets CRA_WEBKIT_DRM=0|1 and CRA_WEBKIT_HOSTS=<host,host> (the scenarios' localhost).
private(set) static var sites: ProtectedMediaSites = load()
- private static let addedKey = "webKitProtectedMediaHosts", removedKey = "webKitProtectedMediaRemovedHosts"
+ /// The Safari's Engine choices and the closed toasts, in the data folder (CRA_DATA_DIR for a test).
+ private static let file = JSONStore<ProtectedMediaChoices>("protected-media.json")
+ private(set) static var choices: ProtectedMediaChoices = file.load(or: { ProtectedMediaChoices() })
private static func load() -> ProtectedMediaSites {
let env = ProcessInfo.processInfo.environment
- let defaults = UserDefaults.standard
- let enabled = env["CRA_WEBKIT_DRM"].map { $0 != "0" } ?? (defaults.object(forKey: "webKitProtectedMedia") as? Bool ?? true)
- let extra = (env["CRA_WEBKIT_HOSTS"] ?? "").split(separator: ",").map(String.init) + (defaults.stringArray(forKey: addedKey) ?? [])
- let removed = defaults.stringArray(forKey: removedKey) ?? []
- return ProtectedMediaSites(isEnabled: enabled, extraHosts: extra, removedHosts: removed)
+ let enabled = env["CRA_WEBKIT_DRM"].map { $0 != "0" } ?? (UserDefaults.standard.object(forKey: "webKitProtectedMedia") as? Bool ?? true)
+ let extra = (env["CRA_WEBKIT_HOSTS"] ?? "").split(separator: ",").map(String.init) + choices.added
+ return ProtectedMediaSites(isEnabled: enabled, extraHosts: extra, removedHosts: choices.removed)
}
- /// The user's choice for `url`'s site (ProtectedMediaSites.choosing), kept and in force at once.
+ /// The user's choice for `url`'s site (the Site Control Center's switch), kept and in force at once.
static func choose(_ engine: PageEngine, for url: String) {
- let defaults = UserDefaults.standard
- let r = ProtectedMediaSites.choosing(engine, for: url, added: defaults.stringArray(forKey: addedKey) ?? [],
- removed: defaults.stringArray(forKey: removedKey) ?? [])
- defaults.set(r.added, forKey: addedKey)
- defaults.set(r.removed, forKey: removedKey)
+ choices = choices.choosing(engine, for: url)
+ file.saveNow(choices)
sites = load()
}
+ /// Whether `service`'s "plays with Safari's engine" toast was closed with its ✕.
+ static func wasTold(_ service: String) -> Bool { choices.told.contains(service) }
+
+ static func told(_ service: String) {
+ guard !wasTold(service) else { return }
+ choices = choices.telling(service)
+ file.saveNow(choices)
+ }
+
static func engine(of browser: CraBrowser) -> PageEngine { browser is WebKitBrowser ? .webKit : .chromium }
/// The service a WebKit page plays ("Spotify"), nil for a Chromium page: Cra tells the user why
diff --git a/Sources/Cra/UI/Windows/MainWindowController.swift b/Sources/Cra/UI/Windows/MainWindowController.swift
index 05f1eaa..850b07c 100644
--- a/Sources/Cra/UI/Windows/MainWindowController.swift
+++ b/Sources/Cra/UI/Windows/MainWindowController.swift
@@ -2363,15 +2363,15 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { once(nil) }
}
+ func debugChooseSafariEngine(_ on: Bool) {
+ if let url = currentBrowser?.currentURL { chooseSafariEngine(on, for: url) }
+ }
+
/// The Site Control Center's Safari's Engine switch: the site plays in WebKit (or Chromium)
/// from now on, and the focused page opens again there. Choosing it is knowing about it: no toast.
private func chooseSafariEngine(_ on: Bool, for url: String) {
PageEngines.choose(on ? .webKit : .chromium, for: url)
- if on, let service = PageEngines.sites.serviceName(for: url) {
- let key = "protectedMediaToldServices"
- let told = UserDefaults.standard.stringArray(forKey: key) ?? []
- if !told.contains(service) { UserDefaults.standard.set(told + [service], forKey: key) }
- }
+ if on, let service = PageEngines.sites.serviceName(for: url) { PageEngines.told(service) }
if let id = browsers.visibleTabID { browsers.reopenInItsEngine(id) }
}
@@ -2684,14 +2684,9 @@ final class MainWindowController: NSWindowController, NSWindowDelegate, BrowserM
/// until its ✕ is pressed, Why? included, so Cra knows it was seen; only then is the service told
/// for good. Shown once a session per service: one left open shows again next launch.
private func tellAboutProtectedMedia(_ service: String) {
- let key = "protectedMediaToldServices"
- guard !(UserDefaults.standard.stringArray(forKey: key) ?? []).contains(service), !offeredProtectedMedia.contains(service),
- window?.isVisible == true else { return }
+ guard !PageEngines.wasTold(service), !offeredProtectedMedia.contains(service), window?.isVisible == true else { return }
offeredProtectedMedia.insert(service)
- let told = {
- let list = UserDefaults.standard.stringArray(forKey: key) ?? []
- if !list.contains(service) { UserDefaults.standard.set(list + [service], forKey: key) }
- }
+ let told = { PageEngines.told(service) }
// A moment after the page shows, so it isn't lost in the tab switch.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [weak self] in
guard let self, let window = self.window, let id = self.browsers.visibleTabID,
diff --git a/Tests/BrowserManagerLifecycleTests.swift b/Tests/BrowserManagerLifecycleTests.swift
index 2c2868f..4265a76 100644
--- a/Tests/BrowserManagerLifecycleTests.swift
+++ b/Tests/BrowserManagerLifecycleTests.swift
@@ -224,8 +224,7 @@ enum BrowserManagerLifecycleTests {
manager.reopenInItsEngine(chosen)
await drainMainQueue()
expect(!(manager.runtime(for: chosen)?.browser is WebKitBrowser), "chosen back, the page opens in Chromium")
- UserDefaults.standard.removeObject(forKey: "webKitProtectedMediaHosts")
- UserDefaults.standard.removeObject(forKey: "webKitProtectedMediaRemovedHosts")
+ expect(PageEngines.choices.added.isEmpty && PageEngines.choices.removed.isEmpty, "chosen back, nothing is left on the lists")
// A late request from a page that already moved changes nothing.
expect(!manager.browser(chromium, handsOffNavigationToURL: "https://www.netflix.com/", method: "GET"), "a retired page can't move its tab again")
diff --git a/Tests/Scenarios/webkit-drm-tabs.scenario b/Tests/Scenarios/webkit-drm-tabs.scenario
index aba3ead..4c353b7 100644
--- a/Tests/Scenarios/webkit-drm-tabs.scenario
+++ b/Tests/Scenarios/webkit-drm-tabs.scenario
@@ -105,6 +105,24 @@ wait 3
cra://debug?cdp=Runtime.evaluate&target=little&params={"expression":"[document.title,'userAgentData' in navigator].join()"}
expect-log Cra cdp Runtime.evaluate .*"value":"Fixture little,false"
+# A Chromium page that asks for Widevine is noticed (Cra's world), and the Safari's Engine switch
+# moves its site to WebKit in place, and back.
+cra://open?url=${PAGE}?n=drm
+expect-log loaded 127\.0\.0\.1
+cra://debug?isolatedJS=String(window.__cra.drm===true)
+expect-log Cra isolatedJS → .*"value":"false"
+cra://debug?cdp=Runtime.evaluate&params={"expression":"navigator.requestMediaKeySystemAccess('com.widevine.alpha',[{initDataTypes:['cenc'],videoCapabilities:[{contentType:'video/mp4'}]}]).then(()=>'widevine:asked',()=>'widevine:asked')","awaitPromise":true}
+expect-log Cra cdp Runtime.evaluate .*"value":"widevine:asked"
+cra://debug?isolatedJS=String(window.__cra.drm===true)
+expect-log Cra isolatedJS → .*"value":"true"
+cra://debug?safariEngine=on
+expect-log moves to WebKit for 127\.0\.0\.1, as chosen
+wait 2
+cra://debug?cdp=Runtime.evaluate&params={"expression":"[document.title,'userAgentData' in navigator].join()"}
+expect-log Cra cdp Runtime.evaluate .*"value":"Fixture drm,false"
+cra://debug?safariEngine=off
+expect-log moves to Chromium for 127\.0\.0\.1, as chosen
+
# Tab sleep: the hidden WebKit page closes (WebKit has no in-place discard) and opens again when shown.
cra://open?url=${WEBKIT}/page.html?n=sleeper
expect-log loaded localhost
diff --git a/Tests/test-browser-manager.sh b/Tests/test-browser-manager.sh
index e41fb11..bf1acef 100755
--- a/Tests/test-browser-manager.sh
+++ b/Tests/test-browser-manager.sh
@@ -13,5 +13,6 @@ xcrun swiftc -swift-version 5 -parse-as-library ${CRA_TEST_SWIFTC_FLAGS:-} -I "$
"$MANAGER_SOURCE" Sources/Cra/Services/NowPlaying.swift Sources/Cra/Services/PageScript.swift Sources/Cra/Services/Scheduler.swift Sources/Cra/Services/DevToolsToggle.swift Sources/Cra/Services/CraLog.swift Sources/Cra/Services/PageProbe.swift Sources/Cra/Services/Persistence.swift \
Sources/Cra/Perf/Perf.swift Packages/CraCore/Sources/CraCore/Perf/*.swift Packages/CraCore/Sources/CraCore/ExtensionPageRetry.swift Packages/CraCore/Sources/CraCore/PermissionPrompt.swift Packages/CraCore/Sources/CraCore/TabSleepPolicy.swift Packages/CraCore/Sources/CraCore/ProtectedMedia.swift Sources/Cra/Services/WebKit/PageEngines.swift Tests/Support/ManualScheduler.swift Tests/BrowserManagerSupport/AppServices.swift \
Tests/BrowserManagerLifecycleTests.swift -o "$TEST_DIR/lifecycle-tests"
-"$TEST_DIR/lifecycle-tests"
+# A data folder of its own: PageEngines keeps protected-media.json there, not in the real Cra's.
+CRA_DATA_DIR="$TEST_DIR/data" "$TEST_DIR/lifecycle-tests"
[ -z "${CRA_TEST_KEEP:-}" ] || cp "$TEST_DIR/lifecycle-tests" "$CRA_TEST_KEEP/"
diff --git a/docs/protected-media.md b/docs/protected-media.md
index a706f8e..58491b9 100644
--- a/docs/protected-media.md
+++ b/docs/protected-media.md
@@ -46,8 +46,7 @@ licence, keys usable, 720p playing). That is the whole requirement.
wrapper around `navigator.requestMediaKeySystemAccess`), the Site Control Center shows a
**Safari's Engine** switch. On, the site plays in WebKit from then on and the page reopens there.
A WebKit page shows it on, so a listed site can be taken back to Chromium the same way
- (`ProtectedMediaSites.choosing`, kept in `webKitProtectedMediaHosts` and
- `webKitProtectedMediaRemovedHosts`). They are players, not whole domains, except where nothing else signs in through the service (Max sends `play.max.com` on to `www.hbomax.com` and signs in on its own hosts):
+ (`ProtectedMediaSites.choosing`, kept in the data folder's `protected-media.json`). They are players, not whole domains, except where nothing else signs in through the service (Max sends `play.max.com` on to `www.hbomax.com` and signs in on its own hosts):
other sites send their "Sign in with Spotify/Tidal/Deezer" through `accounts.spotify.com`,
`login.tidal.com` and `connect.deezer.com`, and those must finish in the engine they started in.
- **A page Cra opens** (a tab restored or created, a link opened in a new tab, a Little Window, an
@@ -96,7 +95,7 @@ services pick their DRM by browser.
plays with Safari's engine" with a Why? button that opens the Site Control Center. It has no
timer and stays through Why?. Only its ✕ closes it, so Cra knows it was seen; the ✕ shows its
round fill only under the pointer. Services whose ✕ was pressed are kept in the
- `protectedMediaToldServices` default. One left open shows again the next session.
+ `told` list of `protected-media.json`. One left open shows again the next session.
- **The Site Control Center**: on a WebKit page, a Protected Media card takes the Extensions
grid's place. It names the service, says why, and lists what that means here: you sign in once,
extensions don't run, and Web Inspector opens instead of DevTools. Learn more opens
@@ -132,10 +131,10 @@ address. A WebKit page signing in on accounts.spotify.com still counts as Spotif
## Settings
defaults write dk.kildahl.cra webKitProtectedMedia -bool NO # every page Chromium's again
- defaults write dk.kildahl.cra webKitProtectedMediaHosts -array crunchyroll.com
- defaults write dk.kildahl.cra webKitProtectedMediaRemovedHosts -array netflix.com
-They are read at launch. A test instance takes `CRA_WEBKIT_DRM=0|1` and
+The Safari's Engine choices and the closed toasts are in the data folder's `protected-media.json`
+(`ProtectedMediaChoices`: `added`, `removed`, `told`), so each test instance (`CRA_DATA_DIR`) keeps
+its own and never writes the daily Cra's. They are read at launch. A test instance takes `CRA_WEBKIT_DRM=0|1` and
`CRA_WEBKIT_HOSTS=<host,host>` (the scenarios list `localhost`).
## Testing