diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index d18f211..9c90292 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -19,17 +19,11 @@ jobs: steps: - name: Checkout uses: actions/checkout@v7 - - - name: Check out WebViewWindow - uses: actions/checkout@v7 with: - repository: gwdevhub/WebViewWindow - path: WebViewWindow + submodules: true - name: Build both targets in Docker run: bash build.sh all - env: - WEBVIEW_WINDOW_DIR: ${{ github.workspace }}/WebViewWindow - name: Upload the built programs uses: actions/upload-artifact@v7 diff --git a/.gitignore b/.gitignore index 64e46df..628b823 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,3 @@ build/ bin/ .idea/ - -# WebViewWindow checked out beside this repo in CI, which is not part of this repo. -/WebViewWindow/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..8420b93 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "WebViewWindow"] + path = WebViewWindow + url = https://github.com/gwdevhub/WebViewWindow.git diff --git a/CMakeLists.txt b/CMakeLists.txt index ba1833e..1edd776 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,8 +5,8 @@ set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) -# WebViewWindow is a sibling checkout by default. Point this at another checkout if it lives elsewhere. -set(WEBVIEW_WINDOW_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../WebViewWindow" CACHE PATH "Path to the WebViewWindow checkout") +# WebViewWindow is the git submodule in this folder by default. Point this at another checkout if it lives elsewhere. +set(WEBVIEW_WINDOW_DIR "${CMAKE_CURRENT_SOURCE_DIR}/WebViewWindow" CACHE PATH "Path to the WebViewWindow checkout") set(WEBVIEW_WINDOW_BUILD_EXAMPLE OFF CACHE BOOL "" FORCE) add_subdirectory("${WEBVIEW_WINDOW_DIR}" WebViewWindow) @@ -41,6 +41,7 @@ add_executable(discord_webview src/Sha256.cpp src/UpdateCheck.cpp src/main.cpp + src/Downloads.cpp src/PagePermissions.cpp ${DW_HOST} ) @@ -66,4 +67,8 @@ if(DW_BUILD_TESTS) target_include_directories(permission_policy_test PRIVATE src) target_link_libraries(permission_policy_test PRIVATE webview_window) add_test(NAME permission_policy COMMAND permission_policy_test) + + add_executable(downloads_test tests/Downloads_test.cpp src/Downloads.cpp) + target_include_directories(downloads_test PRIVATE src) + add_test(NAME downloads COMMAND downloads_test) endif() diff --git a/README.md b/README.md index e42dc81..eae914d 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,8 @@ contains none of Discord's code: the page is loaded from discord.com at run time ## Build -Needs Docker. The WebViewWindow checkout is expected next to this one (`../WebViewWindow`); point `WEBVIEW_WINDOW_DIR` at another -checkout if it lives elsewhere. +Needs Docker. WebViewWindow is a git submodule in `WebViewWindow/`, so clone with `--recurse-submodules` (or run +`git submodule update --init` after cloning). Point `WEBVIEW_WINDOW_DIR` at another checkout if it lives elsewhere. ./build.sh [linux|windows|all] diff --git a/WebViewWindow b/WebViewWindow new file mode 160000 index 0000000..b4b56f1 --- /dev/null +++ b/WebViewWindow @@ -0,0 +1 @@ +Subproject commit b4b56f1cd1d3ba0fedf8a96dc408fc1912851042 diff --git a/build.sh b/build.sh index 4b9cd91..00868d6 100644 --- a/build.sh +++ b/build.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # Builds the program in Docker into bin/: build.sh [linux|windows|all] -# WebViewWindow is read from WEBVIEW_WINDOW_DIR, which defaults to a checkout beside this one. +# WebViewWindow is read from WEBVIEW_WINDOW_DIR, which defaults to the submodule in this repo's WebViewWindow folder. set -euo pipefail target="${1:-all}" @@ -12,9 +12,9 @@ case "$target" in esac root="$(cd "$(dirname "$0")" && pwd)" -webview_window_dir="${WEBVIEW_WINDOW_DIR:-$root/../WebViewWindow}" +webview_window_dir="${WEBVIEW_WINDOW_DIR:-$root/WebViewWindow}" if [ ! -f "$webview_window_dir/CMakeLists.txt" ]; then - echo "WebViewWindow isn't at $webview_window_dir. Check it out there, or set WEBVIEW_WINDOW_DIR to its folder." >&2 + echo "WebViewWindow isn't at $webview_window_dir. Run: git submodule update --init, or set WEBVIEW_WINDOW_DIR to its folder." >&2 exit 1 fi diff --git a/docs/MISSING_FEATURES.md b/docs/MISSING_FEATURES.md index 907c0a2..5a602a0 100644 --- a/docs/MISSING_FEATURES.md +++ b/docs/MISSING_FEATURES.md @@ -37,8 +37,8 @@ are the keys of that object. The main-process side of the channels (`bundle.js`) | Feature | Discord bridge | Status | | --- | --- | --- | -| Desktop notifications | `ipc`: `NOTIFICATION_SHOW`, `NOTIFICATION_CLOSE`, `NOTIFICATIONS_*` | Partial: the page's Notification API is allowed for discord.com, so `Notification.permission` is `granted`. Nothing from the `ipc` channels is used, so the notifications are the WebView's own. | -| Unread badge on the taskbar or dock | `ipc`: `APP_SET_BADGE_COUNT`, `APP_DOCK_SET_BADGE`, `APP_DOCK_BOUNCE` | Missing. | +| Desktop notifications | `ipc`: `NOTIFICATION_SHOW`, `NOTIFICATION_CLOSE`, `NOTIFICATIONS_*` | Done on Linux: the page's Notification API is allowed for discord.com, and WebKitGTK presents the notification to the desktop (`WebViewWindow/tests/linux_notification_test.sh` watches the session bus for it). Windows: not checked. The `ipc` channels aren't used; WebKit and WebView2 present the notifications themselves. | +| Unread badge on the taskbar or dock | `app.setBadgeCount` (`APP_SET_BADGE_COUNT`), `APP_DOCK_SET_BADGE`, `APP_DOCK_BOUNCE` | Missing. The desktop app sets a Windows taskbar overlay from the unread count: `win.setOverlayIcon(appIcons[n], "N notifications")` with one numbered icon for counts 1 to 10, cleared at zero. It also calls `app.setBadgeCount`. This program sets neither. The count is shown only in the custom title bar, from `document.title`. | | Tray icon state (unread, mute) | `ipc`: `SYSTEM_TRAY_SET_STATES`, `SYSTEM_TRAY_SET_ICON`, `SYSTEM_TRAY_SET_STRINGS` | Missing. The tray icon exists, but Discord doesn't update it. | | Taskbar progress and flash | `window.setProgressBar`, `window.flashFrame` | Missing. | | Windows taskbar thumbnail buttons | `thumbar.setThumbarButtons` | Missing (Windows only). | @@ -58,8 +58,8 @@ are the keys of that object. The main-process side of the channels (`bundle.js`) | Feature | Discord bridge | Status | | --- | --- | --- | -| Downloads saved to disk | (WebView download events) | Missing. Downloads aren't handled at all. | -| Open and save dialogs | `fileManager.showOpenDialog`, `saveWithDialog`, `showItemInFolder` | Missing. | +| Downloads saved to disk | (WebView download events) | Done: saved to the Downloads folder under the suggested name, never over an existing file (`tests/Downloads_test.cpp`; `WebViewWindow/tests/linux_download_test.sh` and `windows_download_test.ps1`). | +| Open and save dialogs | `fileManager.showOpenDialog`, `saveWithDialog`, `showItemInFolder` | Missing. The page can't reach a host dialog yet: see the bridge plan below. | | Native clipboard (images, files, cut) | `clipboard.copyImage`, `copyFile`, `cut`, `paste`, `read` | Missing. The web clipboard API is untested. | ## Settings, storage and system @@ -91,9 +91,12 @@ are the keys of that object. The main-process side of the channels (`bundle.js`) ## Plan -1. Permissions for microphone, camera and notifications, by a hook in WebViewWindow (done; the hook is only in the local checkout so far). -2. Downloads and the save dialog (`fileManager`). +1. Permissions for microphone, camera and notifications, by a hook in WebViewWindow. Done. +2. Downloads. Done. A save dialog would need a page-to-host call, which is item 6. 3. Settings and `safeStorage` through the host. 4. Badges and tray state from the page, through a bridge the page can call. 5. Voice and video. Needs a decision: the engine is a Node addon, so this either waits for a different approach or stays out of scope. +6. A bridge the page can call. Most of the features above need the web client to call `DiscordNative`, and it only does so when + the object exists. Providing it is a design decision: it would switch the web client into desktop mode, and each call it makes + would then need a real answer. This needs a decision before any more of the bridge is built. diff --git a/src/Application.cpp b/src/Application.cpp index 1dabe93..1f62325 100644 --- a/src/Application.cpp +++ b/src/Application.cpp @@ -81,6 +81,12 @@ void Application::run() { runEventLoop(); } +void Application::showDiscord() { + if (discord_) { + discord_->present(); + } +} + void Application::showTray() { trayShown_ = showTrayIcon( "Discord", [this] { discord_->present(); }, diff --git a/src/Application.h b/src/Application.h index 3ad378f..5e47246 100644 --- a/src/Application.h +++ b/src/Application.h @@ -46,6 +46,9 @@ class Application { // tray icon, checks for an update in the background, and runs until the Discord window closes. void run(); + // Brings the Discord window to the front, for a later start that was handed to this copy. + void showDiscord(); + // Settings. The choices are saved as they change. bool keepInTaskbar() const { return keepInTaskbar_; } bool trayShown() const { return trayShown_; } diff --git a/src/DiscordWindow.cpp b/src/DiscordWindow.cpp index becca47..5c4791f 100644 --- a/src/DiscordWindow.cpp +++ b/src/DiscordWindow.cpp @@ -8,6 +8,7 @@ #include "Application.h" #include "Host.h" #include "PageScript.h" +#include "Downloads.h" #include "PagePermissions.h" namespace { @@ -47,6 +48,17 @@ DiscordWindow::DiscordWindow(Application& app) : WebViewWindow(WindowOptions{ .hardwareAcceleration = HardwareAcceleration::Always, }), app_(app) { + // Downloads are saved to the Downloads folder, under the name the page suggests, and never over a file already there. + setDownloadChooser([](const std::string& name) -> std::optional { + const std::filesystem::path folder = downloadsFolder(); + try { + std::filesystem::create_directories(folder); + } catch (const std::exception&) { + // Without the folder the platform's default is used. + return std::nullopt; + } + return uniqueDownloadPath(folder, name); + }); auto& methods = handler(); methods.on("moveDrag", [](WebViewWindow& window, const Json&, const Reply& reply) { window.beginMove(); diff --git a/src/Downloads.cpp b/src/Downloads.cpp new file mode 100644 index 0000000..69b4996 --- /dev/null +++ b/src/Downloads.cpp @@ -0,0 +1,43 @@ +#include "Downloads.h" + +#include + +#ifdef _WIN32 +#include +#define DW_TEXT(text) L##text +#else +#define DW_TEXT(text) text +#endif + +std::filesystem::path downloadsFolder() { +#ifdef _WIN32 + const wchar_t* home = _wgetenv(L"USERPROFILE"); +#else + const char* home = std::getenv("HOME"); +#endif + if (!home || !*home) { + return std::filesystem::path("Downloads"); + } + return std::filesystem::path(home) / "Downloads"; +} + +std::filesystem::path uniqueDownloadPath(const std::filesystem::path& folder, const std::string& suggestedName) { + std::filesystem::path name = std::filesystem::path(suggestedName).filename(); + if (name.empty() || name == "." || name == "..") { + name = "download"; + } + std::filesystem::path candidate = folder / name; + // The numbered names keep the original's stem and extension: "archive.tar" becomes "archive.tar (1).gz" for "archive.tar.gz". + const std::filesystem::path::string_type stem = name.stem().native(); + const std::filesystem::path::string_type extension = name.extension().native(); + for (int number = 1; std::filesystem::exists(candidate); ++number) { + std::filesystem::path::string_type numbered = stem; + numbered += DW_TEXT(" ("); + const std::string digits = std::to_string(number); + numbered += std::filesystem::path::string_type(digits.begin(), digits.end()); + numbered += DW_TEXT(")"); + numbered += extension; + candidate = folder / numbered; + } + return candidate; +} diff --git a/src/Downloads.h b/src/Downloads.h new file mode 100644 index 0000000..8cabd99 --- /dev/null +++ b/src/Downloads.h @@ -0,0 +1,14 @@ +// Where Discord's downloads are saved: the user's Downloads folder, under the name the page suggests, without replacing a file that's +// already there. +#pragma once + +#include +#include + +// The user's Downloads folder. +std::filesystem::path downloadsFolder(); + +// A path in folder for a file called suggestedName that isn't already there: the name itself, or "name (1)", "name (2)" and so on +// when it is. The name is reduced to its file name, so a page can't choose a folder, and an empty name is saved as "download". +// Nothing is created. +std::filesystem::path uniqueDownloadPath(const std::filesystem::path& folder, const std::string& suggestedName); diff --git a/src/Host.h b/src/Host.h index 75ab103..b3d2697 100644 --- a/src/Host.h +++ b/src/Host.h @@ -3,6 +3,7 @@ #pragma once #include +#include #include // Opens a web address in the default browser. The address is never run through a shell. @@ -10,3 +11,13 @@ void launchUrl(const std::string& url); // The folder the program keeps its settings in. std::filesystem::path settingsFolder(); + +// One copy runs at a time. A start that finds one running asks it to show its window and then ends. True when the running copy +// answered, so this start should stop; false when none did, so this start carries on as the program. +bool forwardShowRequest(); + +// Accepts show requests from later starts on a thread, and calls handle on that thread for each one. +void listenForShowRequests(std::function handle); + +// Stops answering later starts, so a copy started after this call runs instead of being handed to this one. +void stopListeningForShowRequests(); diff --git a/src/Host.linux.cpp b/src/Host.linux.cpp index 6fc3e69..2a34cd0 100644 --- a/src/Host.linux.cpp +++ b/src/Host.linux.cpp @@ -2,15 +2,20 @@ // itself, which already loads GTK. #include +#include +#include +#include #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -19,11 +24,123 @@ #include #include +#include "Host.h" #include "UpdateCheck.h" #include "WebViewWindow.h" extern char** environ; +namespace { + +// The socket a running copy listens on, in the settings folder. +std::filesystem::path showSocketPath() { + return settingsFolder() / "discord-webview.sock"; +} + +// The listening socket, so stopListeningForShowRequests can end its accept. -1 when this copy isn't listening. +std::atomic listeningSocket{-1}; + +// The address for the socket path, or false when the path is too long for one. +bool showSocketAddress(const std::string& path, sockaddr_un& address) { + if (path.size() >= sizeof(address.sun_path)) { + return false; + } + address = sockaddr_un{}; + address.sun_family = AF_UNIX; + std::memcpy(address.sun_path, path.c_str(), path.size() + 1); + return true; +} + +} // namespace + +bool forwardShowRequest() { + sockaddr_un address{}; + if (!showSocketAddress(showSocketPath().string(), address)) { + return false; + } + const int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (fd < 0) { + return false; + } + bool sent = connect(fd, reinterpret_cast(&address), sizeof(address)) == 0; + if (sent) { + static const char request[] = "show\n"; + sent = send(fd, request, sizeof(request) - 1, MSG_NOSIGNAL) == static_cast(sizeof(request) - 1); + } + if (sent) { + // The running copy answers "ok" once it has taken the request. Without that, nothing is listening, and this copy carries on. + timeval wait{2, 0}; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &wait, sizeof(wait)); + char reply[8] = {}; + const ssize_t received = recv(fd, reply, sizeof(reply) - 1, 0); + sent = received >= 2 && std::string(reply, static_cast(received)).rfind("ok", 0) == 0; + } + close(fd); + return sent; +} + +void listenForShowRequests(std::function handle) { + const std::filesystem::path path = showSocketPath(); + sockaddr_un address{}; + if (!showSocketAddress(path.string(), address)) { + std::fprintf(stderr, "could not listen for other starts: the path is too long\n"); + return; + } + std::error_code ignored; + std::filesystem::create_directories(path.parent_path(), ignored); + const int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (fd < 0) { + return; + } + // Nothing answered forwardShowRequest, so a socket left by a copy that exited is replaced. + unlink(path.c_str()); + if (bind(fd, reinterpret_cast(&address), sizeof(address)) != 0 || listen(fd, 8) != 0) { + std::fprintf(stderr, "could not listen for other starts\n"); + close(fd); + return; + } + listeningSocket = fd; + std::thread([fd, handle = std::move(handle)] { + for (;;) { + const int client = accept4(fd, nullptr, nullptr, SOCK_CLOEXEC); + if (client < 0) { + if (errno == EINTR) { + continue; + } + break; + } + // A client that connects and says nothing gives up after two seconds, so it can't hold up the next one. + timeval wait{2, 0}; + setsockopt(client, SOL_SOCKET, SO_RCVTIMEO, &wait, sizeof(wait)); + std::string line; + char buffer[64]; + ssize_t received = 0; + while (line.find('\n') == std::string::npos && line.size() < sizeof(buffer) && + (received = recv(client, buffer, sizeof(buffer), 0)) > 0) { + line.append(buffer, static_cast(received)); + } + const bool show = line == "show\n"; + if (show) { + send(client, "ok\n", 3, MSG_NOSIGNAL); + } + close(client); + if (show) { + handle(); + } + } + close(fd); + }).detach(); +} + +void stopListeningForShowRequests() { + const int fd = listeningSocket.exchange(-1); + if (fd >= 0) { + // Ends the accept in the listener, which then closes the socket. + shutdown(fd, SHUT_RDWR); + } + unlink(showSocketPath().c_str()); +} + void showError(const std::string& message) { std::fprintf(stderr, "%s\n", message.c_str()); } diff --git a/src/Host.windows.cpp b/src/Host.windows.cpp index 6454684..51428ee 100644 --- a/src/Host.windows.cpp +++ b/src/Host.windows.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -11,7 +12,9 @@ #include #include #include +#include +#include "Host.h" #include "UpdateCheck.h" #include "WebViewWindow.h" @@ -29,8 +32,106 @@ std::wstring toWide(const std::string& text) { return wide; } +// The pipe a running copy listens on. It's per user, so each user's copy takes that user's starts. +std::wstring showPipeName() { + wchar_t user[256] = {}; + DWORD size = sizeof(user) / sizeof(user[0]); + std::wstring name = L"\\\\.\\pipe\\DiscordWebView-"; + if (GetUserNameW(user, &size)) { + name += user; + } + return name; +} + +// Set by stopListeningForShowRequests. A listener that finds it set closes its pipe and ends. +std::atomic listenerStopped{false}; + +// One line, up to its newline. False when the pipe closes or fails first. +bool readShowLine(HANDLE pipe, std::string& line) { + char buffer[64]; + while (line.find('\n') == std::string::npos && line.size() < sizeof(buffer)) { + DWORD read = 0; + if (!ReadFile(pipe, buffer, sizeof(buffer), &read, nullptr) || read == 0) { + return false; + } + line.append(buffer, read); + } + return true; +} + } // namespace +bool forwardShowRequest() { + const std::wstring name = showPipeName(); + // No pipe means no running copy, and a busy one is waited for. + if (!WaitNamedPipeW(name.c_str(), 2000)) { + return false; + } + HANDLE pipe = CreateFileW(name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr); + if (pipe == INVALID_HANDLE_VALUE) { + return false; + } + // The running copy answers "ok" once it has taken the request. Without that, nothing is listening, and this copy carries on. + static const char request[] = "show\n"; + DWORD written = 0; + bool sent = WriteFile(pipe, request, sizeof(request) - 1, &written, nullptr) && written == sizeof(request) - 1; + std::string reply; + sent = sent && readShowLine(pipe, reply) && reply.rfind("ok", 0) == 0; + CloseHandle(pipe); + return sent; +} + +void listenForShowRequests(std::function handle) { + const std::wstring name = showPipeName(); + std::thread([name, handle = std::move(handle)] { + bool first = true; + for (;;) { + // Only the first pipe can be made by this copy; a copy that finds it taken is listened to by the one that made it. + const DWORD openMode = PIPE_ACCESS_DUPLEX | (first ? FILE_FLAG_FIRST_PIPE_INSTANCE : 0); + HANDLE pipe = CreateNamedPipeW(name.c_str(), openMode, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, + 512, 512, 2000, nullptr); + if (pipe == INVALID_HANDLE_VALUE) { + if (first) { + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + continue; + } + first = false; + // Checked once the pipe exists, so the connection that wakes a stopped listener finds it. + if (listenerStopped) { + CloseHandle(pipe); + break; + } + if (!ConnectNamedPipe(pipe, nullptr) && GetLastError() != ERROR_PIPE_CONNECTED) { + CloseHandle(pipe); + continue; + } + std::string line; + const bool show = readShowLine(pipe, line) && line == "show\n"; + if (show) { + DWORD written = 0; + WriteFile(pipe, "ok\n", 3, &written, nullptr); + FlushFileBuffers(pipe); + } + DisconnectNamedPipe(pipe); + CloseHandle(pipe); + if (show) { + handle(); + } + } + }).detach(); +} + +void stopListeningForShowRequests() { + listenerStopped = true; + // A listener waiting for a start is woken by this connection, and then sees that it's stopped. + HANDLE wake = CreateFileW(showPipeName().c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr); + if (wake != INVALID_HANDLE_VALUE) { + CloseHandle(wake); + } +} + void showError(const std::string& message) { std::fprintf(stderr, "%s\n", message.c_str()); MessageBoxA(nullptr, message.c_str(), applicationName().c_str(), MB_OK | MB_ICONERROR); diff --git a/src/main.cpp b/src/main.cpp index 229e62a..b4f0720 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -11,6 +11,10 @@ int main() { try { + // A copy that's already running is asked to show its window, and this start ends. + if (forwardShowRequest()) { + return 0; + } setApplicationName("Discord"); setApplicationIcon(kAppIconPng); initializeWindowing(); @@ -19,7 +23,11 @@ int main() { removeUpdateLeftovers(current); } Application app; + // Listening starts before the window opens, so a start made while it's opening is handed over too. Each request is passed + // to the window's thread. + listenForShowRequests([&app] { runOnUiThread([&app] { app.showDiscord(); }); }); app.run(); + stopListeningForShowRequests(); } catch (const RuntimeMissingError&) { // The dialog has already said what's missing. return 1; diff --git a/tests/Downloads_test.cpp b/tests/Downloads_test.cpp new file mode 100644 index 0000000..e015b2a --- /dev/null +++ b/tests/Downloads_test.cpp @@ -0,0 +1,70 @@ +// Unit tests for where downloads are saved. Exits with 1 when a check fails, and prints each failure. +#include +#include +#include +#include + +#include "Downloads.h" + +namespace fs = std::filesystem; + +namespace { + +int failures = 0; + +void expectPath(const fs::path& got, const fs::path& want, const std::string& label) { + if (got != want) { + std::printf("FAIL: %s gave %s, want %s\n", label.c_str(), got.string().c_str(), want.string().c_str()); + ++failures; + } +} + +void touch(const fs::path& path) { + std::ofstream(path) << "existing"; +} + +} // namespace + +int main() { + const fs::path folder = fs::temp_directory_path() / "discordwebview-downloads-test"; + fs::remove_all(folder); + fs::create_directories(folder); + + // A name that isn't there yet is used as it is, and nothing is created. + expectPath(uniqueDownloadPath(folder, "hello.txt"), folder / "hello.txt", "a free name"); + if (fs::exists(folder / "hello.txt")) { + std::printf("FAIL: uniqueDownloadPath created the file\n"); + ++failures; + } + + // A name already there gets a number, and the numbers go on from there. + touch(folder / "hello.txt"); + expectPath(uniqueDownloadPath(folder, "hello.txt"), folder / "hello (1).txt", "a taken name"); + touch(folder / "hello (1).txt"); + expectPath(uniqueDownloadPath(folder, "hello.txt"), folder / "hello (2).txt", "a second taken name"); + + // The number goes before the last extension, so a double extension stays together. + touch(folder / "archive.tar.gz"); + expectPath(uniqueDownloadPath(folder, "archive.tar.gz"), folder / "archive.tar (1).gz", "a double extension"); + + // The page can't choose a folder: only the file name is used. + expectPath(uniqueDownloadPath(folder, "../../escape.txt"), folder / "escape.txt", "a name with folders"); + + // A name with nothing usable is saved as "download". + expectPath(uniqueDownloadPath(folder, ""), folder / "download", "an empty name"); + expectPath(uniqueDownloadPath(folder, ".."), folder / "download", "a parent folder name"); + + // The Downloads folder is the user's, and is named Downloads. + if (downloadsFolder().filename() != "Downloads") { + std::printf("FAIL: downloadsFolder() is %s\n", downloadsFolder().string().c_str()); + ++failures; + } + + fs::remove_all(folder); + if (failures == 0) { + std::printf("All download checks passed.\n"); + return 0; + } + std::printf("%d download check(s) failed.\n", failures); + return 1; +}