libkazv
Loading...
Searching...
No Matches
client.hpp
Go to the documentation of this file.
1/*
2 * This file is part of libkazv.
3 * SPDX-FileCopyrightText: 2020-2023 tusooa <tusooa@kazv.moe>
4 * SPDX-License-Identifier: AGPL-3.0-or-later
5 */
6
7#pragma once
8#include <libkazv-config.hpp>
9
10#include <lager/reader.hpp>
11#include <immer/box.hpp>
12#include <immer/map.hpp>
13#include <immer/flex_vector.hpp>
14#include <immer/flex_vector_transient.hpp>
15
16#include "sdk-model.hpp"
21
22#include "room/room.hpp"
25
26namespace Kazv
27{
86 class Client
87 {
88 public:
90
92#ifdef KAZV_USE_THREAD_SAFETY_HELPER
93 , EventLoopThreadIdKeeper &
94#endif
95
96 >;
99
101
102 struct InEventLoopTag {};
111 Client(lager::reader<SdkModel> sdk,
112 ContextT ctx, std::nullopt_t);
113
124 Client(lager::reader<SdkModel> sdk,
125 ContextWithDepsT ctx);
126
138 ContextWithDepsT ctx);
139
151
152
163 Client toEventLoop() const;
164
165 /* lager::reader<immer::map<std::string, Room>> */
166 inline auto rooms() const {
167 return clientCursor()
170 }
171
172 /* lager::reader<RangeT<std::string>> */
173 inline auto roomIds() const {
174 return rooms().xform(
175 zug::map([](auto m) {
176 return intoImmer(
177 immer::flex_vector<std::string>{},
178 zug::map([](auto val) { return val.first; }),
179 m);
180 }));
181 }
182
183 auto roomIdsUnderTag(std::string tagId) const -> lager::reader<immer::map<std::string, double>>;
184
191 auto roomIdsByTagId() const -> lager::reader<immer::map<std::string, immer::map<std::string, double>>>;
192
193 KAZV_WRAP_ATTR(ClientModel, clientCursor(), serverUrl)
194 KAZV_WRAP_ATTR(ClientModel, clientCursor(), loggedIn)
195 KAZV_WRAP_ATTR(ClientModel, clientCursor(), userId)
196 KAZV_WRAP_ATTR(ClientModel, clientCursor(), token)
197 KAZV_WRAP_ATTR(ClientModel, clientCursor(), deviceId)
198 KAZV_WRAP_ATTR(ClientModel, clientCursor(), toDevice)
199
208 Room room(std::string id) const;
209
235 Room roomByCursor(lager::reader<std::string> id) const;
236
256 PromiseT passwordLogin(std::string homeserver, std::string username,
257 std::string password, std::string deviceName, bool startSyncingOnSuccess) const;
258
264 [[deprecated("Specify startSyncingOnSuccess explicitly")]]
265 PromiseT passwordLogin(std::string homeserver, std::string username,
266 std::string password, std::string deviceName) const;
267
285 PromiseT tokenLogin(std::string homeserver, std::string username,
286 std::string token, std::string deviceId, bool startSyncingOnSuccess) const;
287
293 [[deprecated("Specify startSyncingOnSuccess explicitly")]]
294 PromiseT tokenLogin(std::string homeserver, std::string username,
295 std::string token, std::string deviceId) const;
296
315 std::string homeserver,
316 std::string loginToken,
317 std::optional<std::string> deviceName,
318 bool startSyncingOnSuccess
319 ) const;
320
326 [[deprecated("Specify startSyncingOnSuccess explicitly")]]
328 std::string homeserver,
329 std::string loginToken,
330 std::optional<std::string> deviceName
331 ) const;
332
343 auto shouldSync() const -> lager::reader<bool>;
344
359 PromiseT logout() const;
360
374 PromiseT autoDiscover(std::string userId) const;
375
395 std::optional<std::string> name = {},
396 std::optional<std::string> alias = {},
397 immer::array<std::string> invite = {},
398 std::optional<bool> isDirect = {},
399 bool allowFederate = true,
400 std::optional<std::string> topic = {},
401 JsonWrap powerLevelContentOverride = json::object(),
402 std::optional<CreateRoomPreset> preset = std::nullopt,
403 immer::array<Event> initialState = immer::array<Event>()
404 ) const;
405
413 PromiseT joinRoomById(std::string roomId) const;
414
424 PromiseT joinRoom(std::string roomId, immer::array<std::string> serverName) const;
425
438 PromiseT uploadContent(immer::box<Bytes> content,
439 std::string uploadId,
440 std::optional<std::string> filename = std::nullopt,
441 std::optional<std::string> contentType = std::nullopt) const;
442
452 PromiseT uploadContent(FileDesc file) const;
453
454
465 inline std::string mxcUriToHttp(std::string mxcUri) const {
466 using namespace CursorOp;
467 auto [serverName, mediaId] = mxcUriToMediaDesc(mxcUri);
468 return (+clientCursor())
469 .template job<GetContentJob>()
470 .make(serverName, mediaId).url();
471 }
472
483 std::string mxcUriToHttpV1(std::string mxcUri) const;
484
499 PromiseT downloadContent(std::string mxcUri,
500 std::optional<FileDesc> downloadTo = std::nullopt) const;
501
519 PromiseT downloadThumbnail(std::string mxcUri,
520 int width,
521 int height,
522 std::optional<ThumbnailResizingMethod> method = std::nullopt,
523 std::optional<FileDesc> downloadTo = std::nullopt) const;
524
534 PromiseT getProfile(std::string userId) const;
535
543 PromiseT setAvatarUrl(std::optional<std::string> avatarUrl) const;
544
552 PromiseT setDisplayName(std::optional<std::string> displayName) const;
553
554 // lager::reader<bool>
555 inline auto syncing() const {
556 return clientCursor()[&ClientModel::syncing];
557 }
558
580 PromiseT startSyncing() const;
581
594 PromiseT stopSyncing() const;
595
604
615 PromiseT doOneSyncCycle() const;
616
624 auto devicesOfUser(std::string userId) const -> lager::reader<immer::flex_vector<DeviceKeyInfo>>;
625
634 PromiseT setDeviceTrustLevel(std::string userId, std::string deviceId, DeviceTrustLevel trustLevel) const;
635
641 auto trustLevelNeededToSendKeys() const -> lager::reader<DeviceTrustLevel>;
642
651
657 auto directRoomMap() const -> lager::reader<immer::map<std::string, std::string>>;
658
664 auto accountData() const -> lager::reader<immer::map<std::string, Event>>;
665
672 PromiseT setAccountData(Event accountDataEvent) const;
673
680
697 template<class Archive>
698 void serializeTo(Archive &ar) const {
699 ar << sdkCursor().get();
700 }
701
709 PromiseT getVersions(std::string homeserver) const;
710
718 auto supportVersions() const -> lager::reader<immer::array<std::string>>;
719
728 PromiseT addDirectRoom(std::string userId, std::string roomId) const;
729
737 BaseJob getRoomIdByAliasJob(std::string roomAlias) const;
738
749 PromiseT purgeRoomEvents(immer::map<std::string, std::size_t> roomIdToMaxToKeepMap) const;
750
761 PromiseT loadEventsFromStorage(immer::map<std::string, EventList> timelineEvents, immer::map<std::string, EventList> relatedEvents) const;
762
770 PromiseT importFromKeyBackupFile(std::string fileContent, std::string password) const;
771
783
793 PromiseT requestOutgoingToDeviceVerification(std::string userId, std::string deviceId) const;
794
804 PromiseT readyForVerification(std::string userId, std::string deviceId) const;
805
812 PromiseT cancelVerification(std::string userId, std::string deviceId) const;
813
820 PromiseT confirmVerificationSasMatch(std::string userId, std::string deviceId) const;
821
828 PromiseT denyVerificationSasMatch(std::string userId, std::string deviceId) const;
829
834
835 private:
836 void syncForever(std::optional<int> retryTime = std::nullopt) const;
837
838 const lager::reader<SdkModel> &sdkCursor() const;
839 lager::reader<ClientModel> clientCursor() const;
840
841 std::optional<lager::reader<SdkModel>> m_sdk;
842 std::optional<lager::reader<ClientModel>> m_client;
843 ContextT m_ctx;
844 std::optional<DepsT> m_deps;
845 KAZV_DECLARE_THREAD_ID();
846 KAZV_DECLARE_EVENT_LOOP_THREAD_ID_KEEPER(m_deps.has_value() ? &lager::get<EventLoopThreadIdKeeper &>(m_deps.value()) : 0);
847 };
848
849}
Definition basejob.hpp:68
Represent a Matrix client.
Definition client.hpp:87
PromiseT setAccountData(Event accountDataEvent) const
Set the account data that is not associated with any room.
Definition client.cpp:730
PromiseT setDisplayName(std::optional< std::string > displayName) const
Change the display name of the current user.
Definition client.cpp:674
auto directRoomMap() const -> lager::reader< immer::map< std::string, std::string > >
Get the map from direct messaging room ids to user ids.
Definition client.cpp:708
Room roomByCursor(lager::reader< std::string > id) const
Get the room with id.
Definition client.cpp:124
auto roomIdsByTagId() const -> lager::reader< immer::map< std::string, immer::map< std::string, double > > >
Get the room ids under all tags.
Definition client.cpp:720
PromiseT setTrustLevelNeededToSendKeys(DeviceTrustLevel trustLevel) const
Set the trust level needed to send keys to a device.
Definition client.cpp:703
PromiseT tokenLogin(std::string homeserver, std::string username, std::string token, std::string deviceId, bool startSyncingOnSuccess) const
Login using token and deviceId.
Definition client.cpp:191
PromiseT getVersions(std::string homeserver) const
Get all supported versions.
Definition client.cpp:740
PromiseT joinRoomById(std::string roomId) const
Join a room by its id.
Definition client.cpp:280
PromiseT joinRoom(std::string roomId, immer::array< std::string > serverName) const
Join a room by its id or alias.
Definition client.cpp:285
PromiseT cancelVerification(std::string userId, std::string deviceId) const
Cancel a verification process.
Definition client.cpp:463
PromiseT doOneSyncCycle() const
Call the sync endpoint once and process the response.
Definition client.cpp:586
std::string mxcUriToHttp(std::string mxcUri) const
Convert a MXC URI to an HTTP(s) URI.
Definition client.hpp:465
auto trustLevelNeededToSendKeys() const -> lager::reader< DeviceTrustLevel >
Get the trust level needed to send keys to a device.
Definition client.cpp:698
NotificationHandler notificationHandler() const
Get a notification handler that works on this Client.
Definition client.cpp:735
Client toEventLoop() const
Create a Client that is not constructed from a cursor.
Definition client.cpp:109
auto syncing() const
Definition client.hpp:555
PromiseT setAvatarUrl(std::optional< std::string > avatarUrl) const
Change the avatar url of the current user.
Definition client.cpp:669
SingleTypePromise< DefaultRetType > PromiseT
Definition client.hpp:100
PromiseT logout() const
Set the shouldSync internal flag to false, and then logout current session.
Definition client.cpp:221
PromiseT processVerificationEventsFromSync(EventList toDeviceEvents) const
Process verification events from a sync result.
Definition client.cpp:367
std::string mxcUriToHttpV1(std::string mxcUri) const
Convert a MXC URI to an HTTP(s) URI that needs Authorization.
Definition client.cpp:317
auto roomIds() const
Definition client.hpp:173
PromiseT readyForVerification(std::string userId, std::string deviceId) const
Signal that the user is ready for an incoming verification request.
Definition client.cpp:427
PromiseT purgeRoomEvents(immer::map< std::string, std::size_t > roomIdToMaxToKeepMap) const
Purge events in room, keeping the latest numToKeep events.
Definition client.cpp:780
Context< ActionT > ContextT
Definition client.hpp:97
PromiseT downloadContent(std::string mxcUri, std::optional< FileDesc > downloadTo=std::nullopt) const
Download content from the content repository.
Definition client.cpp:325
PromiseT stopSyncing() const
Stop the indefinite syncing started by startSyncing().
Definition client.cpp:553
PromiseT denyVerificationSasMatch(std::string userId, std::string deviceId) const
Deny an sas match for a verification process.
Definition client.cpp:483
BaseJob getRoomIdByAliasJob(std::string roomAlias) const
Get a GetRoomIdByAliasJob.
Definition client.cpp:775
auto accountData() const -> lager::reader< immer::map< std::string, Event > >
Get the account data that is not associated with any room.
Definition client.cpp:725
PromiseT requestOutgoingToDeviceVerification(std::string userId, std::string deviceId) const
Request an outgoing verification using to-device message.
Definition client.cpp:392
void serializeTo(Archive &ar) const
Serialize the model to a Boost.Serialization archive.
Definition client.hpp:698
PromiseT ensureInitVerificationTracker() const
Ensure the VerificationTracker is initialized.
Definition client.cpp:493
auto shouldSync() const -> lager::reader< bool >
Get the shouldSync field of current ClientModel.
Definition client.cpp:217
PromiseT loadEventsFromStorage(immer::map< std::string, EventList > timelineEvents, immer::map< std::string, EventList > relatedEvents) const
Load events from storage into the model.
Definition client.cpp:785
PromiseT setDeviceTrustLevel(std::string userId, std::string deviceId, DeviceTrustLevel trustLevel) const
Set the trust level of a device.
Definition client.cpp:693
Room room(std::string id) const
Get the room with id .
Definition client.cpp:115
ClientAction ActionT
Definition client.hpp:89
PromiseT autoDiscover(std::string userId) const
Automatically discover the homeserver for userId.
Definition client.cpp:229
PromiseT addDirectRoom(std::string userId, std::string roomId) const
Mark a room as a direct chat by send the m.direct account data.
Definition client.cpp:750
lager::deps< JobInterface &, EventInterface &, SdkModelCursorKey, RandomInterface &, VerificationTracker & > DepsT
Definition client.hpp:96
auto devicesOfUser(std::string userId) const -> lager::reader< immer::flex_vector< DeviceKeyInfo > >
Get the info of all devices of user userId that supports encryption.
Definition client.cpp:679
auto supportVersions() const -> lager::reader< immer::array< std::string > >
Get all supported versions.
Definition client.cpp:745
PromiseT importFromKeyBackupFile(std::string fileContent, std::string password) const
Import keys from a key backup file.
Definition client.cpp:793
PromiseT uploadContent(immer::box< Bytes > content, std::string uploadId, std::optional< std::string > filename=std::nullopt, std::optional< std::string > contentType=std::nullopt) const
Upload content to the content repository.
Definition client.cpp:291
PromiseT downloadThumbnail(std::string mxcUri, int width, int height, std::optional< ThumbnailResizingMethod > method=std::nullopt, std::optional< FileDesc > downloadTo=std::nullopt) const
Download a thumbnail from the content repository.
Definition client.cpp:331
PromiseT getProfile(std::string userId) const
Fetch the profile of a user.
Definition client.cpp:664
PromiseT confirmVerificationSasMatch(std::string userId, std::string deviceId) const
Confirm an sas match for a verification process.
Definition client.cpp:473
PromiseT ensureReadyForSyncing() const
Ensure the Client can start syncing using doOneSyncCycle().
Definition client.cpp:558
PromiseT createRoom(RoomVisibility v, std::optional< std::string > name={}, std::optional< std::string > alias={}, immer::array< std::string > invite={}, std::optional< bool > isDirect={}, bool allowFederate=true, std::optional< std::string > topic={}, JsonWrap powerLevelContentOverride=json::object(), std::optional< CreateRoomPreset > preset=std::nullopt, immer::array< Event > initialState=immer::array< Event >()) const
Create a room.
Definition client.cpp:248
PromiseT mLoginTokenLogin(std::string homeserver, std::string loginToken, std::optional< std::string > deviceName, bool startSyncingOnSuccess) const
Login using a login token.
Definition client.cpp:160
auto roomIdsUnderTag(std::string tagId) const -> lager::reader< immer::map< std::string, double > >
Definition client.cpp:713
PromiseT passwordLogin(std::string homeserver, std::string username, std::string password, std::string deviceName, bool startSyncingOnSuccess) const
Login using the password.
Definition client.cpp:133
PromiseT startSyncing() const
Start syncing if the Client is not syncing.
Definition client.cpp:342
auto rooms() const
Definition client.hpp:166
Definition context.hpp:130
Definition eventinterface.hpp:15
Definition event.hpp:21
A class to handle a notification.
Definition notification-handler.hpp:22
Definition random-generator.hpp:16
Represent a Matrix room.
Definition room.hpp:38
Definition promise-interface.hpp:122
#define KAZV_WRAP_ATTR(_type, _d, _attr)
Definition clientutil.hpp:152
Definition location.hpp:10
RoomVisibility
Definition client-model.hpp:40
DeviceTrustLevel
Definition device-list-tracker.hpp:27
lager::dep::key< SdkModelCursorTag, lager::dep::fn< std::shared_ptr< lager::reader< SdkModel > > > > SdkModelCursorKey
Definition sdk-model-cursor-tag.hpp:23
detail::IntoImmerT intoImmer
Definition cursorutil.hpp:88
std::pair< std::string, std::string > mxcUriToMediaDesc(std::string mxcUri)
Definition content.cpp:17
std::variant< RoomListAction, LoginAction, TokenLoginAction, MLoginTokenLoginAction, LogoutAction, HardLogoutAction, GetWellknownAction, GetVersionsAction, SyncAction, SetShouldSyncAction, PostInitialFiltersAction, SetAccountDataAction, PaginateTimelineAction, SendMessageAction, SendStateEventAction, SaveLocalEchoAction, UpdateLocalEchoStatusAction, RedactEventAction, CreateRoomAction, GetRoomStatesAction, GetStateEventAction, InviteToRoomAction, JoinRoomByIdAction, JoinRoomAction, LeaveRoomAction, ForgetRoomAction, KickAction, BanAction, UnbanAction, SetAccountDataPerRoomAction, ProcessResponseAction, SetTypingAction, PostReceiptAction, SetReadMarkerAction, UploadContentAction, DownloadContentAction, DownloadThumbnailAction, SendToDeviceMessageAction, SendMultipleToDeviceMessagesAction, UploadIdentityKeysAction, GenerateAndUploadOneTimeKeysAction, QueryKeysAction, EnsureKeysFromDevicesAction, ClaimKeysAction, EncryptMegOlmEventAction, SetDeviceTrustLevelAction, SetDevicesTrustLevelsAction, SetTrustLevelNeededToSendKeysAction, PrepareForSharingRoomKeyAction, ImportFromKeyBackupFileAction, NotifyVerificationTrackerModelAction, GetUserProfileAction, SetAvatarUrlAction, SetDisplayNameAction, ResubmitJobAction, LoadEventsFromStorageAction, PurgeRoomTimelineAction > ClientAction
Definition clientfwd.hpp:160
immer::flex_vector< Event > EventList
Definition types.hpp:107
Definition clientutil.hpp:140
Definition client-model.hpp:59
RoomListModel roomList
Definition client-model.hpp:76
bool syncing
Definition client-model.hpp:66
Definition client.hpp:102
Definition jobinterface.hpp:21
immer::map< std::string, RoomModel > rooms
Definition room-model.hpp:451
Definition sdk-model.hpp:26
A stateful tracker for all verification processes.
Definition verification-tracker.hpp:98
#define KAZV_DECLARE_EVENT_LOOP_THREAD_ID_KEEPER(_initializer)
Definition thread-safety-helper.hpp:75