Skip to content

Play your Steam library's Windows games on a jailbroken PS5.

C++

Refresh the library when Steam licenses change

Leonardo Lobato026452d6d41b
diff --git a/src/app/library_controller.h b/src/app/library_controller.h
index c76a985..b60af2d 100644
--- a/src/app/library_controller.h
+++ b/src/app/library_controller.h
@@ -15,6 +15,8 @@ class LibraryController {
void Tick();
std::optional<steam::LibraryError> TakeClearResult();
bool NeedsRenewal() const { return offline_ || needs_renewal_; }
+ // A load, refresh or clear is still running.
+ bool Busy() const { return request_ != 0 || clearing_; }
private:
void Loading();
homebrew::Simulation& model_;
diff --git a/src/homebrew/controller.cpp b/src/homebrew/controller.cpp
index cfb5fdd..94314ef 100644
--- a/src/homebrew/controller.cpp
+++ b/src/homebrew/controller.cpp
@@ -253,6 +253,7 @@ void Controller::Tick() {
for (const auto& event : service_->Pump(16)) Apply(event);
lap(0);
if(library_) { library_->Tick();AdvanceClear(); }
+ TickLicenseChanges();
lap(1);
if(persistence_) { persistence_->Tick();AdvanceOrganizationClear(); }
lap(2);
@@ -1462,6 +1463,20 @@ void Controller::Apply(const steam::SteamEvent& event) {
}
}
}
+void Controller::TickLicenseChanges() {
+ if (!license_changes_ || !library_) return;
+ const auto changes = license_changes_();
+ const auto now = std::chrono::steady_clock::now();
+ // Each change restarts the wait, so a burst of license lists makes one refresh.
+ if (seen_license_changes_ && changes != *seen_license_changes_) license_refresh_at_ = now + license_refresh_delay_;
+ seen_license_changes_ = changes;
+ if (!license_refresh_at_) return;
+ if (established_auth_ != AuthState::SignedIn || model_.state().account.id.empty()) { license_refresh_at_.reset(); return; }
+ // A refresh, sign-in or sign-out in progress: wait for it, then refresh with the new licenses.
+ if (now < *license_refresh_at_ || phase_ != Phase::Idle || library_->Busy() || library_->NeedsRenewal()) return;
+ license_refresh_at_.reset();
+ library_->Refresh();
+}
void Controller::TickSelfUpdate() {
if (!self_update_) return;
for (const auto& request : model_.TakeSelfUpdateRequests()) {
diff --git a/src/homebrew/controller.hpp b/src/homebrew/controller.hpp
index c1293ab..4d983e9 100644
--- a/src/homebrew/controller.hpp
+++ b/src/homebrew/controller.hpp
@@ -38,6 +38,13 @@ class Controller {
void SetStoreDetails(steam::StoreDetailsService* store_details) { store_details_ = store_details; }
// Playden's own update: the controller passes the player's requests on and shows its state.
void SetSelfUpdate(update::UpdateService* self_update) { self_update_ = self_update; }
+ // Counts changes to the account's Steam licenses (steam::CmLicenseChanges): the library refreshes
+ // once they settle for `delay`, so a game added on another device shows up.
+ void SetLicenseChanges(std::function<std::uint64_t()> changes,
+ std::chrono::steady_clock::duration delay = std::chrono::seconds(5)) {
+ license_changes_ = std::move(changes);
+ license_refresh_delay_ = delay;
+ }
Controller(const Controller&) = delete;
Controller& operator=(const Controller&) = delete;
private:
@@ -65,6 +72,11 @@ class Controller {
std::optional<GameId> requested_store_detail_;
void TickInstalls();
void TickSelfUpdate();
+ void TickLicenseChanges();
+ std::function<std::uint64_t()> license_changes_;
+ std::chrono::steady_clock::duration license_refresh_delay_{};
+ std::optional<std::uint64_t> seen_license_changes_;
+ std::optional<std::chrono::steady_clock::time_point> license_refresh_at_;
update::UpdateService* self_update_ = nullptr;
std::uint64_t self_update_revision_ = ~0ull;
steam::DownloadRate self_update_rate_;
diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cpp
index 643c2bb..932d81f 100644
--- a/src/homebrew/ps5.cpp
+++ b/src/homebrew/ps5.cpp
@@ -563,6 +563,8 @@ int main() {
playden::steam::StoreDetailsService store_details(playden::homebrew::StoreFetch(paths.trust_store));
services.SetStoreDetails(&store_details);
services.SetSelfUpdate(&self_update);
+ // A game bought or added to the library elsewhere: Steam pushes the new license list.
+ services.SetLicenseChanges([steam_cm] { return playden::steam::CmLicenseChanges(*steam_cm); });
#endif
#if PLAYDEN_UI_SIMULATION
playden::homebrew::Render renderer(paths.assets_root);
diff --git a/src/steam/backend/cm_client.cpp b/src/steam/backend/cm_client.cpp
index 5e15f80..4015aaa 100644
--- a/src/steam/backend/cm_client.cpp
+++ b/src/steam/backend/cm_client.cpp
@@ -346,6 +346,11 @@ class CmClient::Session {
std::uint64_t steam_id() const { return steam_id_; }
+ // The license list Steam last pushed, and how many it has pushed: one after logon, and another
+ // whenever the account's licenses change (a game bought or added to the library).
+ const std::optional<cm::LicenseList>& licenses() const { return licenses_; }
+ std::uint64_t license_serial() const { return license_serial_; }
+
// An idle turn until the deadline: answers the server and sends a heartbeat when due. kTimeout
// means the session is still fine.
CmError Idle() { return WaitFor([] { return false; }); }
@@ -426,6 +431,7 @@ class CmClient::Session {
return;
}
licenses_ = std::move(list);
+ ++license_serial_;
break;
}
case cm::kEMsgClientLoggedOff: {
@@ -483,6 +489,7 @@ class CmClient::Session {
bool logon_pending_ = false;
std::optional<cm::LogonResponse> logon_;
std::optional<cm::LicenseList> licenses_;
+ std::uint64_t license_serial_ = 0;
bool logged_off_ = false;
std::int32_t heartbeat_seconds_ = 0;
Clock::time_point next_heartbeat_{};
@@ -514,6 +521,7 @@ class CmSharedSession {
private:
friend class CmClient;
+ friend std::uint64_t CmLicenseChanges(const CmSharedSession& shared);
// Keeps an idle session alive: answers the server and sends heartbeats on its interval. A call
// waiting for the session never waits more than one short turn.
void Pump() {
@@ -527,13 +535,31 @@ class CmSharedSession {
session_->Rebind(Clock::now() + std::chrono::milliseconds(100), kNoCancel);
const auto idle = session_->Idle();
if (idle != CmError::kTimeout && idle != CmError::kNone) Drop();
+ else NoteLicenses();
}
}
stop_lock.lock();
stop_wake_.wait_for(stop_lock, std::chrono::milliseconds(100), [this] { return stop_; });
}
}
+ // Compares the license list the session last received with the account's previous one. Steam
+ // pushes a new list when a license is added or removed; the first list after a logon only
+ // repeats what the library fetch already reads, unless it changed while the session was closed.
+ // Called with mutex_ held, whenever a call or the pump has let the session read frames.
+ void NoteLicenses() {
+ if (!session_ || session_->license_serial() == noted_serial_ || !session_->licenses()) return;
+ noted_serial_ = session_->license_serial();
+ std::set<std::uint32_t> packages;
+ for (const auto& license : session_->licenses()->licenses) packages.insert(license.package_id);
+ const auto account = session_->steam_id();
+ if (account == licensed_account_ && packages != licensed_packages_)
+ license_changes_.fetch_add(1, std::memory_order_acq_rel);
+ licensed_account_ = account;
+ licensed_packages_ = std::move(packages);
+ }
void Drop() {
+ NoteLicenses();
+ noted_serial_ = 0;
if (transport_) CmClient::EndSession(session_.get(), transport_.get(), [](const std::string& line) {
std::lock_guard<std::mutex> lock(g_log_mutex);
if (g_log) g_log("owner=shared " + line);
@@ -547,6 +573,10 @@ class CmSharedSession {
std::unique_ptr<MessageTransport> transport_;
std::unique_ptr<CmClient::Session> session_;
std::string key_;
+ std::uint64_t noted_serial_ = 0;
+ std::uint64_t licensed_account_ = 0;
+ std::set<std::uint32_t> licensed_packages_;
+ std::atomic<std::uint64_t> license_changes_{0};
std::mutex stop_mutex_;
std::condition_variable stop_wake_;
bool stop_ = false;
@@ -555,6 +585,10 @@ class CmSharedSession {
std::shared_ptr<CmSharedSession> MakeCmSharedSession() { return std::make_shared<CmSharedSession>(); }
+std::uint64_t CmLicenseChanges(const CmSharedSession& shared) {
+ return shared.license_changes_.load(std::memory_order_acquire);
+}
+
void CmClient::EndSession(Session* session, MessageTransport* transport,
const std::function<void(const std::string&)>& log) {
// No ClientLogOff: as the Steam client, the connection just closes so the saved sign-in stays valid.
@@ -627,6 +661,7 @@ void CmClient::Release(Lease* lease, CmError result) {
// The shared session stays for the next call unless this one left it in an unknown state.
const bool clean = result == CmError::kNone || result == CmError::kRejected;
if (!clean || !lease->session || !lease->session->usable()) shared_->Drop();
+ else shared_->NoteLicenses();
lease->session = nullptr;
lease->hold.unlock();
return;
diff --git a/src/steam/backend/cm_client.h b/src/steam/backend/cm_client.h
index c5e6067..6a8c5fe 100644
--- a/src/steam/backend/cm_client.h
+++ b/src/steam/backend/cm_client.h
@@ -121,6 +121,10 @@ struct CmClientHooks {
// credentials change or Steam drops it. Destroying the session logs off.
class CmSharedSession;
std::shared_ptr<CmSharedSession> MakeCmSharedSession();
+// How many times Steam pushed a license list on the shared session whose packages differ from the
+// account's previous one: a game bought, added to the library or removed while Playden runs. It
+// starts at 0, and a new account's first list never counts. Safe from any thread.
+std::uint64_t CmLicenseChanges(const CmSharedSession& shared);
// Without a shared session, a CM session per call: directory, connect (first four endpoints), hello,
// logon with the stored refresh token, the pushed license list, then package PICS in batches of 50.
diff --git a/tests/cm_client_test.cpp b/tests/cm_client_test.cpp
index 2a40d7b..38ee71e 100644
--- a/tests/cm_client_test.cpp
+++ b/tests/cm_client_test.cpp
@@ -520,6 +520,64 @@ void SharedSessionLogsOnAgainForNewCredentials() {
assert(CountSent(script, cm::kEMsgClientLogon) == 2 && CountSent(script, cm::kEMsgClientLogOff) == 0);
}
+std::vector<std::uint8_t> LicenseListFrame(const std::vector<std::uint32_t>& packages) {
+ proto::Writer licenses;
+ for (const auto package : packages) {
+ proto::Writer license;
+ license.AddVarint(1, package);
+ license.AddFixed32(2, 1500000000);
+ licenses.AddMessage(2, license);
+ }
+ return ServerFrame(cm::kEMsgClientLicenseList, licenses.bytes());
+}
+
+bool WaitForLicenseChanges(const CmSharedSession& shared, std::uint64_t wanted) {
+ const auto deadline = std::chrono::steady_clock::now() + 2s;
+ while (CmLicenseChanges(shared) != wanted && std::chrono::steady_clock::now() < deadline)
+ std::this_thread::sleep_for(5ms);
+ return CmLicenseChanges(shared) == wanted;
+}
+
+// Steam pushes the license list again when a license is added (a free game added to the library on
+// another device). Only a different set of packages counts, also across a new logon.
+void SharedSessionCountsLicenseChanges() {
+ auto script = std::make_shared<Script>();
+ script->on_logon = {ServerFrame(cm::kEMsgClientLogOnResponse, LogonResponseBody(1, 9)), LicenseListFrame({100, 200})};
+ script->on_service = {ServerFrame(cm::kEMsgServiceMethodResponse, {}, std::nullopt, 1)};
+ auto shared = MakeCmSharedSession();
+ auto client = MakeClient(script);
+ client.SetSharedSession(shared);
+ std::atomic<bool> cancel{false};
+ assert(Ping(client, cancel) == CmError::kNone);
+ // The first list after the first logon is what the library already reads.
+ assert(CmLicenseChanges(*shared) == 0);
+ {
+ std::lock_guard<std::mutex> lock(script->mutex);
+ script->Queue(LicenseListFrame({200, 100}));
+ }
+ std::this_thread::sleep_for(400ms);
+ assert(CmLicenseChanges(*shared) == 0);
+ // Pushed while the session is idle: the pump reads it.
+ {
+ std::lock_guard<std::mutex> lock(script->mutex);
+ script->Queue(LicenseListFrame({100, 200, 300}));
+ }
+ assert(WaitForLicenseChanges(*shared, 1));
+ // A rotated token logs on again; the list it gets differs from the last one seen.
+ {
+ std::lock_guard<std::mutex> lock(script->mutex);
+ script->on_logon = {ServerFrame(cm::kEMsgClientLogOnResponse, LogonResponseBody(1, 9)), LicenseListFrame({100, 300})};
+ }
+ auto rotated = Session();
+ rotated.refresh_token = "synthetic.rotated.token";
+ assert(client.WithServiceSession(rotated, 3000, cancel, [](const CmClient::ServiceCall& call, std::uint64_t) {
+ std::vector<std::uint8_t> reply;
+ return call("Cloud.Ping#1", {}, &reply, nullptr);
+ }) == CmError::kNone);
+ assert(WaitForLicenseChanges(*shared, 2));
+ assert(CountSent(script, cm::kEMsgClientLogon) == 2);
+}
+
// A call waiting while another holds the shared session (a long library license scan, issue #47)
// can be canceled, and its deadline starts only once it has the session.
void WaitingForTheSharedSessionIsCancelableAndUntimed() {
@@ -790,6 +848,7 @@ int main(int argc, char** argv) {
SharedSessionServesEveryClientWithOneLogon();
ResetCmBackoff();
SharedSessionLogsOnAgainForNewCredentials();
+ SharedSessionCountsLicenseChanges();
ResetCmBackoff();
WaitingForTheSharedSessionIsCancelableAndUntimed();
ResetCmBackoff();
diff --git a/tests/homebrew_account_test.cpp b/tests/homebrew_account_test.cpp
index ced8cc4..6ae172c 100644
--- a/tests/homebrew_account_test.cpp
+++ b/tests/homebrew_account_test.cpp
@@ -90,8 +90,11 @@ class Backend final : public AuthBackend {
class LibraryBackendFixture final : public LibraryBackend {
public:
std::atomic<int> calls{0};
- LibraryResult Fetch(const StoredSession&,const std::atomic<bool>&) override {
- ++calls;return {LibraryError::kNone,{{42,"Connected synthetic game",{},{},{}}},false};
+ std::atomic<bool> block{false};
+ LibraryResult Fetch(const StoredSession&,const std::atomic<bool>& cancel) override {
+ ++calls;
+ while (block && !cancel) std::this_thread::sleep_for(1ms);
+ return {LibraryError::kNone,{{42,"Connected synthetic game",{},{},{}}},false};
}
};
class CacheFixture final : public LibraryRepository {
@@ -449,6 +452,57 @@ void ConnectedLibraryAndOfflineRestart() {
assert(!repo.Load().value() && !cache.value && model.state().games.empty());
}
}
+// Ticks for a while, for checks that something does not happen.
+void TickFor(Controller& controller,std::chrono::milliseconds duration) {
+ const auto until=std::chrono::steady_clock::now()+duration;
+ while (std::chrono::steady_clock::now()<until) { controller.Tick(); std::this_thread::sleep_for(1ms); }
+}
+// Steam pushed a changed license list (a game added to the library elsewhere): the library refreshes
+// once the changes settle, never during another refresh, and only while signed in.
+void LicenseChangesRefreshTheLibrary() {
+ Repository repo;repo.value=Session();CacheFixture cache;
+ {
+ Simulation model({}, {},ModelMode::Live);Backend backend;LibraryBackendFixture library_backend;
+ LibraryService library_service(library_backend,repo,&cache);
+ Controller controller(model,backend,repo,&library_service);
+ std::atomic<std::uint64_t> changes{0};
+ controller.SetLicenseChanges([&changes] { return changes.load(); },150ms);
+ Wait(controller,[&]{return model.state().games.size()==1 && !model.state().library_loading;});
+ assert(library_backend.calls==1);
+ TickFor(controller,300ms);
+ assert(library_backend.calls==1);
+ // A burst of lists makes one refresh, after the wait.
+ changes=1;controller.Tick();changes=2;controller.Tick();
+ TickFor(controller,100ms);
+ assert(library_backend.calls==1);
+ Wait(controller,[&]{return library_backend.calls==2 && !model.state().library_loading;});
+ TickFor(controller,300ms);
+ assert(library_backend.calls==2);
+ // A change while a refresh runs waits for it to finish.
+ library_backend.block=true;changes=3;
+ Wait(controller,[&]{return library_backend.calls==3;});
+ changes=4;
+ TickFor(controller,400ms);
+ assert(library_backend.calls==3 && model.state().library_loading);
+ library_backend.block=false;
+ Wait(controller,[&]{return library_backend.calls==4 && !model.state().library_loading;});
+ TickFor(controller,300ms);
+ assert(library_backend.calls==4 && model.state().games.size()==1);
+ }
+ {
+ // Offline: the saved library stays as it is.
+ Simulation model({}, {},ModelMode::Live);Backend backend;backend.error=AuthError::kNetwork;
+ LibraryBackendFixture library_backend;LibraryService library_service(library_backend,repo,&cache);
+ Controller controller(model,backend,repo,&library_service);
+ std::atomic<std::uint64_t> changes{0};
+ controller.SetLicenseChanges([&changes] { return changes.load(); },50ms);
+ Wait(controller,[&]{return model.state().account.authentication==AuthState::Offline && model.state().games.size()==1 &&
+ !model.state().library_loading;});
+ changes=1;
+ TickFor(controller,300ms);
+ assert(library_backend.calls==0 && model.state().account.authentication==AuthState::Offline);
+ }
+}
void RepeatedClearPreservesFirstIntent() {
for(bool switching:{false,true}) {
Repository repo;repo.value=Session();CacheFixture cache;
@@ -501,4 +555,4 @@ void SlowLicenseCheckShowsAfterAFewSeconds() {
}
std::filesystem::remove_all(root);
}
-int main() { PasswordSignInWithGuardCode(); PasswordFailuresAndCancel(); SlowLicenseCheckShowsAfterAFewSeconds(); CanceledStorageRetryKeepsSavedSessionIntent(); RevokedSessionCleanupRetriesAfterStorageRecovery(); StorageFailureKeepsVisibleAccount(); StorageFailureRetriesSavedSession(); ChallengeAndCancel(); AuthenticationRestoreAndSignOut(); FailedClearDoesNotSwitch(); SignInAgainKeepsTheAccount(); ExitHonorsClearWithoutStartingNewQr(); StorageFailureAndRevocation(); ConnectedLibraryAndOfflineRestart(); ShutdownClearsLibraryBeforeSession(); RepeatedClearPreservesFirstIntent(); }
+int main() { PasswordSignInWithGuardCode(); PasswordFailuresAndCancel(); SlowLicenseCheckShowsAfterAFewSeconds(); CanceledStorageRetryKeepsSavedSessionIntent(); RevokedSessionCleanupRetriesAfterStorageRecovery(); StorageFailureKeepsVisibleAccount(); StorageFailureRetriesSavedSession(); ChallengeAndCancel(); AuthenticationRestoreAndSignOut(); FailedClearDoesNotSwitch(); SignInAgainKeepsTheAccount(); ExitHonorsClearWithoutStartingNewQr(); StorageFailureAndRevocation(); ConnectedLibraryAndOfflineRestart(); LicenseChangesRefreshTheLibrary(); ShutdownClearsLibraryBeforeSession(); RepeatedClearPreservesFirstIntent(); }