libkazv
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"
17 #include "client/client-model.hpp"
19 #include "sdk-model-cursor-tag.hpp"
20 
21 #include "room/room.hpp"
22 #include "notification-handler.hpp"
23 
24 namespace Kazv
25 {
58  class Client
59  {
60  public:
62 
64 #ifdef KAZV_USE_THREAD_SAFETY_HELPER
65  , EventLoopThreadIdKeeper &
66 #endif
67 
68  >;
71 
73 
74  struct InEventLoopTag {};
83  Client(lager::reader<SdkModel> sdk,
84  ContextT ctx, std::nullopt_t);
85 
96  Client(lager::reader<SdkModel> sdk,
97  ContextWithDepsT ctx);
98 
110  ContextWithDepsT ctx);
111 
122  Client(InEventLoopTag, ContextT ctx, DepsT deps);
123 
124 
135  Client toEventLoop() const;
136 
137  /* lager::reader<immer::map<std::string, Room>> */
138  inline auto rooms() const {
139  return clientCursor()
142  }
143 
144  /* lager::reader<RangeT<std::string>> */
145  inline auto roomIds() const {
146  return rooms().xform(
147  zug::map([](auto m) {
148  return intoImmer(
149  immer::flex_vector<std::string>{},
150  zug::map([](auto val) { return val.first; }),
151  m);
152  }));
153  }
154 
155  auto roomIdsUnderTag(std::string tagId) const -> lager::reader<immer::map<std::string, double>>;
156 
163  auto roomIdsByTagId() const -> lager::reader<immer::map<std::string, immer::map<std::string, double>>>;
164 
165  KAZV_WRAP_ATTR(ClientModel, clientCursor(), serverUrl)
166  KAZV_WRAP_ATTR(ClientModel, clientCursor(), loggedIn)
167  KAZV_WRAP_ATTR(ClientModel, clientCursor(), userId)
168  KAZV_WRAP_ATTR(ClientModel, clientCursor(), token)
169  KAZV_WRAP_ATTR(ClientModel, clientCursor(), deviceId)
170  KAZV_WRAP_ATTR(ClientModel, clientCursor(), toDevice)
171 
180  Room room(std::string id) const;
181 
207  Room roomByCursor(lager::reader<std::string> id) const;
208 
226  PromiseT passwordLogin(std::string homeserver, std::string username,
227  std::string password, std::string deviceName) const;
228 
244  PromiseT tokenLogin(std::string homeserver, std::string username,
245  std::string token, std::string deviceId) const;
246 
252  auto shouldSync() const -> lager::reader<bool>;
253 
261  PromiseT logout() const;
262 
276  PromiseT autoDiscover(std::string userId) const;
277 
296  RoomVisibility v,
297  std::optional<std::string> name = {},
298  std::optional<std::string> alias = {},
299  immer::array<std::string> invite = {},
300  std::optional<bool> isDirect = {},
301  bool allowFederate = true,
302  std::optional<std::string> topic = {},
303  JsonWrap powerLevelContentOverride = json::object(),
304  std::optional<CreateRoomPreset> preset = std::nullopt,
305  immer::array<Event> initialState = immer::array<Event>()
306  ) const;
307 
315  PromiseT joinRoomById(std::string roomId) const;
316 
326  PromiseT joinRoom(std::string roomId, immer::array<std::string> serverName) const;
327 
340  PromiseT uploadContent(immer::box<Bytes> content,
341  std::string uploadId,
342  std::optional<std::string> filename = std::nullopt,
343  std::optional<std::string> contentType = std::nullopt) const;
344 
354  PromiseT uploadContent(FileDesc file) const;
355 
356 
367  inline std::string mxcUriToHttp(std::string mxcUri) const {
368  using namespace CursorOp;
369  auto [serverName, mediaId] = mxcUriToMediaDesc(mxcUri);
370  return (+clientCursor())
371  .template job<GetContentJob>()
372  .make(serverName, mediaId).url();
373  }
374 
389  PromiseT downloadContent(std::string mxcUri,
390  std::optional<FileDesc> downloadTo = std::nullopt) const;
391 
409  PromiseT downloadThumbnail(std::string mxcUri,
410  int width,
411  int height,
412  std::optional<ThumbnailResizingMethod> method = std::nullopt,
413  std::optional<FileDesc> downloadTo = std::nullopt) const;
414 
424  PromiseT getProfile(std::string userId) const;
425 
433  PromiseT setAvatarUrl(std::optional<std::string> avatarUrl) const;
434 
442  PromiseT setDisplayName(std::optional<std::string> displayName) const;
443 
444  // lager::reader<bool>
445  inline auto syncing() const {
446  return clientCursor()[&ClientModel::syncing];
447  }
448 
460  PromiseT startSyncing() const;
461 
469  PromiseT stopSyncing() const;
470 
478  auto devicesOfUser(std::string userId) const -> lager::reader<immer::flex_vector<DeviceKeyInfo>>;
479 
488  PromiseT setDeviceTrustLevel(std::string userId, std::string deviceId, DeviceTrustLevel trustLevel) const;
489 
495  auto trustLevelNeededToSendKeys() const -> lager::reader<DeviceTrustLevel>;
496 
505 
511  auto directRoomMap() const -> lager::reader<immer::map<std::string, std::string>>;
512 
518  auto accountData() const -> lager::reader<immer::map<std::string, Event>>;
519 
526  PromiseT setAccountData(Event accountDataEvent) const;
527 
534 
551  template<class Archive>
552  void serializeTo(Archive &ar) const {
553  ar << sdkCursor().get();
554  }
555 
556  private:
557  void syncForever(std::optional<int> retryTime = std::nullopt) const;
558 
559  const lager::reader<SdkModel> &sdkCursor() const;
560  lager::reader<ClientModel> clientCursor() const;
561 
562  std::optional<lager::reader<SdkModel>> m_sdk;
563  std::optional<lager::reader<ClientModel>> m_client;
564  ContextT m_ctx;
565  std::optional<DepsT> m_deps;
566  KAZV_DECLARE_THREAD_ID();
567  KAZV_DECLARE_EVENT_LOOP_THREAD_ID_KEEPER(m_deps.has_value() ? &lager::get<EventLoopThreadIdKeeper &>(m_deps.value()) : 0);
568  };
569 
570 }
Represent a Matrix client.
Definition: client.hpp:59
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:421
PromiseT setAccountData(Event accountDataEvent) const
Set the account data that is not associated with any room.
Definition: client.cpp:443
PromiseT setDisplayName(std::optional< std::string > displayName) const
Change the display name of the current user.
Definition: client.cpp:387
Room roomByCursor(lager::reader< std::string > id) const
Get the room with id.
Definition: client.cpp:74
PromiseT setTrustLevelNeededToSendKeys(DeviceTrustLevel trustLevel) const
Set the trust level needed to send keys to a device.
Definition: client.cpp:416
lager::deps< JobInterface &, EventInterface &, SdkModelCursorKey, RandomInterface & > DepsT
Definition: client.hpp:68
PromiseT joinRoomById(std::string roomId) const
Join a room by its id.
Definition: client.cpp:182
PromiseT joinRoom(std::string roomId, immer::array< std::string > serverName) const
Join a room by its id or alias.
Definition: client.cpp:187
std::string mxcUriToHttp(std::string mxcUri) const
Convert a MXC URI to an HTTP(s) URI.
Definition: client.hpp:367
auto trustLevelNeededToSendKeys() const -> lager::reader< DeviceTrustLevel >
Get the trust level needed to send keys to a device.
Definition: client.cpp:411
NotificationHandler notificationHandler() const
Get a notification handler that works on this Client.
Definition: client.cpp:448
Client toEventLoop() const
Create a Client that is not constructed from a cursor.
Definition: client.cpp:59
auto syncing() const
Definition: client.hpp:445
PromiseT setAvatarUrl(std::optional< std::string > avatarUrl) const
Change the avatar url of the current user.
Definition: client.cpp:382
SingleTypePromise< DefaultRetType > PromiseT
Definition: client.hpp:72
PromiseT logout() const
Stop syncing and then logout current session.
Definition: client.cpp:123
auto roomIds() const
Definition: client.hpp:145
Context< ActionT > ContextT
Definition: client.hpp:69
PromiseT downloadContent(std::string mxcUri, std::optional< FileDesc > downloadTo=std::nullopt) const
Download content from the content repository.
Definition: client.cpp:219
PromiseT stopSyncing() const
Stop the indefinite syncing.
Definition: client.cpp:348
void serializeTo(Archive &ar) const
Serialize the model to a Boost.Serialization archive.
Definition: client.hpp:552
auto shouldSync() const -> lager::reader< bool >
Get the shouldSync field of current ClientModel.
Definition: client.cpp:119
auto roomIdsUnderTag(std::string tagId) const -> lager::reader< immer::map< std::string, double >>
Definition: client.cpp:426
PromiseT setDeviceTrustLevel(std::string userId, std::string deviceId, DeviceTrustLevel trustLevel) const
Set the trust level of a device.
Definition: client.cpp:406
Room room(std::string id) const
Get the room with id .
Definition: client.cpp:65
ClientAction ActionT
Definition: client.hpp:61
PromiseT autoDiscover(std::string userId) const
Automatically discover the homeserver for userId.
Definition: client.cpp:131
PromiseT tokenLogin(std::string homeserver, std::string username, std::string token, std::string deviceId) const
Login using token and deviceId.
Definition: client.cpp:102
Client(lager::reader< SdkModel > sdk, ContextT ctx, std::nullopt_t)
Constructor.
Definition: client.cpp:17
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:193
auto roomIdsByTagId() const -> lager::reader< immer::map< std::string, immer::map< std::string, double >>>
Get the room ids under all tags.
Definition: client.cpp:433
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:225
PromiseT getProfile(std::string userId) const
Fetch the profile of a user.
Definition: client.cpp:377
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:150
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:392
PromiseT passwordLogin(std::string homeserver, std::string username, std::string password, std::string deviceName) const
Login using the password.
Definition: client.cpp:83
auto accountData() const -> lager::reader< immer::map< std::string, Event >>
Get the account data that is not associated with any room.
Definition: client.cpp:438
PromiseT startSyncing() const
Start syncing if the Client is not syncing.
Definition: client.cpp:236
auto rooms() const
Definition: client.hpp:138
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:229
Definition: location.hpp:10
std::variant< RoomListAction, LoginAction, TokenLoginAction, 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, ClaimKeysAction, EncryptMegOlmEventAction, SetDeviceTrustLevelAction, SetTrustLevelNeededToSendKeysAction, PrepareForSharingRoomKeyAction, GetUserProfileAction, SetAvatarUrlAction, SetDisplayNameAction, ResubmitJobAction > ClientAction
Definition: clientfwd.hpp:145
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
Definition: clientutil.hpp:217
Definition: client-model.hpp:59
RoomListModel roomList
Definition: client-model.hpp:76
bool syncing
Definition: client-model.hpp:66
Definition: client.hpp:74
Definition: jobinterface.hpp:21
immer::map< std::string, RoomModel > rooms
Definition: room-model.hpp:399