Files
hrynco-kswitcher/src/google_drive.cpp
T

680 lines
28 KiB
C++

#include <winsock2.h>
#include <ws2tcpip.h>
#include <bcrypt.h>
#include <wincrypt.h>
#include <wincred.h>
#include <shellapi.h>
#include <objbase.h>
#include "google_drive.h"
#include "sync.h"
#include "google_drive_oauth.h"
#include "http_handle.h"
#include "json.hpp"
#if __has_include("google_drive_oauth_config.h")
#include "google_drive_oauth_config.h"
#endif
#include <array>
#include <charconv>
#include <initializer_list>
#include <string_view>
namespace ks
{
namespace
{
using Json = nlohmann::json;
constexpr std::string_view Scope = "https://www.googleapis.com/auth/drive.appdata";
constexpr auto TokenHost = L"oauth2.googleapis.com";
constexpr auto DriveHost = L"www.googleapis.com";
constexpr auto NativeName = "kswitcher-win32-settings.json";
constexpr auto PreviewName = "kswitcher-settings.json";
constexpr auto SyncName = "kswitcher-win32-sync-v1.json";
constexpr auto Reconnect = "Google Drive needs authorization again. Reconnect your Google account.";
constexpr auto Network = "Could not reach Google Drive. Check your connection and try again.";
#ifdef KS_GOOGLE_CLIENT_ID
constexpr std::string_view ClientId = KS_GOOGLE_CLIENT_ID, ClientSecret = KS_GOOGLE_CLIENT_SECRET;
#else
constexpr std::string_view ClientId, ClientSecret;
#endif
void requireConfiguration()
{
if (!googleDriveConfigured()) throw std::runtime_error("Google Drive is unavailable in this build.");
}
std::wstring credentialName()
{
return L"KSwitcher.GoogleDrive/" + wide(std::string(ClientId));
}
std::string refreshToken()
{
PCREDENTIALW raw{};
if (!CredReadW(credentialName().c_str(), CRED_TYPE_GENERIC, 0, &raw))
{
if (GetLastError() == ERROR_NOT_FOUND) return {};
throw std::runtime_error("Could not read the Google Drive connection from Windows Credential Manager.");
}
struct Credential
{
PCREDENTIALW value;
~Credential()
{
if (value->CredentialBlobSize) SecureZeroMemory(value->CredentialBlob, value->CredentialBlobSize);
CredFree(value);
}
} credential{raw};
if (!raw->CredentialBlobSize) return {};
return {reinterpret_cast<const char *>(raw->CredentialBlob), raw->CredentialBlobSize};
}
void saveRefreshToken(std::string &token)
{
if (token.empty() || token.size() > CRED_MAX_CREDENTIAL_BLOB_SIZE)
throw std::runtime_error("Google did not return a usable offline connection. Reconnect and allow access.");
auto target = credentialName();
CREDENTIALW credential{};
credential.Type = CRED_TYPE_GENERIC;
credential.TargetName = target.data();
credential.CredentialBlobSize = static_cast<DWORD>(token.size());
credential.CredentialBlob = reinterpret_cast<LPBYTE>(token.data());
credential.Persist = CRED_PERSIST_LOCAL_MACHINE;
if (!CredWriteW(&credential, 0))
throw std::runtime_error("Could not save the Google Drive connection in Windows Credential Manager.");
}
std::string urlEncode(std::string_view value)
{
constexpr char hex[] = "0123456789ABCDEF";
std::string result;
for (unsigned char c : value)
{
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
c == '-' || c == '_' || c == '.' || c == '~') result += static_cast<char>(c);
else
{
result += '%';
result += hex[c >> 4];
result += hex[c & 15];
}
}
return result;
}
std::string form(std::initializer_list<std::pair<std::string_view, std::string_view>> fields)
{
std::string result;
for (const auto &[key, value] : fields)
{
if (!result.empty()) result += '&';
result += key;
result += '=';
result += urlEncode(value);
}
return result;
}
std::optional<std::string> urlDecode(std::string_view value)
{
auto digit = [](char c)
{
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
};
std::string result;
while (!value.empty())
{
const char c = value.front();
value.remove_prefix(1);
if (c != '%') result += (c == '+' ? ' ' : c);
else
{
if (value.size() < 2 || digit(value[0]) < 0 || digit(value[1]) < 0) return {};
result += static_cast<char>(digit(value[0]) * 16 + digit(value[1]));
value.remove_prefix(2);
}
}
return result;
}
std::string base64Url(const std::array<unsigned char, 32> &data)
{
std::array<char, 45> encoded{};
DWORD length = static_cast<DWORD>(encoded.size());
if (!CryptBinaryToStringA(data.data(), static_cast<DWORD>(data.size()),
CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, encoded.data(), &length))
throw std::runtime_error("Could not start a secure Google connection.");
std::string result(encoded.data(), length);
for (char &c : result)
{
if (c == '/') c = '_';
if (c == '+') c = '-';
}
result.resize(result.find('='));
return result;
}
std::string randomParameter()
{
std::array<unsigned char, 32> data{};
if (BCryptGenRandom(nullptr, data.data(), static_cast<ULONG>(data.size()), BCRYPT_USE_SYSTEM_PREFERRED_RNG) < 0)
throw std::runtime_error("Could not start a secure Google connection.");
return base64Url(data);
}
}
std::string google_drive_oauth::challengeFor(const std::string &verifier)
{
BCRYPT_ALG_HANDLE algorithm{};
if (BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA256_ALGORITHM, nullptr, 0) < 0)
throw std::runtime_error("Could not start a secure Google connection.");
std::array<unsigned char, 32> hash{};
const auto status = BCryptHash(algorithm, nullptr, 0,
reinterpret_cast<PUCHAR>(const_cast<char *>(verifier.data())), static_cast<ULONG>(verifier.size()),
hash.data(), static_cast<ULONG>(hash.size()));
BCryptCloseAlgorithmProvider(algorithm, 0);
if (status < 0) throw std::runtime_error("Could not start a secure Google connection.");
return base64Url(hash);
}
namespace
{
struct HttpResponse { DWORD status{}; Bytes body; };
HttpResponse https(const wchar_t *host, const wchar_t *method, const std::wstring &path,
const std::wstring &headers, std::string &payload, size_t limit)
{
HttpHandle session{WinHttpOpen(L"KSwitcher Google Drive/1", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0)};
if (!session.h || !WinHttpSetTimeouts(session.h, 5000, 5000, 10000, 10000))
throw std::runtime_error(Network);
HttpHandle connection{WinHttpConnect(session.h, host, INTERNET_DEFAULT_HTTPS_PORT, 0)};
HttpHandle request{connection.h ? WinHttpOpenRequest(connection.h, method, path.c_str(), nullptr,
WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE) : nullptr};
DWORD redirects = WINHTTP_OPTION_REDIRECT_POLICY_NEVER;
DWORD disable = WINHTTP_DISABLE_COOKIES | WINHTTP_DISABLE_AUTHENTICATION;
if (!request.h ||
!WinHttpSetOption(request.h, WINHTTP_OPTION_REDIRECT_POLICY, &redirects, sizeof(redirects)) ||
!WinHttpSetOption(request.h, WINHTTP_OPTION_DISABLE_FEATURE, &disable, sizeof(disable)) ||
!WinHttpSendRequest(request.h, headers.c_str(), static_cast<DWORD>(headers.size()),
payload.empty() ? WINHTTP_NO_REQUEST_DATA : payload.data(), static_cast<DWORD>(payload.size()),
static_cast<DWORD>(payload.size()), 0) ||
!WinHttpReceiveResponse(request.h, nullptr))
throw std::runtime_error(Network);
HttpResponse response;
DWORD length = sizeof(response.status);
if (!WinHttpQueryHeaders(request.h, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX, &response.status, &length, WINHTTP_NO_HEADER_INDEX))
throw std::runtime_error(Network);
if (response.status < 200 || response.status >= 300) return response;
const auto deadline = GetTickCount64() + 30000;
for (;;)
{
unsigned char buffer[8192];
DWORD count{};
if (GetTickCount64() >= deadline || !WinHttpReadData(request.h, buffer, sizeof(buffer), &count))
throw std::runtime_error(Network);
if (!count) return response;
if (count > limit - response.body.size())
throw std::runtime_error(limit == GoogleDriveBackupLimit ? "This Drive backup exceeds the 2 MiB limit." :
"Google returned an oversized response.");
response.body.insert(response.body.end(), buffer, buffer + count);
}
}
struct ClearString
{
std::string &value;
~ClearString() { if (!value.empty()) SecureZeroMemory(value.data(), value.size()); }
};
struct Tokens { std::string access, refresh; };
Tokens requestTokens(std::string payload)
{
ClearString clear{payload};
payload += "&" + form({{"client_id", ClientId}, {"client_secret", ClientSecret}});
auto response = https(TokenHost, L"POST", L"/token", L"Content-Type: application/x-www-form-urlencoded\r\n",
payload, 64 * 1024);
if (response.status == 400 || response.status == 401 || response.status == 403)
throw std::runtime_error(Reconnect);
if (response.status < 200 || response.status >= 300)
throw std::runtime_error("Google could not authorize the connection. Try again.");
const auto data = Json::parse(response.body, nullptr, false);
if (!response.body.empty()) SecureZeroMemory(response.body.data(), response.body.size());
try
{
Tokens tokens{data.at("access_token").get<std::string>(), data.value("refresh_token", "")};
if (tokens.access.empty() || tokens.access.find_first_not_of(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~+/=") != std::string::npos)
throw std::runtime_error("Invalid Google access token.");
return tokens;
}
catch (const std::exception &)
{
throw std::runtime_error("Google returned an invalid authorization response.");
}
}
struct Winsock
{
Winsock()
{
WSADATA data{};
if (WSAStartup(MAKEWORD(2, 2), &data)) throw std::runtime_error("Could not open a local sign-in callback.");
}
~Winsock() { WSACleanup(); }
};
struct Socket
{
SOCKET handle;
~Socket() { if (handle != INVALID_SOCKET) closesocket(handle); }
};
}
std::optional<std::string> google_drive_oauth::callbackCode(std::string_view request, std::string_view state)
{
constexpr std::string_view prefix = "GET /oauth/callback?";
const auto end = request.find(' ', prefix.size());
if (!request.starts_with(prefix) || end == std::string_view::npos) return {};
auto query = request.substr(prefix.size(), end - prefix.size());
std::optional<std::string> returnedState, code;
bool denied = false;
while (!query.empty())
{
const auto next = query.find('&');
const auto entry = query.substr(0, next);
const auto equals = entry.find('=');
if (equals != std::string_view::npos)
{
const auto key = entry.substr(0, equals);
const auto value = entry.substr(equals + 1);
if (key == "state")
{
if (returnedState) return {};
returnedState = urlDecode(value);
if (!returnedState) return {};
}
if (key == "code")
{
if (code) return {};
code = urlDecode(value);
if (!code) return {};
}
if (key == "error") denied = true;
}
if (next == std::string_view::npos) break;
query.remove_prefix(next + 1);
}
if (!returnedState || *returnedState != state) return {};
return denied ? std::string{} : code.value_or("");
}
namespace
{
void checkCanceled(std::stop_token stop)
{
if (stop.stop_requested()) throw std::runtime_error("Google sign-in was canceled.");
}
std::optional<std::string> readCallback(SOCKET socket, std::string_view state, std::stop_token stop)
{
const DWORD timeout = 200;
const auto timeoutValue = reinterpret_cast<const char *>(&timeout);
if (setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, timeoutValue, sizeof(timeout)) ||
setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, timeoutValue, sizeof(timeout))) return {};
const auto deadline = GetTickCount64() + 2000;
std::string request;
for (;;)
{
checkCanceled(stop);
if (GetTickCount64() >= deadline || request.size() >= 8192) return {};
char buffer[1024];
const auto count = recv(socket, buffer, static_cast<int>(sizeof(buffer)), 0);
if (count <= 0) return {};
request.append(buffer, count);
if (request.find("\r\n") != request.npos) break;
}
auto code = google_drive_oauth::callbackCode(request.substr(0, request.find("\r\n")), state);
const std::string message = !code ? "This sign-in response did not match KSwitcher." :
code->empty() ? "Google sign-in was canceled. Return to KSwitcher." : "Return to KSwitcher to finish signing in.";
const std::string reply = std::string(code ? "HTTP/1.1 200 OK" : "HTTP/1.1 400 Bad Request") +
"\r\nContent-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\nReferrer-Policy: no-referrer"
"\r\nConnection: close\r\nContent-Length: " + std::to_string(message.size()) + "\r\n\r\n" + message;
send(socket, reply.data(), static_cast<int>(reply.size()), 0);
return code;
}
std::string waitForCode(SOCKET listener, const std::string &state, std::stop_token stop)
{
const auto deadline = GetTickCount64() + 120000;
while (GetTickCount64() < deadline)
{
checkCanceled(stop);
fd_set readable;
FD_ZERO(&readable);
FD_SET(listener, &readable);
timeval interval{0, 200000};
const int ready = select(0, &readable, nullptr, nullptr, &interval);
if (!ready) continue;
Socket peer{ready == SOCKET_ERROR ? INVALID_SOCKET : accept(listener, nullptr, nullptr)};
if (peer.handle == INVALID_SOCKET) throw std::runtime_error("Could not receive the Google sign-in response.");
const auto code = readCallback(peer.handle, state, stop);
if (!code) continue;
if (code->empty()) throw std::runtime_error("Google sign-in was declined or canceled.");
return *code;
}
throw std::runtime_error("Google sign-in timed out. Connect again to retry.");
}
void checkDrive(DWORD status)
{
if (status == 401) throw std::runtime_error(Reconnect);
if (status == 403) throw std::runtime_error("Google Drive denied access. Reconnect or check your account's access.");
if (status == 404) throw std::runtime_error("The requested file is no longer available on Google Drive.");
if (status == 412) throw std::runtime_error("The Google Drive profile changed on another PC. Sync again.");
if (status < 200 || status >= 300) throw std::runtime_error("Google Drive could not complete the request. Try again.");
}
HttpResponse driveRequest(const wchar_t *method, const std::string &path, const std::string &access,
const std::wstring &contentType = {}, std::string payload = {}, size_t limit = 64 * 1024,
const std::wstring &additionalHeaders = {})
{
auto response = https(DriveHost, method, wide(path), L"Authorization: Bearer " + wide(access) + L"\r\n" +
(contentType.empty() ? L"" : L"Content-Type: " + contentType + L"\r\n") + additionalHeaders, payload, limit);
checkDrive(response.status);
return response;
}
std::string accessToken()
{
requireConfiguration();
auto refresh = refreshToken();
ClearString clear{refresh};
if (refresh.empty()) throw std::runtime_error(Reconnect);
return requestTokens(form({{"grant_type", "refresh_token"}, {"refresh_token", refresh}})).access;
}
struct DriveFile { std::string id; std::wstring created; };
DriveFile driveFile(const Json &file)
{
DriveFile result{file.at("id").get<std::string>(), wide(file.at("createdTime").get<std::string>())};
if (result.id.empty() || result.created.empty()) throw std::runtime_error("Incomplete backup metadata.");
return result;
}
Json driveFilePage(const std::string &access, const std::string &filter, size_t count,
std::string_view page, std::string_view fields)
{
const auto query = form({{"spaces", "appDataFolder"}, {"pageSize", std::to_string(count)},
{"orderBy", "createdTime desc"}, {"q", filter}, {"fields", fields}});
const auto response = driveRequest(L"GET", "/drive/v3/files?" + query +
(page.empty() ? "" : "&pageToken=" + urlEncode(page)), access);
auto data = Json::parse(response.body, nullptr, false);
if (!data.is_object() || !data.contains("files") || !data.at("files").is_array() ||
data.value("incompleteSearch", false))
throw std::runtime_error("Google Drive returned an unreadable file list.");
return data;
}
std::vector<DriveFile> matchingFiles(const std::string &access, const std::string &filter, size_t count)
{
std::vector<DriveFile> matches;
std::string page;
// Drive can return an empty page with a continuation token.
for (int i = 0; i < 20; ++i)
{
const auto data = driveFilePage(access, filter, count, page, "nextPageToken,incompleteSearch,files(id,createdTime)");
try
{
const auto &files = data.at("files").get_ref<const Json::array_t &>();
for (const auto &file : files)
{
matches.push_back(driveFile(file));
if (matches.size() == count) return matches;
}
page = data.value("nextPageToken", "");
if (page.empty()) return matches;
}
catch (const std::exception &)
{
throw std::runtime_error("Google Drive returned an unreadable backup list.");
}
}
throw std::runtime_error("Google Drive did not finish listing backups. Try again.");
}
DriveFile createDriveFile(const std::string &access, const std::string &name, const std::string &settings)
{
if (settings.size() > GoogleDriveBackupLimit) throw std::runtime_error("Settings exceed the 2 MiB Drive limit.");
const auto boundary = randomParameter();
const auto metadata = Json{{"name", name}, {"parents", Json::array({"appDataFolder"})}}.dump();
auto payload = "--" + boundary + "\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n" +
metadata + "\r\n--" + boundary + "\r\nContent-Type: application/json\r\n\r\n" +
settings + "\r\n--" + boundary + "--\r\n";
const auto response = driveRequest(L"POST", "/upload/drive/v3/files?uploadType=multipart&fields=id%2CcreatedTime",
access, L"multipart/related; boundary=" + wide(boundary), std::move(payload));
try { return driveFile(Json::parse(response.body, nullptr, false)); }
catch (const std::exception &) { throw std::runtime_error("Google Drive did not confirm the upload."); }
}
class GoogleDriveSync final : public SyncProvider
{
std::string access, name;
std::string file;
std::wstring etag;
uint64_t revision{};
std::string findProfile()
{
auto files = matchingFiles(access, "name = '" + name + "'", 2);
if (files.size() > 1) throw std::runtime_error("Multiple Google Drive sync profiles were found. Automatic sync is paused.");
return files.empty() ? std::string{} : urlEncode(files.front().id);
}
std::wstring revisionTag()
{
// Drive v2 exposes the ETag and enforces it on the media PUT.
const auto meta = driveRequest(L"GET", "/drive/v2/files/" + file + "?fields=etag", access);
const auto tag = Json::parse(meta.body).at("etag").get<std::string>();
if (tag.size() < 3 || tag.size() > 1024 || tag.front() != '"' || tag.back() != '"' ||
tag.find_first_of("\r\n") != tag.npos)
throw std::runtime_error("Google Drive returned an invalid sync revision.");
return wide(tag);
}
public:
GoogleDriveSync(std::string token, std::string profileName) : access(std::move(token)), name(std::move(profileName)) {}
~GoogleDriveSync() override { ClearString clear{access}; }
SyncDocument read() override
{
file = findProfile();
if (file.empty())
{
etag.clear();
revision = 0;
return {};
}
for (int attempt = 0; attempt < 3; ++attempt)
{
const auto before = revisionTag();
const auto media = driveRequest(L"GET", "/drive/v3/files/" + file + "?alt=media",
access, {}, {}, GoogleDriveBackupLimit);
etag = revisionTag();
if (before != etag) continue;
const auto profile = Json::parse(media.body, [](int depth, Json::parse_event_t, Json &)
{
if (depth > 32) throw std::runtime_error("Invalid Google Drive synchronization profile.");
return true;
});
if (profile.value("format", "") != "kswitcher-drive-sync-v1" ||
!profile.at("revision").is_number_unsigned())
throw std::runtime_error("Unsupported Google Drive synchronization profile.");
revision = profile.at("revision").get<uint64_t>();
if (!revision || revision == UINT64_MAX) throw std::runtime_error("Invalid Google Drive sync revision.");
const auto settings = profile.at("settings").dump();
return {revision, Bytes(settings.begin(), settings.end())};
}
throw std::runtime_error("The Google Drive profile changed during download. Sync again.");
}
uint64_t write(const Bytes &settings, uint64_t expectedRevision) override
{
if (revision != expectedRevision) throw std::runtime_error("The Google Drive profile changed. Sync again.");
const auto body = Json{{"format", "kswitcher-drive-sync-v1"}, {"revision", revision + 1},
{"settings", Json::parse(settings)}}.dump();
if (body.size() > GoogleDriveBackupLimit) throw std::runtime_error("Settings exceed the 2 MiB Drive limit.");
if (!revision)
{
if (!findProfile().empty()) throw std::runtime_error("Google Drive already has a sync profile. Sync again.");
createDriveFile(access, name, body);
findProfile();
}
else
{
driveRequest(L"PUT", "/upload/drive/v2/files/" + file + "?uploadType=media&fields=id", access,
L"application/json", body, 64 * 1024, L"If-Match: " + etag + L"\r\n");
}
return ++revision;
}
};
}
bool googleDriveConfigured()
{
return !ClientId.empty() && !ClientSecret.empty();
}
bool googleDriveConnected()
{
if (!googleDriveConfigured()) return false;
auto token = refreshToken();
ClearString clear{token};
return !token.empty();
}
std::string googleDriveCredentialKey()
{
auto token = refreshToken();
ClearString clear{token};
return token.empty() ? std::string{} : google_drive_oauth::challengeFor(token);
}
std::unique_ptr<SyncProvider> makeGoogleDriveSyncProvider()
{
return std::make_unique<GoogleDriveSync>(accessToken(), SyncName);
}
void connectGoogleDrive(std::stop_token stop)
{
requireConfiguration();
checkCanceled(stop);
Winsock winsock;
Socket listener{socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)};
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
int length = sizeof(address);
const BOOL exclusive = TRUE;
if (listener.handle == INVALID_SOCKET ||
setsockopt(listener.handle, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, reinterpret_cast<const char *>(&exclusive), sizeof(exclusive)) ||
bind(listener.handle, reinterpret_cast<const sockaddr *>(&address), length) ||
listen(listener.handle, SOMAXCONN) ||
getsockname(listener.handle, reinterpret_cast<sockaddr *>(&address), &length))
throw std::runtime_error("Could not open a local sign-in callback.");
const auto redirect = "http://127.0.0.1:" + std::to_string(ntohs(address.sin_port)) + "/oauth/callback";
const auto state = randomParameter();
const auto verifier = randomParameter();
const auto url = wide("https://accounts.google.com/o/oauth2/v2/auth?" + form({
{"client_id", ClientId}, {"redirect_uri", redirect}, {"response_type", "code"}, {"scope", Scope},
{"access_type", "offline"}, {"prompt", "consent select_account"}, {"state", state},
{"code_challenge", google_drive_oauth::challengeFor(verifier)}, {"code_challenge_method", "S256"}}));
const auto initialized = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
const auto opened = ShellExecuteW(nullptr, L"open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
if (SUCCEEDED(initialized)) CoUninitialize();
if (reinterpret_cast<INT_PTR>(opened) <= 32)
throw std::runtime_error("Could not open the system browser.");
auto code = waitForCode(listener.handle, state, stop);
ClearString clearCode{code};
checkCanceled(stop);
auto tokens = requestTokens(form({{"grant_type", "authorization_code"}, {"code", code},
{"redirect_uri", redirect}, {"code_verifier", verifier}}));
ClearString clearAccess{tokens.access}, clearRefresh{tokens.refresh};
checkCanceled(stop);
saveRefreshToken(tokens.refresh);
}
void disconnectGoogleDrive()
{
requireConfiguration();
if (!CredDeleteW(credentialName().c_str(), CRED_TYPE_GENERIC, 0) && GetLastError() != ERROR_NOT_FOUND)
throw std::runtime_error("Could not remove the Google Drive connection from Windows Credential Manager.");
}
GoogleDriveBackupPage listGoogleDriveBackups(std::string_view page)
{
auto access = accessToken();
ClearString clear{access};
const auto filter = std::string("name = '") + PreviewName + "' or name = '" + NativeName + "'";
std::string token(page);
// An empty page with a continuation token can occur before the end.
for (int attempt = 0; attempt < 20; ++attempt)
{
const auto data = driveFilePage(access, filter, 50, token,
"nextPageToken,incompleteSearch,files(id,createdTime,name,size)");
GoogleDriveBackupPage result;
try
{
result.nextPage = data.value("nextPageToken", "");
for (const auto &file : data.at("files"))
{
auto info = driveFile(file);
const auto name = file.at("name").get<std::string>();
if (name != NativeName && name != PreviewName) continue;
std::optional<uint64_t> size;
if (file.contains("size"))
{
const auto value = file.at("size").get<std::string>();
uint64_t parsed{};
const auto [end, error] = std::from_chars(value.data(), value.data() + value.size(), parsed);
if (error == std::errc{} && end == value.data() + value.size()) size = parsed;
}
result.backups.push_back({std::move(info.id), std::move(info.created), size, name == PreviewName});
}
}
catch (const std::exception &)
{
throw std::runtime_error("Google Drive returned an unreadable backup list.");
}
if (!result.backups.empty() || result.nextPage.empty()) return result;
token = std::move(result.nextPage);
}
throw std::runtime_error("Google Drive did not finish listing backups. Try again.");
}
GoogleDriveBackupInfo uploadGoogleDriveBackup(const Bytes &settings)
{
auto access = accessToken();
ClearString clear{access};
auto file = createDriveFile(access, NativeName, {settings.begin(), settings.end()});
return {std::move(file.id), std::move(file.created), settings.size(), false};
}
Bytes fetchGoogleDriveBackup(std::string_view id)
{
if (id.empty()) throw std::runtime_error("Select a Google Drive backup to restore.");
auto access = accessToken();
ClearString clear{access};
auto response = driveRequest(L"GET", "/drive/v3/files/" + urlEncode(id) + "?alt=media",
access, {}, {}, GoogleDriveBackupLimit);
return std::move(response.body);
}
}