Page Menu
Home
Phorge
Search
Configure Global Search
Log In
Files
F140088
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Award Token
Flag For Later
Size
20 KB
Referenced Files
None
Subscribers
None
View Options
diff --git a/src/client/client.cpp b/src/client/client.cpp
index 4bfa7c5..9e5b584 100644
--- a/src/client/client.cpp
+++ b/src/client/client.cpp
@@ -1,372 +1,372 @@
/*
* Copyright (C) 2020-2021 Tusooa Zhu <tusooa@kazv.moe>
*
* This file is part of libkazv.
*
* libkazv is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* libkazv is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with libkazv. If not, see <https://www.gnu.org/licenses/>.
*/
#include <libkazv-config.hpp>
#include <filesystem>
#include <lager/constant.hpp>
#include "client.hpp"
namespace Kazv
{
Client::Client(lager::reader<SdkModel> sdk,
ContextT ctx, std::nullopt_t)
: m_sdk(sdk)
, m_client(sdk.map(&SdkModel::c))
, m_ctx(std::move(ctx))
{
}
Client::Client(lager::reader<SdkModel> sdk,
ContextWithDepsT ctx)
: m_sdk(sdk)
, m_client(sdk.map(&SdkModel::c))
, m_ctx(ctx)
, m_deps(std::move(ctx))
{
}
Client::Client(InEventLoopTag,
ContextWithDepsT ctx)
: m_sdk(std::nullopt)
, m_client(std::nullopt)
, m_ctx(ctx)
, m_deps(std::move(ctx))
#ifdef KAZV_USE_THREAD_SAFETY_HELPER
, KAZV_ON_EVENT_LOOP_VAR(true)
#endif
{
}
Client::Client(InEventLoopTag,
ContextT ctx, DepsT deps)
: m_sdk(std::nullopt)
, m_client(std::nullopt)
, m_ctx(std::move(ctx))
, m_deps(std::move(deps))
#ifdef KAZV_USE_THREAD_SAFETY_HELPER
, KAZV_ON_EVENT_LOOP_VAR(true)
#endif
{
}
Client Client::toEventLoop() const
{
return Client(InEventLoopTag{}, m_ctx, m_deps.value());
}
Room Client::room(std::string id) const
{
if (m_deps.has_value()) {
return Room(sdkCursor(), lager::make_constant(id), m_ctx, m_deps.value());
} else {
return Room(sdkCursor(), lager::make_constant(id), m_ctx);
}
}
Room Client::roomByCursor(lager::reader<std::string> id) const
{
if (m_deps.has_value()) {
return Room(sdkCursor(), id, m_ctx, m_deps.value());
} else {
return Room(sdkCursor(), id, m_ctx);
}
}
auto Client::passwordLogin(std::string homeserver, std::string username,
std::string password, std::string deviceName) const
-> PromiseT
{
auto p1 = m_ctx.dispatch(LoginAction{
homeserver, username, password, deviceName});
p1
.then([that=toEventLoop()](auto stat) {
if (! stat.success()) {
return;
}
// It is meaningless to wait for it in a Promise
// that is never exposed to the user.
that.startSyncing();
});
return p1;
}
auto Client::tokenLogin(std::string homeserver, std::string username,
std::string token, std::string deviceId) const
-> PromiseT
{
auto p1 = m_ctx.dispatch(TokenLoginAction{
homeserver, username, token, deviceId});
p1
.then([that=toEventLoop()](auto stat) {
if (! stat.success()) {
return;
}
that.startSyncing();
});
return p1;
}
auto Client::autoDiscover(std::string userId) const
-> PromiseT
{
return m_ctx.dispatch(GetWellknownAction{userId})
.then([that=toEventLoop()](auto stat) {
if (!stat.success()) {
return that.m_ctx.createResolvedPromise(stat);
}
- return that.m_ctx.dispatch(GetVersionsAction{stat.dataStr("serverUrl")})
+ return that.m_ctx.dispatch(GetVersionsAction{stat.dataStr("homeserverUrl")})
.then([that, stat](auto stat2) {
if (!stat2.success()) {
return stat2;
} else {
return stat;
}
});
});
}
auto Client::createRoom(RoomVisibility v,
std::optional<std::string> name,
std::optional<std::string> alias,
immer::array<std::string> invite,
std::optional<bool> isDirect,
bool allowFederate,
std::optional<std::string> topic,
JsonWrap powerLevelContentOverride) const
-> PromiseT
{
CreateRoomAction a;
a.visibility = v;
a.name = name;
a.roomAliasName = alias;
a.invite = invite;
a.isDirect = isDirect;
a.topic = topic;
a.powerLevelContentOverride = powerLevelContentOverride;
// Synapse won't buy it if we do not provide
// a creationContent object.
a.creationContent = json{
{"m.federate", allowFederate}
};
return m_ctx.dispatch(std::move(a));
}
auto Client::joinRoomById(std::string roomId) const -> PromiseT
{
return m_ctx.dispatch(JoinRoomByIdAction{roomId});
}
auto Client::joinRoom(std::string roomId, immer::array<std::string> serverName) const
-> PromiseT
{
return m_ctx.dispatch(JoinRoomAction{roomId, serverName});
}
auto Client::uploadContent(immer::box<Bytes> content,
std::string uploadId,
std::optional<std::string> filename,
std::optional<std::string> contentType) const
-> PromiseT
{
return m_ctx.dispatch(UploadContentAction{
FileDesc(FileContent{content.get().begin(), content.get().end()}),
filename, contentType, uploadId});
}
auto Client::uploadContent(FileDesc file) const
-> PromiseT
{
auto basename = file.name()
? std::optional(std::filesystem::path(file.name().value()).filename().native())
: std::nullopt;
return m_ctx.dispatch(UploadContentAction{
file,
// use only basename to prevent path info being leaked
basename,
file.contentType(),
// uploadId unused
std::string{}});
}
auto Client::downloadContent(std::string mxcUri, std::optional<FileDesc> downloadTo) const
-> PromiseT
{
return m_ctx.dispatch(DownloadContentAction{mxcUri, downloadTo});
}
auto Client::downloadThumbnail(
std::string mxcUri,
int width,
int height,
std::optional<ThumbnailResizingMethod> method,
std::optional<FileDesc> downloadTo) const
-> PromiseT
{
return m_ctx.dispatch(DownloadThumbnailAction{mxcUri, width, height, method, std::nullopt, downloadTo});
}
auto Client::startSyncing() const -> PromiseT
{
KAZV_VERIFY_THREAD_ID();
using namespace Kazv::CursorOp;
if (+syncing()) {
return m_ctx.createResolvedPromise(true);
}
auto p1 = m_ctx.createResolvedPromise(true)
.then([that=toEventLoop()](auto) {
// post filters, if filters are incomplete
if ((+that.clientCursor()[&ClientModel::initialSyncFilterId]).empty()
|| (+that.clientCursor()[&ClientModel::incrementalSyncFilterId]).empty()) {
return that.m_ctx.dispatch(PostInitialFiltersAction{});
}
return that.m_ctx.createResolvedPromise(true);
})
.then([that=toEventLoop()](auto stat) {
if (! stat.success()) {
return that.m_ctx.createResolvedPromise(stat);
}
// Upload identity keys if we need to
if (+that.clientCursor()[&ClientModel::crypto]
&& ! +that.clientCursor()[&ClientModel::identityKeysUploaded]) {
return that.m_ctx.dispatch(UploadIdentityKeysAction{});
} else {
return that.m_ctx.createResolvedPromise(true);
}
});
p1
.then([m_ctx=m_ctx](auto stat) {
m_ctx.dispatch(SetShouldSyncAction{true});
return stat;
})
.then([that=toEventLoop()](auto stat) {
if (stat.success()) {
that.syncForever();
}
});
return p1;
}
auto Client::syncForever(std::optional<int> retryTime) const -> void
{
KAZV_VERIFY_THREAD_ID();
// assert (m_deps);
using namespace CursorOp;
bool isInitialSync = ! (+clientCursor()[&ClientModel::syncToken]).has_value();
bool shouldSync = +clientCursor()[&ClientModel::shouldSync];
if (! shouldSync) {
return;
}
//
auto syncRes = m_ctx.dispatch(SyncAction{});
auto uploadOneTimeKeysRes = syncRes
.then([that=toEventLoop()](auto stat) {
if (! stat.success()) {
return that.m_ctx.createResolvedPromise(stat);
}
auto &rg = lager::get<RandomInterface &>(that.m_deps.value());
bool hasCrypto{+that.clientCursor()[&ClientModel::crypto]};
if (! hasCrypto) {
return that.m_ctx.createResolvedPromise(true);
}
auto numKeysToGenerate = (+that.clientCursor()).numOneTimeKeysNeeded();
return that.m_ctx.dispatch(GenerateAndUploadOneTimeKeysAction{
numKeysToGenerate,
rg.generateRange<RandomData>(GenerateAndUploadOneTimeKeysAction::randomSize(numKeysToGenerate))
});
});
auto queryKeysRes = syncRes
.then([that=toEventLoop(), isInitialSync](auto stat) {
if (! stat.success()) {
return that.m_ctx.createResolvedPromise(stat);
}
bool hasCrypto{+that.clientCursor()[&ClientModel::crypto]};
return hasCrypto
? that.m_ctx.dispatch(QueryKeysAction{isInitialSync})
: that.m_ctx.createResolvedPromise(true);
});
m_ctx.promiseInterface()
.all(std::vector<PromiseT>{uploadOneTimeKeysRes, queryKeysRes})
.then([that=toEventLoop(), retryTime](auto stat) {
if (stat.success()) {
that.syncForever(); // reset retry time
} else {
auto firstRetryTime = +that.clientCursor()[&ClientModel::firstRetryMs];
auto retryTimeFactor = +that.clientCursor()[&ClientModel::retryTimeFactor];
auto maxRetryTime = +that.clientCursor()[&ClientModel::maxRetryMs];
auto curRetryTime = retryTime ? retryTime.value() : firstRetryTime;
if (curRetryTime > maxRetryTime) { curRetryTime = maxRetryTime; }
auto nextRetryTime = curRetryTime * retryTimeFactor;
kzo.client.warn() << "Sync failed, retrying in " << curRetryTime << "ms" << std::endl;
auto &jh = getJobHandler(that.m_deps.value());
jh.setTimeout([that=that.toEventLoop(), nextRetryTime]() { that.syncForever(nextRetryTime); },
curRetryTime);
}
});
}
void Client::stopSyncing() const
{
m_ctx.dispatch(SetShouldSyncAction{false});
}
lager::reader<ClientModel> Client::clientCursor() const
{
KAZV_VERIFY_THREAD_ID();
if (m_client.has_value()) {
return m_client.value();
} else {
assert(m_deps.has_value());
return lager::get<SdkModelCursorKey>(m_deps.value())->map(&SdkModel::c);
}
}
const lager::reader<SdkModel> &Client::sdkCursor() const
{
KAZV_VERIFY_THREAD_ID();
if (m_sdk.has_value()) {
return m_sdk.value();
} else {
assert(m_deps.has_value());
return *(lager::get<SdkModelCursorKey>(m_deps.value()));
}
}
}
diff --git a/src/tests/client/discovery-test.cpp b/src/tests/client/discovery-test.cpp
index 5964118..4c98a6b 100644
--- a/src/tests/client/discovery-test.cpp
+++ b/src/tests/client/discovery-test.cpp
@@ -1,230 +1,231 @@
/*
* This file is part of libkazv.
* SPDX-FileCopyrightText: 2022 Tusooa Zhu <tusooa@kazv.moe>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#include <libkazv-config.hpp>
#include <catch2/catch.hpp>
#include <boost/asio.hpp>
#include <asio-promise-handler.hpp>
#include <cursorutil.hpp>
#include <sdk-model.hpp>
#include <client/client.hpp>
#include "client-test-util.hpp"
static const json wellKnownResponseJson = R"({
"m.homeserver": {
"base_url": "https://matrix.example.com"
},
"m.identity_server": {
"base_url": "https://identity.example.com"
},
"org.example.custom.property": {
"app_url": "https://custom.app.example.org"
}
})"_json;
static const json versionsResponseJson = R"({
"unstable_features": {
"org.example.my_feature": true
},
"versions": [
"r0.0.1",
"v1.1"
]
})"_json;
TEST_CASE("Auto-discovery tests", "[client][discovery]")
{
using namespace Kazv::CursorOp;
using Catch::Matchers::StartsWith;
WHEN("We do a discovery")
{
ClientModel m;
auto [resModel, dontCareEffect] = ClientModel::update(m, GetWellknownAction{"@foo:example.com"});
THEN("We should send to the server address as in the userId")
{
REQUIRE(resModel.nextJobs.size() == 1);
auto job = resModel.nextJobs[0];
REQUIRE_THAT(job.url(), StartsWith("https://example.com/"));
+ REQUIRE(job.dataStr("serverUrl") == "https://example.com");
}
}
WHEN("We do a discovery no remote part provided")
{
ClientModel m;
auto [resModel, dontCareEffect] = ClientModel::update(m, GetWellknownAction{"@foo"});
THEN("We should not send any job")
{
REQUIRE(resModel.nextJobs.size() == 0);
}
}
WHEN("We do a discovery 0-length part provided")
{
ClientModel m;
auto [resModel, dontCareEffect] = ClientModel::update(m, GetWellknownAction{"@foo:"});
THEN("We should not send any job")
{
REQUIRE(resModel.nextJobs.size() == 0);
}
}
// Test different server names
// https://spec.matrix.org/v1.1/appendices/#server-name
WHEN("We do a discovery with server names containing ports")
{
ClientModel m;
auto [resModel, dontCareEffect] = ClientModel::update(m, GetWellknownAction{"@foo:example.com:8080"});
THEN("We should send to the server address as in the userId")
{
REQUIRE(resModel.nextJobs.size() == 1);
auto job = resModel.nextJobs[0];
REQUIRE_THAT(job.url(), StartsWith("https://example.com:8080/"));
}
}
WHEN("We do a discovery with server names containing ipv4 address")
{
ClientModel m;
auto [resModel, dontCareEffect] = ClientModel::update(m, GetWellknownAction{"@foo:1.2.3.4:8080"});
THEN("We should send to the server address as in the userId")
{
REQUIRE(resModel.nextJobs.size() == 1);
auto job = resModel.nextJobs[0];
REQUIRE_THAT(job.url(), StartsWith("https://1.2.3.4:8080/"));
}
}
WHEN("We do a discovery with server names containing ipv6 address")
{
ClientModel m;
auto [resModel, dontCareEffect] = ClientModel::update(m, GetWellknownAction{"@foo:[1234:5678::abcd]:5678"});
THEN("We should send to the server address as in the userId")
{
REQUIRE(resModel.nextJobs.size() == 1);
auto job = resModel.nextJobs[0];
REQUIRE_THAT(job.url(), StartsWith("https://[1234:5678::abcd]:5678/"));
}
}
boost::asio::io_context io;
AsioPromiseHandler ph{io.get_executor()};
auto store = createTestClientStore(ph);
WHEN("We got a successful response")
{
auto resp = createResponse("GetWellknown", wellKnownResponseJson,
json{{"serverUrl", "https://example.com"}});
THEN("We should return the server url in the response")
{
store.dispatch(ProcessResponseAction{resp})
.then([](auto stat) {
REQUIRE(stat.success());
auto data = stat.dataStr("homeserverUrl");
REQUIRE(data == std::string("https://matrix.example.com"));
});
}
}
WHEN("We got 404")
{
auto resp = createResponse("GetWellknown", wellKnownResponseJson,
json{{"serverUrl", "https://example.com"}});
resp.statusCode = 404;
THEN("We should return the server in the user id")
{
store.dispatch(ProcessResponseAction{resp})
.then([](auto stat) {
REQUIRE(stat.success());
auto data = stat.dataStr("homeserverUrl");
REQUIRE(data == std::string("https://example.com"));
});
}
}
WHEN("We got other error codes")
{
auto resp = createResponse("GetWellknown", wellKnownResponseJson,
json{{"serverUrl", "https://example.com"}});
resp.statusCode = 500;
THEN("We should FAIL_PROMPT")
{
store.dispatch(ProcessResponseAction{resp})
.then([](auto stat) {
REQUIRE(!stat.success());
auto data = stat.dataStr("error");
REQUIRE(data == std::string("FAIL_PROMPT"));
});
}
}
io.run();
}
TEST_CASE("GetVersions", "[client][discovery]")
{
using namespace Kazv::CursorOp;
boost::asio::io_context io;
AsioPromiseHandler ph{io.get_executor()};
auto store = createTestClientStore(ph);
WHEN("We got a successful response")
{
auto resp = createResponse("GetVersions", versionsResponseJson);
THEN("We should return the versions supported")
{
store.dispatch(ProcessResponseAction{resp})
.then([](auto stat) {
REQUIRE(stat.success());
auto data = stat.dataJson("versions");
REQUIRE(data == immer::flex_vector<std::string>{
"r0.0.1",
"v1.1"
});
});
}
}
WHEN("We got an error")
{
auto resp = createResponse("GetVersions", json());
resp.statusCode = 400;
THEN("We should fail")
{
store.dispatch(ProcessResponseAction{resp})
.then([](auto stat) {
REQUIRE(!stat.success());
REQUIRE(stat.dataJson("errorCode") == "400");
});
}
}
io.run();
}
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Sun, Jan 19, 12:23 PM (7 h, 54 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
55157
Default Alt Text
(20 KB)
Attached To
Mode
rL libkazv
Attached
Detach File
Event Timeline
Log In to Comment