Skip to content

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

C++

Add the Files tab to the web page

Leonardo Lobatoc3d3ec612b30
diff --git a/cmake/Web.cmake b/cmake/Web.cmake
index a8df5c7..337f18f 100644
--- a/cmake/Web.cmake
+++ b/cmake/Web.cmake
@@ -91,6 +91,10 @@ if(BUILD_TESTING AND NOT PLAYDEN_PLATFORM_PS5)
add_executable(web_files_api_test "${CMAKE_SOURCE_DIR}/tests/web_files_api_test.cpp")
target_link_libraries(web_files_api_test PRIVATE playden_web)
add_test(NAME web_files_api COMMAND web_files_api_test)
+ # A real server over a made-up game for a browser or a script; prints each pairing code.
+ add_executable(web_files_fixture_server "${CMAKE_SOURCE_DIR}/tests/web_files_fixture_server.cpp")
+ target_link_libraries(web_files_fixture_server PRIVATE playden_web)
+ add_test(NAME web_files_smoke COMMAND python3 -I "${CMAKE_SOURCE_DIR}/tests/test_web_files_smoke.py" $<TARGET_FILE:web_files_fixture_server>)
# The console's path handling (no descriptor-relative opens), run on the host.
add_executable(web_file_store_native_policy_test
"${CMAKE_SOURCE_DIR}/tests/web_file_store_test.cpp"
diff --git a/src/homebrew/controller.cpp b/src/homebrew/controller.cpp
index 208bc38..71786bb 100644
--- a/src/homebrew/controller.cpp
+++ b/src/homebrew/controller.cpp
@@ -1940,13 +1940,89 @@ void Controller::TickWebAccess() {
live.url = snapshot.url;
live.port = snapshot.port;
live.error = snapshot.error;
+ live.pairing_code = snapshot.pairing_code;
model_.ApplyLiveWebAccess(live);
+ TickWebFiles();
// The page's Quit Playden; it waits for a game being prepared.
if (web_->TakeQuitRequest()) {
if (shutdown_log_) shutdown_log_("quit requested from web access");
model_.RequestQuit();
}
}
+void Controller::TickWebFiles() {
+ const auto now = std::chrono::steady_clock::now();
+ if (now < web_files_next_) return;
+ web_files_next_ = now + std::chrono::seconds(1);
+ const auto& state = model_.state();
+ const auto runtime = runtime_ ? runtime_->Shared() : nullptr;
+ web::FileCatalog catalog;
+ catalog.known = true;
+ std::map<GameId, web::FileGame> games;
+ const auto entry = [&](const GameId& id) -> web::FileGame& {
+ auto& game = games[id];
+ if (!game.id.empty()) return game;
+ game.id = ToInstallId(id);
+ game.kind = id.store == Store::kLocal ? "imported" : "steam";
+ game.app = id.steam_app().value_or(0);
+ const auto cloud = state.cloud.find(id);
+ game.cloud = CloudCapable(id) && (cloud == state.cloud.end() || cloud->second.status != CloudStatus::Unsupported);
+ for (const auto& known : state.games)
+ if (known.id == id) {
+ game.name = known.title;
+ game.last_played = known.last_played;
+ break;
+ }
+ return game;
+ };
+ for (const auto& location : locations_) {
+ auto& game = entry(location.game);
+ game.game_folder = location.root;
+ game.game_folder_shown = location.root;
+ game.drive_absent = !location.available;
+ game.drive = location.root.rfind("/mnt/usb", 0) == 0 ? "usb" : location.root.rfind("/mnt/ext", 0) == 0 ? "m2" : "console";
+ }
+ std::map<std::uint32_t, std::string> names;
+ if (runtime) {
+ catalog.setting_up = runtime->preparing_app.has_value();
+ for (const auto& install : runtime->installs) {
+ if (!install.prefix_root.empty()) entry(install.game).bottle = runtime_->HostFilePath(install.prefix_root);
+ }
+ for (const auto& kept : runtime->kept_bottles) {
+ if (games.count(kept.game) && !games[kept.game].bottle.empty()) continue;
+ auto& game = entry(kept.game);
+ game.bottle = runtime_->HostFilePath(kept.data_root + "/library/prefixes/game");
+ if (game.name.empty()) game.name = kept.name;
+ game.installed = !game.game_folder.empty();
+ }
+ const auto game_of = [&](std::uint32_t number) -> web::FileGame* {
+ for (const auto& install : runtime->installs)
+ if (install.runtime_number == number) return &entry(install.game);
+ for (const auto& kept : runtime->kept_bottles)
+ if (kept.runtime_number == number) return &entry(kept.game);
+ return nullptr;
+ };
+ for (const auto& [number, bytes] : runtime->save_bytes)
+ if (auto* game = game_of(number)) game->windows_user_bytes = bytes;
+ for (const auto& [number, version] : runtime->physx_needed)
+ if (auto* game = game_of(number)) game->physx_needed = version;
+ for (const auto& [number, activity] : runtime->activity)
+ if (auto* game = game_of(number)) game->running = activity.first == runtime::NativeActivity::kActive;
+ if (runtime->preparing_app)
+ if (auto* game = game_of(*runtime->preparing_app)) game->setting_up = true;
+ // Asking takes the console a moment, so only while the page is in use, and one game a second.
+ if (web_->FilesInUse() && !runtime->installs.empty()) {
+ web_activity_next_ %= runtime->installs.size();
+ runtime_->CheckActivity(runtime->installs[web_activity_next_++].runtime_number);
+ }
+ }
+ catalog.games.reserve(games.size());
+ for (auto& [id, game] : games) {
+ if (game.name.empty()) game.name = game.id;
+ catalog.games.push_back(std::move(game));
+ }
+ web_->SetFileCatalog(std::move(catalog));
+}
+
void Controller::TickDownloadServers() {
const auto requests = model_.TakeDownloadServerRequests();
if (!download_servers_) return;
diff --git a/src/homebrew/controller.hpp b/src/homebrew/controller.hpp
index 33307bd..b471ad8 100644
--- a/src/homebrew/controller.hpp
+++ b/src/homebrew/controller.hpp
@@ -120,6 +120,10 @@ class Controller {
steam::DownloadServerService* download_servers_ = nullptr;
web::Service* web_ = nullptr;
void TickWebAccess();
+ // Reports what the page's Files tab offers, about once a second, and keeps the running games current while it is in use.
+ void TickWebFiles();
+ std::chrono::steady_clock::time_point web_files_next_{};
+ std::size_t web_activity_next_ = 0; // the next game whose title to ask about
std::string download_servers_account_;
std::optional<LiveDownloadServers> shown_download_servers_;
void TickSelfUpdate();
diff --git a/src/homebrew/host.cpp b/src/homebrew/host.cpp
index cef7a14..a718acb 100644
--- a/src/homebrew/host.cpp
+++ b/src/homebrew/host.cpp
@@ -7,6 +7,7 @@
#include "homebrew/program_icon.hpp"
#include "homebrew/simulation.hpp"
#include "homebrew/controller.hpp"
+#include "runtime/private_directories.h"
#include "steam/install_volumes.h"
#include "installs/game_move.h"
#include "stores/local/copy_runner.h"
@@ -747,6 +748,12 @@ int main(int argc, char** argv) {
web_config.server.log = [log_directory](const std::string& line) {
playden::app::AppendLogLine(log_directory, "web.log", line);
};
+ web_config.files.free_space = [](const std::string& path) -> std::optional<std::uint64_t> {
+ const auto space = playden::steam::QueryVolumeSpace(path);
+ return space ? std::optional<std::uint64_t>(space->free_bytes) : std::nullopt;
+ };
+ for (const auto& private_path : playden::runtime::PrivateProfilePaths())
+ web_config.files.private_profile_paths.push_back(private_path.generic_string());
web = std::make_unique<playden::web::Service>(std::move(web_config));
services->SetWebAccess(web.get());
}
diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cpp
index 399feae..541cddb 100644
--- a/src/homebrew/ps5.cpp
+++ b/src/homebrew/ps5.cpp
@@ -6,6 +6,7 @@
#include "homebrew/simulation.hpp"
#include "homebrew/store_art.hpp"
#include "homebrew/controller.hpp"
+#include "runtime/private_directories.h"
#include "steam/install_volumes.h"
#include "installs/game_move.h"
#include "stores/local/copy_runner.h"
@@ -896,6 +897,14 @@ int main() {
"/data/homebrew/" PLAYDEN_PS5_TITLE_ID};
web_config.server.log = [](const std::string& line) { playden::app::AppendLogLine(log_root, "web.log", line); };
web_config.address_fallback = [] { return playden::ps5::ConsoleAddress(); };
+ // Files: path work waits for the runtime's batches, and never runs while root is raised (effective_uid.cpp).
+ web_config.files.try_hold = [] { return playden::ps5::TryHoldEffectiveUid(); };
+ web_config.files.free_space = [](const std::string& path) -> std::optional<std::uint64_t> {
+ const auto space = playden::steam::QueryVolumeSpace(path, playden::steam::kConsoleSystemReserve);
+ return space ? std::optional<std::uint64_t>(space->free_bytes) : std::nullopt;
+ };
+ for (const auto& private_path : playden::runtime::PrivateProfilePaths())
+ web_config.files.private_profile_paths.push_back(private_path.generic_string());
playden::web::Service web(std::move(web_config));
playden::homebrew::Controller services(simulation, stores, &persistence, &installs, &cloud, runtime_host.get(), auth_log);
services.SetDownloadServers(&servers);
diff --git a/src/homebrew/runtime_host.hpp b/src/homebrew/runtime_host.hpp
index 8a58434..c322f0f 100644
--- a/src/homebrew/runtime_host.hpp
+++ b/src/homebrew/runtime_host.hpp
@@ -453,6 +453,8 @@ class RuntimeHost {
// The same state without a copy per call: shared and read-only, made again only after a change.
// The UI reads it many times a frame; Snapshot() copies every field each time.
std::shared_ptr<const RuntimeSnapshot> Shared() const;
+ // A console path, as this process opens it (differs only in a host test's namespace).
+ std::string HostFilePath(const std::string& console_path) const { return HostPath(console_path).string(); }
// Queues preparation of a downloaded game, or a retry of a failed one. Games are prepared one
// at a time, in the order asked; asking again for a queued game keeps its place.
void Prepare(RuntimePrepareRequest request);
diff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cpp
index 63cd263..16d88d3 100644
--- a/src/homebrew/simulation.cpp
+++ b/src/homebrew/simulation.cpp
@@ -3898,6 +3898,7 @@ void Simulation::RequestQuit() {
void Simulation::ApplyLiveWebAccess(const LiveWebAccess& snapshot) {
if (web_access_ == snapshot) return;
web_access_ = snapshot;
+ state_.web_pairing_code = snapshot.pairing_code;
rebuild_view();
}
@@ -7491,23 +7492,23 @@ void Simulation::rebuild_view() {
LiveWebAccess shown = web_access_;
if (!live()) shown = state_.web_access ? LiveWebAccess{"on", "http://192.168.1.50:7031/", 7031, {}} : LiveWebAccess{};
if (!state_.web_access) {
- toggle.subtitle = "Off: Playden's logs can't be opened from a browser.";
+ toggle.subtitle = "Off: Playden's logs and game files can't be opened from a browser.";
} else if (shown.state == "on" && !shown.url.empty()) {
- toggle.subtitle = "Playden's logs on the local network while Playden is open.";
+ toggle.subtitle = "Playden's logs and game files on the local network while Playden is open.";
auto& address = add("settings-web-address", RowKind::Status, "Open on a phone or computer on the same network", "");
address.value = shown.url.substr(0, shown.url.size() - 1); // without the trailing "/"
- address.subtitle = "Shows Playden's logs, with your Steam name removed. Nothing can be changed from there yet.";
+ address.subtitle = "Shows Playden's logs, with your Steam name removed. Pair the browser to reach game files.";
address.qr = shown.url;
address.enabled = false; // nothing to do on it: focus stays on the switch
} else if (shown.state == "on") {
- toggle.subtitle = "Playden's logs on the local network while Playden is open.";
+ toggle.subtitle = "Playden's logs and game files on the local network while Playden is open.";
auto& address = add("settings-web-address", RowKind::Status, "Address unknown", "");
address.value = "port " + std::to_string(shown.port);
address.subtitle = "Open the console's IP address shown in the PS5's network settings, port " +
std::to_string(shown.port) + ", on a phone or computer on the same network.";
address.enabled = false; // nothing to do on it: focus stays on the switch
} else if (shown.state == "failed") {
- toggle.subtitle = "Playden's logs on the local network while Playden is open.";
+ toggle.subtitle = "Playden's logs and game files on the local network while Playden is open.";
auto& problem = add("settings-web-problem", RowKind::Status, "Web access is not open", "");
problem.subtitle = "Web access could not start: " + shown.error + ". Turn it off and on to try again.";
problem.enabled = false; // nothing to do on it: focus stays on the switch
diff --git a/src/homebrew/simulation.hpp b/src/homebrew/simulation.hpp
index bfc76c3..5b99adf 100644
--- a/src/homebrew/simulation.hpp
+++ b/src/homebrew/simulation.hpp
@@ -69,6 +69,7 @@ struct LiveWebAccess {
std::string url; // on: http://<address>:<port>/, empty when the address is unknown
std::uint16_t port = 0;
std::string error; // failed: why
+ std::string pairing_code; // a browser asked to pair: the code to show now; empty when none
bool operator==(const LiveWebAccess&) const = default;
};
enum class JobState { Queued, Downloading, Pausing, Paused, Verifying, Downloaded, Failed, Cancelled, Interrupted };
@@ -861,7 +862,8 @@ struct State {
std::string download_server;
bool hide_run_once_help = false; // "Don't show again" on Run launcher or setup's dialog
bool hide_launcher_help = false; // ...and on the one for turning on Start through a launcher
- bool web_access = true; // Settings › Web access: the logs page on the local network (on by default)
+ bool web_access = true; // Settings › Web access: the logs and game files page on the local network (on by default)
+ std::string web_pairing_code; // live: a browser asked to pair; shown in a corner over every screen
bool controller_connected = true;
ControllerState controller;
bool persistence_available = true;
diff --git a/src/homebrew/view.cpp b/src/homebrew/view.cpp
index 8d56969..762ac0b 100644
--- a/src/homebrew/view.cpp
+++ b/src/homebrew/view.cpp
@@ -537,6 +537,7 @@ class Render::Impl
draw_persistent_status(scene, state);
draw_footer(scene, view);
draw_overlays(state, view);
+ draw_web_pairing(state);
focus_motion_.end_frame();
if (live_artwork_) {
live_artwork_->EndFrame();
@@ -3576,6 +3577,23 @@ class Render::Impl
}
}
+ // A browser asked to pair. In a corner, over everything and taking no input: a device on the network can make
+ // this appear, so it must not get in the way of what the player is doing.
+ void draw_web_pairing(const State &state)
+ {
+ if (state.web_pairing_code.empty())
+ return;
+ const gfx::Rect panel{1288.0F, 118.0F, 536.0F, 150.0F};
+ overlay_.shadow(panel, 10.0F, 28.0F, gfx::Color::rgb(0x000000, 0.6F));
+ overlay_.rounded_rect(panel, 10.0F, kPanel);
+ ui::text(overlay_, fonts_.semibold, "Pair a browser with Playden", panel.x + 28.0F, panel.y + 42.0F, 24.0F, kText);
+ std::string code = state.web_pairing_code;
+ if (code.size() == 6)
+ code.insert(3, " ");
+ ui::text(overlay_, fonts_.semibold, code, panel.x + 28.0F, panel.y + 96.0F, 48.0F, kAccent);
+ ui::text(overlay_, fonts_.regular, "Type this code in the browser", panel.x + 28.0F, panel.y + 130.0F, 18.0F, kSecondary);
+ }
+
void draw_overlays(const State &state, const ViewData &view)
{
ui::Canvas overlay{overlay_, fonts_, renderer_.glass_texture(), clock_};
diff --git a/src/web/files_api.cpp b/src/web/files_api.cpp
index 34ddf7d..7df49cc 100644
--- a/src/web/files_api.cpp
+++ b/src/web/files_api.cpp
@@ -13,6 +13,10 @@ namespace {
const std::vector<std::pair<std::string, std::string>> kNoStore = {{"Cache-Control", "no-store"}};
constexpr const char* kCookie = "playden_files";
+std::int64_t SteadySeconds() {
+ return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
+}
+
std::string Quoted(std::string_view text) {
std::string out = "\"";
for (const char raw : text) {
@@ -43,6 +47,14 @@ void Fail(Response& response, const FileError& error) {
response.Send(error.status, "text/plain; charset=utf-8", error.message + "\n", headers);
}
+// A game's setup holds the path lock for minutes, so a file action answers now, not after the short wait for the lock.
+void SendSettingUp(Response& response) {
+ auto headers = kNoStore;
+ headers.emplace_back("Retry-After", "5");
+ headers.emplace_back("X-Playden-Busy", "setup");
+ response.Send(503, "text/plain; charset=utf-8", "Playden is setting up a game. Files are available when it finishes.\n", headers);
+}
+
// A cookie's value from the Cookie header.
std::string CookieValue(const Request& request, std::string_view name) {
const auto header = HeaderValue(request, "cookie");
@@ -133,9 +145,16 @@ std::string FilesApi::PairingCode() const { return pairing_.ActiveCode(); }
void FilesApi::CancelPairing() { pairing_.Cancel(); }
+bool FilesApi::InUse() const {
+ const auto used = last_used_.load();
+ return used != 0 && SteadySeconds() - used < 30;
+}
+
bool FilesApi::Paired(const Request& request) {
const auto token = CookieValue(request, kCookie);
- return !token.empty() && pairing_.Paired(token);
+ if (token.empty() || !pairing_.Paired(token)) return false;
+ last_used_.store(SteadySeconds());
+ return true;
}
bool FilesApi::RequirePaired(const Request& request, Response& response) {
@@ -158,6 +177,11 @@ std::optional<FileGame> FilesApi::Game(const std::string& id) const {
return std::nullopt;
}
+bool FilesApi::SettingUp() const {
+ std::lock_guard<std::mutex> lock(mutex_);
+ return catalog_.setting_up;
+}
+
std::vector<std::pair<std::string, FileRoot>> FilesApi::Roots(const FileGame& game) const {
std::vector<std::pair<std::string, FileRoot>> roots;
if (!game.bottle.empty()) {
@@ -192,6 +216,10 @@ bool FilesApi::Find(const Request& request, Response& response, FileGame* game,
SendError(response, 404, "No such game.");
return false;
}
+ if (SettingUp()) {
+ SendSettingUp(response);
+ return false;
+ }
*game = *found;
for (auto& [root_id, value] : Roots(*found))
if (named == root_id) {
@@ -257,14 +285,20 @@ void FilesApi::Register(Router& router) {
body += ",\"game_folder\":" + Quoted(game->game_folder_shown) + ",\"roots\":[";
bool first = true;
std::vector<RedistFolderInfo> redist;
+ const bool setting_up = SettingUp();
bool redist_busy = false;
+ // Once the lock is busy, the other roots would each wait for it too.
+ bool busy = setting_up;
for (const auto& [root_id, root] : Roots(*game)) {
FileListing listing;
// Only whether it exists: a busy lock leaves it unknown, and the page can still open it.
- const auto error = store_.List(root, std::string(), &listing);
+ const auto error = busy ? FileError{503, std::string()} : store_.List(root, std::string(), &listing);
+ if (error.status == 503) busy = true;
body += std::string(first ? "" : ",") + "{" + Field("id", root_id) + "," + Field("exists", error.ok() ? listing.exists : true) + "}";
first = false;
- if (root_id == "game" && store_.RedistFolders(root, &redist).status == 503) redist_busy = true;
+ // Asked for by the game's own page only: a look through a game folder is too slow for every folder opened.
+ if (root_id == "game" && QueryValue(request.query, "redist") == std::string("1") && (busy || store_.RedistFolders(root, &redist).status == 503))
+ redist_busy = true;
}
body += "],\"redist\":[";
for (std::size_t i = 0; i < redist.size(); ++i) {
@@ -274,7 +308,7 @@ void FilesApi::Register(Router& router) {
for (std::size_t j = 0; j < folder.sample.size(); ++j) body += (j ? "," : "") + Quoted(folder.sample[j]);
body += "]}";
}
- SendJson(response, 200, body + "]," + Field("redist_busy", redist_busy) + "}");
+ SendJson(response, 200, body + "]," + Field("redist_busy", redist_busy) + "," + Field("all_setting_up", setting_up) + "}");
});
router.Exact("/api/files/list", [this](const Request& request, const std::string&, Response& response) {
if (!RequirePaired(request, response)) return;
diff --git a/src/web/files_api.h b/src/web/files_api.h
index 9f07e73..e93f712 100644
--- a/src/web/files_api.h
+++ b/src/web/files_api.h
@@ -63,6 +63,8 @@ class FilesApi {
void SetCatalog(FileCatalog catalog);
std::string PairingCode() const;
void CancelPairing();
+ // A paired browser asked for something in the last half a minute.
+ bool InUse() const;
private:
class Transfer;
@@ -72,6 +74,7 @@ class FilesApi {
// The game and root a request names. False: answered.
bool Find(const Request& request, Response& response, FileGame* game, FileRoot* root);
std::optional<FileGame> Game(const std::string& id) const;
+ bool SettingUp() const;
std::vector<std::pair<std::string, FileRoot>> Roots(const FileGame& game) const;
FilesConfig config_;
@@ -80,6 +83,7 @@ class FilesApi {
mutable std::mutex mutex_;
FileCatalog catalog_;
std::atomic<int> transfers_{0};
+ std::atomic<std::int64_t> last_used_{0}; // steady seconds; 0: never
};
} // namespace playden::web
diff --git a/src/web/page/index.html b/src/web/page/index.html
index d72e215..bf6f011 100644
--- a/src/web/page/index.html
+++ b/src/web/page/index.html
@@ -38,6 +38,11 @@ nav span { color: var(--soft); white-space: nowrap; }
nav span.on { color: var(--ink); box-shadow: inset 0 -2px 0 var(--accent); padding-bottom: 2px; }
nav span.later { opacity: .55; }
nav span.later em { font-style: normal; font-size: 11px; letter-spacing: .06em; text-transform: uppercase; margin-left: 4px; }
+nav a { color: var(--soft); text-decoration: none; white-space: nowrap; }
+nav a:hover { color: var(--ink); }
+nav a.on { color: var(--ink); box-shadow: inset 0 -2px 0 var(--accent); padding-bottom: 2px; }
+.top-end { display: flex; align-items: center; gap: 8px 20px; flex-wrap: wrap; }
+header { position: relative; }
.facts { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1px; background: var(--line);
border: 1px solid var(--line); border-radius: 6px; overflow: hidden; margin: 0 0 24px; }
@@ -78,7 +83,93 @@ td.radio { width: 1%; }
input[type=radio] { accent-color: var(--accent); margin: 0; }
td.empty { color: var(--soft); }
+/* Files */
+.crumbs { display: flex; flex-wrap: wrap; gap: 2px 6px; align-items: baseline; font-size: 14px; color: var(--soft); margin: 0 0 16px; overflow-wrap: anywhere; }
+.crumbs a { text-decoration: none; }
+.crumbs a:hover { text-decoration: underline; }
+.crumbs b { color: var(--ink); font-weight: 600; }
+.title-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin: 0 0 4px; }
+.title-row h2 { margin: 0; font-size: 26px; line-height: 1.2; font-weight: 600; overflow-wrap: anywhere; }
+.lede { color: var(--soft); margin: 0 0 20px; max-width: 76ch; }
+.mono { font: 400 13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--soft); overflow-wrap: anywhere; }
+.bar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin: 0 0 12px; }
+.bar .end { margin-left: auto; }
+.primary { font: 600 14px/1.5 "Barlow", sans-serif; background: var(--accent); color: var(--on-accent); border: 0; border-radius: 4px; padding: 5px 12px;
+ cursor: pointer; white-space: nowrap; text-decoration: none; display: inline-block; }
+.primary:hover { background: #f59a57; }
+.primary:disabled, .ghost:disabled { cursor: not-allowed; opacity: .45; }
+.ghost.danger { color: #f2a48f; }
+.badge { display: inline-block; font-size: 12px; font-weight: 600; padding: 1px 8px; border-radius: 99px; border: 1px solid var(--line); color: var(--soft);
+ white-space: nowrap; vertical-align: middle; margin-left: 6px; }
+.badge.running { border-color: var(--warn); color: var(--warn); }
+.badge.ok { border-color: var(--ok); color: var(--ok); }
+.search { font: 400 14px/1.5 "Barlow", sans-serif; color: var(--ink); background: var(--row); border: 1px solid var(--line); border-radius: 4px; padding: 5px 10px; min-width: 260px; max-width: 100%; }
+td.entry-name { font-weight: 600; overflow-wrap: anywhere; }
+td.entry-name a { color: var(--ink); text-decoration: none; }
+td.entry-name a:hover { color: var(--accent); }
+td.entry-name span { display: block; color: var(--soft); font-size: 13px; font-weight: 400; }
+td.entry-name span.badge { display: inline-block; font-size: 12px; font-weight: 600; }
+td.entry-name .folder::before { content: ""; display: inline-block; width: 9px; height: 7px; margin-right: 8px; border: 1.5px solid var(--accent); border-radius: 1px; }
+td.acts { text-align: right; white-space: nowrap; }
+td.acts > * { margin-left: 6px; }
+td.status { color: var(--accent); font-weight: 600; font-size: 14px; white-space: nowrap; }
+.drop-hint { border: 1px dashed #4a4338; border-radius: 6px; padding: 32px 16px; text-align: center; color: var(--soft); margin-top: 8px; }
+.drop-hint strong { display: block; color: var(--ink); font-weight: 600; margin-bottom: 4px; }
+main.dragging { outline: 2px dashed var(--accent); outline-offset: 8px; }
+.scrim { position: fixed; inset: 0; z-index: 5; background: rgba(6, 5, 4, .72); display: flex; align-items: center; justify-content: center; padding: 16px; }
+.dialog { width: 100%; max-width: 520px; max-height: 100%; overflow: auto; background: var(--row-open); border: 1px solid #38332b; border-radius: 8px; padding: 22px 24px; }
+.dialog h3 { margin: 0 0 6px; font-size: 20px; font-weight: 600; }
+.dialog p { margin: 0 0 12px; color: var(--soft); font-size: 15px; }
+.dialog ul { border: 1px solid var(--line); border-radius: 6px; margin: 0 0 14px; padding: 4px 12px; list-style: none; font-size: 14px; max-height: 200px; overflow: auto; overflow-wrap: anywhere; }
+.dialog li { padding: 6px 0; }
+.dialog li + li { border-top: 1px solid var(--line); }
+.dialog .foot { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 10px; margin-top: 16px; }
+.choice { display: flex; gap: 10px; align-items: flex-start; font-size: 15px; padding: 6px 0; }
+.choice small { display: block; color: var(--soft); font-size: 13px; }
+.pair { max-width: 520px; margin: 40px auto 0; }
+.pair h2 { margin: 0 0 8px; font-size: 26px; line-height: 1.2; font-weight: 600; }
+.pair p { color: var(--soft); margin: 0 0 12px; }
+.pair input { font: 600 30px/1.2 "Barlow", sans-serif; letter-spacing: .25em; color: var(--ink); background: var(--row); border: 1px solid #4a4338; border-radius: 6px; padding: 10px 14px; width: 100%; max-width: 280px; margin-bottom: 12px; }
+.chip { display: inline-flex; align-items: center; gap: 8px; font: 600 13px/1.4 "Barlow", sans-serif; color: var(--ink); background: var(--row-open); border: 1px solid #4a4338;
+ border-radius: 99px; padding: 4px 12px; cursor: pointer; white-space: nowrap; }
+.chip:hover, .chip[aria-expanded="true"] { border-color: var(--accent); }
+.meter { display: block; height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; }
+.meter i { display: block; height: 100%; background: var(--accent); }
+.chip .meter { width: 64px; }
+.panel { position: absolute; right: 0; top: 100%; margin-top: 8px; width: 420px; max-width: 100%; z-index: 4; background: var(--row-open); border: 1px solid #38332b; border-radius: 8px; padding: 14px 16px; }
+.panel .head { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px; font-weight: 600; margin-bottom: 8px; }
+.panel .head span { color: var(--soft); font-weight: 400; font-size: 14px; }
+.panel ul { list-style: none; margin: 10px 0 0; padding: 0; font-size: 14px; max-height: 280px; overflow: auto; }
+.panel li { padding: 7px 0; border-top: 1px solid var(--line); }
+.panel li .line { display: flex; justify-content: space-between; gap: 12px; font-weight: 600; overflow-wrap: anywhere; }
+.panel li .line span { color: var(--soft); font-weight: 400; white-space: nowrap; }
+.panel li .line span.done { color: var(--ok); }
+.panel li .line span.bad { color: #f2a48f; white-space: normal; }
+.panel li small { display: block; color: var(--soft); font-size: 13px; overflow-wrap: anywhere; }
+.panel li .meter { height: 4px; margin-top: 5px; }
+.panel .foot { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-top: 10px; }
+.panel .foot small { color: var(--soft); font-size: 13px; }
+.editor { display: block; margin: 0; padding: 14px 16px; width: 100%; min-height: 360px; background: var(--row); color: var(--ink); border: 1px solid var(--line); border-radius: 6px;
+ font: 400 14px/1.6 ui-monospace, SFMono-Regular, Menlo, monospace; resize: vertical; }
+
@media (max-width: 720px) {
+ .primary, .ghost, .chip { min-height: 44px; padding: 8px 14px; }
+ .search { width: 100%; min-width: 0; min-height: 44px; }
+ .panel { width: 100%; }
+ table.files, table.files tbody { display: block; }
+ table.files thead { display: none; }
+ table.files tbody tr { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: 4px 10px; align-items: center; padding: 10px 2px; border-top: 1px solid var(--line); }
+ table.files tbody tr:last-child { border-bottom: 1px solid var(--line); }
+ table.files td { border: 0; padding: 0; background: none !important; white-space: normal; }
+ table.files td.pick { grid-row: 1; }
+ table.files td.entry-name { grid-row: 1; grid-column: 2; }
+ table.files td.pick + td.entry-name { grid-column: 2; }
+ table.files td.size { grid-row: 1; grid-column: 3; color: var(--soft); font-size: 13px; white-space: nowrap; }
+ table.files td.when { grid-column: 2 / -1; font-size: 13px; }
+ table.files td.status { grid-column: 2 / -1; }
+ table.files td.acts { grid-column: 1 / -1; text-align: left; white-space: normal; display: flex; flex-wrap: wrap; gap: 6px; }
+ table.files td.acts > * { margin-left: 0; }
+ table.files td.acts:empty { display: none; }
.facts .wide { display: none; }
thead, td.title, td.when-wide { display: none; }
table, tbody { display: block; }
@@ -106,7 +197,11 @@ td.empty { color: var(--soft); }
<main>
<header>
<h1>Playden<small id="where">on PS5</small></h1>
- <nav aria-label="Sections"><span class="on">Logs</span><span class="later">Recipes<em>later</em></span><span class="later">Files<em>later</em></span></nav>
+ <div class="top-end">
+ <button class="chip" type="button" id="transfers-chip" aria-expanded="false" hidden></button>
+ <nav aria-label="Sections"><a href="#/logs" id="tab-logs">Logs</a><span class="later">Recipes<em>later</em></span><a href="#/files" id="tab-files">Files</a></nav>
+ </div>
+ <section class="panel" id="transfers-panel" aria-label="Uploads" hidden></section>
</header>
<div class="problem" id="problem" role="alert" hidden>
@@ -114,6 +209,9 @@ td.empty { color: var(--soft); }
<button class="ghost" type="button" id="retry">Try again</button>
</div>
+ <section id="files-view" hidden></section>
+
+ <section id="logs-view">
<dl class="facts" id="facts">
<div><dt>Playden</dt><dd id="fact-version">…</dd></div>
<div class="wide"><dt>Package</dt><dd id="fact-package">…</dd></div>
@@ -141,7 +239,9 @@ td.empty { color: var(--soft); }
<thead><tr><th>File</th><th>Changed</th><th class="num">Size</th><th class="num"></th></tr></thead>
<tbody></tbody>
</table>
+ </section>
</main>
+<div class="scrim" id="dialog-scrim" hidden></div>
<script>
(() => {
const $ = (id) => document.getElementById(id);
@@ -152,6 +252,7 @@ td.empty { color: var(--soft); }
for (const [key, value] of Object.entries(attributes)) {
if (key === "class") node.className = value;
else if (key === "text") node.textContent = value;
+ else if (key === "style") node.style.cssText = value;
else node.setAttribute(key, value);
}
for (const child of children) if (child) node.append(child);
@@ -297,7 +398,636 @@ td.empty { color: var(--soft); }
fail(error instanceof TypeError ? "Playden isn't answering. Is it open on the PS5?" : `Playden didn't quit (${error.message}).`);
}
});
+
+ // Files: everything below stays on this one page. Moving between screens only changes the hash, because a reload
+ // would cancel an upload.
+ const pane = $("files-view");
+ const clear = () => pane.replaceChildren();
+ const ROOTS = {
+ user: { label: "Windows user folder", detail: "Documents, AppData, Saved Games", windows: "C:\\users\\prospero" },
+ steam: { label: "Steam saves", detail: "Used by games that save through Steam", windows: "C:\\Program Files (x86)\\Steam\\userdata\\0" },
+ programdata: { label: "ProgramData", detail: "Shared by every Windows program", windows: "C:\\ProgramData" },
+ public: { label: "Public Documents", detail: "Shared by every Windows user", windows: "C:\\users\\Public\\Documents" },
+ game: { label: "Game folder", detail: "Game files, mods and game-side configs" },
+ };
+ const longSize = (bytes) => {
+ if (bytes < 1024 * 1024 * 1024) return size(bytes);
+ return `${(bytes / 1024 / 1024 / 1024).toFixed(1)} GB`;
+ };
+ const q = (values) => Object.entries(values).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&");
+ const button = (text, onClick, kind = "ghost") => {
+ const node = element("button", { class: kind, type: "button", text });
+ node.addEventListener("click", onClick);
+ return node;
+ };
+ const anchor = (text, href, kind = "ghost") => element("a", { class: kind, href, text });
+ const gameHash = (game) => `#/files/${encodeURIComponent(game)}`;
+ const folderHash = (game, root, path) => `${gameHash(game)}/${root}${path ? "/" + path.split("/").map(encodeURIComponent).join("/") : ""}`;
+ const editHash = (game, root, path) => `#/edit/${encodeURIComponent(game)}/${root}/${path.split("/").map(encodeURIComponent).join("/")}`;
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+ const files = { game: null, root: null, path: "", listing: null, selected: new Set(), route: 0, poll: 0, games: null };
+
+ class Answer extends Error {
+ constructor(status, message) {
+ super(message);
+ this.status = status;
+ }
+ }
+ const busyWords = () => files.setting_up
+ ? "Playden is setting up a game. Files are available when it finishes."
+ : "Playden is busy. Try again in a moment.";
+ // Answers 503 while a game's setup or another transfer has the way: a few quiet tries first.
+ const api = async (path, options = {}) => {
+ for (let attempt = 0; ; ++attempt) {
+ let response;
+ try {
+ response = await fetch(path, { cache: "no-store", ...options });
+ } catch (error) {
+ throw new Answer(0, "Playden isn't answering. Is it open on the PS5? It closes when a game starts.");
+ }
+ // A setup takes minutes: say so now. Anything else that's busy is over in a moment.
+ files.setting_up = response.status === 503 && response.headers.get("X-Playden-Busy") === "setup";
+ if (response.status === 503 && !files.setting_up && attempt < 3) { await sleep(1000); continue; }
+ const text = await response.text();
+ if (response.ok) {
+ const answer = text ? JSON.parse(text) : {};
+ files.setting_up = !!(answer.games ? answer.setting_up : answer.all_setting_up);
+ return answer;
+ }
+ if (response.status === 401) { showPairing(); throw new Answer(401, "Pair this browser first."); }
+ throw new Answer(response.status, response.status === 503 ? busyWords() : text.trim() || `Playden answered ${response.status}.`);
+ }
+ };
+ const act = (path) => api(path, { method: "POST", headers: { "X-Playden-Action": "files" } });
+ const report = (error) => {
+ if (error.status === 401) return;
+ fail(error.message);
+ };
+
+ // Pairing
+ const showPairing = () => {
+ ++files.route;
+ clearInterval(files.poll);
+ clear();
+ const code = element("input", { inputmode: "numeric", autocomplete: "one-time-code", maxlength: "6", "aria-label": "The code on the TV", placeholder: "000000" });
+ const note = element("p", { text: "" });
+ const pair = async () => {
+ $("problem").hidden = true;
+ try {
+ await act(`/api/pair/confirm?${q({ code: code.value.trim() })}`);
+ route();
+ } catch (error) { report(error); }
+ };
+ code.addEventListener("keydown", (event) => { if (event.key === "Enter") pair(); });
+ const ask = async (replace) => {
+ $("problem").hidden = true;
+ try {
+ await act(`/api/pair/start${replace ? "?new=1" : ""}`);
+ note.textContent = "The PS5 shows a 6-digit code for two minutes. Type it here.";
+ code.focus();
+ } catch (error) { report(error); }
+ };
+ pane.append(element("div", { class: "pair" },
+ element("h2", { text: "Pair this browser" }),
+ element("p", { text: "Game files can hold your saves and account details, so Playden asks once before showing them. The pairing ends when Playden closes." }),
+ note, code,
+ element("div", { class: "bar" }, button("Pair", pair, "primary"), button("Show a new code", () => ask(true)))));
+ ask(false);
+ };
+
+ // Games
+ const whereLabel = (game) => !game.drive ? "—" : game.drive_absent ? "Drive not connected" : game.drive === "usb" ? "USB drive" : game.drive === "m2" ? "M.2 drive" : "Console";
+ const gameBadges = (game) => {
+ const badges = [];
+ if (game.running) badges.push(element("span", { class: "badge running", text: "Running" }));
+ if (!game.installed) badges.push(element("span", { class: "badge", text: "Not installed" }));
+ if (game.kind === "imported") badges.push(element("span", { class: "badge", text: "Imported" }));
+ return badges;
+ };
+ const showGames = async () => {
+ const token = ++files.route;
+ clearInterval(files.poll);
+ let filter = "";
+ const search = element("input", { class: "search", type: "search", placeholder: "Find a game", "aria-label": "Find a game" });
+ const body = element("tbody");
+ const paint = () => {
+ const shown = (files.games.games || []).filter((game) => game.name.toLowerCase().includes(filter));
+ shown.sort((left, right) => Number(right.running) - Number(left.running) || (right.last_played || 0) - (left.last_played || 0) || left.name.localeCompare(right.name));
+ body.replaceChildren(...shown.map((game) => element("tr", {},
+ element("td", { class: "entry-name" }, element("a", { href: gameHash(game.id), text: game.name }), ...gameBadges(game),
+ element("span", { text: game.app ? `app ${game.app}` : game.id })),
+ element("td", { class: "soft when" , text: whereLabel(game) }),
+ element("td", { class: "soft when", text: game.cloud ? "Cloud sync" : "No Cloud sync" }),
+ element("td", { class: "soft when", text: game.last_played ? when(game.last_played) : "—" }),
+ element("td", { class: "num soft size", text: game.windows_user_bytes !== undefined ? longSize(game.windows_user_bytes) : "" }))));
+ if (!shown.length)
+ body.append(element("tr", {}, element("td", { class: "empty", colspan: "5", text: filter ? "No game has that name." : "No games with files yet." })));
+ };
+ search.addEventListener("input", () => { filter = search.value.toLowerCase(); paint(); });
+ const load = async () => {
+ files.games = await api("/api/files/games");
+ if (token === files.route) paint();
+ };
+ try { await load(); } catch (error) { return report(error); }
+ if (token !== files.route) return;
+ clear();
+ pane.append(element("div", { class: "title-row" }, element("h2", { text: "Game files" })),
+ element("p", { class: "lede", text: "Saves, configs and mods for each game. Pick a game to download, replace or add files." }),
+ element("div", { class: "bar" }, search),
+ element("table", { class: "files" },
+ element("thead", {}, element("tr", {}, element("th", { text: "Game" }), element("th", { text: "Installed on" }), element("th", { text: "Cloud" }),
+ element("th", { text: "Last played" }), element("th", { class: "num", text: "Windows user folders" }))),
+ body),
+ element("p", { class: "note", text: "Playden answers only while it is open. Starting a game ends this page until Playden opens again." }));
+ files.poll = setInterval(() => { load().catch(() => {}); }, 5000);
+ };
+
+ const rootRow = (game, root) => {
+ const info = ROOTS[root.id] || { label: root.id, detail: "" };
+ const where = root.id === "game" ? game.game_folder : info.windows;
+ return element("tr", {},
+ element("td", { class: "entry-name" }, element("a", { class: "folder", href: folderHash(game.id, root.id, ""), text: info.label }), element("span", { text: info.detail })),
+ element("td", { class: "mono when", text: where || "" }),
+ element("td", { class: "soft when", text: root.exists ? "" : "Empty" }),
+ element("td", { class: "acts" }, anchor("Open", folderHash(game.id, root.id, ""))));
+ };
+ const showGame = async (id) => {
+ const token = ++files.route;
+ clearInterval(files.poll);
+ let game;
+ files.listing = null;
+ try { game = await api(`/api/files/game?${q({ game: id, redist: 1 })}`); } catch (error) { if (token === files.route) report(error); return; }
+ if (token !== files.route) return;
+ clear();
+ pane.append(element("nav", { class: "crumbs", "aria-label": "Path" }, element("a", { href: "#/files", text: "Games" }), element("span", { text: "/" }), element("b", { text: game.name })));
+ pane.append(element("div", { class: "title-row" }, element("h2", { text: game.name }), ...gameBadges(game),
+ game.cloud ? element("span", { class: "badge ok", text: "Cloud sync" }) : ""));
+ const lede = [];
+ if (!game.installed) lede.push("You uninstalled this game, and Playden kept its saves.");
+ if (game.cloud) lede.push("A save you upload here can replace the one in Steam Cloud at the next sync.");
+ if (game.kind === "imported") lede.push("You added this game yourself, so Playden doesn't know where it saves. Look in the folders below.");
+ if (lede.length) pane.append(element("p", { class: "lede", text: lede.join(" ") }));
+ if (game.running) pane.append(runningNote());
+ if (game.physx_needed !== undefined) {
+ const version = game.physx_needed ? `PhysX ${game.physx_needed}` : "PhysX";
+ pane.append(element("div", { class: "problem" }, element("p", { text: `This game needs ${version}.` }),
+ element("p", { class: "note", text: game.drive_absent || !game.roots.some((root) => root.id === "game")
+ ? "Its game folder isn't available. Connect its drive to add the installer."
+ : "Upload its installer to the game's _Redist folder, then press Play on the PS5. The file name must start with \"physx\" and end in .msi or .exe." }),
+ game.roots.some((root) => root.id === "game")
+ ? element("div", { class: "bar" }, button("Open _Redist", async () => {
+ try {
+ if (!game.redist.some((folder) => folder.path.toLowerCase() === "_redist")) await act(`/api/files/mkdir?${q({ game: id, root: "game", path: "_Redist" })}`);
+ location.hash = folderHash(id, "game", (game.redist.find((folder) => folder.path.toLowerCase() === "_redist") || { path: "_Redist" }).path);
+ } catch (error) { report(error); }
+ }, "primary")) : ""));
+ }
+ if (game.drive_absent) pane.append(element("div", { class: "problem" }, element("p", { text: "Connect this game's drive to reach its game folder." }), element("p", { class: "note", text: "Its saves are on the console, below." })));
+ const bottleRoots = game.roots.filter((root) => root.id !== "game");
+ if (bottleRoots.length) {
+ pane.append(element("div", { class: "sub", text: "Saves & configs · on the console" }));
+ pane.append(element("table", { class: "files" }, element("tbody", {}, ...bottleRoots.map((root) => rootRow(game, root)))));
+ }
+ const gameRoot = game.roots.find((root) => root.id === "game");
+ if (gameRoot) {
+ pane.append(element("div", { class: "sub", text: `Game folder · ${whereLabel(game).toLowerCase()}` }));
+ pane.append(element("table", { class: "files" }, element("tbody", {}, rootRow(game, gameRoot))));
+ if (game.redist_busy) pane.append(element("p", { class: "note", text: busyWords() }));
+ if (game.redist.length) {
+ pane.append(element("div", { class: "sub", text: "Redistributable installers · in the game folder" }));
+ pane.append(element("table", { class: "files" }, element("tbody", {}, ...game.redist.map((folder) => element("tr", {},
+ element("td", { class: "entry-name" }, element("a", { class: "folder", href: folderHash(id, "game", folder.path), text: folder.path }),
+ element("span", { text: folder.physx_installer ? `Play installs ${folder.physx_installer.split("/").pop()} from here` : "" })),
+ element("td", { class: "soft when", text: folder.sample.join(", ") + (folder.entries > folder.sample.length ? `, ${folder.entries - folder.sample.length} more` : "") }),
+ element("td", { class: "num soft size", text: folder.bytes ? longSize(folder.bytes) : folder.entries ? "" : "Empty" }),
+ element("td", { class: "acts" }, anchor("Open", folderHash(id, "game", folder.path))))))));
+ }
+ pane.append(element("p", { class: "note", text: "Playden looks for PhysX in folders named _Redist, _CommonRedist, CommonRedist, Redist, Redists, Redistributable, Redistributables, Support, __Installer, _Installer, Installer, Installers, Prerequisites, Prereqs, PhysX, DirectX, VCRedist or DotNet, at the top of the game folder or one level down." }));
+ }
+ if (!bottleRoots.length && !gameRoot) pane.append(element("p", { class: "lede", text: "This game has no folders to show yet." }));
+ };
+ const runningNote = () => element("div", { class: "problem", role: "status" },
+ element("p", { text: "This game is running on the PS5, in the background." }),
+ element("p", { class: "note", text: "It can overwrite files you change here. To be safe, close it on the PS5 first." }));
+
+ // Folders
+ const relPath = (name) => (files.path ? `${files.path}/${name}` : name);
+ const breadcrumbs = (game, root, path, last) => {
+ const nav = element("nav", { class: "crumbs", "aria-label": "Path" }, element("a", { href: "#/files", text: "Games" }), element("span", { text: "/" }),
+ element("a", { href: gameHash(game.id), text: game.name }), element("span", { text: "/" }));
+ const parts = path ? path.split("/") : [];
+ const label = (ROOTS[root] || { label: root }).label;
+ if (!parts.length && !last) nav.append(element("b", { text: label }));
+ else nav.append(element("a", { href: folderHash(game.id, root, ""), text: label }));
+ parts.forEach((part, index) => {
+ nav.append(element("span", { text: "/" }));
+ if (index === parts.length - 1 && !last) nav.append(element("b", { text: part }));
+ else nav.append(element("a", { href: folderHash(game.id, root, parts.slice(0, index + 1).join("/")), text: part }));
+ });
+ if (last) { nav.append(element("span", { text: "/" })); nav.append(element("b", { text: last })); }
+ return nav;
+ };
+ const isText = (entry) => entry.size <= 1024 * 1024 && /\.(ini|cfg|txt|json|xml|conf|config|lua|yaml|yml|toml|csv|log|vdf)$/i.test(entry.name);
+ const editableRow = (entry) => !entry.read_only && !entry.recoverable;
+ const paintFolder = () => {
+ const { game, root, path, listing } = files;
+ const ctx = { game: game.id, root };
+ clear();
+ pane.append(breadcrumbs(game, root, path));
+ if (game.running) pane.append(runningNote());
+ const upload = button("Upload files", () => picker.click(), "primary");
+ const picker = element("input", { type: "file", multiple: "", hidden: "", "aria-label": "Files to upload" });
+ picker.addEventListener("change", () => { addFiles([...picker.files]); picker.value = ""; });
+ const newFolder = button("New folder", () => askNewFolder());
+ const zip = anchor("Download folder (.zip)", `/api/files/zip?${q({ ...ctx, path })}`);
+ const selected = [...files.selected];
+ const bar = element("div", { class: "bar" }, upload, picker, newFolder, listing.exists ? zip : "");
+ if (listing.read_only) { upload.disabled = true; newFolder.disabled = true; }
+ if (selected.length) bar.append(button(`Delete ${selected.length} selected`, () => askDelete(selected), "ghost danger end"));
+ if (listing.read_only)
+ pane.append(element("p", { class: "lede", text: "Read-only: Playden writes this folder itself when it prepares the game, so changes here wouldn't last. Change these settings in Game settings on the PS5." }));
+ if (root === "game" && !listing.read_only)
+ pane.append(element("p", { class: "note", style: "margin:0 0 14px", text: "A game update can overwrite the game's own files, and uninstalling removes this folder with everything you added." }));
+ pane.append(bar);
+ const queued = transfers.items.filter((item) => item.game === game.id && item.root === root && item.path === path && item.state !== "done");
+ const rows = listing.entries.map((entry) => {
+ const full = relPath(entry.name);
+ const pending = !entry.directory && queued.find((item) => item.name.toLowerCase() === entry.name.toLowerCase());
+ const check = element("input", { type: "checkbox", "aria-label": `Select ${entry.name}` });
+ check.checked = files.selected.has(entry.name);
+ check.disabled = !!entry.read_only;
+ check.addEventListener("change", () => {
+ if (check.checked) files.selected.add(entry.name); else files.selected.delete(entry.name);
+ paintFolder();
+ });
+ const name = entry.directory
+ ? element("td", { class: "entry-name" }, element("a", { class: "folder", href: folderHash(game.id, root, full), text: entry.name }), entry.read_only ? element("span", { text: "Read-only. Playden writes this folder." }) : "")
+ : element("td", { class: "entry-name" }, entry.name);
+ if (!entry.directory && entry.recoverable) name.append(element("span", { text: "Recoverable: an earlier replace stopped here. Restore it to get this file back." }));
+ else if (!entry.directory && entry.previous) name.append(element("span", { text: `Previous version from ${when(entry.previous.modified).toLowerCase()}, ${longSize(entry.previous.size)}` }));
+ if (entry.name.toLowerCase() === "configs.user.ini") name.append(element("span", { text: "Names your Steam account. Look through it before you share it." }));
+ const acts = element("td", { class: "acts" });
+ if (!entry.directory) {
+ if (!entry.recoverable) acts.append(anchor("Download", `/api/files/download?${q({ ...ctx, path: full })}`));
+ if (entry.previous) {
+ acts.append(anchor(entry.recoverable ? "Download" : "Download previous", `/api/files/download?${q({ ...ctx, path: full, previous: 1 })}`));
+ if (!entry.read_only) acts.append(button("Restore", () => restore(full)));
+ }
+ if (isText(entry) && editableRow(entry)) acts.append(anchor("Edit", editHash(game.id, root, full)));
+ }
+ const status = pending
+ ? element("td", { class: "status", text: pending.state === "active" ? `Uploading ${Math.round(pending.fraction * 100)}%` : pending.state === "waiting" ? "Waiting to upload" : "Upload failed" })
+ : element("td", { class: "soft when", text: when(entry.modified) });
+ return element("tr", {}, element("td", { class: "pick" }, check), name, status,
+ element("td", { class: "num soft size", text: entry.directory ? "" : longSize(entry.size) }), acts);
+ });
+ // Files on their way that aren't listed yet.
+ for (const item of queued)
+ if (!listing.entries.some((entry) => entry.name.toLowerCase() === item.name.toLowerCase()))
+ rows.push(element("tr", {}, element("td", { class: "pick" }), element("td", { class: "entry-name" }, item.name),
+ element("td", { class: "status", text: item.state === "active" ? `Uploading ${Math.round(item.fraction * 100)}%` : item.state === "waiting" ? "Waiting to upload" : "Upload failed" }),
+ element("td", { class: "num soft size", text: longSize(item.file.size) }), element("td", { class: "acts" })));
+ if (rows.length) {
+ pane.append(element("table", { class: "files" },
+ element("thead", {}, element("tr", {}, element("th", {}), element("th", { text: "Name" }), element("th", { text: "Changed" }), element("th", { class: "num", text: "Size" }), element("th", {}))),
+ element("tbody", {}, ...rows)));
+ } else {
+ pane.append(element("div", { class: "drop-hint" }, element("strong", { text: "This folder is empty" }),
+ listing.read_only ? "" : "Drop files here to upload them, or use Upload files."));
+ }
+ if (listing.unshown) pane.append(element("p", { class: "note", text: `${listing.unshown} ${listing.unshown === 1 ? "file" : "files"} can't be shown here.` }));
+ if (listing.truncated) pane.append(element("p", { class: "note", text: "This folder has too many files to list them all." }));
+ if (!listing.read_only && rows.length) pane.append(element("p", { class: "note", text: "Drop files anywhere on this page to upload them. A file you replace is kept as its previous version." }));
+ const windows = (ROOTS[root] || {}).windows;
+ if (windows) pane.append(element("p", { class: "note mono", text: path ? `${windows}\\${path.split("/").join("\\")}` : windows }));
+ else if (game.game_folder) pane.append(element("p", { class: "note mono", text: path ? `${game.game_folder}/${path}` : game.game_folder }));
+ };
+ const fetchListing = (game, root, path) => api(`/api/files/list?${q({ game, root, path })}`);
+ const showFolder = async (id, root, path) => {
+ const token = ++files.route;
+ clearInterval(files.poll);
+ files.listing = null;
+ let game, listing;
+ try {
+ game = await api(`/api/files/game?${q({ game: id })}`);
+ if (token !== files.route) return;
+ listing = await fetchListing(id, root, path);
+ } catch (error) {
+ if (token !== files.route) return;
+ if (error.status !== 503 || !files.setting_up) return report(error);
+ // Opens by itself when the setup ends.
+ clear();
+ pane.append(element("p", { class: "lede", text: error.message }));
+ setTimeout(() => { if (token === files.route) route(); }, 5000);
+ return;
+ }
+ // An answer for a screen the player has left changes nothing.
+ if (token !== files.route) return;
+ Object.assign(files, { game, root, path, listing, selected: new Set() });
+ paintFolder();
+ };
+ const onFolder = (game, root, path) => !!files.listing && !!files.game && location.hash === folderHash(game, root, path);
+ const refreshFolder = async () => {
+ if (!files.game || !files.listing) return;
+ const token = files.route;
+ const { root, path } = files;
+ const game = files.game.id;
+ let listing;
+ try { listing = await fetchListing(game, root, path); } catch (error) { if (token === files.route) report(error); return; }
+ if (token === files.route && onFolder(game, root, path)) {
+ files.listing = listing;
+ paintFolder();
+ }
+ };
+
+ // Dialogs
+ const dialog = (title, ...children) => {
+ const scrim = $("dialog-scrim");
+ const box = element("div", { class: "dialog", role: "dialog", "aria-modal": "true", "aria-label": title }, element("h3", { text: title }), ...children);
+ scrim.replaceChildren(box);
+ scrim.hidden = false;
+ return () => { scrim.hidden = true; scrim.replaceChildren(); };
+ };
+ const askNewFolder = () => {
+ const name = element("input", { class: "search", style: "width:100%", "aria-label": "Folder name", placeholder: "Folder name" });
+ let close;
+ const make = async () => {
+ if (!name.value) return;
+ try {
+ await act(`/api/files/mkdir?${q({ game: files.game.id, root: files.root, path: relPath(name.value) })}`);
+ close();
+ refreshFolder();
+ } catch (error) { close(); report(error); }
+ };
+ name.addEventListener("keydown", (event) => { if (event.key === "Enter") make(); });
+ close = dialog("New folder", name, element("div", { class: "foot" }, button("Cancel", () => close()), button("Make folder", make, "primary")));
+ name.focus();
+ };
+ const askDelete = (names) => {
+ // Fixed now: the player can move to another folder or game while these go.
+ const batch = { game: files.game.id, root: files.root, paths: names.map(relPath) };
+ let close;
+ const remove = async () => {
+ close();
+ for (const path of batch.paths) {
+ try { await act(`/api/files/delete?${q({ game: batch.game, root: batch.root, path })}`); }
+ catch (error) { report(error); break; }
+ }
+ files.selected = new Set();
+ refreshFolder();
+ };
+ close = dialog(`Delete ${names.length} ${names.length === 1 ? "item" : "items"}?`,
+ element("p", { text: "They are deleted from the PS5 with any previous versions, and can't be restored from here. Only empty folders can be deleted." }),
+ element("ul", {}, ...names.map((name) => element("li", { text: name }))),
+ element("div", { class: "foot" }, button("Keep them", () => close()), button("Delete", remove, "primary")));
+ };
+ const restore = async (full) => {
+ try { await act(`/api/files/restore?${q({ game: files.game.id, root: files.root, path: full })}`); }
+ catch (error) { report(error); }
+ refreshFolder();
+ };
+
+ // Uploads: one at a time, whatever screen is showing. The indicator is in the header of every screen.
+ const transfers = { items: [], active: null, open: false };
+ const addFiles = (list) => {
+ if (!list.length || !files.game || !files.listing || files.listing.read_only) return;
+ const taken = list.filter((file) => files.listing.entries.some((entry) => !entry.directory && entry.name.toLowerCase() === file.name.toLowerCase()));
+ const queue = (chosen, overwrite) => {
+ for (const file of chosen)
+ transfers.items.push({ file, name: file.name, game: files.game.id, gameName: files.game.name, root: files.root, path: files.path, overwrite, state: "waiting", fraction: 0, message: "" });
+ paintTransfers();
+ paintFolder();
+ nextTransfer();
+ };
+ if (!taken.length) return queue(list, false);
+ let close;
+ const replace = element("input", { type: "radio", name: "clash", checked: "" });
+ const skip = element("input", { type: "radio", name: "clash" });
+ const free = list.filter((file) => !taken.includes(file));
+ close = dialog(`${taken.length} of ${list.length} ${list.length === 1 ? "file" : "files"} already ${taken.length === 1 ? "exists" : "exist"}`,
+ element("p", { text: "This folder already has these files:" }),
+ element("ul", {}, ...taken.map((file) => element("li", { text: file.name }))),
+ element("label", { class: "choice" }, replace, element("span", {}, "Replace them", element("small", { text: "The current files are kept as their previous versions." }))),
+ element("label", { class: "choice" }, skip, element("span", {}, "Skip them", element("small", { text: free.length ? `Upload only the other ${free.length}.` : "Upload nothing." }))),
+ element("div", { class: "foot" }, button("Cancel", () => close()), button("Upload", () => {
+ close();
+ queue(free, false);
+ if (replace.checked) queue(taken, true);
+ }, "primary")));
+ };
+ const finish = (item, state, message) => {
+ item.state = state;
+ item.message = message || "";
+ item.xhr = null;
+ transfers.active = null;
+ paintTransfers();
+ if (onFolder(item.game, item.root, item.path)) refreshFolder();
+ nextTransfer();
+ // All went well: the indicator goes away by itself. A failure stays until it is read and cleared.
+ if (transfers.items.every((candidate) => candidate.state === "done" || candidate.state === "cancelled"))
+ setTimeout(() => {
+ if (transfers.open || !transfers.items.every((candidate) => candidate.state === "done" || candidate.state === "cancelled")) return;
+ transfers.items = [];
+ paintTransfers();
+ }, 5000);
+ };
+ const nextTransfer = () => {
+ if (transfers.active) return;
+ const item = transfers.items.find((candidate) => candidate.state === "waiting");
+ paintTransfers();
+ if (!item) return;
+ // A setup can take many minutes: ask until it's over, with no file on the way and no limit on the wait.
+ if (files.setting_up) {
+ if (transfers.asking) return;
+ transfers.asking = true;
+ fetch("/api/files/games", { cache: "no-store" })
+ .then((response) => (response.ok ? response.json() : null))
+ .then((answer) => { files.setting_up = !!(answer && answer.setting_up); })
+ .catch(() => { files.setting_up = false; })
+ .finally(() => {
+ transfers.asking = false;
+ setTimeout(nextTransfer, files.setting_up ? 3000 : 0);
+ });
+ return;
+ }
+ transfers.active = item;
+ item.state = "active";
+ const xhr = new XMLHttpRequest();
+ item.xhr = xhr;
+ const full = item.path ? `${item.path}/${item.name}` : item.name;
+ xhr.open("POST", `/api/files/upload?${q({ game: item.game, root: item.root, path: full, overwrite: item.overwrite ? 1 : 0 })}`);
+ xhr.setRequestHeader("X-Playden-Action", "files");
+ let painted = 0;
+ xhr.upload.addEventListener("progress", (event) => {
+ if (!event.lengthComputable) return;
+ item.fraction = event.total ? event.loaded / event.total : 1;
+ const now = Date.now();
+ if (now - painted < 250) return;
+ painted = now;
+ paintTransfers();
+ if (onFolder(item.game, item.root, item.path)) paintFolder();
+ });
+ xhr.addEventListener("load", () => {
+ if (xhr.status >= 200 && xhr.status < 300) { item.fraction = 1; return finish(item, "done"); }
+ if (xhr.status === 503) files.setting_up = xhr.getResponseHeader("X-Playden-Busy") === "setup";
+ if (xhr.status === 503 && !files.setting_up && (item.busy = (item.busy || 0) + 1) > 150) {
+ // About five minutes of waiting: it fails, so the rest of the queue isn't held up behind it.
+ return finish(item, "failed", busyWords());
+ }
+ if (xhr.status === 503) {
+ // A setup or another transfer has the way: this one waits its turn.
+ item.state = "waiting";
+ item.fraction = 0;
+ item.xhr = null;
+ transfers.active = null;
+ paintTransfers();
+ if (onFolder(item.game, item.root, item.path)) paintFolder();
+ setTimeout(nextTransfer, 2000);
+ return;
+ }
+ if (xhr.status === 401) showPairing();
+ finish(item, "failed", xhr.responseText.trim() || `Playden answered ${xhr.status}.`);
+ });
+ xhr.addEventListener("error", () => {
+ // Whatever else is queued can't go either.
+ finish(item, "failed", "Playden stopped answering. The old file is still there.");
+ fail("Playden stopped answering during your upload. It closes when a game starts. Open Playden on the PS5, then try again.");
+ });
+ xhr.addEventListener("abort", () => finish(item, "cancelled"));
+ xhr.send(item.file);
+ paintTransfers();
+ };
+ const cancelTransfer = (item) => {
+ if (item.xhr) return item.xhr.abort();
+ item.state = "cancelled";
+ paintTransfers();
+ };
+ const paintTransfers = () => {
+ const chip = $("transfers-chip"), panel = $("transfers-panel");
+ const items = transfers.items.filter((item) => item.state !== "cancelled");
+ const live = items.filter((item) => item.state === "waiting" || item.state === "active");
+ if (!items.length) {
+ chip.hidden = panel.hidden = true;
+ return;
+ }
+ const total = items.reduce((sum, item) => sum + item.file.size, 0);
+ const sent = items.reduce((sum, item) => sum + (item.state === "done" ? item.file.size : item.state === "active" ? item.file.size * item.fraction : 0), 0);
+ const percent = total ? Math.round((sent / total) * 100) : 100;
+ const failed = items.filter((item) => item.state === "failed").length;
+ const position = items.filter((item) => item.state === "done" || item.state === "failed").length + 1;
+ chip.hidden = false;
+ chip.setAttribute("aria-expanded", transfers.open ? "true" : "false");
+ chip.replaceChildren(live.length ? `${transfers.active ? "Uploading" : "Waiting to upload"} ${Math.min(position, items.length)} of ${items.length} · ${percent}%` : failed ? `${failed} ${failed === 1 ? "upload" : "uploads"} failed` : "Uploads finished",
+ element("span", { class: "meter" }, element("i", { style: `width:${percent}%` })));
+ panel.hidden = !transfers.open;
+ if (!transfers.open) return;
+ const rows = items.map((item) => {
+ const state = item.state === "done" ? element("span", { class: "done", text: "Done" })
+ : item.state === "failed" ? element("span", { class: "bad", text: item.message })
+ : element("span", { text: item.state === "active" ? `${Math.round(item.fraction * 100)}%` : "Waiting" });
+ const row = element("li", {}, element("div", { class: "line" }, item.name, state),
+ element("small", { text: `${item.gameName} › ${item.path || (ROOTS[item.root] || {}).label || item.root}` }));
+ if (item.state === "active") row.append(element("span", { class: "meter" }, element("i", { style: `width:${Math.round(item.fraction * 100)}%` })));
+ if (item.state === "active" || item.state === "waiting") row.append(button("Cancel", () => cancelTransfer(item)));
+ return row;
+ });
+ panel.replaceChildren(element("div", { class: "head" }, "Uploads", element("span", { text: `${longSize(sent)} of ${longSize(total)}` })),
+ element("span", { class: "meter" }, element("i", { style: `width:${percent}%` })),
+ element("ul", {}, ...rows),
+ element("div", { class: "foot" }, element("small", { text: live.length ? "Keep this tab open until they finish." : "" }),
+ live.length
+ ? button("Cancel all", () => { for (const item of [...live]) cancelTransfer(item); })
+ : button("Clear", () => { transfers.items = []; transfers.open = false; paintTransfers(); })));
+ };
+ $("transfers-chip").addEventListener("click", () => { transfers.open = !transfers.open; paintTransfers(); });
+ // The panel sits over the page: a click anywhere else closes it, so it never stands in the way.
+ document.addEventListener("click", (event) => {
+ if (!transfers.open || event.target.closest("#transfers-chip, #transfers-panel")) return;
+ transfers.open = false;
+ paintTransfers();
+ });
+ window.addEventListener("beforeunload", (event) => {
+ if (transfers.items.some((item) => item.state === "waiting" || item.state === "active")) {
+ event.preventDefault();
+ event.returnValue = "";
+ }
+ });
+ const inFolder = () => location.hash.startsWith("#/files/") && !!files.listing && !files.listing.read_only;
+ document.addEventListener("dragover", (event) => {
+ if (!inFolder()) return;
+ event.preventDefault();
+ document.querySelector("main").classList.add("dragging");
+ });
+ document.addEventListener("dragleave", (event) => {
+ if (event.relatedTarget === null) document.querySelector("main").classList.remove("dragging");
+ });
+ document.addEventListener("drop", (event) => {
+ document.querySelector("main").classList.remove("dragging");
+ if (!inFolder()) return;
+ event.preventDefault();
+ addFiles([...event.dataTransfer.files]);
+ });
+
+ // The config editor: small text files, saved only if the file is still what was opened.
+ const showEditor = async (id, root, path) => {
+ const token = ++files.route;
+ clearInterval(files.poll);
+ let game, text;
+ try {
+ game = await api(`/api/files/game?${q({ game: id })}`);
+ text = await api(`/api/files/text?${q({ game: id, root, path })}`);
+ } catch (error) { return report(error); }
+ if (token !== files.route) return;
+ const parts = path.split("/");
+ const name = parts.pop();
+ const folder = parts.join("/");
+ const area = element("textarea", { class: "editor", spellcheck: "false", "aria-label": `Contents of ${name}` });
+ area.value = text.text;
+ const back = () => { location.hash = folderHash(id, root, folder); };
+ const save = async () => {
+ $("problem").hidden = true;
+ try {
+ await api(`/api/files/upload?${q({ game: id, root, path, if_sha256: text.sha256 })}`,
+ { method: "POST", headers: { "X-Playden-Action": "files" }, body: new Blob([area.value]) });
+ back();
+ } catch (error) { report(error); }
+ };
+ clear();
+ pane.append(breadcrumbs(game, root, folder, name),
+ element("div", { class: "bar" }, button("Save", save, "primary"), button("Discard", back), anchor("Download", `/api/files/download?${q({ game: id, root, path })}`)),
+ game.running ? runningNote() : "",
+ area,
+ element("p", { class: "note", text: "Save keeps the old version as this file's previous version." }));
+ };
+
+ // Which screen the address names.
+ const route = () => {
+ const hash = location.hash || "#/logs";
+ const inFiles = hash.startsWith("#/files") || hash.startsWith("#/edit");
+ $("logs-view").hidden = inFiles;
+ $("files-view").hidden = !inFiles;
+ $("tab-logs").classList.toggle("on", !inFiles);
+ $("tab-files").classList.toggle("on", inFiles);
+ $("problem").hidden = true;
+ clearInterval(files.poll);
+ if (!inFiles) { ++files.route; return; }
+ const parts = hash.slice(2).split("/").map(decodeURIComponent);
+ const token = ++files.route;
+ files.listing = null;
+ (async () => {
+ const paired = await fetch("/api/pair/status", { cache: "no-store" }).then((response) => response.json()).catch(() => null);
+ if (token !== files.route) return;
+ if (!paired) return fail("Playden isn't answering. Is it open on the PS5? It closes when a game starts.");
+ if (!paired.paired) return showPairing();
+ if (parts[0] === "edit") return showEditor(parts[1], parts[2], parts.slice(3).join("/"));
+ if (parts.length === 1) return showGames();
+ if (parts.length === 2) return showGame(parts[1]);
+ return showFolder(parts[1], parts[2], parts.slice(3).join("/"));
+ })().catch(report);
+ };
+ window.addEventListener("hashchange", route);
load();
+ route();
})();
</script>
</body>
diff --git a/src/web/service.cpp b/src/web/service.cpp
index 5658702..4a12730 100644
--- a/src/web/service.cpp
+++ b/src/web/service.cpp
@@ -154,6 +154,8 @@ void Service::SetFileCatalog(FileCatalog catalog) { files_.SetCatalog(std::move(
void Service::CancelPairing() { files_.CancelPairing(); }
+bool Service::FilesInUse() const { return files_.InUse(); }
+
void Service::Shutdown() {
{
std::lock_guard<std::mutex> lock(mutex_);
diff --git a/src/web/service.h b/src/web/service.h
index ffad0db..c09b6fa 100644
--- a/src/web/service.h
+++ b/src/web/service.h
@@ -58,6 +58,8 @@ class Service {
void SetFileCatalog(FileCatalog catalog);
// The player dismissed the pairing code on the TV.
void CancelPairing();
+ // A paired browser used the Files tab in the last half a minute.
+ bool FilesInUse() const;
// True once after the page asked Playden to quit; the caller quits.
bool TakeQuitRequest();
// Stops the server and the worker. Safe to call twice.
diff --git a/tests/test_web_files_smoke.py b/tests/test_web_files_smoke.py
new file mode 100644
index 0000000..97daccf
--- /dev/null
+++ b/tests/test_web_files_smoke.py
@@ -0,0 +1,127 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: GPL-3.0-or-later
+"""Drives the Files tab's API against a real server, as the page does: pair, list, upload, replace, restore, zip, delete."""
+import http.client
+import io
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import urllib.parse
+import zipfile
+
+
+def main(server_binary):
+ with tempfile.TemporaryDirectory(dir=os.path.realpath(tempfile.gettempdir())) as folder:
+ server = subprocess.Popen([server_binary, folder], stdout=subprocess.PIPE, text=True)
+ try:
+ port = int(server.stdout.readline().strip().split("=")[1])
+ run(port, server)
+ finally:
+ server.kill()
+ server.wait()
+ print("web_files_smoke: ok")
+
+
+def run(port, server):
+ cookie = {}
+
+ def call(method, route, body=None, action=True, **query):
+ target = route + ("?" + urllib.parse.urlencode(query) if query else "")
+ connection = http.client.HTTPConnection("127.0.0.1", port, timeout=20)
+ headers = {}
+ if action:
+ headers["X-Playden-Action"] = "files"
+ if "value" in cookie:
+ headers["Cookie"] = cookie["value"]
+ connection.request(method, target, body=body, headers=headers)
+ response = connection.getresponse()
+ data = response.read()
+ result = (response.status, data, dict(response.getheaders()))
+ connection.close()
+ return result
+
+ def ok(result):
+ assert 200 <= result[0] < 300, result[:2]
+ return json.loads(result[1]) if result[2].get("Content-Type", "").startswith("application/json") else result[1]
+
+ # Unpaired.
+ assert call("GET", "/api/files/games")[0] == 401
+ assert json.loads(call("GET", "/api/pair/status")[1]) == {"paired": False}
+
+ # Pair with the code the TV shows.
+ ok(call("POST", "/api/pair/start"))
+ code = server.stdout.readline().strip().split("=")[1]
+ result = call("POST", "/api/pair/confirm", code=code)
+ ok(result)
+ cookie["value"] = result[2]["Set-Cookie"].split(";")[0]
+ assert json.loads(call("GET", "/api/pair/status")[1]) == {"paired": True}
+
+ # The games.
+ games = ok(call("GET", "/api/files/games"))["games"]
+ assert {game["id"] for game in games} == {"steam-12210", "local-3fa9c1", "steam-1091500", "steam-274520"}
+ assert next(game for game in games if game["id"] == "steam-1091500")["running"] is True
+
+ # A game playing in place from USB: its redistributable folders, by Play's rules, and what it needs.
+ wolverine = ok(call("GET", "/api/files/game", game="local-3fa9c1", redist=1))
+ assert wolverine["physx_needed"] == "2.8.1"
+ assert [folder["path"] for folder in wolverine["redist"]] == ["Support"]
+ # An unplugged drive leaves the saves.
+ cyberpunk = ok(call("GET", "/api/files/game", game="steam-1091500"))
+ assert "game" not in [root["id"] for root in cyberpunk["roots"]] and "user" in [root["id"] for root in cyberpunk["roots"]]
+ # An uninstalled game keeps its saves.
+ darkwood = ok(call("GET", "/api/files/list", game="steam-274520", root="user", path="AppData/LocalLow/Acid Wizard Studio/Darkwood"))
+ assert [entry["name"] for entry in darkwood["entries"]] == ["save.dat"]
+
+ # The GTA IV save a player asked about: found, and downloaded.
+ place = dict(game="steam-12210", root="user")
+ save_folder = "Documents/Rockstar Games/GTA IV/Profiles/7A3C91F0"
+ listing = ok(call("GET", "/api/files/list", path=save_folder, **place))
+ assert [entry["name"] for entry in listing["entries"]] == ["cfg.set", "SGTA400"]
+ original = ok(call("GET", "/api/files/download", path=save_folder + "/SGTA400", **place))
+ assert len(original) == 512 * 1024
+
+ # Replace it, see the previous version, restore it.
+ path = save_folder + "/SGTA400"
+ assert call("POST", "/api/files/upload", body=b"new", path=path, **place)[0] == 409
+ assert ok(call("POST", "/api/files/upload", body=b"new", path=path, overwrite=1, **place))["replaced"] is True
+ assert ok(call("GET", "/api/files/download", path=path, **place)) == b"new"
+ entry = next(e for e in ok(call("GET", "/api/files/list", path=save_folder, **place))["entries"] if e["name"] == "SGTA400")
+ assert entry["previous"]["size"] == 512 * 1024
+ assert ok(call("GET", "/api/files/download", path=path, previous=1, **place)) == original
+ ok(call("POST", "/api/files/restore", path=path, **place))
+ assert ok(call("GET", "/api/files/download", path=path, **place)) == original
+
+ # A large upload, in one request.
+ large = os.urandom(8 * 1024 * 1024)
+ ok(call("POST", "/api/files/upload", body=large, path="Documents/large.bin", **place))
+ assert ok(call("GET", "/api/files/download", path="Documents/large.bin", **place)) == large
+ ok(call("POST", "/api/files/delete", path="Documents/large.bin", **place))
+ assert call("GET", "/api/files/download", path="Documents/large.bin", **place)[0] == 404
+
+ # A folder as a zip that opens.
+ archive = zipfile.ZipFile(io.BytesIO(ok(call("GET", "/api/files/zip", path=save_folder, **place))))
+ assert archive.testzip() is None and "7A3C91F0/cfg.set" in archive.namelist()
+
+ # Read-only and hidden in the game folder.
+ game_place = dict(game="steam-12210", root="game")
+ names = [entry["name"] for entry in ok(call("GET", "/api/files/list", **game_place))["entries"]]
+ assert ".playden-install.json" not in names and "steam_settings" in names
+ assert call("POST", "/api/files/upload", body=b"x", path="steam_settings/configs.user.ini", overwrite=1, **game_place)[0] == 403
+
+ # The editor's round trip.
+ text = ok(call("GET", "/api/files/text", path="autoexec.cfg", **game_place))
+ ok(call("POST", "/api/files/upload", body=b"fps_max 120\n", path="autoexec.cfg", if_sha256=text["sha256"], **game_place))
+ assert call("POST", "/api/files/upload", body=b"stale", path="autoexec.cfg", if_sha256=text["sha256"], **game_place)[0] == 409
+
+ # PhysX for a game playing from USB: a new _Redist folder, then the installer; the page now names it.
+ wolverine_place = dict(game="local-3fa9c1", root="game")
+ ok(call("POST", "/api/files/mkdir", path="_Redist", **wolverine_place))
+ ok(call("POST", "/api/files/upload", body=b"msi", path="_Redist/PhysX_9.09.msi", **wolverine_place))
+ wolverine = ok(call("GET", "/api/files/game", game="local-3fa9c1", redist=1))
+ assert next(folder for folder in wolverine["redist"] if folder["path"] == "_Redist")["physx_installer"] == "_Redist/PhysX_9.09.msi"
+
+
+if __name__ == "__main__":
+ main(sys.argv[1])
diff --git a/tests/web_files_api_test.cpp b/tests/web_files_api_test.cpp
index 509352d..eb58866 100644
--- a/tests/web_files_api_test.cpp
+++ b/tests/web_files_api_test.cpp
@@ -183,7 +183,8 @@ int main() {
CHECK(body.find("\"name\":\"Grand \\\"Theft\\\" Auto IV\"") != std::string::npos && body.find("\"running\":true") != std::string::npos);
CHECK(body.find(game_folder.string()) == std::string::npos);
// The game's page: roots, redistributable folders, what it needs.
- body = Body(get("/api/files/game?game=steam-12210", cookie));
+ CHECK(Body(get("/api/files/game?game=steam-12210", cookie)).find("_Redist") == std::string::npos);
+ body = Body(get("/api/files/game?game=steam-12210&redist=1", cookie));
for (const char* part : {"\"id\":\"user\"", "\"id\":\"steam\"", "\"id\":\"programdata\"", "\"id\":\"public\"", "\"id\":\"game\"", "\"physx_needed\":\"2.8.1\"", "\"path\":\"_Redist\"",
"\"physx_installer\":\"_Redist/PhysX.msi\"", "/mnt/usb0/playden/import/Game"})
CHECK(body.find(part) != std::string::npos);
@@ -295,6 +296,21 @@ int main() {
CHECK(Status(get("/api/files/download?" + game + "game&path=game.exe", cookie)) == 200);
}
+ // A game's setup: file actions say so at once, and the game's page still opens without touching the disk.
+ {
+ auto during = catalog;
+ during.setting_up = true;
+ service.SetFileCatalog(during);
+ const auto started = std::chrono::steady_clock::now();
+ answer = get("/api/files/list?" + game + "user", cookie);
+ CHECK(Status(answer) == 503 && answer.find("X-Playden-Busy: setup") != std::string::npos && answer.find("setting up a game") != std::string::npos);
+ answer = get("/api/files/game?game=steam-12210&redist=1", cookie);
+ CHECK(Status(answer) == 200 && answer.find("\"all_setting_up\":true") != std::string::npos && answer.find("\"redist_busy\":true") != std::string::npos);
+ CHECK(std::chrono::steady_clock::now() - started < std::chrono::seconds(1));
+ service.SetFileCatalog(catalog);
+ CHECK(Status(get("/api/files/list?" + game + "user", cookie)) == 200);
+ }
+
service.Shutdown();
fs::remove_all(base);
std::puts("web_files_api: ok");
diff --git a/tests/web_files_fixture_server.cpp b/tests/web_files_fixture_server.cpp
new file mode 100644
index 0000000..7ce5347
--- /dev/null
+++ b/tests/web_files_fixture_server.cpp
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// A real web server over made-up games in a folder, for tests/test_web_files_smoke.py and for trying the page in a
+// browser: web_files_fixture_server <empty folder> [port]. Prints "port=<n>", then each pairing code as "code=<digits>".
+#include "web/service.h"
+
+#include <chrono>
+#include <cstdio>
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <string>
+#include <thread>
+
+using namespace playden::web;
+namespace fs = std::filesystem;
+
+namespace {
+void Put(const fs::path& path, const std::string& text) {
+ fs::create_directories(path.parent_path());
+ std::ofstream(path, std::ios::binary) << text;
+}
+} // namespace
+
+int main(int argc, char** argv) {
+ if (argc < 2) return 2;
+ fs::create_directories(argv[1]);
+ const auto base = fs::canonical(argv[1]);
+ const std::uint16_t wanted = argc > 2 ? static_cast<std::uint16_t>(std::atoi(argv[2])) : 0;
+
+ const auto bottle = [&](const std::string& id) { return base / "games" / id / "library/prefixes/game"; };
+ const auto gta = bottle("steam-12210");
+ Put(gta / "drive_c/users/prospero/Documents/Rockstar Games/GTA IV/Profiles/7A3C91F0/SGTA400", std::string(512 * 1024, 's'));
+ Put(gta / "drive_c/users/prospero/Documents/Rockstar Games/GTA IV/Profiles/7A3C91F0/cfg.set", "config");
+ Put(gta / "drive_c/users/prospero/AppData/Roaming/settings.ini", "[video]\nvsync=1\n");
+ fs::create_directories(gta / "drive_c/ProgramData");
+ const auto gta_folder = base / "usb/playden-games/steam-12210";
+ Put(gta_folder / "GTAIV.exe", "exe");
+ Put(gta_folder / "autoexec.cfg", "fps_max 60\n");
+ Put(gta_folder / "steam_settings/configs.user.ini", "[user::general]\naccount_name=Player\n");
+ Put(gta_folder / ".playden-install.json", "{}");
+ const auto wolverine = bottle("local-3fa9c1");
+ fs::create_directories(wolverine / "drive_c/users/prospero/Documents");
+ const auto wolverine_folder = base / "usb/playden/import/Wolverine";
+ Put(wolverine_folder / "Binaries/Wolverine.exe", "exe");
+ Put(wolverine_folder / "Support/DirectX/DXSETUP.exe", "dx");
+ const auto darkwood = bottle("steam-274520");
+ Put(darkwood / "drive_c/users/prospero/AppData/LocalLow/Acid Wizard Studio/Darkwood/save.dat", "kept");
+
+ FileCatalog catalog;
+ catalog.known = true;
+ {
+ FileGame game;
+ game.id = "steam-12210";
+ game.name = "Grand Theft Auto IV";
+ game.kind = "steam";
+ game.app = 12210;
+ game.bottle = gta.string();
+ game.game_folder = gta_folder.string();
+ game.game_folder_shown = "/mnt/usb0/playden-games/steam-12210";
+ game.drive = "usb";
+ game.windows_user_bytes = 18'000'000;
+ game.last_played = 1793700000;
+ catalog.games.push_back(game);
+ game = {};
+ game.id = "local-3fa9c1";
+ game.name = "X-Men Origins - Wolverine";
+ game.kind = "imported";
+ game.bottle = wolverine.string();
+ game.game_folder = wolverine_folder.string();
+ game.game_folder_shown = "/mnt/usb0/playden/import/Wolverine";
+ game.drive = "usb";
+ game.physx_needed = "2.8.1";
+ catalog.games.push_back(game);
+ game = {};
+ game.id = "steam-1091500";
+ game.name = "Cyberpunk 2077";
+ game.kind = "steam";
+ game.app = 1091500;
+ game.bottle = bottle("steam-1091500").string();
+ game.drive = "usb";
+ game.game_folder = (base / "absent").string();
+ game.game_folder_shown = "/mnt/usb0/absent";
+ game.drive_absent = true;
+ game.running = true;
+ game.cloud = true;
+ catalog.games.push_back(game);
+ game = {};
+ game.id = "steam-274520";
+ game.name = "Darkwood";
+ game.kind = "steam";
+ game.app = 274520;
+ game.bottle = darkwood.string();
+ game.installed = false;
+ game.cloud = true;
+ catalog.games.push_back(game);
+ }
+ fs::create_directories(bottle("steam-1091500") / "drive_c/users/prospero");
+
+ ServiceConfig config;
+ config.paths = {(base / "logs").string(), (base / "homebrew").string(), (base / "kits").string(), (base / "app").string()};
+ fs::create_directories(base / "logs");
+ config.server.first_port = config.server.last_port = wanted;
+ config.server.loopback_only = true;
+ Service service(std::move(config));
+ service.SetFileCatalog(catalog);
+ service.SetEnabled(true);
+ std::string shown;
+ bool reported = false;
+ while (true) {
+ const auto snapshot = service.Snapshot();
+ if (!reported && snapshot.state == ServiceSnapshot::State::kOn) {
+ std::printf("port=%u\n", snapshot.port);
+ std::fflush(stdout);
+ reported = true;
+ }
+ if (snapshot.state == ServiceSnapshot::State::kFailed) {
+ std::fprintf(stderr, "%s\n", snapshot.error.c_str());
+ return 1;
+ }
+ if (snapshot.pairing_code != shown) {
+ shown = snapshot.pairing_code;
+ if (!shown.empty()) {
+ std::printf("code=%s\n", shown.c_str());
+ std::fflush(stdout);
+ }
+ }
+ std::this_thread::sleep_for(std::chrono::milliseconds(20));
+ }
+}