@devanachat/sdk 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,39 @@ All notable changes to this project are documented in this file.
4
4
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project follows
5
5
  [semver](https://semver.org) (`0.x` minor releases may break the API).
6
6
 
7
+ ## [Unreleased]
8
+
9
+ ### Added
10
+
11
+ - Typing notifications: the `Type` command and the `Typing` event (`{location, userId}`), for rooms other than
12
+ `ClassicText`. `RoomsManager.typing.get(roomId, topicId)` returns the ids of the users typing in a topic, tracked from
13
+ the first call, each leaving `TYPING_TIMEOUT_MS` after their last notification or with their message.
14
+ `RoomsManager.typing.notify(roomId, topicId)` sends `Type` at most once per `TYPING_INTERVAL_MS`.
15
+ - Sticky messages: `Topic.stickyMessage`, `CreateMessage.sticky`, `NewMessage.sticky`, `UpdateTopic.stickyMessageId`
16
+ (a message id sticks it, `null` unsticks it) and the `ManagePins` permission. The topics tracked by `RoomsManager`
17
+ take a new sticky message from `NewMessage` and drop it when it is redacted.
18
+ - Role icons: `Role.icon` (`RoleIcon` - an emoji or an emoticon of the space, `{type, value}` like a reaction) and
19
+ `UpdateRole.icon` (an icon sets it, `null` removes it).
20
+ - Guests: `Space.guestRole` and `UpdateSpace.guestRole` (a role of the space given to temporary accounts when they
21
+ join, `null` turns it off); `SpacesManager` clears it when the role is deleted. The `SendAttachments` permission
22
+ covers attachments and links in messages.
23
+ - `Error.subcode`: an optional refinement of `code`. `ErrorCode.SpaceJoinRestricted` (`JoinSpace` refused) comes with
24
+ `Guests` (the space does not accept temporary accounts) or `Vpn` (it does not accept connections through a VPN or
25
+ Tor).
26
+
27
+ ### Changed
28
+
29
+ - `PermissionsManager.calculatePermissions` follows the server: on every layer the space default role (everyone) is
30
+ applied before the other roles, so a deny of another role overrides what everyone allows. An allow of any role still
31
+ wins over a deny of another one.
32
+ - `LeaveRoom` with `ignore: true` is answered only with `RoomLeft`: like a plain `LeaveRoom`, it requires the membership
33
+ of the room and fails for a closed conversation instead of answering `Ok`.
34
+
35
+ ### Fixed
36
+
37
+ - After a reconnect, or the first session after a snapshot import, `RoomsManager.getMembers()` of an unchanged
38
+ private conversation sent `GetRoomMembers` instead of using its participants.
39
+
7
40
  ## [0.10.0]
8
41
 
9
42
  ### Added
@@ -58,6 +58,8 @@ __webpack_require__.d(__webpack_exports__, {
58
58
  SearchRange: () => (/* reexport */ SearchRange),
59
59
  SpaceFeature: () => (/* reexport */ SpaceFeature),
60
60
  SpaceIntent: () => (/* reexport */ SpaceIntent),
61
+ TYPING_INTERVAL_MS: () => (/* reexport */ TYPING_INTERVAL_MS),
62
+ TYPING_TIMEOUT_MS: () => (/* reexport */ TYPING_TIMEOUT_MS),
61
63
  UiPurpose: () => (/* reexport */ UiPurpose),
62
64
  UserFeature: () => (/* reexport */ UserFeature),
63
65
  UserStatus: () => (/* reexport */ UserStatus),
@@ -1928,6 +1930,129 @@ class FollowedTopicsManager extends EventTarget {
1928
1930
  this.invalidateUnreadSummaries(roomId);
1929
1931
  }
1930
1932
  }
1933
+ ;// ./src/state-tracker/TypingManager.ts
1934
+
1935
+ const TYPING_INTERVAL_MS = 5000;
1936
+ const TYPING_TIMEOUT_MS = 2 * TYPING_INTERVAL_MS;
1937
+
1938
+ /**
1939
+ * Ids of the users typing in a topic, each mapped to the time (`Date.now()`) its typing expires at.
1940
+ */
1941
+
1942
+ class TypingManager {
1943
+ topics = new IndexedCollection();
1944
+ lastSentAt = new Map();
1945
+ constructor(tracker) {
1946
+ this.tracker = tracker;
1947
+ this.tracker.client.on('Typing', ev => this.handleTyping(ev));
1948
+ this.tracker.client.on('NewMessage', ev => this.handleNewMessage(ev));
1949
+ this.tracker.client.on('TopicDeleted', ev => this.handleTopicDeleted(ev));
1950
+ this.tracker.client.on('RoomLeft', ev => this.handleRoomGone(ev));
1951
+ this.tracker.client.on('RoomDeleted', ev => this.handleRoomGone(ev));
1952
+ this.tracker.client.on('Session', () => this.handleSession());
1953
+ }
1954
+
1955
+ /**
1956
+ * Users typing in the topic, without you. Tracking of the topic starts with the first call, so the collection
1957
+ * fills up with the next notifications, within {@link TYPING_INTERVAL_MS}. A user leaves it
1958
+ * {@link TYPING_TIMEOUT_MS} after their last notification or at once with their message in the topic.
1959
+ * Only ids are kept - resolve the users yourself, e.g. from {@link RoomsManager.getMembers}.
1960
+ */
1961
+ get(roomId, topicId) {
1962
+ if (!this.topics.has(topicId)) {
1963
+ this.topics.set([topicId, {
1964
+ roomId,
1965
+ users: new ObservableIndexedCollection()
1966
+ }]);
1967
+ }
1968
+ return this.topics.get(topicId).users;
1969
+ }
1970
+
1971
+ /**
1972
+ * Tell the other members of the room that you are typing in the topic. Call it on every change of the text:
1973
+ * the command is sent at most once per {@link TYPING_INTERVAL_MS} for a topic, and again right after your
1974
+ * message in it. Classic rooms do not support typing.
1975
+ */
1976
+ notify(roomId, topicId) {
1977
+ const now = Date.now();
1978
+ if (now - (this.lastSentAt.get(topicId) ?? -Infinity) < TYPING_INTERVAL_MS) {
1979
+ return;
1980
+ }
1981
+ this.lastSentAt.set(topicId, now);
1982
+ this.tracker.client.send('Type', {
1983
+ location: {
1984
+ roomId,
1985
+ topicId
1986
+ }
1987
+ }).catch(() => undefined);
1988
+ }
1989
+ handleTyping(ev) {
1990
+ const topic = this.topics.get(ev.location.topicId);
1991
+ if (!topic || ev.userId === this.tracker.me?.id) {
1992
+ return;
1993
+ }
1994
+ topic.users.set([ev.userId, Date.now() + TYPING_TIMEOUT_MS]);
1995
+ this.scheduleExpiry(topic);
1996
+ }
1997
+ handleNewMessage(ev) {
1998
+ const topicId = ev.message.location.topicId;
1999
+ const authorId = ev.message.author.user.id;
2000
+ if (authorId === this.tracker.me?.id) {
2001
+ this.lastSentAt.delete(topicId);
2002
+ return;
2003
+ }
2004
+ const topic = this.topics.get(topicId);
2005
+ if (topic?.users.has(authorId)) {
2006
+ topic.users.delete(authorId);
2007
+ this.scheduleExpiry(topic);
2008
+ }
2009
+ }
2010
+ handleTopicDeleted(ev) {
2011
+ this.clear(ev.location.topicId);
2012
+ }
2013
+ handleRoomGone(ev) {
2014
+ for (const [topicId, topic] of this.topics.items.entries()) {
2015
+ if (topic.roomId === ev.id) {
2016
+ this.clear(topicId);
2017
+ }
2018
+ }
2019
+ }
2020
+ handleSession() {
2021
+ this.lastSentAt.clear();
2022
+ for (const topic of this.topics.items.values()) {
2023
+ clearTimeout(topic.timer);
2024
+ topic.users.deleteAll();
2025
+ }
2026
+ }
2027
+ clear(topicId) {
2028
+ const topic = this.topics.get(topicId);
2029
+ if (topic) {
2030
+ clearTimeout(topic.timer);
2031
+ topic.users.deleteAll();
2032
+ }
2033
+ this.lastSentAt.delete(topicId);
2034
+ }
2035
+ scheduleExpiry(topic) {
2036
+ clearTimeout(topic.timer);
2037
+ topic.timer = undefined;
2038
+ if (!topic.users.length) {
2039
+ return;
2040
+ }
2041
+ const nextExpiry = Math.min(...topic.users.items.values());
2042
+ topic.timer = setTimeout(() => this.expire(topic), Math.max(0, nextExpiry - Date.now()));
2043
+ }
2044
+ expire(topic) {
2045
+ const now = Date.now();
2046
+ const expiredIds = [];
2047
+ for (const [userId, expiresAt] of topic.users.items.entries()) {
2048
+ if (expiresAt <= now) {
2049
+ expiredIds.push(userId);
2050
+ }
2051
+ }
2052
+ topic.users.delete(...expiredIds);
2053
+ this.scheduleExpiry(topic);
2054
+ }
2055
+ }
1931
2056
  ;// ./src/protocol/schemes/User.ts
1932
2057
  /**
1933
2058
  * Availability of a user, aggregated over all of their sessions.
@@ -2145,9 +2270,11 @@ function isSameUser(a, b) {
2145
2270
 
2146
2271
 
2147
2272
 
2273
+
2148
2274
  class RoomsManager {
2149
2275
  messages;
2150
2276
  followedTopics;
2277
+ typing;
2151
2278
  list = new ObservableIndexedObjectCollection('id');
2152
2279
  topics = new IndexedCollection();
2153
2280
  members = new IndexedCollection();
@@ -2159,6 +2286,7 @@ class RoomsManager {
2159
2286
  this.tracker = tracker;
2160
2287
  this.messages = new MessagesManager(tracker);
2161
2288
  this.followedTopics = new FollowedTopicsManager(tracker);
2289
+ this.typing = new TypingManager(tracker);
2162
2290
  this.tracker.client.on('NewMessage', ev => this.handleNewMessage(ev));
2163
2291
  this.tracker.client.on('MessagesRedacted', ev => this.handleMessagesRedacted(ev));
2164
2292
  this.tracker.client.on('NewTopic', ev => this.handleNewTopic(ev));
@@ -2551,6 +2679,9 @@ class RoomsManager {
2551
2679
  extras: ''
2552
2680
  };
2553
2681
  });
2682
+
2683
+ // GetRoomMembers is not supported for private conversations
2684
+ this.membersPromises.register(Promise.resolve(), room.id);
2554
2685
  if (current?.length === members.length && members.every(member => current.get(member.user.id) === member)) {
2555
2686
  return;
2556
2687
  }
@@ -2558,8 +2689,6 @@ class RoomsManager {
2558
2689
  id: room.id,
2559
2690
  members
2560
2691
  });
2561
- // GetRoomMembers is not supported for private conversations
2562
- this.membersPromises.register(Promise.resolve(), room.id);
2563
2692
  }
2564
2693
  handleRoomLeft(ev) {
2565
2694
  this.deleteRoom(ev.id);
@@ -2649,7 +2778,8 @@ class RoomsManager {
2649
2778
  const newTopic = {
2650
2779
  ...topic,
2651
2780
  messageCount: topic.messageCount + 1,
2652
- lastMessage: ev.message
2781
+ lastMessage: ev.message,
2782
+ stickyMessage: ev.sticky ? ev.message : topic.stickyMessage
2653
2783
  };
2654
2784
  topics.set(newTopic);
2655
2785
  this.updatePmDefaultTopic(ev.message.location.roomId, newTopic);
@@ -2661,10 +2791,14 @@ class RoomsManager {
2661
2791
  if (topic) {
2662
2792
  const messageCount = Math.max(topic.messageCount - ev.ids.length, 0);
2663
2793
  const lastMessage = messageCount > 0 ? await this.messages._resolveLastMessage(ev.location) : null;
2794
+ // Read after the await - a message stuck meanwhile must not be replaced with the stale one
2795
+ const currentSticky = (topics.get(ev.location.topicId) ?? topic).stickyMessage;
2796
+ const stickyMessage = ev.ids.includes(currentSticky?.id) ? null : currentSticky;
2664
2797
  const newTopic = {
2665
2798
  ...topic,
2666
2799
  messageCount,
2667
- lastMessage
2800
+ lastMessage,
2801
+ stickyMessage
2668
2802
  };
2669
2803
  topics.set(newTopic);
2670
2804
  this.updatePmDefaultTopic(ev.location.roomId, newTopic);
@@ -2874,6 +3008,13 @@ class SpacesManager {
2874
3008
  }
2875
3009
  handleRoleDeleted(ev) {
2876
3010
  this.roles.get(ev.spaceId).delete(ev.id);
3011
+ const space = this.list.get(ev.spaceId);
3012
+ if (space?.guestRole === ev.id) {
3013
+ this.list.set({
3014
+ ...space,
3015
+ guestRole: null
3016
+ });
3017
+ }
2877
3018
  this.syncSpaceRoles(ev.spaceId);
2878
3019
  }
2879
3020
 
@@ -3142,6 +3283,14 @@ class Permissions {
3142
3283
  UseExternalEmoticons: {
3143
3284
  value: 1 << 26,
3144
3285
  maxLayer: Layer.Room
3286
+ },
3287
+ ManagePins: {
3288
+ value: 1 << 27,
3289
+ maxLayer: Layer.Topic
3290
+ },
3291
+ SendAttachments: {
3292
+ value: 1 << 28,
3293
+ maxLayer: Layer.Topic
3145
3294
  }
3146
3295
  };
3147
3296
  static getNames() {
@@ -3275,7 +3424,7 @@ class PermissionsManager extends EventTarget {
3275
3424
  userId
3276
3425
  }).then(v => v.overwrites));
3277
3426
  }
3278
- return this.resolveOverwritesHierarchy(await Promise.all(promises));
3427
+ return this.resolveOverwritesHierarchy([].concat(...(await Promise.all(promises))));
3279
3428
  }
3280
3429
 
3281
3430
  /**
@@ -3352,34 +3501,22 @@ class PermissionsManager extends EventTarget {
3352
3501
  type: 'Role',
3353
3502
  roleId
3354
3503
  })));
3355
- return this.resolveOverwritesFromRolesByOrder(location.spaceId, roleOverwrites);
3356
- }
3357
- async resolveOverwritesFromRolesByOrder(spaceId, overwrites) {
3358
- let allows = 0,
3359
- denies = 0;
3360
- const roles = await this.tracker.spaces.getRoles(spaceId);
3361
- const sortedOverwrites = overwrites.sort((a, b) => roles.get(a.target.roleId).priority - roles.get(b.target.roleId).priority);
3362
-
3363
- // Max length of bit word
3364
- const permissionsLength = overwrites.reduce((previousValue, currentValue) => Math.max(previousValue, currentValue.overwrites.allow?.toString(2).length ?? 0, currentValue.overwrites.deny?.toString(2).length ?? 0), 0);
3365
- sortedOverwrites.forEach(overwriteEvent => {
3366
- const overwrites = overwriteEvent.overwrites;
3367
- const revDecDenies = overwrites.deny?.toString(2).split('').reverse().join('') ?? '';
3368
- const revDecAllows = overwrites.allow?.toString(2).split('').reverse().join('') ?? '';
3369
- for (let i = 0; i < permissionsLength; i++) {
3370
- const deny = parseInt(revDecDenies[i] ?? '0');
3371
- const allow = parseInt(revDecAllows[i] ?? '0');
3372
- if (deny) {
3373
- denies |= 1 << i;
3374
- }
3375
- if (allow) {
3376
- allows |= 1 << i;
3377
- }
3378
- }
3379
- });
3504
+ // The space default role (everyone) has the space id; it is applied before the other roles, as on the server.
3505
+ const isDefaultRole = overwrites => overwrites.target.roleId === location.spaceId;
3506
+ return [this.mergeRolesOverwrites(roleOverwrites.filter(isDefaultRole)), this.mergeRolesOverwrites(roleOverwrites.filter(overwrites => !isDefaultRole(overwrites)))];
3507
+ }
3508
+ mergeRolesOverwrites(rolesOverwrites) {
3509
+ let allow = 0,
3510
+ deny = 0;
3511
+ for (const {
3512
+ overwrites
3513
+ } of rolesOverwrites) {
3514
+ allow |= overwrites.allow ?? 0;
3515
+ deny |= overwrites.deny ?? 0;
3516
+ }
3380
3517
  return {
3381
- allow: allows,
3382
- deny: denies
3518
+ allow,
3519
+ deny
3383
3520
  };
3384
3521
  }
3385
3522
  resolveOverwritesHierarchy(permissionOverwritesValues) {
@@ -4338,6 +4475,7 @@ let ErrorCode = /*#__PURE__*/function (ErrorCode) {
4338
4475
  ErrorCode["MessageNotFound"] = "MessageNotFoundException";
4339
4476
  ErrorCode["RoomIgnored"] = "RoomIgnoredException";
4340
4477
  ErrorCode["RoomNotFound"] = "RoomNotFoundException";
4478
+ ErrorCode["SpaceJoinRestricted"] = "SpaceJoinRestrictedException";
4341
4479
  ErrorCode["TopicNotFound"] = "TopicNotFoundException";
4342
4480
  ErrorCode["UserNotFound"] = "UserNotFoundException";
4343
4481
  return ErrorCode;
@@ -4475,6 +4613,7 @@ let SpaceIntent = /*#__PURE__*/function (SpaceIntent) {
4475
4613
 
4476
4614
 
4477
4615
 
4616
+
4478
4617
  module.exports = __webpack_exports__;
4479
4618
  /******/ })()
4480
4619
  ;