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
254 PromiseT passwordLogin(std::string homeserver, std::string username,
255 std::string password, std::string deviceName) const;
256
272 PromiseT tokenLogin(std::string homeserver, std::string username,
273 std::string token, std::string deviceId) const;
274
291 std::string homeserver,
292 std::string loginToken,
293 std::optional<std::string> deviceName
294 ) const;
295
301 auto shouldSync() const -> lager::reader<bool>;
302
310 PromiseT logout() const;
311
325 PromiseT autoDiscover(std::string userId) const;
326
346 std::optional<std::string> name = {},
347 std::optional<std::string> alias = {},
348 immer::array<std::string> invite = {},
349 std::optional<bool> isDirect = {},
350 bool allowFederate = true,
351 std::optional<std::string> topic = {},
352 JsonWrap powerLevelContentOverride = json::object(),
353 std::optional<CreateRoomPreset> preset = std::nullopt,
354 immer::array<Event> initialState = immer::array<Event>()
355 ) const;
356
364 PromiseT joinRoomById(std::string roomId) const;
365
375 PromiseT joinRoom(std::string roomId, immer::array<std::string> serverName) const;
376
389 PromiseT uploadContent(immer::box<Bytes> content,
390 std::string uploadId,
391 std::optional<std::string> filename = std::nullopt,
392 std::optional<std::string> contentType = std::nullopt) const;
393
403 PromiseT uploadContent(FileDesc file) const;
404
405
416 inline std::string mxcUriToHttp(std::string mxcUri) const {
417 using namespace CursorOp;
418 auto [serverName, mediaId] = mxcUriToMediaDesc(mxcUri);
419 return (+clientCursor())
420 .template job<GetContentJob>()
421 .make(serverName, mediaId).url();
422 }
423
434 std::string mxcUriToHttpV1(std::string mxcUri) const;
435
450 PromiseT downloadContent(std::string mxcUri,
451 std::optional<FileDesc> downloadTo = std::nullopt) const;
452
470 PromiseT downloadThumbnail(std::string mxcUri,
471 int width,
472 int height,
473 std::optional<ThumbnailResizingMethod> method = std::nullopt,
474 std::optional<FileDesc> downloadTo = std::nullopt) const;
475
485 PromiseT getProfile(std::string userId) const;
486
494 PromiseT setAvatarUrl(std::optional<std::string> avatarUrl) const;
495
503 PromiseT setDisplayName(std::optional<std::string> displayName) const;
504
505 // lager::reader<bool>
506 inline auto syncing() const {
507 return clientCursor()[&ClientModel::syncing];
508 }
509
521 PromiseT startSyncing() const;
522
530 PromiseT stopSyncing() const;
531
539 auto devicesOfUser(std::string userId) const -> lager::reader<immer::flex_vector<DeviceKeyInfo>>;
540
549 PromiseT setDeviceTrustLevel(std::string userId, std::string deviceId, DeviceTrustLevel trustLevel) const;
550
556 auto trustLevelNeededToSendKeys() const -> lager::reader<DeviceTrustLevel>;
557
566
572 auto directRoomMap() const -> lager::reader<immer::map<std::string, std::string>>;
573
579 auto accountData() const -> lager::reader<immer::map<std::string, Event>>;
580
587 PromiseT setAccountData(Event accountDataEvent) const;
588
595
612 template<class Archive>
613 void serializeTo(Archive &ar) const {
614 ar << sdkCursor().get();
615 }
616
624 PromiseT getVersions(std::string homeserver) const;
625
633 auto supportVersions() const -> lager::reader<immer::array<std::string>>;
634
643 PromiseT addDirectRoom(std::string userId, std::string roomId) const;
644
652 BaseJob getRoomIdByAliasJob(std::string roomAlias) const;
653
664 PromiseT purgeRoomEvents(immer::map<std::string, std::size_t> roomIdToMaxToKeepMap) const;
665
676 PromiseT loadEventsFromStorage(immer::map<std::string, EventList> timelineEvents, immer::map<std::string, EventList> relatedEvents) const;
677
685 PromiseT importFromKeyBackupFile(std::string fileContent, std::string password) const;
686
698
708 PromiseT requestOutgoingToDeviceVerification(std::string userId, std::string deviceId) const;
709
719 PromiseT readyForVerification(std::string userId, std::string deviceId) const;
720
727 PromiseT cancelVerification(std::string userId, std::string deviceId) const;
728
735 PromiseT confirmVerificationSasMatch(std::string userId, std::string deviceId) const;
736
743 PromiseT denyVerificationSasMatch(std::string userId, std::string deviceId) const;
744
749
750 private:
751 void syncForever(std::optional<int> retryTime = std::nullopt) const;
752
753 const lager::reader<SdkModel> &sdkCursor() const;
754 lager::reader<ClientModel> clientCursor() const;
755
756 std::optional<lager::reader<SdkModel>> m_sdk;
757 std::optional<lager::reader<ClientModel>> m_client;
758 ContextT m_ctx;
759 std::optional<DepsT> m_deps;
760 KAZV_DECLARE_THREAD_ID();
761 KAZV_DECLARE_EVENT_LOOP_THREAD_ID_KEEPER(m_deps.has_value() ? &lager::get<EventLoopThreadIdKeeper &>(m_deps.value()) : 0);
762 };
763
764}
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:687
PromiseT setDisplayName(std::optional< std::string > displayName) const
Change the display name of the current user.
Definition client.cpp:631
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:665
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:677
PromiseT setTrustLevelNeededToSendKeys(DeviceTrustLevel trustLevel) const
Set the trust level needed to send keys to a device.
Definition client.cpp:660
PromiseT getVersions(std::string homeserver) const
Get all supported versions.
Definition client.cpp:697
PromiseT joinRoomById(std::string roomId) const
Join a room by its id.
Definition client.cpp:252
PromiseT joinRoom(std::string roomId, immer::array< std::string > serverName) const
Join a room by its id or alias.
Definition client.cpp:257
PromiseT cancelVerification(std::string userId, std::string deviceId) const
Cancel a verification process.
Definition client.cpp:455
std::string mxcUriToHttp(std::string mxcUri) const
Convert a MXC URI to an HTTP(s) URI.
Definition client.hpp:416
auto trustLevelNeededToSendKeys() const -> lager::reader< DeviceTrustLevel >
Get the trust level needed to send keys to a device.
Definition client.cpp:655
NotificationHandler notificationHandler() const
Get a notification handler that works on this Client.
Definition client.cpp:692
Client toEventLoop() const
Create a Client that is not constructed from a cursor.
Definition client.cpp:109
auto syncing() const
Definition client.hpp:506
PromiseT setAvatarUrl(std::optional< std::string > avatarUrl) const
Change the avatar url of the current user.
Definition client.cpp:626
PromiseT mLoginTokenLogin(std::string homeserver, std::string loginToken, std::optional< std::string > deviceName) const
Login using a login token.
Definition client.cpp:152
SingleTypePromise< DefaultRetType > PromiseT
Definition client.hpp:100
PromiseT logout() const
Stop syncing and then logout current session.
Definition client.cpp:193
PromiseT processVerificationEventsFromSync(EventList toDeviceEvents) const
Process verification events from a sync result.
Definition client.cpp:359
std::string mxcUriToHttpV1(std::string mxcUri) const
Convert a MXC URI to an HTTP(s) URI that needs Authorization.
Definition client.cpp:289
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:419
PromiseT purgeRoomEvents(immer::map< std::string, std::size_t > roomIdToMaxToKeepMap) const
Purge events in room, keeping the latest numToKeep events.
Definition client.cpp:737
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:297
PromiseT stopSyncing() const
Stop the indefinite syncing.
Definition client.cpp:592
PromiseT denyVerificationSasMatch(std::string userId, std::string deviceId) const
Deny an sas match for a verification process.
Definition client.cpp:475
BaseJob getRoomIdByAliasJob(std::string roomAlias) const
Get a GetRoomIdByAliasJob.
Definition client.cpp:732
auto accountData() const -> lager::reader< immer::map< std::string, Event > >
Get the account data that is not associated with any room.
Definition client.cpp:682
PromiseT requestOutgoingToDeviceVerification(std::string userId, std::string deviceId) const
Request an outgoing verification using to-device message.
Definition client.cpp:384
void serializeTo(Archive &ar) const
Serialize the model to a Boost.Serialization archive.
Definition client.hpp:613
PromiseT ensureInitVerificationTracker() const
Ensure the VerificationTracker is initialized.
Definition client.cpp:485
auto shouldSync() const -> lager::reader< bool >
Get the shouldSync field of current ClientModel.
Definition client.cpp:189
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:742
PromiseT setDeviceTrustLevel(std::string userId, std::string deviceId, DeviceTrustLevel trustLevel) const
Set the trust level of a device.
Definition client.cpp:650
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:201
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:707
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:636
PromiseT tokenLogin(std::string homeserver, std::string username, std::string token, std::string deviceId) const
Login using token and deviceId.
Definition client.cpp:172
auto supportVersions() const -> lager::reader< immer::array< std::string > >
Get all supported versions.
Definition client.cpp:702
PromiseT importFromKeyBackupFile(std::string fileContent, std::string password) const
Import keys from a key backup file.
Definition client.cpp:750
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:263
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:303
PromiseT getProfile(std::string userId) const
Fetch the profile of a user.
Definition client.cpp:621
PromiseT confirmVerificationSasMatch(std::string userId, std::string deviceId) const
Confirm an sas match for a verification process.
Definition client.cpp:465
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:220
auto roomIdsUnderTag(std::string tagId) const -> lager::reader< immer::map< std::string, double > >
Definition client.cpp:670
PromiseT passwordLogin(std::string homeserver, std::string username, std::string password, std::string deviceName) const
Login using the password.
Definition client.cpp:133
PromiseT startSyncing() const
Start syncing if the Client is not syncing.
Definition client.cpp:314
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:420
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